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 |
|---|---|---|---|---|
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available
a : Optional[int] = {
"configuration_altclip": [
"ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP",
"AltCLIPConfig",
"AltCLIPTextConfig",
"AltCLIPVisionConfig",
],
"processing_altclip": ["AltCLIPProcessor"],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
a : Union[str, Any] = [
"ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST",
"AltCLIPPreTrainedModel",
"AltCLIPModel",
"AltCLIPTextModel",
"AltCLIPVisionModel",
]
if TYPE_CHECKING:
from .configuration_altclip import (
ALTCLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
AltCLIPConfig,
AltCLIPTextConfig,
AltCLIPVisionConfig,
)
from .processing_altclip import AltCLIPProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_altclip import (
ALTCLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
AltCLIPModel,
AltCLIPPreTrainedModel,
AltCLIPTextModel,
AltCLIPVisionModel,
)
else:
import sys
a : Tuple = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
| 63 |
# DISCLAIMER: This code is strongly influenced by https://github.com/pesser/pytorch_diffusion
# and https://github.com/hojonathanho/diffusion
import math
from dataclasses import dataclass
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.schedulers.scheduling_utils import SchedulerMixin
from diffusers.utils import BaseOutput, deprecate
@dataclass
# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->DDIM
class _lowerCamelCase ( a ):
"""simple docstring"""
UpperCAmelCase_ : torch.FloatTensor
UpperCAmelCase_ : Optional[torch.FloatTensor] =None
def lowerCAmelCase__( lowercase : Tuple , lowercase : str=0.9_9_9 , lowercase : Tuple="cosine" , ) -> Optional[Any]:
if alpha_transform_type == "cosine":
def alpha_bar_fn(lowercase : List[Any] ):
return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2 ) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(lowercase : Union[str, Any] ):
return math.exp(t * -1_2.0 )
else:
raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" )
__snake_case : Union[str, Any] = []
for i in range(lowercase ):
__snake_case : Any = i / num_diffusion_timesteps
__snake_case : Optional[Any] = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(lowercase ) / alpha_bar_fn(lowercase ) , lowercase ) )
return torch.tensor(lowercase , dtype=torch.floataa )
class _lowerCamelCase ( a , a ):
"""simple docstring"""
UpperCAmelCase_ : Dict =1
@register_to_config
def __init__( self , UpperCAmelCase = 1000 , UpperCAmelCase = 0.0_001 , UpperCAmelCase = 0.02 , UpperCAmelCase = "linear" , UpperCAmelCase = None , UpperCAmelCase = True , UpperCAmelCase = True , UpperCAmelCase = 0 , UpperCAmelCase = "epsilon" , UpperCAmelCase = 1.0 , **UpperCAmelCase , ) -> int:
'''simple docstring'''
if kwargs.get("set_alpha_to_one" , UpperCAmelCase ) is not None:
__snake_case : str = (
"The `set_alpha_to_one` argument is deprecated. Please use `set_alpha_to_zero` instead."
)
deprecate("set_alpha_to_one" , "1.0.0" , UpperCAmelCase , standard_warn=UpperCAmelCase )
__snake_case : Any = kwargs["set_alpha_to_one"]
if trained_betas is not None:
__snake_case : Union[str, Any] = torch.tensor(UpperCAmelCase , dtype=torch.floataa )
elif beta_schedule == "linear":
__snake_case : List[str] = torch.linspace(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , dtype=torch.floataa )
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
__snake_case : Tuple = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , UpperCAmelCase , dtype=torch.floataa ) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
__snake_case : Union[str, Any] = betas_for_alpha_bar(UpperCAmelCase )
else:
raise NotImplementedError(F"""{beta_schedule} does is not implemented for {self.__class__}""" )
__snake_case : str = 1.0 - self.betas
__snake_case : Optional[Any] = torch.cumprod(self.alphas , dim=0 )
# At every step in inverted ddim, we are looking into the next alphas_cumprod
# For the final step, there is no next alphas_cumprod, and the index is out of bounds
# `set_alpha_to_zero` decides whether we set this parameter simply to zero
# in this case, self.step() just output the predicted noise
# or whether we use the final alpha of the "non-previous" one.
__snake_case : List[Any] = torch.tensor(0.0 ) if set_alpha_to_zero else self.alphas_cumprod[-1]
# standard deviation of the initial noise distribution
__snake_case : Dict = 1.0
# setable values
__snake_case : Tuple = None
__snake_case : int = torch.from_numpy(np.arange(0 , UpperCAmelCase ).copy().astype(np.intaa ) )
def UpperCAmelCase ( self , UpperCAmelCase , UpperCAmelCase = None ) -> torch.FloatTensor:
'''simple docstring'''
return sample
def UpperCAmelCase ( self , UpperCAmelCase , UpperCAmelCase = None ) -> Optional[Any]:
'''simple docstring'''
if num_inference_steps > self.config.num_train_timesteps:
raise ValueError(
F"""`num_inference_steps`: {num_inference_steps} cannot be larger than `self.config.train_timesteps`:"""
F""" {self.config.num_train_timesteps} as the unet model trained with this scheduler can only handle"""
F""" maximal {self.config.num_train_timesteps} timesteps.""" )
__snake_case : List[str] = num_inference_steps
__snake_case : List[str] = self.config.num_train_timesteps // self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
__snake_case : List[Any] = (np.arange(0 , UpperCAmelCase ) * step_ratio).round().copy().astype(np.intaa )
__snake_case : List[str] = torch.from_numpy(UpperCAmelCase ).to(UpperCAmelCase )
self.timesteps += self.config.steps_offset
def UpperCAmelCase ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase = 0.0 , UpperCAmelCase = False , UpperCAmelCase = None , UpperCAmelCase = True , ) -> Union[DDIMSchedulerOutput, Tuple]:
'''simple docstring'''
__snake_case : Dict = timestep + self.config.num_train_timesteps // self.num_inference_steps
# 2. compute alphas, betas
# change original implementation to exactly match noise levels for analogous forward process
__snake_case : str = self.alphas_cumprod[timestep]
__snake_case : Tuple = (
self.alphas_cumprod[prev_timestep]
if prev_timestep < self.config.num_train_timesteps
else self.final_alpha_cumprod
)
__snake_case : Optional[Any] = 1 - alpha_prod_t
# 3. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
if self.config.prediction_type == "epsilon":
__snake_case : Any = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
__snake_case : Dict = model_output
elif self.config.prediction_type == "sample":
__snake_case : Optional[int] = model_output
__snake_case : Union[str, Any] = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
elif self.config.prediction_type == "v_prediction":
__snake_case : Dict = (alpha_prod_t**0.5) * sample - (beta_prod_t**0.5) * model_output
__snake_case : Dict = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
else:
raise ValueError(
F"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, `sample`, or"""
" `v_prediction`" )
# 4. Clip or threshold "predicted x_0"
if self.config.clip_sample:
__snake_case : Any = pred_original_sample.clamp(
-self.config.clip_sample_range , self.config.clip_sample_range )
# 5. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__snake_case : Any = (1 - alpha_prod_t_prev) ** 0.5 * pred_epsilon
# 6. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__snake_case : int = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
if not return_dict:
return (prev_sample, pred_original_sample)
return DDIMSchedulerOutput(prev_sample=UpperCAmelCase , pred_original_sample=UpperCAmelCase )
def __len__( self ) -> Optional[Any]:
'''simple docstring'''
return self.config.num_train_timesteps
| 243 | 0 |
'''simple docstring'''
from typing import Optional, Tuple
import jax
import jax.numpy as jnp
from flax import linen as nn
from flax.core.frozen_dict import FrozenDict
from transformers import CLIPConfig, FlaxPreTrainedModel
from transformers.models.clip.modeling_flax_clip import FlaxCLIPVisionModule
def UpperCAmelCase_ ( lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=1E-1_2 ):
"""simple docstring"""
lowercase = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(lowerCAmelCase_ , axis=1 ) , a_min=lowerCAmelCase_ ) ).T
lowercase = jnp.divide(emb_a.T , jnp.clip(jnp.linalg.norm(lowerCAmelCase_ , axis=1 ) , a_min=lowerCAmelCase_ ) ).T
return jnp.matmul(lowerCAmelCase_ , norm_emb_a.T )
class UpperCAmelCase ( nn.Module ):
UpperCAmelCase : CLIPConfig
UpperCAmelCase : jnp.dtype = jnp.floataa
def UpperCAmelCase__ (self : int ) -> Any:
lowercase = FlaxCLIPVisionModule(self.config.vision_config )
lowercase = nn.Dense(self.config.projection_dim , use_bias=A__ , dtype=self.dtype )
lowercase = self.param("concept_embeds" , jax.nn.initializers.ones , (1_7, self.config.projection_dim) )
lowercase = self.param(
"special_care_embeds" , jax.nn.initializers.ones , (3, self.config.projection_dim) )
lowercase = self.param("concept_embeds_weights" , jax.nn.initializers.ones , (1_7,) )
lowercase = self.param("special_care_embeds_weights" , jax.nn.initializers.ones , (3,) )
def __call__(self : Union[str, Any] , A__ : Dict ) -> Tuple:
lowercase = self.vision_model(A__ )[1]
lowercase = self.visual_projection(A__ )
lowercase = jax_cosine_distance(A__ , self.special_care_embeds )
lowercase = jax_cosine_distance(A__ , self.concept_embeds )
# increase this value to create a stronger `nfsw` filter
# at the cost of increasing the possibility of filtering benign image inputs
lowercase = 0.0
lowercase = special_cos_dist - self.special_care_embeds_weights[None, :] + adjustment
lowercase = jnp.round(A__ , 3 )
lowercase = jnp.any(special_scores > 0 , axis=1 , keepdims=A__ )
# Use a lower threshold if an image has any special care concept
lowercase = is_special_care * 0.0_1
lowercase = cos_dist - self.concept_embeds_weights[None, :] + special_adjustment
lowercase = jnp.round(A__ , 3 )
lowercase = jnp.any(concept_scores > 0 , axis=1 )
return has_nsfw_concepts
class UpperCAmelCase ( _lowercase ):
UpperCAmelCase : Tuple = CLIPConfig
UpperCAmelCase : List[Any] = '''clip_input'''
UpperCAmelCase : Union[str, Any] = FlaxStableDiffusionSafetyCheckerModule
def __init__(self : Tuple , A__ : CLIPConfig , A__ : Optional[Tuple] = None , A__ : int = 0 , A__ : jnp.dtype = jnp.floataa , A__ : bool = True , **A__ : Tuple , ) -> Union[str, Any]:
if input_shape is None:
lowercase = (1, 2_2_4, 2_2_4, 3)
lowercase = self.module_class(config=A__ , dtype=A__ , **A__ )
super().__init__(A__ , A__ , input_shape=A__ , seed=A__ , dtype=A__ , _do_init=_do_init )
def UpperCAmelCase__ (self : Any , A__ : jax.random.KeyArray , A__ : Tuple , A__ : FrozenDict = None ) -> FrozenDict:
# init input tensor
lowercase = jax.random.normal(A__ , A__ )
lowercase , lowercase = jax.random.split(A__ )
lowercase = {"params": params_rng, "dropout": dropout_rng}
lowercase = self.module.init(A__ , A__ )["params"]
return random_params
def __call__(self : int , A__ : Any , A__ : dict = None , ) -> Optional[Any]:
lowercase = jnp.transpose(A__ , (0, 2, 3, 1) )
return self.module.apply(
{"params": params or self.params} , jnp.array(A__ , dtype=jnp.floataa ) , rngs={} , )
| 459 |
'''simple docstring'''
import warnings
from contextlib import contextmanager
from ....processing_utils import ProcessorMixin
class UpperCAmelCase ( _lowercase ):
UpperCAmelCase : Optional[Any] = '''MCTCTFeatureExtractor'''
UpperCAmelCase : Tuple = '''AutoTokenizer'''
def __init__(self : int , A__ : Tuple , A__ : Union[str, Any] ) -> Dict:
super().__init__(A__ , A__ )
lowercase = self.feature_extractor
lowercase = False
def __call__(self : Tuple , *A__ : str , **A__ : Dict ) -> int:
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor(*A__ , **A__ )
if "raw_speech" in kwargs:
warnings.warn("Using `raw_speech` as a keyword argument is deprecated. Use `audio` instead." )
lowercase = kwargs.pop("raw_speech" )
else:
lowercase = kwargs.pop("audio" , A__ )
lowercase = kwargs.pop("sampling_rate" , A__ )
lowercase = kwargs.pop("text" , A__ )
if len(A__ ) > 0:
lowercase = args[0]
lowercase = 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:
lowercase = self.feature_extractor(A__ , *A__ , sampling_rate=A__ , **A__ )
if text is not None:
lowercase = self.tokenizer(A__ , **A__ )
if text is None:
return inputs
elif audio is None:
return encodings
else:
lowercase = encodings["input_ids"]
return inputs
def UpperCAmelCase__ (self : Tuple , *A__ : str , **A__ : str ) -> str:
return self.tokenizer.batch_decode(*A__ , **A__ )
def UpperCAmelCase__ (self : Any , *A__ : List[Any] , **A__ : List[str] ) -> Tuple:
# For backward compatibility
if self._in_target_context_manager:
return self.current_processor.pad(*A__ , **A__ )
lowercase = kwargs.pop("input_features" , A__ )
lowercase = kwargs.pop("labels" , A__ )
if len(A__ ) > 0:
lowercase = args[0]
lowercase = args[1:]
if input_features is not None:
lowercase = self.feature_extractor.pad(A__ , *A__ , **A__ )
if labels is not None:
lowercase = self.tokenizer.pad(A__ , **A__ )
if labels is None:
return input_features
elif input_features is None:
return labels
else:
lowercase = labels["input_ids"]
return input_features
def UpperCAmelCase__ (self : Tuple , *A__ : Optional[int] , **A__ : Optional[int] ) -> Tuple:
return self.tokenizer.decode(*A__ , **A__ )
@contextmanager
def UpperCAmelCase__ (self : Optional[Any] ) -> Union[str, Any]:
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." )
lowercase = True
lowercase = self.tokenizer
yield
lowercase = self.feature_extractor
lowercase = False
| 459 | 1 |
"""simple docstring"""
import unittest
from transformers import MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING, AutoTokenizer, is_vision_available
from transformers.pipelines import pipeline
from transformers.pipelines.document_question_answering import apply_tesseract
from transformers.testing_utils import (
is_pipeline_test,
nested_simplify,
require_detectrona,
require_pytesseract,
require_tf,
require_torch,
require_vision,
slow,
)
from .test_pipelines_common import ANY
if is_vision_available():
from PIL import Image
from transformers.image_utils import load_image
else:
class UpperCamelCase__ :
"""simple docstring"""
@staticmethod
def snake_case__ ( *SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> List[Any]:
pass
def _lowerCamelCase ( UpperCAmelCase_ : Tuple ) -> Tuple:
"""simple docstring"""
return None
# This is a pinned image from a specific revision of a document question answering space, hosted by HuggingFace,
# so we can expect it to be available.
UpperCamelCase = (
'https://huggingface.co/spaces/impira/docquery/resolve/2f6c96314dc84dfda62d40de9da55f2f5165d403/invoice.png'
)
@is_pipeline_test
@require_torch
@require_vision
class UpperCamelCase__ ( unittest.TestCase ):
"""simple docstring"""
A__ : Optional[int] = MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING
@require_pytesseract
@require_vision
def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> Optional[Any]:
A__ = pipeline(
"document-question-answering" , model=lowerCamelCase__ , tokenizer=lowerCamelCase__ , image_processor=lowerCamelCase__ )
A__ = INVOICE_URL
A__ = list(zip(*apply_tesseract(load_image(lowerCamelCase__ ) , lowerCamelCase__ , "" ) ) )
A__ = "What is the placebo?"
A__ = [
{
"image": load_image(lowerCamelCase__ ),
"question": question,
},
{
"image": image,
"question": question,
},
{
"image": image,
"question": question,
"word_boxes": word_boxes,
},
]
return dqa_pipeline, examples
def snake_case__ ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) -> List[str]:
A__ = dqa_pipeline(lowerCamelCase__ , top_k=2 )
self.assertEqual(
lowerCamelCase__ , [
[
{"score": ANY(lowerCamelCase__ ), "answer": ANY(lowerCamelCase__ ), "start": ANY(lowerCamelCase__ ), "end": ANY(lowerCamelCase__ )},
{"score": ANY(lowerCamelCase__ ), "answer": ANY(lowerCamelCase__ ), "start": ANY(lowerCamelCase__ ), "end": ANY(lowerCamelCase__ )},
]
]
* 3 , )
@require_torch
@require_detectrona
@require_pytesseract
def snake_case__ ( self ) -> Optional[Any]:
A__ = pipeline("document-question-answering" , model="hf-internal-testing/tiny-random-layoutlmv2" )
A__ = INVOICE_URL
A__ = "How many cats are there?"
A__ = [
{"score": 0.0_0_0_1, "answer": "oy 2312/2019", "start": 38, "end": 39},
{"score": 0.0_0_0_1, "answer": "oy 2312/2019 DUE", "start": 38, "end": 40},
]
A__ = dqa_pipeline(image=lowerCamelCase__ , question=lowerCamelCase__ , top_k=2 )
self.assertEqual(nested_simplify(lowerCamelCase__ , decimals=4 ) , lowerCamelCase__ )
A__ = dqa_pipeline({"image": image, "question": question} , top_k=2 )
self.assertEqual(nested_simplify(lowerCamelCase__ , decimals=4 ) , lowerCamelCase__ )
# This image does not detect ANY text in it, meaning layoutlmv2 should fail.
# Empty answer probably
A__ = "./tests/fixtures/tests_samples/COCO/000000039769.png"
A__ = dqa_pipeline(image=lowerCamelCase__ , question=lowerCamelCase__ , top_k=2 )
self.assertEqual(lowerCamelCase__ , [] )
# We can optionnally pass directly the words and bounding boxes
A__ = "./tests/fixtures/tests_samples/COCO/000000039769.png"
A__ = []
A__ = []
A__ = dqa_pipeline(image=lowerCamelCase__ , question=lowerCamelCase__ , words=lowerCamelCase__ , boxes=lowerCamelCase__ , top_k=2 )
self.assertEqual(lowerCamelCase__ , [] )
@slow
@require_torch
@require_detectrona
@require_pytesseract
def snake_case__ ( self ) -> Optional[Any]:
A__ = pipeline(
"document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , )
A__ = INVOICE_URL
A__ = "What is the invoice number?"
A__ = dqa_pipeline(image=lowerCamelCase__ , question=lowerCamelCase__ , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.9_9_4_4, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.0_0_0_9, "answer": "us-001", "start": 16, "end": 16},
] , )
A__ = dqa_pipeline({"image": image, "question": question} , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.9_9_4_4, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.0_0_0_9, "answer": "us-001", "start": 16, "end": 16},
] , )
A__ = dqa_pipeline(
[{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
[
{"score": 0.9_9_4_4, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.0_0_0_9, "answer": "us-001", "start": 16, "end": 16},
],
]
* 2 , )
@slow
@require_torch
@require_detectrona
@require_pytesseract
def snake_case__ ( self ) -> Optional[Any]:
A__ = pipeline(
"document-question-answering" , model="tiennvcs/layoutlmv2-base-uncased-finetuned-docvqa" , revision="9977165" , max_seq_len=50 , )
A__ = INVOICE_URL
A__ = "What is the invoice number?"
A__ = dqa_pipeline(image=lowerCamelCase__ , question=lowerCamelCase__ , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.9_9_7_4, "answer": "1110212019", "start": 23, "end": 23},
{"score": 0.9_9_4_8, "answer": "us-001", "start": 16, "end": 16},
] , )
A__ = dqa_pipeline({"image": image, "question": question} , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.9_9_7_4, "answer": "1110212019", "start": 23, "end": 23},
{"score": 0.9_9_4_8, "answer": "us-001", "start": 16, "end": 16},
] , )
A__ = dqa_pipeline(
[{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
[
{"score": 0.9_9_7_4, "answer": "1110212019", "start": 23, "end": 23},
{"score": 0.9_9_4_8, "answer": "us-001", "start": 16, "end": 16},
]
]
* 2 , )
@slow
@require_torch
@require_pytesseract
@require_vision
def snake_case__ ( self ) -> int:
A__ = AutoTokenizer.from_pretrained(
"impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=lowerCamelCase__ )
A__ = pipeline(
"document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=lowerCamelCase__ , revision="3dc6de3" , )
A__ = INVOICE_URL
A__ = "What is the invoice number?"
A__ = dqa_pipeline(image=lowerCamelCase__ , question=lowerCamelCase__ , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.4_2_5_1, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.0_8_1_9, "answer": "1110212019", "start": 23, "end": 23},
] , )
A__ = dqa_pipeline({"image": image, "question": question} , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.4_2_5_1, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.0_8_1_9, "answer": "1110212019", "start": 23, "end": 23},
] , )
A__ = dqa_pipeline(
[{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
[
{"score": 0.4_2_5_1, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.0_8_1_9, "answer": "1110212019", "start": 23, "end": 23},
]
]
* 2 , )
A__ = list(zip(*apply_tesseract(load_image(lowerCamelCase__ ) , lowerCamelCase__ , "" ) ) )
# This model should also work if `image` is set to None
A__ = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.4_2_5_1, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.0_8_1_9, "answer": "1110212019", "start": 23, "end": 23},
] , )
@slow
@require_torch
@require_pytesseract
@require_vision
def snake_case__ ( self ) -> Union[str, Any]:
A__ = AutoTokenizer.from_pretrained(
"impira/layoutlm-document-qa" , revision="3dc6de3" , add_prefix_space=lowerCamelCase__ )
A__ = pipeline(
"document-question-answering" , model="impira/layoutlm-document-qa" , tokenizer=lowerCamelCase__ , revision="3dc6de3" , max_seq_len=50 , )
A__ = INVOICE_URL
A__ = "What is the invoice number?"
A__ = dqa_pipeline(image=lowerCamelCase__ , question=lowerCamelCase__ , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.9_9_9_9, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.9_9_9_8, "answer": "us-001", "start": 16, "end": 16},
] , )
A__ = dqa_pipeline(
[{"image": image, "question": question}, {"image": image, "question": question}] , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
[
{"score": 0.9_9_9_9, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.9_9_9_8, "answer": "us-001", "start": 16, "end": 16},
]
]
* 2 , )
A__ = list(zip(*apply_tesseract(load_image(lowerCamelCase__ ) , lowerCamelCase__ , "" ) ) )
# This model should also work if `image` is set to None
A__ = dqa_pipeline({"image": None, "word_boxes": word_boxes, "question": question} , top_k=2 )
self.assertEqual(
nested_simplify(lowerCamelCase__ , decimals=4 ) , [
{"score": 0.9_9_9_9, "answer": "us-001", "start": 16, "end": 16},
{"score": 0.9_9_9_8, "answer": "us-001", "start": 16, "end": 16},
] , )
@slow
@require_torch
def snake_case__ ( self ) -> List[Any]:
A__ = pipeline(
"document-question-answering" , model="naver-clova-ix/donut-base-finetuned-docvqa" , tokenizer=AutoTokenizer.from_pretrained("naver-clova-ix/donut-base-finetuned-docvqa" ) , feature_extractor="naver-clova-ix/donut-base-finetuned-docvqa" , )
A__ = INVOICE_URL
A__ = "What is the invoice number?"
A__ = dqa_pipeline(image=lowerCamelCase__ , question=lowerCamelCase__ , top_k=2 )
self.assertEqual(nested_simplify(lowerCamelCase__ , decimals=4 ) , [{"answer": "us-001"}] )
@require_tf
@unittest.skip("Document question answering not implemented in TF" )
def snake_case__ ( self ) -> List[str]:
pass
| 104 |
'''simple docstring'''
import torch
from torch import nn
from transformers import CLIPPreTrainedModel, CLIPVisionModel
from ...models.attention import BasicTransformerBlock
from ...utils import logging
snake_case_ : Any = logging.get_logger(__name__) # pylint: disable=invalid-name
class lowercase__ ( snake_case_ ):
'''simple docstring'''
def __init__( self , lowerCamelCase__ , lowerCamelCase__=7_6_8 ):
'''simple docstring'''
super().__init__(lowerCamelCase__ )
UpperCamelCase = proj_size
UpperCamelCase = CLIPVisionModel(lowerCamelCase__ )
UpperCamelCase = PaintByExampleMapper(lowerCamelCase__ )
UpperCamelCase = nn.LayerNorm(config.hidden_size )
UpperCamelCase = nn.Linear(config.hidden_size , self.proj_size )
# uncondition for scaling
UpperCamelCase = nn.Parameter(torch.randn((1, 1, self.proj_size) ) )
def UpperCAmelCase ( self , lowerCamelCase__ , lowerCamelCase__=False ):
'''simple docstring'''
UpperCamelCase = self.model(pixel_values=lowerCamelCase__ )
UpperCamelCase = clip_output.pooler_output
UpperCamelCase = self.mapper(latent_states[:, None] )
UpperCamelCase = self.final_layer_norm(lowerCamelCase__ )
UpperCamelCase = self.proj_out(lowerCamelCase__ )
if return_uncond_vector:
return latent_states, self.uncond_vector
return latent_states
class lowercase__ ( nn.Module ):
'''simple docstring'''
def __init__( self , lowerCamelCase__ ):
'''simple docstring'''
super().__init__()
UpperCamelCase = (config.num_hidden_layers + 1) // 5
UpperCamelCase = config.hidden_size
UpperCamelCase = 1
UpperCamelCase = nn.ModuleList(
[
BasicTransformerBlock(lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , activation_fn='''gelu''' , attention_bias=lowerCamelCase__ )
for _ in range(lowerCamelCase__ )
] )
def UpperCAmelCase ( self , lowerCamelCase__ ):
'''simple docstring'''
for block in self.blocks:
UpperCamelCase = block(lowerCamelCase__ )
return hidden_states
| 212 | 0 |
import argparse
import collections
import os
import re
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_table.py
lowercase__ ='src/transformers'
lowercase__ ='docs/source/en'
lowercase__ ='.'
def __UpperCamelCase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] ):
with open(lowerCAmelCase__ , '''r''' , encoding='''utf-8''' , newline='''\n''' ) as f:
__a : Any = f.readlines()
# Find the start prompt.
__a : List[Any] = 0
while not lines[start_index].startswith(lowerCAmelCase__ ):
start_index += 1
start_index += 1
__a : Any = start_index
while not lines[end_index].startswith(lowerCAmelCase__ ):
end_index += 1
end_index -= 1
while len(lines[start_index] ) <= 1:
start_index += 1
while len(lines[end_index] ) <= 1:
end_index -= 1
end_index += 1
return "".join(lines[start_index:end_index] ), start_index, end_index, lines
# Add here suffixes that are used to identify models, separated by |
lowercase__ ='Model|Encoder|Decoder|ForConditionalGeneration'
# Regexes that match TF/Flax/PT model names.
lowercase__ =re.compile(R'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
lowercase__ =re.compile(R'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
lowercase__ =re.compile(R'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# This is to make sure the transformers module imported is the one in the repo.
lowercase__ =direct_transformers_import(TRANSFORMERS_PATH)
def __UpperCamelCase ( lowerCAmelCase__ : Union[str, Any] ):
__a : Any = re.finditer('''.+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)''' , lowerCAmelCase__ )
return [m.group(0 ) for m in matches]
def __UpperCamelCase ( lowerCAmelCase__ : str , lowerCAmelCase__ : Optional[int] ):
__a : Optional[int] = 2 if text == '''✅''' or text == '''❌''' else len(lowerCAmelCase__ )
__a : List[Any] = (width - text_length) // 2
__a : Tuple = width - text_length - left_indent
return " " * left_indent + text + " " * right_indent
def __UpperCamelCase ( ):
__a : List[str] = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
__a : Optional[Any] = {
name: config_maping_names[code]
for code, name in transformers_module.MODEL_NAMES_MAPPING.items()
if code in config_maping_names
}
__a : Union[str, Any] = {name: config.replace('''Config''' , '''''' ) for name, config in model_name_to_config.items()}
# Dictionaries flagging if each model prefix has a slow/fast tokenizer, backend in PT/TF/Flax.
__a : Optional[int] = collections.defaultdict(lowerCAmelCase__ )
__a : List[Any] = collections.defaultdict(lowerCAmelCase__ )
__a : Dict = collections.defaultdict(lowerCAmelCase__ )
__a : Tuple = collections.defaultdict(lowerCAmelCase__ )
__a : Union[str, Any] = collections.defaultdict(lowerCAmelCase__ )
# Let's lookup through all transformers object (once).
for attr_name in dir(lowerCAmelCase__ ):
__a : Any = None
if attr_name.endswith('''Tokenizer''' ):
__a : Union[str, Any] = slow_tokenizers
__a : List[str] = attr_name[:-9]
elif attr_name.endswith('''TokenizerFast''' ):
__a : Union[str, Any] = fast_tokenizers
__a : List[Any] = attr_name[:-1_3]
elif _re_tf_models.match(lowerCAmelCase__ ) is not None:
__a : List[str] = tf_models
__a : Tuple = _re_tf_models.match(lowerCAmelCase__ ).groups()[0]
elif _re_flax_models.match(lowerCAmelCase__ ) is not None:
__a : List[str] = flax_models
__a : str = _re_flax_models.match(lowerCAmelCase__ ).groups()[0]
elif _re_pt_models.match(lowerCAmelCase__ ) is not None:
__a : Union[str, Any] = pt_models
__a : int = _re_pt_models.match(lowerCAmelCase__ ).groups()[0]
if lookup_dict is not None:
while len(lowerCAmelCase__ ) > 0:
if attr_name in model_name_to_prefix.values():
__a : List[str] = True
break
# Try again after removing the last word in the name
__a : str = ''''''.join(camel_case_split(lowerCAmelCase__ )[:-1] )
# Let's build that table!
__a : Optional[int] = list(model_name_to_config.keys() )
model_names.sort(key=str.lower )
__a : Optional[int] = ['''Model''', '''Tokenizer slow''', '''Tokenizer fast''', '''PyTorch support''', '''TensorFlow support''', '''Flax Support''']
# We'll need widths to properly display everything in the center (+2 is to leave one extra space on each side).
__a : Any = [len(lowerCAmelCase__ ) + 2 for c in columns]
__a : Union[str, Any] = max([len(lowerCAmelCase__ ) for name in model_names] ) + 2
# Build the table per se
__a : List[str] = '''|''' + '''|'''.join([_center_text(lowerCAmelCase__ , lowerCAmelCase__ ) for c, w in zip(lowerCAmelCase__ , lowerCAmelCase__ )] ) + '''|\n'''
# Use ":-----:" format to center-aligned table cell texts
table += "|" + "|".join([''':''' + '''-''' * (w - 2) + ''':''' for w in widths] ) + "|\n"
__a : Union[str, Any] = {True: '''✅''', False: '''❌'''}
for name in model_names:
__a : str = model_name_to_prefix[name]
__a : str = [
name,
check[slow_tokenizers[prefix]],
check[fast_tokenizers[prefix]],
check[pt_models[prefix]],
check[tf_models[prefix]],
check[flax_models[prefix]],
]
table += "|" + "|".join([_center_text(lowerCAmelCase__ , lowerCAmelCase__ ) for l, w in zip(lowerCAmelCase__ , lowerCAmelCase__ )] ) + "|\n"
return table
def __UpperCamelCase ( lowerCAmelCase__ : Optional[int]=False ):
__a , __a , __a , __a : Optional[int] = _find_text_in_file(
filename=os.path.join(lowerCAmelCase__ , '''index.md''' ) , start_prompt='''<!--This table is updated automatically from the auto modules''' , end_prompt='''<!-- End table-->''' , )
__a : Union[str, Any] = get_model_table_from_auto_modules()
if current_table != new_table:
if overwrite:
with open(os.path.join(lowerCAmelCase__ , '''index.md''' ) , '''w''' , encoding='''utf-8''' , newline='''\n''' ) as f:
f.writelines(lines[:start_index] + [new_table] + lines[end_index:] )
else:
raise ValueError(
'''The model table in the `index.md` has not been updated. Run `make fix-copies` to fix this.''' )
if __name__ == "__main__":
lowercase__ =argparse.ArgumentParser()
parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
lowercase__ =parser.parse_args()
check_model_table(args.fix_and_overwrite)
| 326 |
from typing import List, Optional, Union
import numpy as np
import torch
import torchaudio.compliance.kaldi as ta_kaldi
from ...feature_extraction_sequence_utils import SequenceFeatureExtractor
from ...feature_extraction_utils import BatchFeature
from ...utils import PaddingStrategy, TensorType, logging
lowercase__ =logging.get_logger(__name__)
class UpperCamelCase__ ( __lowercase ):
_SCREAMING_SNAKE_CASE : int = ["input_features", "attention_mask"]
def __init__(self : Dict , snake_case_ : Tuple=8_0 , snake_case_ : Tuple=1_6_0_0_0 , snake_case_ : Union[str, Any]=8_0 , snake_case_ : List[Any]=0.0 , snake_case_ : Optional[Any]=True , snake_case_ : Any=True , snake_case_ : int=True , **snake_case_ : Dict , ):
super().__init__(feature_size=snake_case_ , sampling_rate=snake_case_ , padding_value=snake_case_ , **snake_case_ )
__a : int = num_mel_bins
__a : Dict = do_ceptral_normalize
__a : Union[str, Any] = normalize_means
__a : int = normalize_vars
__a : Optional[Any] = True
def lowerCAmelCase (self : Any , snake_case_ : np.ndarray , ):
__a : Union[str, Any] = waveform * (2**1_5) # Kaldi compliance: 16-bit signed integers
__a : Any = torch.from_numpy(snake_case_ ).unsqueeze(0 )
__a : List[Any] = ta_kaldi.fbank(snake_case_ , num_mel_bins=self.num_mel_bins , sample_frequency=self.sampling_rate )
return features.numpy()
@staticmethod
def lowerCAmelCase (snake_case_ : np.ndarray , snake_case_ : int , snake_case_ : Optional[bool] = True , snake_case_ : Optional[bool] = True , snake_case_ : float = 0.0 , ):
# make sure we normalize float32 arrays
if normalize_means:
__a : Optional[int] = x[:input_length].mean(axis=0 )
__a : Optional[int] = np.subtract(snake_case_ , snake_case_ )
if normalize_vars:
__a : Optional[Any] = x[:input_length].std(axis=0 )
__a : Optional[Any] = np.divide(snake_case_ , snake_case_ )
if input_length < x.shape[0]:
__a : Optional[int] = padding_value
# make sure array is in float32
__a : Tuple = x.astype(np.floataa )
return x
def lowerCAmelCase (self : List[Any] , snake_case_ : List[np.ndarray] , snake_case_ : Optional[np.ndarray] = None ):
__a : Optional[Any] = attention_mask.sum(-1 ) if attention_mask is not None else [x.shape[0] for x in input_features]
return [
self.utterance_cmvn(snake_case_ , snake_case_ , self.normalize_means , self.normalize_vars , self.padding_value )
for x, n in zip(snake_case_ , snake_case_ )
]
def __call__(self : List[str] , snake_case_ : Union[np.ndarray, List[float], List[np.ndarray], List[List[float]]] , snake_case_ : Union[bool, str, PaddingStrategy] = False , snake_case_ : Optional[int] = None , snake_case_ : bool = False , snake_case_ : Optional[int] = None , snake_case_ : Optional[Union[str, TensorType]] = None , snake_case_ : Optional[int] = None , snake_case_ : Optional[bool] = None , **snake_case_ : int , ):
if sampling_rate is not None:
if sampling_rate != self.sampling_rate:
raise ValueError(
f"The model corresponding to this feature extractor: {self} was trained using a sampling rate of"
f" {self.sampling_rate}. Please make sure that the provided `raw_speech` input was sampled with"
f" {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.''' )
__a : Dict = isinstance(snake_case_ , np.ndarray ) and len(raw_speech.shape ) > 1
if is_batched_numpy and len(raw_speech.shape ) > 2:
raise ValueError(f"Only mono-channel audio is supported for input to {self}" )
__a : List[str] = is_batched_numpy or (
isinstance(snake_case_ , (list, tuple) ) and (isinstance(raw_speech[0] , (np.ndarray, tuple, list) ))
)
if is_batched:
__a : Optional[int] = [np.asarray(snake_case_ , dtype=np.floataa ) for speech in raw_speech]
elif not is_batched and not isinstance(snake_case_ , np.ndarray ):
__a : Optional[int] = np.asarray(snake_case_ , dtype=np.floataa )
elif isinstance(snake_case_ , np.ndarray ) and raw_speech.dtype is np.dtype(np.floataa ):
__a : Optional[Any] = raw_speech.astype(np.floataa )
# always return batch
if not is_batched:
__a : Dict = [raw_speech]
# extract fbank features
__a : Union[str, Any] = [self._extract_fbank_features(snake_case_ ) for waveform in raw_speech]
# convert into correct format for padding
__a : str = BatchFeature({'''input_features''': features} )
__a : Union[str, Any] = self.pad(
snake_case_ , padding=snake_case_ , max_length=snake_case_ , truncation=snake_case_ , pad_to_multiple_of=snake_case_ , return_attention_mask=snake_case_ , **snake_case_ , )
# make sure list is in array format
__a : List[Any] = padded_inputs.get('''input_features''' )
if isinstance(input_features[0] , snake_case_ ):
__a : List[str] = [np.asarray(snake_case_ , dtype=np.floataa ) for feature in input_features]
__a : Tuple = padded_inputs.get('''attention_mask''' )
if attention_mask is not None:
__a : Optional[int] = [np.asarray(snake_case_ , dtype=np.intaa ) for array in attention_mask]
# Utterance-level cepstral mean and variance normalization
if self.do_ceptral_normalize:
__a : int = (
np.array(snake_case_ , dtype=np.intaa )
if self._get_padding_strategies(snake_case_ , max_length=snake_case_ ) is not PaddingStrategy.DO_NOT_PAD
else None
)
__a : List[str] = self.normalize(
padded_inputs['''input_features'''] , attention_mask=snake_case_ )
if return_tensors is not None:
__a : Optional[int] = padded_inputs.convert_to_tensors(snake_case_ )
return padded_inputs
| 326 | 1 |
'''simple docstring'''
import unittest
from transformers import EsmConfig, is_torch_available
from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import EsmForMaskedLM, EsmForSequenceClassification, EsmForTokenClassification, EsmModel
from transformers.models.esm.modeling_esm import (
ESM_PRETRAINED_MODEL_ARCHIVE_LIST,
EsmEmbeddings,
create_position_ids_from_input_ids,
)
class a__ :
'''simple docstring'''
def __init__( self , lowerCamelCase_ , lowerCamelCase_=13 , lowerCamelCase_=7 , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=False , lowerCamelCase_=True , lowerCamelCase_=33 , lowerCamelCase_=32 , lowerCamelCase_=5 , lowerCamelCase_=4 , lowerCamelCase_=37 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=5_12 , lowerCamelCase_=16 , lowerCamelCase_=2 , lowerCamelCase_=0.02 , lowerCamelCase_=3 , lowerCamelCase_=4 , lowerCamelCase_=None , ) -> List[str]:
lowerCAmelCase__ = parent
lowerCAmelCase__ = batch_size
lowerCAmelCase__ = seq_length
lowerCAmelCase__ = is_training
lowerCAmelCase__ = use_input_mask
lowerCAmelCase__ = use_token_type_ids
lowerCAmelCase__ = use_labels
lowerCAmelCase__ = vocab_size
lowerCAmelCase__ = hidden_size
lowerCAmelCase__ = num_hidden_layers
lowerCAmelCase__ = num_attention_heads
lowerCAmelCase__ = intermediate_size
lowerCAmelCase__ = hidden_act
lowerCAmelCase__ = hidden_dropout_prob
lowerCAmelCase__ = attention_probs_dropout_prob
lowerCAmelCase__ = max_position_embeddings
lowerCAmelCase__ = type_vocab_size
lowerCAmelCase__ = type_sequence_label_size
lowerCAmelCase__ = initializer_range
lowerCAmelCase__ = num_labels
lowerCAmelCase__ = num_choices
lowerCAmelCase__ = scope
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowerCAmelCase__ = None
if self.use_input_mask:
lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] )
lowerCAmelCase__ = None
lowerCAmelCase__ = None
lowerCAmelCase__ = None
if self.use_labels:
lowerCAmelCase__ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
lowerCAmelCase__ = ids_tensor([self.batch_size] , self.num_choices )
lowerCAmelCase__ = self.get_config()
return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
return EsmConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , )
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Optional[int]:
lowerCAmelCase__ = EsmModel(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
lowerCAmelCase__ = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ )
lowerCAmelCase__ = model(lowerCamelCase_ )
lowerCAmelCase__ = model(lowerCamelCase_ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) )
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Any:
lowerCAmelCase__ = EsmForMaskedLM(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
lowerCAmelCase__ = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def __SCREAMING_SNAKE_CASE ( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ) -> Union[str, Any]:
lowerCAmelCase__ = self.num_labels
lowerCAmelCase__ = EsmForTokenClassification(config=lowerCamelCase_ )
model.to(lowerCamelCase_ )
model.eval()
lowerCAmelCase__ = model(lowerCamelCase_ , attention_mask=lowerCamelCase_ , labels=lowerCamelCase_ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
lowerCAmelCase__ = self.prepare_config_and_inputs()
(
(
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) , (
lowerCAmelCase__
) ,
) = config_and_inputs
lowerCAmelCase__ = {'''input_ids''': input_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_torch
class a__ ( a__ , a__ , unittest.TestCase ):
'''simple docstring'''
lowercase__ : Optional[Any] = False
lowercase__ : Optional[Any] = (
(
EsmForMaskedLM,
EsmModel,
EsmForSequenceClassification,
EsmForTokenClassification,
)
if is_torch_available()
else ()
)
lowercase__ : int = ()
lowercase__ : Optional[int] = (
{
"feature-extraction": EsmModel,
"fill-mask": EsmForMaskedLM,
"text-classification": EsmForSequenceClassification,
"token-classification": EsmForTokenClassification,
"zero-shot": EsmForSequenceClassification,
}
if is_torch_available()
else {}
)
lowercase__ : Tuple = True
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
lowerCAmelCase__ = EsmModelTester(self )
lowerCAmelCase__ = ConfigTester(self , config_class=lowerCamelCase_ , hidden_size=37 )
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
self.config_tester.run_common_tests()
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase_ )
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
lowerCAmelCase__ = type
self.model_tester.create_and_check_model(*lowerCamelCase_ )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase_ )
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowerCamelCase_ )
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> Dict:
for model_name in ESM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowerCAmelCase__ = EsmModel.from_pretrained(lowerCamelCase_ )
self.assertIsNotNone(lowerCamelCase_ )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()[0]
lowerCAmelCase__ = EsmEmbeddings(config=lowerCamelCase_ )
lowerCAmelCase__ = torch.as_tensor([[12, 31, 13, model.padding_idx]] )
lowerCAmelCase__ = torch.as_tensor(
[
[
0 + model.padding_idx + 1,
1 + model.padding_idx + 1,
2 + model.padding_idx + 1,
model.padding_idx,
]
] )
lowerCAmelCase__ = create_position_ids_from_input_ids(lowerCamelCase_ , model.padding_idx )
self.assertEqual(position_ids.shape , expected_positions.shape )
self.assertTrue(torch.all(torch.eq(lowerCamelCase_ , lowerCamelCase_ ) ) )
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
lowerCAmelCase__ = self.model_tester.prepare_config_and_inputs()[0]
lowerCAmelCase__ = EsmEmbeddings(config=lowerCamelCase_ )
lowerCAmelCase__ = torch.empty(2 , 4 , 30 )
lowerCAmelCase__ = [
0 + embeddings.padding_idx + 1,
1 + embeddings.padding_idx + 1,
2 + embeddings.padding_idx + 1,
3 + embeddings.padding_idx + 1,
]
lowerCAmelCase__ = torch.as_tensor([expected_single_positions, expected_single_positions] )
lowerCAmelCase__ = embeddings.create_position_ids_from_inputs_embeds(lowerCamelCase_ )
self.assertEqual(position_ids.shape , expected_positions.shape )
self.assertTrue(torch.all(torch.eq(lowerCamelCase_ , lowerCamelCase_ ) ) )
@unittest.skip('''Esm does not support embedding resizing''' )
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
pass
@unittest.skip('''Esm does not support embedding resizing''' )
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''' )
def __SCREAMING_SNAKE_CASE ( self ) -> List[Any]:
pass
@require_torch
class a__ ( a__ ):
'''simple docstring'''
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> Any:
with torch.no_grad():
lowerCAmelCase__ = EsmForMaskedLM.from_pretrained('''facebook/esm2_t6_8M_UR50D''' )
model.eval()
lowerCAmelCase__ = torch.tensor([[0, 1, 2, 3, 4, 5]] )
lowerCAmelCase__ = model(lowerCamelCase_ )[0]
lowerCAmelCase__ = 33
lowerCAmelCase__ = torch.Size((1, 6, vocab_size) )
self.assertEqual(output.shape , lowerCamelCase_ )
lowerCAmelCase__ = torch.tensor(
[[[8.9_215, -10.5_898, -6.4_671], [-6.3_967, -13.9_114, -1.1_212], [-7.7_812, -13.9_516, -3.7_406]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase_ , atol=1e-4 ) )
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> List[str]:
with torch.no_grad():
lowerCAmelCase__ = EsmModel.from_pretrained('''facebook/esm2_t6_8M_UR50D''' )
model.eval()
lowerCAmelCase__ = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] )
lowerCAmelCase__ = model(lowerCamelCase_ )[0]
# compare the actual values for a slice.
lowerCAmelCase__ = torch.tensor(
[[[0.1_444, 0.5_413, 0.3_248], [0.3_034, 0.0_053, 0.3_108], [0.3_228, -0.2_499, 0.3_415]]] )
self.assertTrue(torch.allclose(output[:, :3, :3] , lowerCamelCase_ , atol=1e-4 ) ) | 90 |
"""simple docstring"""
import math
import sys
def _lowerCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
_lowercase: Any = ''''''
try:
with open(_UpperCamelCase , '''rb''' ) as binary_file:
_lowercase: Dict = binary_file.read()
for dat in data:
_lowercase: List[str] = f'''{dat:08b}'''
result += curr_byte
return result
except OSError:
print('''File not accessible''' )
sys.exit()
def _lowerCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
_lowercase: Any = {'''0''': '''0''', '''1''': '''1'''}
_lowercase , _lowercase: Optional[int] = '''''', ''''''
_lowercase: Dict = len(_UpperCamelCase )
for i in range(len(_UpperCamelCase ) ):
curr_string += data_bits[i]
if curr_string not in lexicon:
continue
_lowercase: Any = lexicon[curr_string]
result += last_match_id
_lowercase: Optional[int] = last_match_id + '''0'''
if math.loga(_UpperCamelCase ).is_integer():
_lowercase: str = {}
for curr_key in list(_UpperCamelCase ):
_lowercase: List[Any] = lexicon.pop(_UpperCamelCase )
_lowercase: Tuple = new_lex
_lowercase: List[Any] = last_match_id + '''1'''
index += 1
_lowercase: List[Any] = ''''''
return result
def _lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase ):
"""simple docstring"""
_lowercase: Optional[Any] = 8
try:
with open(_UpperCamelCase , '''wb''' ) as opened_file:
_lowercase: List[Any] = [
to_write[i : i + byte_length]
for i in range(0 , len(_UpperCamelCase ) , _UpperCamelCase )
]
if len(result_byte_array[-1] ) % byte_length == 0:
result_byte_array.append('''10000000''' )
else:
result_byte_array[-1] += "1" + "0" * (
byte_length - len(result_byte_array[-1] ) - 1
)
for elem in result_byte_array[:-1]:
opened_file.write(int(_UpperCamelCase , 2 ).to_bytes(1 , byteorder='''big''' ) )
except OSError:
print('''File not accessible''' )
sys.exit()
def _lowerCAmelCase ( _UpperCamelCase ):
"""simple docstring"""
_lowercase: Any = 0
for letter in data_bits:
if letter == "1":
break
counter += 1
_lowercase: List[str] = data_bits[counter:]
_lowercase: Union[str, Any] = data_bits[counter + 1 :]
return data_bits
def _lowerCAmelCase ( _UpperCamelCase , _UpperCamelCase ):
"""simple docstring"""
_lowercase: Tuple = read_file_binary(_UpperCamelCase )
_lowercase: Optional[Any] = remove_prefix(_UpperCamelCase )
_lowercase: Dict = decompress_data(_UpperCamelCase )
write_file_binary(_UpperCamelCase , _UpperCamelCase )
if __name__ == "__main__":
compress(sys.argv[1], sys.argv[2])
| 353 | 0 |
"""simple docstring"""
from __future__ import annotations
def _UpperCAmelCase ( lowerCamelCase__ ):
"""simple docstring"""
lowerCAmelCase__ = str(__UpperCAmelCase )
return len(__UpperCAmelCase ) == 9 and set(__UpperCAmelCase ) == set("""123456789""" )
def _UpperCAmelCase ( ):
"""simple docstring"""
for base_num in range(9999 , 4999 , -1 ):
lowerCAmelCase__ = 10_0002 * base_num
if is_9_pandigital(__UpperCAmelCase ):
return candidate
for base_num in range(333 , 99 , -1 ):
lowerCAmelCase__ = 100_2003 * base_num
if is_9_pandigital(__UpperCAmelCase ):
return candidate
return None
if __name__ == "__main__":
print(F"{solution() = }")
| 713 | """simple docstring"""
import os
from math import logaa
def _UpperCAmelCase ( lowerCamelCase__ = "base_exp.txt" ):
"""simple docstring"""
lowerCAmelCase__ = 0
lowerCAmelCase__ = 0
for i, line in enumerate(open(os.path.join(os.path.dirname(lowerCamelCase__ ) , lowerCamelCase__ ) ) ):
lowerCAmelCase__ , lowerCAmelCase__ = list(map(lowerCamelCase__ , line.split(""",""" ) ) )
if x * logaa(lowerCamelCase__ ) > largest:
lowerCAmelCase__ = x * logaa(lowerCamelCase__ )
lowerCAmelCase__ = i + 1
return result
if __name__ == "__main__":
print(solution())
| 674 | 0 |
import gc
import random
import unittest
import numpy as np
import torch
from transformers import XLMRobertaTokenizer
from diffusers import (
AltDiffusionImgaImgPipeline,
AutoencoderKL,
PNDMScheduler,
UNetaDConditionModel,
)
from diffusers.image_processor import VaeImageProcessor
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
RobertaSeriesConfig,
RobertaSeriesModelWithTransformation,
)
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
enable_full_determinism()
class __UpperCamelCase ( unittest.TestCase ):
"""simple docstring"""
def _UpperCAmelCase ( self ) -> List[str]:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@property
def _UpperCAmelCase ( self ) -> Dict:
a__ = 1
a__ = 3
a__ = (3_2, 3_2)
a__ = floats_tensor((batch_size, num_channels) + sizes , rng=random.Random(0 ) ).to(SCREAMING_SNAKE_CASE )
return image
@property
def _UpperCAmelCase ( self ) -> Union[str, Any]:
torch.manual_seed(0 )
a__ = UNetaDConditionModel(
block_out_channels=(3_2, 6_4) , layers_per_block=2 , sample_size=3_2 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=3_2 , )
return model
@property
def _UpperCAmelCase ( self ) -> Dict:
torch.manual_seed(0 )
a__ = AutoencoderKL(
block_out_channels=[3_2, 6_4] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , )
return model
@property
def _UpperCAmelCase ( self ) -> int:
torch.manual_seed(0 )
a__ = RobertaSeriesConfig(
hidden_size=3_2 , project_dim=3_2 , intermediate_size=3_7 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_0_0_6 , )
return RobertaSeriesModelWithTransformation(SCREAMING_SNAKE_CASE )
@property
def _UpperCAmelCase ( self ) -> int:
def extract(*SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ):
class __UpperCamelCase :
"""simple docstring"""
def __init__( self ) -> Tuple:
a__ = torch.ones([0] )
def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> Tuple:
self.pixel_values.to(SCREAMING_SNAKE_CASE )
return self
return Out()
return extract
def _UpperCAmelCase ( self ) -> Union[str, Any]:
a__ = '''cpu''' # ensure determinism for the device-dependent torch.Generator
a__ = self.dummy_cond_unet
a__ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE )
a__ = self.dummy_vae
a__ = self.dummy_text_encoder
a__ = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' )
a__ = 7_7
a__ = self.dummy_image.to(SCREAMING_SNAKE_CASE )
a__ = init_image / 2 + 0.5
# make sure here that pndm scheduler skips prk
a__ = AltDiffusionImgaImgPipeline(
unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE , feature_extractor=self.dummy_extractor , )
a__ = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=SCREAMING_SNAKE_CASE )
a__ = alt_pipe.to(SCREAMING_SNAKE_CASE )
alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE )
a__ = '''A painting of a squirrel eating a burger'''
a__ = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(0 )
a__ = alt_pipe(
[prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=SCREAMING_SNAKE_CASE , )
a__ = output.images
a__ = torch.Generator(device=SCREAMING_SNAKE_CASE ).manual_seed(0 )
a__ = alt_pipe(
[prompt] , generator=SCREAMING_SNAKE_CASE , guidance_scale=6.0 , num_inference_steps=2 , output_type='''np''' , image=SCREAMING_SNAKE_CASE , return_dict=SCREAMING_SNAKE_CASE , )[0]
a__ = image[0, -3:, -3:, -1]
a__ = image_from_tuple[0, -3:, -3:, -1]
assert image.shape == (1, 3_2, 3_2, 3)
a__ = np.array([0.44_27, 0.37_31, 0.42_49, 0.49_41, 0.45_46, 0.41_48, 0.41_93, 0.46_66, 0.44_99] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-3
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 5e-3
@unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' )
def _UpperCAmelCase ( self ) -> Union[str, Any]:
a__ = self.dummy_cond_unet
a__ = PNDMScheduler(skip_prk_steps=SCREAMING_SNAKE_CASE )
a__ = self.dummy_vae
a__ = self.dummy_text_encoder
a__ = XLMRobertaTokenizer.from_pretrained('''hf-internal-testing/tiny-xlm-roberta''' )
a__ = 7_7
a__ = self.dummy_image.to(SCREAMING_SNAKE_CASE )
# put models in fp16
a__ = unet.half()
a__ = vae.half()
a__ = bert.half()
# make sure here that pndm scheduler skips prk
a__ = AltDiffusionImgaImgPipeline(
unet=SCREAMING_SNAKE_CASE , scheduler=SCREAMING_SNAKE_CASE , vae=SCREAMING_SNAKE_CASE , text_encoder=SCREAMING_SNAKE_CASE , tokenizer=SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE , feature_extractor=self.dummy_extractor , )
a__ = VaeImageProcessor(vae_scale_factor=alt_pipe.vae_scale_factor , do_normalize=SCREAMING_SNAKE_CASE )
a__ = alt_pipe.to(SCREAMING_SNAKE_CASE )
alt_pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE )
a__ = '''A painting of a squirrel eating a burger'''
a__ = torch.manual_seed(0 )
a__ = alt_pipe(
[prompt] , generator=SCREAMING_SNAKE_CASE , num_inference_steps=2 , output_type='''np''' , image=SCREAMING_SNAKE_CASE , ).images
assert image.shape == (1, 3_2, 3_2, 3)
@unittest.skipIf(torch_device != '''cuda''' , '''This test requires a GPU''' )
def _UpperCAmelCase ( self ) -> Tuple:
a__ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/img2img/sketch-mountains-input.jpg''' )
# resize to resolution that is divisible by 8 but not 16 or 32
a__ = init_image.resize((7_6_0, 5_0_4) )
a__ = '''BAAI/AltDiffusion'''
a__ = AltDiffusionImgaImgPipeline.from_pretrained(
SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE , )
pipe.to(SCREAMING_SNAKE_CASE )
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE )
pipe.enable_attention_slicing()
a__ = '''A fantasy landscape, trending on artstation'''
a__ = torch.manual_seed(0 )
a__ = pipe(
prompt=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , generator=SCREAMING_SNAKE_CASE , output_type='''np''' , )
a__ = output.images[0]
a__ = image[2_5_5:2_5_8, 3_8_3:3_8_6, -1]
assert image.shape == (5_0_4, 7_6_0, 3)
a__ = np.array([0.93_58, 0.93_97, 0.95_99, 0.99_01, 1.00_00, 1.00_00, 0.98_82, 1.00_00, 1.00_00] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch_gpu
class __UpperCamelCase ( unittest.TestCase ):
"""simple docstring"""
def _UpperCAmelCase ( self ) -> Optional[Any]:
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _UpperCAmelCase ( self ) -> Optional[int]:
a__ = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/img2img/sketch-mountains-input.jpg''' )
a__ = init_image.resize((7_6_8, 5_1_2) )
a__ = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/img2img/fantasy_landscape_alt.npy''' )
a__ = '''BAAI/AltDiffusion'''
a__ = AltDiffusionImgaImgPipeline.from_pretrained(
SCREAMING_SNAKE_CASE , safety_checker=SCREAMING_SNAKE_CASE , )
pipe.to(SCREAMING_SNAKE_CASE )
pipe.set_progress_bar_config(disable=SCREAMING_SNAKE_CASE )
pipe.enable_attention_slicing()
a__ = '''A fantasy landscape, trending on artstation'''
a__ = torch.manual_seed(0 )
a__ = pipe(
prompt=SCREAMING_SNAKE_CASE , image=SCREAMING_SNAKE_CASE , strength=0.75 , guidance_scale=7.5 , generator=SCREAMING_SNAKE_CASE , output_type='''np''' , )
a__ = output.images[0]
assert image.shape == (5_1_2, 7_6_8, 3)
# img2img is flaky across GPUs even in fp32, so using MAE here
assert np.abs(expected_image - image ).max() < 1e-2
| 194 |
import logging
import os
from .state import PartialState
class __UpperCamelCase ( logging.LoggerAdapter ):
"""simple docstring"""
@staticmethod
def _UpperCAmelCase ( SCREAMING_SNAKE_CASE ) -> Optional[Any]:
a__ = PartialState()
return not main_process_only or (main_process_only and state.is_main_process)
def _UpperCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) -> Optional[int]:
if PartialState._shared_state == {}:
raise RuntimeError(
'''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' )
a__ = kwargs.pop('''main_process_only''' , SCREAMING_SNAKE_CASE )
a__ = kwargs.pop('''in_order''' , SCREAMING_SNAKE_CASE )
if self.isEnabledFor(SCREAMING_SNAKE_CASE ):
if self._should_log(SCREAMING_SNAKE_CASE ):
a__ , a__ = self.process(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
self.logger.log(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
elif in_order:
a__ = PartialState()
for i in range(state.num_processes ):
if i == state.process_index:
a__ , a__ = self.process(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
self.logger.log(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , *SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE )
state.wait_for_everyone()
def __a ( __UpperCAmelCase , __UpperCAmelCase = None ):
if log_level is None:
a__ = os.environ.get('''ACCELERATE_LOG_LEVEL''' , __UpperCAmelCase )
a__ = logging.getLogger(__UpperCAmelCase )
if log_level is not None:
logger.setLevel(log_level.upper() )
logger.root.setLevel(log_level.upper() )
return MultiProcessAdapter(__UpperCAmelCase , {} )
| 194 | 1 |
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 convert_to_rgb, 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
if is_vision_available():
import PIL
_lowerCamelCase : List[str] = logging.get_logger(__name__)
class __snake_case (UpperCAmelCase__ ):
lowerCAmelCase__ = ["pixel_values"]
def __init__( self : Optional[Any] , _UpperCAmelCase : bool = True , _UpperCAmelCase : Dict[str, int] = None , _UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _UpperCAmelCase : bool = True , _UpperCAmelCase : Union[int, float] = 1 / 255 , _UpperCAmelCase : bool = True , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : bool = True , **_UpperCAmelCase : Optional[int] , ) -> None:
'''simple docstring'''
super().__init__(**lowerCamelCase__ )
_lowerCAmelCase : Optional[int] = size if size is not None else {"height": 384, "width": 384}
_lowerCAmelCase : str = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
_lowerCAmelCase : Dict = do_resize
_lowerCAmelCase : List[str] = size
_lowerCAmelCase : List[str] = resample
_lowerCAmelCase : Optional[Any] = do_rescale
_lowerCAmelCase : List[str] = rescale_factor
_lowerCAmelCase : Optional[int] = do_normalize
_lowerCAmelCase : Union[str, Any] = image_mean if image_mean is not None else OPENAI_CLIP_MEAN
_lowerCAmelCase : Tuple = image_std if image_std is not None else OPENAI_CLIP_STD
_lowerCAmelCase : Tuple = do_convert_rgb
def SCREAMING_SNAKE_CASE ( self : Optional[int] , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Dict[str, int] , _UpperCAmelCase : PILImageResampling = PILImageResampling.BICUBIC , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : str , ) -> np.ndarray:
'''simple docstring'''
_lowerCAmelCase : Optional[int] = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
if "height" not in size or "width" not in size:
raise ValueError(f"The `size` dictionary must contain the keys `height` and `width`. Got {size.keys()}" )
_lowerCAmelCase : Optional[Any] = (size["height"], size["width"])
return resize(lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def SCREAMING_SNAKE_CASE ( self : Dict , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[int, float] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : Tuple , ) -> str:
'''simple docstring'''
return rescale(lowerCamelCase__ , scale=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def SCREAMING_SNAKE_CASE ( self : str , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Union[float, List[float]] , _UpperCAmelCase : Optional[Union[str, ChannelDimension]] = None , **_UpperCAmelCase : List[str] , ) -> np.ndarray:
'''simple docstring'''
return normalize(lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ , data_format=lowerCamelCase__ , **lowerCamelCase__ )
def SCREAMING_SNAKE_CASE ( self : Optional[int] , _UpperCAmelCase : ImageInput , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[Dict[str, int]] = None , _UpperCAmelCase : PILImageResampling = None , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[float] = None , _UpperCAmelCase : Optional[bool] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[float, List[float]]] = None , _UpperCAmelCase : Optional[Union[str, TensorType]] = None , _UpperCAmelCase : bool = None , _UpperCAmelCase : ChannelDimension = ChannelDimension.FIRST , **_UpperCAmelCase : Dict , ) -> PIL.Image.Image:
'''simple docstring'''
_lowerCAmelCase : Any = do_resize if do_resize is not None else self.do_resize
_lowerCAmelCase : Any = resample if resample is not None else self.resample
_lowerCAmelCase : Any = do_rescale if do_rescale is not None else self.do_rescale
_lowerCAmelCase : Tuple = rescale_factor if rescale_factor is not None else self.rescale_factor
_lowerCAmelCase : List[Any] = do_normalize if do_normalize is not None else self.do_normalize
_lowerCAmelCase : Union[str, Any] = image_mean if image_mean is not None else self.image_mean
_lowerCAmelCase : Dict = image_std if image_std is not None else self.image_std
_lowerCAmelCase : Optional[Any] = do_convert_rgb if do_convert_rgb is not None else self.do_convert_rgb
_lowerCAmelCase : List[Any] = size if size is not None else self.size
_lowerCAmelCase : Dict = get_size_dict(lowerCamelCase__ , default_to_square=lowerCamelCase__ )
_lowerCAmelCase : List[Any] = make_list_of_images(lowerCamelCase__ )
if not valid_images(lowerCamelCase__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None or resample is None:
raise ValueError("""Size and resample must be specified if do_resize is True.""" )
if do_rescale and rescale_factor is None:
raise ValueError("""Rescale factor must be specified if do_rescale is True.""" )
if do_normalize and (image_mean is None or image_std is None):
raise ValueError("""Image mean and std must be specified if do_normalize is True.""" )
# PIL RGBA images are converted to RGB
if do_convert_rgb:
_lowerCAmelCase : List[Any] = [convert_to_rgb(lowerCamelCase__ ) for image in images]
# All transformations expect numpy arrays.
_lowerCAmelCase : Any = [to_numpy_array(lowerCamelCase__ ) for image in images]
if do_resize:
_lowerCAmelCase : Union[str, Any] = [self.resize(image=lowerCamelCase__ , size=lowerCamelCase__ , resample=lowerCamelCase__ ) for image in images]
if do_rescale:
_lowerCAmelCase : List[Any] = [self.rescale(image=lowerCamelCase__ , scale=lowerCamelCase__ ) for image in images]
if do_normalize:
_lowerCAmelCase : Dict = [self.normalize(image=lowerCamelCase__ , mean=lowerCamelCase__ , std=lowerCamelCase__ ) for image in images]
_lowerCAmelCase : List[str] = [to_channel_dimension_format(lowerCamelCase__ , lowerCamelCase__ ) for image in images]
_lowerCAmelCase : List[str] = BatchFeature(data={"""pixel_values""": images} , tensor_type=lowerCamelCase__ )
return encoded_outputs
| 718 |
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.linear_model import LinearRegression
# Splitting the dataset into the Training set and Test set
from sklearn.model_selection import train_test_split
# Fitting Polynomial Regression to the dataset
from sklearn.preprocessing import PolynomialFeatures
# Importing the dataset
_lowerCamelCase : Dict = pd.read_csv(
"https://s3.us-west-2.amazonaws.com/public.gamelab.fun/dataset/"
"position_salaries.csv"
)
_lowerCamelCase : Union[str, Any] = dataset.iloc[:, 1:2].values
_lowerCamelCase : Any = dataset.iloc[:, 2].values
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase : Optional[int] = train_test_split(X, y, test_size=0.2, random_state=0)
_lowerCamelCase : Optional[Any] = PolynomialFeatures(degree=4)
_lowerCamelCase : Optional[Any] = poly_reg.fit_transform(X)
_lowerCamelCase : Dict = LinearRegression()
pol_reg.fit(X_poly, y)
def _UpperCAmelCase ():
'''simple docstring'''
plt.scatter(UpperCamelCase_ , UpperCamelCase_ , color="""red""" )
plt.plot(UpperCamelCase_ , pol_reg.predict(poly_reg.fit_transform(UpperCamelCase_ ) ) , color="""blue""" )
plt.title("""Truth or Bluff (Linear Regression)""" )
plt.xlabel("""Position level""" )
plt.ylabel("""Salary""" )
plt.show()
if __name__ == "__main__":
viz_polymonial()
# Predicting a new result with Polymonial Regression
pol_reg.predict(poly_reg.fit_transform([[5.5]]))
# output should be 132148.43750003
| 196 | 0 |
__a : str = '''
# Installazione di Transformers
! pip install transformers datasets
# Per installare dalla fonte invece dell\'ultima versione rilasciata, commenta il comando sopra e
# rimuovi la modalità commento al comando seguente.
# ! pip install git+https://github.com/huggingface/transformers.git
'''
__a : Optional[int] = [{'''type''': '''code''', '''content''': INSTALL_CONTENT}]
__a : Tuple = {
'''{processor_class}''': '''FakeProcessorClass''',
'''{model_class}''': '''FakeModelClass''',
'''{object_class}''': '''FakeObjectClass''',
}
| 637 |
def lowerCAmelCase__ ( ):
snake_case_ : Optional[int] = 0
for i in range(1 , 10_01 ):
total += i**i
return str(_a )[-10:]
if __name__ == "__main__":
print(solution())
| 568 | 0 |
"""simple docstring"""
def lowerCAmelCase_ ( lowercase_ : list , lowercase_ : int = 0 ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Union[str, Any] = length or len(lowercase_ )
__SCREAMING_SNAKE_CASE : Union[str, Any] = False
for i in range(length - 1 ):
if list_data[i] > list_data[i + 1]:
__SCREAMING_SNAKE_CASE : Optional[int] = list_data[i + 1], list_data[i]
__SCREAMING_SNAKE_CASE : Any = True
return list_data if not swapped else bubble_sort(lowercase_ , length - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 717 |
"""simple docstring"""
def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : List[str] , lowercase_ : Tuple , lowercase_ : int , lowercase_ : int , lowercase_ : Optional[int] ):
'''simple docstring'''
if index == r:
for j in range(lowercase_ ):
print(data[j] , end=''' ''' )
print(''' ''' )
return
# When no more elements are there to put in data[]
if i >= n:
return
# current is included, put next at next location
__SCREAMING_SNAKE_CASE : str = arr[i]
combination_util(lowercase_ , lowercase_ , lowercase_ , index + 1 , lowercase_ , i + 1 )
# current is excluded, replace it with
# next (Note that i+1 is passed, but
# index is not changed)
combination_util(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , i + 1 )
# The main function that prints all combinations
# of size r in arr[] of size n. This function
# mainly uses combinationUtil()
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[Any] , lowercase_ : Optional[Any] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = [0] * r
# Print all combination using temporary array 'data[]'
combination_util(lowercase_ , lowercase_ , lowercase_ , 0 , lowercase_ , 0 )
if __name__ == "__main__":
# Driver code to check the function above
_lowerCamelCase = [10, 20, 30, 40, 50]
print_combination(arr, len(arr), 3)
# This code is contributed by Ambuj sahu
| 401 | 0 |
import re
import string
from collections import Counter
import sacrebleu
import sacremoses
from packaging import version
import datasets
a : Any = "\n@inproceedings{xu-etal-2016-optimizing,\n title = {Optimizing Statistical Machine Translation for Text Simplification},\n authors={Xu, Wei and Napoles, Courtney and Pavlick, Ellie and Chen, Quanze and Callison-Burch, Chris},\n journal = {Transactions of the Association for Computational Linguistics},\n volume = {4},\n year={2016},\n url = {https://www.aclweb.org/anthology/Q16-1029},\n pages = {401--415\n},\n@inproceedings{post-2018-call,\n title = \"A Call for Clarity in Reporting {BLEU} Scores\",\n author = \"Post, Matt\",\n booktitle = \"Proceedings of the Third Conference on Machine Translation: Research Papers\",\n month = oct,\n year = \"2018\",\n address = \"Belgium, Brussels\",\n publisher = \"Association for Computational Linguistics\",\n url = \"https://www.aclweb.org/anthology/W18-6319\",\n pages = \"186--191\",\n}\n"
a : List[Any] = "\\nWIKI_SPLIT is the combination of three metrics SARI, EXACT and SACREBLEU\nIt can be used to evaluate the quality of machine-generated texts.\n"
a : Any = "\nCalculates sari score (between 0 and 100) given a list of source and predicted\nsentences, and a list of lists of reference sentences. It also computes the BLEU score as well as the exact match score.\nArgs:\n sources: list of source sentences where each sentence should be a string.\n predictions: list of predicted sentences where each sentence should be a string.\n references: list of lists of reference sentences where each sentence should be a string.\nReturns:\n sari: sari score\n sacrebleu: sacrebleu score\n exact: exact score\n\nExamples:\n >>> sources=[\"About 95 species are currently accepted .\"]\n >>> predictions=[\"About 95 you now get in .\"]\n >>> references=[[\"About 95 species are currently known .\"]]\n >>> wiki_split = datasets.load_metric(\"wiki_split\")\n >>> results = wiki_split.compute(sources=sources, predictions=predictions, references=references)\n >>> print(results)\n {'sari': 21.805555555555557, 'sacrebleu': 14.535768424205482, 'exact': 0.0}\n"
def lowerCamelCase__ ( __lowerCamelCase : List[Any] ):
def remove_articles(__lowerCamelCase : List[str] ):
__UpperCAmelCase : List[str] = re.compile(R"""\b(a|an|the)\b""" , re.UNICODE )
return re.sub(__lowerCamelCase , """ """ , __lowerCamelCase )
def white_space_fix(__lowerCamelCase : List[str] ):
return " ".join(text.split() )
def remove_punc(__lowerCamelCase : Any ):
__UpperCAmelCase : List[Any] = set(string.punctuation )
return "".join(ch for ch in text if ch not in exclude )
def lower(__lowerCamelCase : Tuple ):
return text.lower()
return white_space_fix(remove_articles(remove_punc(lower(__lowerCamelCase ) ) ) )
def lowerCamelCase__ ( __lowerCamelCase : str , __lowerCamelCase : int ):
return int(normalize_answer(__lowerCamelCase ) == normalize_answer(__lowerCamelCase ) )
def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Any ):
__UpperCAmelCase : Optional[int] = [any(compute_exact(__lowerCamelCase , __lowerCamelCase ) for ref in refs ) for pred, refs in zip(__lowerCamelCase , __lowerCamelCase )]
return (sum(__lowerCamelCase ) / len(__lowerCamelCase )) * 100
def lowerCamelCase__ ( __lowerCamelCase : Union[str, Any] , __lowerCamelCase : Any , __lowerCamelCase : Optional[int] , __lowerCamelCase : str ):
__UpperCAmelCase : Dict = [rgram for rgrams in rgramslist for rgram in rgrams]
__UpperCAmelCase : Optional[int] = Counter(__lowerCamelCase )
__UpperCAmelCase : List[Any] = Counter(__lowerCamelCase )
__UpperCAmelCase : str = Counter()
for sgram, scount in sgramcounter.items():
__UpperCAmelCase : int = scount * numref
__UpperCAmelCase : Union[str, Any] = Counter(__lowerCamelCase )
__UpperCAmelCase : Tuple = Counter()
for cgram, ccount in cgramcounter.items():
__UpperCAmelCase : str = ccount * numref
# KEEP
__UpperCAmelCase : Dict = sgramcounter_rep & cgramcounter_rep
__UpperCAmelCase : str = keepgramcounter_rep & rgramcounter
__UpperCAmelCase : Optional[Any] = sgramcounter_rep & rgramcounter
__UpperCAmelCase : int = 0
__UpperCAmelCase : Dict = 0
for keepgram in keepgramcountergood_rep:
keeptmpscorea += keepgramcountergood_rep[keepgram] / keepgramcounter_rep[keepgram]
# Fix an alleged bug [2] in the keep score computation.
# keeptmpscore2 += keepgramcountergood_rep[keepgram] / keepgramcounterall_rep[keepgram]
keeptmpscorea += keepgramcountergood_rep[keepgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__UpperCAmelCase : int = 1
__UpperCAmelCase : Union[str, Any] = 1
if len(__lowerCamelCase ) > 0:
__UpperCAmelCase : Optional[int] = keeptmpscorea / len(__lowerCamelCase )
if len(__lowerCamelCase ) > 0:
# Fix an alleged bug [2] in the keep score computation.
# keepscore_recall = keeptmpscore2 / len(keepgramcounterall_rep)
__UpperCAmelCase : Optional[int] = keeptmpscorea / sum(keepgramcounterall_rep.values() )
__UpperCAmelCase : Tuple = 0
if keepscore_precision > 0 or keepscore_recall > 0:
__UpperCAmelCase : Optional[Any] = 2 * keepscore_precision * keepscore_recall / (keepscore_precision + keepscore_recall)
# DELETION
__UpperCAmelCase : List[str] = sgramcounter_rep - cgramcounter_rep
__UpperCAmelCase : Union[str, Any] = delgramcounter_rep - rgramcounter
__UpperCAmelCase : Union[str, Any] = sgramcounter_rep - rgramcounter
__UpperCAmelCase : Any = 0
__UpperCAmelCase : Dict = 0
for delgram in delgramcountergood_rep:
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounter_rep[delgram]
deltmpscorea += delgramcountergood_rep[delgram] / delgramcounterall_rep[delgram]
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__UpperCAmelCase : Union[str, Any] = 1
if len(__lowerCamelCase ) > 0:
__UpperCAmelCase : Any = deltmpscorea / len(__lowerCamelCase )
# ADDITION
__UpperCAmelCase : Optional[int] = set(__lowerCamelCase ) - set(__lowerCamelCase )
__UpperCAmelCase : List[str] = set(__lowerCamelCase ) & set(__lowerCamelCase )
__UpperCAmelCase : Tuple = set(__lowerCamelCase ) - set(__lowerCamelCase )
__UpperCAmelCase : Any = 0
for addgram in addgramcountergood:
addtmpscore += 1
# Define 0/0=1 instead of 0 to give higher scores for predictions that match
# a target exactly.
__UpperCAmelCase : Dict = 1
__UpperCAmelCase : str = 1
if len(__lowerCamelCase ) > 0:
__UpperCAmelCase : Dict = addtmpscore / len(__lowerCamelCase )
if len(__lowerCamelCase ) > 0:
__UpperCAmelCase : str = addtmpscore / len(__lowerCamelCase )
__UpperCAmelCase : Tuple = 0
if addscore_precision > 0 or addscore_recall > 0:
__UpperCAmelCase : Union[str, Any] = 2 * addscore_precision * addscore_recall / (addscore_precision + addscore_recall)
return (keepscore, delscore_precision, addscore)
def lowerCamelCase__ ( __lowerCamelCase : Optional[Any] , __lowerCamelCase : Union[str, Any] , __lowerCamelCase : List[Any] ):
__UpperCAmelCase : Optional[int] = len(__lowerCamelCase )
__UpperCAmelCase : Any = ssent.split(""" """ )
__UpperCAmelCase : List[str] = csent.split(""" """ )
__UpperCAmelCase : List[str] = []
__UpperCAmelCase : Optional[int] = []
__UpperCAmelCase : Optional[int] = []
__UpperCAmelCase : List[Any] = []
__UpperCAmelCase : Optional[int] = []
__UpperCAmelCase : Dict = []
__UpperCAmelCase : Tuple = []
__UpperCAmelCase : Union[str, Any] = []
__UpperCAmelCase : Optional[Any] = []
__UpperCAmelCase : Optional[int] = []
for rsent in rsents:
__UpperCAmelCase : List[str] = rsent.split(""" """ )
__UpperCAmelCase : List[str] = []
__UpperCAmelCase : int = []
__UpperCAmelCase : str = []
ragramslist.append(__lowerCamelCase )
for i in range(0 , len(__lowerCamelCase ) - 1 ):
if i < len(__lowerCamelCase ) - 1:
__UpperCAmelCase : Optional[Any] = ragrams[i] + """ """ + ragrams[i + 1]
ragrams.append(__lowerCamelCase )
if i < len(__lowerCamelCase ) - 2:
__UpperCAmelCase : Union[str, Any] = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2]
ragrams.append(__lowerCamelCase )
if i < len(__lowerCamelCase ) - 3:
__UpperCAmelCase : Union[str, Any] = ragrams[i] + """ """ + ragrams[i + 1] + """ """ + ragrams[i + 2] + """ """ + ragrams[i + 3]
ragrams.append(__lowerCamelCase )
ragramslist.append(__lowerCamelCase )
ragramslist.append(__lowerCamelCase )
ragramslist.append(__lowerCamelCase )
for i in range(0 , len(__lowerCamelCase ) - 1 ):
if i < len(__lowerCamelCase ) - 1:
__UpperCAmelCase : Tuple = sagrams[i] + """ """ + sagrams[i + 1]
sagrams.append(__lowerCamelCase )
if i < len(__lowerCamelCase ) - 2:
__UpperCAmelCase : Any = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2]
sagrams.append(__lowerCamelCase )
if i < len(__lowerCamelCase ) - 3:
__UpperCAmelCase : Union[str, Any] = sagrams[i] + """ """ + sagrams[i + 1] + """ """ + sagrams[i + 2] + """ """ + sagrams[i + 3]
sagrams.append(__lowerCamelCase )
for i in range(0 , len(__lowerCamelCase ) - 1 ):
if i < len(__lowerCamelCase ) - 1:
__UpperCAmelCase : Optional[int] = cagrams[i] + """ """ + cagrams[i + 1]
cagrams.append(__lowerCamelCase )
if i < len(__lowerCamelCase ) - 2:
__UpperCAmelCase : Dict = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2]
cagrams.append(__lowerCamelCase )
if i < len(__lowerCamelCase ) - 3:
__UpperCAmelCase : Tuple = cagrams[i] + """ """ + cagrams[i + 1] + """ """ + cagrams[i + 2] + """ """ + cagrams[i + 3]
cagrams.append(__lowerCamelCase )
((__UpperCAmelCase) , (__UpperCAmelCase) , (__UpperCAmelCase)) : Optional[int] = SARIngram(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
((__UpperCAmelCase) , (__UpperCAmelCase) , (__UpperCAmelCase)) : Optional[Any] = SARIngram(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
((__UpperCAmelCase) , (__UpperCAmelCase) , (__UpperCAmelCase)) : Union[str, Any] = SARIngram(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
((__UpperCAmelCase) , (__UpperCAmelCase) , (__UpperCAmelCase)) : int = SARIngram(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase , __lowerCamelCase )
__UpperCAmelCase : Optional[int] = sum([keepascore, keepascore, keepascore, keepascore] ) / 4
__UpperCAmelCase : Optional[int] = sum([delascore, delascore, delascore, delascore] ) / 4
__UpperCAmelCase : List[Any] = sum([addascore, addascore, addascore, addascore] ) / 4
__UpperCAmelCase : int = (avgkeepscore + avgdelscore + avgaddscore) / 3
return finalscore
def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : bool = True , __lowerCamelCase : str = "13a" , __lowerCamelCase : bool = True ):
# Normalization is requried for the ASSET dataset (one of the primary
# datasets in sentence simplification) to allow using space
# to split the sentence. Even though Wiki-Auto and TURK datasets,
# do not require normalization, we do it for consistency.
# Code adapted from the EASSE library [1] written by the authors of the ASSET dataset.
# [1] https://github.com/feralvam/easse/blob/580bba7e1378fc8289c663f864e0487188fe8067/easse/utils/preprocessing.py#L7
if lowercase:
__UpperCAmelCase : Union[str, Any] = sentence.lower()
if tokenizer in ["13a", "intl"]:
if version.parse(sacrebleu.__version__ ).major >= 2:
__UpperCAmelCase : List[str] = sacrebleu.metrics.bleu._get_tokenizer(__lowerCamelCase )()(__lowerCamelCase )
else:
__UpperCAmelCase : Optional[int] = sacrebleu.TOKENIZERS[tokenizer]()(__lowerCamelCase )
elif tokenizer == "moses":
__UpperCAmelCase : Optional[int] = sacremoses.MosesTokenizer().tokenize(__lowerCamelCase , return_str=__lowerCamelCase , escape=__lowerCamelCase )
elif tokenizer == "penn":
__UpperCAmelCase : Optional[int] = sacremoses.MosesTokenizer().penn_tokenize(__lowerCamelCase , return_str=__lowerCamelCase )
else:
__UpperCAmelCase : str = sentence
if not return_str:
__UpperCAmelCase : Optional[int] = normalized_sent.split()
return normalized_sent
def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : Any , __lowerCamelCase : int ):
if not (len(__lowerCamelCase ) == len(__lowerCamelCase ) == len(__lowerCamelCase )):
raise ValueError("""Sources length must match predictions and references lengths.""" )
__UpperCAmelCase : Union[str, Any] = 0
for src, pred, refs in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ):
sari_score += SARIsent(normalize(__lowerCamelCase ) , normalize(__lowerCamelCase ) , [normalize(__lowerCamelCase ) for sent in refs] )
__UpperCAmelCase : List[str] = sari_score / len(__lowerCamelCase )
return 100 * sari_score
def lowerCamelCase__ ( __lowerCamelCase : Any , __lowerCamelCase : List[str] , __lowerCamelCase : Optional[Any]="exp" , __lowerCamelCase : Optional[int]=None , __lowerCamelCase : Tuple=False , __lowerCamelCase : Optional[Any]=False , __lowerCamelCase : str=False , ):
__UpperCAmelCase : Optional[int] = len(references[0] )
if any(len(__lowerCamelCase ) != references_per_prediction for refs in references ):
raise ValueError("""Sacrebleu requires the same number of references for each prediction""" )
__UpperCAmelCase : Optional[Any] = [[refs[i] for refs in references] for i in range(__lowerCamelCase )]
__UpperCAmelCase : Union[str, Any] = sacrebleu.corpus_bleu(
__lowerCamelCase , __lowerCamelCase , smooth_method=__lowerCamelCase , smooth_value=__lowerCamelCase , force=__lowerCamelCase , lowercase=__lowerCamelCase , use_effective_order=__lowerCamelCase , )
return output.score
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class a ( datasets.Metric ):
"""simple docstring"""
def UpperCAmelCase ( self : Union[str, Any] ) -> Dict:
return datasets.MetricInfo(
description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features(
{
"""predictions""": datasets.Value("""string""" , id="""sequence""" ),
"""references""": datasets.Sequence(datasets.Value("""string""" , id="""sequence""" ) , id="""references""" ),
} ) , codebase_urls=[
"""https://github.com/huggingface/transformers/blob/master/src/transformers/data/metrics/squad_metrics.py""",
"""https://github.com/cocoxu/simplification/blob/master/SARI.py""",
"""https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/utils/sari_hook.py""",
"""https://github.com/mjpost/sacreBLEU""",
] , reference_urls=[
"""https://www.aclweb.org/anthology/Q16-1029.pdf""",
"""https://github.com/mjpost/sacreBLEU""",
"""https://en.wikipedia.org/wiki/BLEU""",
"""https://towardsdatascience.com/evaluating-text-output-in-nlp-bleu-at-your-own-risk-e8609665a213""",
] , )
def UpperCAmelCase ( self : int , __lowercase : str , __lowercase : Optional[int] , __lowercase : int ) -> Union[str, Any]:
__UpperCAmelCase : str = {}
result.update({"""sari""": compute_sari(sources=__lowercase , predictions=__lowercase , references=__lowercase )} )
result.update({"""sacrebleu""": compute_sacrebleu(predictions=__lowercase , references=__lowercase )} )
result.update({"""exact""": compute_em(predictions=__lowercase , references=__lowercase )} )
return result
| 63 |
__a = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
def lowerCamelCase__ ( _lowercase ):
'''simple docstring'''
if not isinstance(_lowercase , _lowercase ):
UpperCAmelCase_ : Union[str, Any] = f'''a bytes-like object is required, not \'{data.__class__.__name__}\''''
raise TypeError(_lowercase )
UpperCAmelCase_ : Any = ''''''.join(bin(_lowercase )[2:].zfill(8 ) for byte in data )
UpperCAmelCase_ : Any = len(_lowercase ) % 6 != 0
if padding_needed:
# The padding that will be added later
UpperCAmelCase_ : Union[str, Any] = B'''=''' * ((6 - len(_lowercase ) % 6) // 2)
# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream += "0" * (6 - len(_lowercase ) % 6)
else:
UpperCAmelCase_ : int = B''''''
# Encode every 6 binary digits to their corresponding Base64 character
return (
"".join(
B64_CHARSET[int(binary_stream[index : index + 6] , 2 )]
for index in range(0 , len(_lowercase ) , 6 ) ).encode()
+ padding
)
def lowerCamelCase__ ( _lowercase ):
'''simple docstring'''
if not isinstance(_lowercase , _lowercase ) and not isinstance(_lowercase , _lowercase ):
UpperCAmelCase_ : Tuple = (
'''argument should be a bytes-like object or ASCII string, '''
f'''not \'{encoded_data.__class__.__name__}\''''
)
raise TypeError(_lowercase )
# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
if isinstance(_lowercase , _lowercase ):
try:
UpperCAmelCase_ : Any = encoded_data.decode('''utf-8''' )
except UnicodeDecodeError:
raise ValueError('''base64 encoded data should only contain ASCII characters''' )
UpperCAmelCase_ : str = encoded_data.count('''=''' )
# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found."
else:
assert all(
char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found."
# Check the padding
assert len(_lowercase ) % 4 == 0 and padding < 3, "Incorrect padding"
if padding:
# Remove padding if there is one
UpperCAmelCase_ : List[Any] = encoded_data[:-padding]
UpperCAmelCase_ : List[Any] = ''''''.join(
bin(B64_CHARSET.index(_lowercase ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2]
else:
UpperCAmelCase_ : Tuple = ''''''.join(
bin(B64_CHARSET.index(_lowercase ) )[2:].zfill(6 ) for char in encoded_data )
UpperCAmelCase_ : str = [
int(binary_stream[index : index + 8] , 2 )
for index in range(0 , len(_lowercase ) , 8 )
]
return bytes(_lowercase )
if __name__ == "__main__":
import doctest
doctest.testmod() | 30 | 0 |
from typing import List, Optional, Union
from ...configuration_utils import PretrainedConfig
from ...utils import logging
SCREAMING_SNAKE_CASE : int = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE : Union[str, Any] = {
'huggingface/informer-tourism-monthly': (
'https://huggingface.co/huggingface/informer-tourism-monthly/resolve/main/config.json'
),
# See all Informer models at https://huggingface.co/models?filter=informer
}
class _lowerCamelCase( a__ ):
lowercase_ : Optional[Any] = """informer"""
lowercase_ : Optional[Any] = {
"""hidden_size""": """d_model""",
"""num_attention_heads""": """encoder_attention_heads""",
"""num_hidden_layers""": """encoder_layers""",
}
def __init__( self, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = "student_t", lowerCamelCase = "nll", lowerCamelCase = 1, lowerCamelCase = None, lowerCamelCase = "mean", lowerCamelCase = 0, lowerCamelCase = 0, lowerCamelCase = 0, lowerCamelCase = 0, lowerCamelCase = None, lowerCamelCase = None, lowerCamelCase = 64, lowerCamelCase = 32, lowerCamelCase = 32, lowerCamelCase = 2, lowerCamelCase = 2, lowerCamelCase = 2, lowerCamelCase = 2, lowerCamelCase = True, lowerCamelCase = "gelu", lowerCamelCase = 0.0_5, lowerCamelCase = 0.1, lowerCamelCase = 0.1, lowerCamelCase = 0.1, lowerCamelCase = 0.1, lowerCamelCase = 1_00, lowerCamelCase = 0.0_2, lowerCamelCase=True, lowerCamelCase = "prob", lowerCamelCase = 5, lowerCamelCase = True, **lowerCamelCase, ) -> List[str]:
"""simple docstring"""
_lowercase : List[str] = prediction_length
_lowercase : Any = context_length or prediction_length
_lowercase : Any = distribution_output
_lowercase : Tuple = loss
_lowercase : Dict = input_size
_lowercase : List[Any] = num_time_features
_lowercase : Tuple = lags_sequence if lags_sequence is not None else [1, 2, 3, 4, 5, 6, 7]
_lowercase : str = scaling
_lowercase : Optional[Any] = num_dynamic_real_features
_lowercase : Dict = num_static_real_features
_lowercase : List[str] = num_static_categorical_features
# set cardinality
if cardinality and num_static_categorical_features > 0:
if len(lowercase__) != num_static_categorical_features:
raise ValueError(
'The cardinality should be a list of the same length as `num_static_categorical_features`')
_lowercase : Union[str, Any] = cardinality
else:
_lowercase : int = [0]
# set embedding_dimension
if embedding_dimension and num_static_categorical_features > 0:
if len(lowercase__) != num_static_categorical_features:
raise ValueError(
'The embedding dimension should be a list of the same length as `num_static_categorical_features`')
_lowercase : List[Any] = embedding_dimension
else:
_lowercase : List[str] = [min(50, (cat + 1) // 2) for cat in self.cardinality]
_lowercase : Optional[Any] = num_parallel_samples
# Transformer architecture configuration
_lowercase : int = input_size * len(self.lags_sequence) + self._number_of_features
_lowercase : Union[str, Any] = d_model
_lowercase : str = encoder_attention_heads
_lowercase : Tuple = decoder_attention_heads
_lowercase : Tuple = encoder_ffn_dim
_lowercase : Optional[int] = decoder_ffn_dim
_lowercase : List[str] = encoder_layers
_lowercase : int = decoder_layers
_lowercase : Dict = dropout
_lowercase : List[str] = attention_dropout
_lowercase : Optional[int] = activation_dropout
_lowercase : List[Any] = encoder_layerdrop
_lowercase : Union[str, Any] = decoder_layerdrop
_lowercase : Tuple = activation_function
_lowercase : Union[str, Any] = init_std
_lowercase : Union[str, Any] = use_cache
# Informer
_lowercase : List[Any] = attention_type
_lowercase : Optional[int] = sampling_factor
_lowercase : Tuple = distil
super().__init__(is_encoder_decoder=lowercase__, **lowercase__)
@property
def UpperCamelCase ( self) -> int:
"""simple docstring"""
return (
sum(self.embedding_dimension)
+ self.num_dynamic_real_features
+ self.num_time_features
+ self.num_static_real_features
+ self.input_size * 2 # the log1p(abs(loc)) and log(scale) features
)
| 703 |
def UpperCamelCase_( lowerCamelCase_ ) -> int:
assert (
isinstance(lowerCamelCase_ , lowerCamelCase_ ) and number_of_steps > 0
), F'''number_of_steps needs to be positive integer, your input {number_of_steps}'''
if number_of_steps == 1:
return 1
_lowercase , _lowercase : Dict = 1, 1
for _ in range(number_of_steps - 1 ):
_lowercase , _lowercase : Tuple = current + previous, current
return current
if __name__ == "__main__":
import doctest
doctest.testmod()
| 354 | 0 |
"""simple docstring"""
def __UpperCAmelCase ( __UpperCamelCase = 10_00 ):
return sum(2 * a * ((a - 1) // 2) for a in range(3 , n + 1 ) )
if __name__ == "__main__":
print(solution())
| 76 |
import copy
import inspect
import unittest
from transformers import AutoBackbone
from transformers.configuration_utils import PretrainedConfig
from transformers.testing_utils import require_timm, require_torch, torch_device
from transformers.utils.import_utils import is_torch_available
from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor
if is_torch_available():
import torch
from transformers import TimmBackbone, TimmBackboneConfig
from ...test_pipeline_mixin import PipelineTesterMixin
class lowerCamelCase :
def __init__( self , lowercase__ , lowercase__=None , lowercase__=None , lowercase__=None , lowercase__="resnet50" , lowercase__=3 , lowercase__=3_2 , lowercase__=3 , lowercase__=True , lowercase__=True , ):
__UpperCAmelCase : List[str] = parent
__UpperCAmelCase : Dict = out_indices if out_indices is not None else [4]
__UpperCAmelCase : List[Any] = stage_names
__UpperCAmelCase : int = out_features
__UpperCAmelCase : Union[str, Any] = backbone
__UpperCAmelCase : Optional[Any] = batch_size
__UpperCAmelCase : Optional[Any] = image_size
__UpperCAmelCase : Optional[int] = num_channels
__UpperCAmelCase : List[Any] = use_pretrained_backbone
__UpperCAmelCase : Dict = is_training
def A( self):
__UpperCAmelCase : Optional[Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])
__UpperCAmelCase : Tuple = self.get_config()
return config, pixel_values
def A( self):
return TimmBackboneConfig(
image_size=self.image_size , num_channels=self.num_channels , out_features=self.out_features , out_indices=self.out_indices , stage_names=self.stage_names , use_pretrained_backbone=self.use_pretrained_backbone , backbone=self.backbone , )
def A( self , lowercase__ , lowercase__):
__UpperCAmelCase : Tuple = TimmBackbone(config=lowercase__)
model.to(lowercase__)
model.eval()
with torch.no_grad():
__UpperCAmelCase : Union[str, Any] = model(lowercase__)
self.parent.assertEqual(
result.feature_map[-1].shape , (self.batch_size, model.channels[-1], 1_4, 1_4) , )
def A( self):
__UpperCAmelCase : Dict = self.prepare_config_and_inputs()
__UpperCAmelCase , __UpperCAmelCase : List[Any] = config_and_inputs
__UpperCAmelCase : List[Any] = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
@require_timm
class lowerCamelCase ( _UpperCamelCase , _UpperCamelCase , _UpperCamelCase , unittest.TestCase ):
_lowerCAmelCase : Dict = (TimmBackbone,) if is_torch_available() else ()
_lowerCAmelCase : str = {'''feature-extraction''': TimmBackbone} if is_torch_available() else {}
_lowerCAmelCase : List[str] = False
_lowerCAmelCase : str = False
_lowerCAmelCase : List[Any] = False
_lowerCAmelCase : List[str] = False
def A( self):
__UpperCAmelCase : List[Any] = TimmBackboneModelTester(self)
__UpperCAmelCase : int = ConfigTester(self , config_class=lowercase__ , has_text_modality=lowercase__)
def A( self):
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def A( self):
__UpperCAmelCase : int = '''resnet18'''
__UpperCAmelCase : List[str] = '''microsoft/resnet-18'''
__UpperCAmelCase : Any = AutoBackbone.from_pretrained(lowercase__ , use_timm_backbone=lowercase__)
__UpperCAmelCase : Union[str, Any] = AutoBackbone.from_pretrained(lowercase__)
self.assertEqual(len(timm_model.out_features) , len(transformers_model.out_features))
self.assertEqual(len(timm_model.stage_names) , len(transformers_model.stage_names))
self.assertEqual(timm_model.channels , transformers_model.channels)
# Out indices are set to the last layer by default. For timm models, we don't know
# the number of layers in advance, so we set it to (-1,), whereas for transformers
# models, we set it to [len(stage_names) - 1] (kept for backward compatibility).
self.assertEqual(timm_model.out_indices , (-1,))
self.assertEqual(transformers_model.out_indices , [len(timm_model.stage_names) - 1])
__UpperCAmelCase : Union[str, Any] = AutoBackbone.from_pretrained(lowercase__ , use_timm_backbone=lowercase__ , out_indices=[1, 2, 3])
__UpperCAmelCase : Any = AutoBackbone.from_pretrained(lowercase__ , out_indices=[1, 2, 3])
self.assertEqual(timm_model.out_indices , transformers_model.out_indices)
self.assertEqual(len(timm_model.out_features) , len(transformers_model.out_features))
self.assertEqual(timm_model.channels , transformers_model.channels)
@unittest.skip('''TimmBackbone doesn\'t support feed forward chunking''')
def A( self):
pass
@unittest.skip('''TimmBackbone doesn\'t have num_hidden_layers attribute''')
def A( self):
pass
@unittest.skip('''TimmBackbone initialization is managed on the timm side''')
def A( self):
pass
@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''')
def A( self):
pass
@unittest.skip('''TimmBackbone models doesn\'t have inputs_embeds''')
def A( self):
pass
@unittest.skip('''TimmBackbone model cannot be created without specifying a backbone checkpoint''')
def A( self):
pass
@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
def A( self):
pass
@unittest.skip('''model weights aren\'t tied in TimmBackbone.''')
def A( self):
pass
@unittest.skip('''model weights aren\'t tied in TimmBackbone.''')
def A( self):
pass
@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
def A( self):
pass
@unittest.skip('''Only checkpoints on timm can be loaded into TimmBackbone''')
def A( self):
pass
@unittest.skip('''TimmBackbone doesn\'t have hidden size info in its configuration.''')
def A( self):
pass
@unittest.skip('''TimmBackbone doesn\'t support output_attentions.''')
def A( self):
pass
@unittest.skip('''Safetensors is not supported by timm.''')
def A( self):
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
def A( self):
pass
def A( self):
__UpperCAmelCase , __UpperCAmelCase : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__UpperCAmelCase : Any = model_class(lowercase__)
__UpperCAmelCase : Optional[int] = inspect.signature(model.forward)
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__UpperCAmelCase : Optional[int] = [*signature.parameters.keys()]
__UpperCAmelCase : Dict = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , lowercase__)
def A( self):
__UpperCAmelCase , __UpperCAmelCase : str = self.model_tester.prepare_config_and_inputs_for_common()
__UpperCAmelCase : Tuple = True
__UpperCAmelCase : Optional[int] = self.has_attentions
# no need to test all models as different heads yield the same functionality
__UpperCAmelCase : Optional[Any] = self.all_model_classes[0]
__UpperCAmelCase : Optional[int] = model_class(lowercase__)
model.to(lowercase__)
__UpperCAmelCase : Tuple = self._prepare_for_class(lowercase__ , lowercase__)
__UpperCAmelCase : Optional[int] = model(**lowercase__)
__UpperCAmelCase : List[str] = outputs[0][-1]
# Encoder-/Decoder-only models
__UpperCAmelCase : Dict = outputs.hidden_states[0]
hidden_states.retain_grad()
if self.has_attentions:
__UpperCAmelCase : Optional[int] = outputs.attentions[0]
attentions.retain_grad()
output.flatten()[0].backward(retain_graph=lowercase__)
self.assertIsNotNone(hidden_states.grad)
if self.has_attentions:
self.assertIsNotNone(attentions.grad)
def A( self):
__UpperCAmelCase , __UpperCAmelCase : Dict = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__UpperCAmelCase : Optional[Any] = model_class(lowercase__)
model.to(lowercase__)
model.eval()
__UpperCAmelCase : Union[str, Any] = model(**lowercase__)
self.assertEqual(len(result.feature_maps) , len(config.out_indices))
self.assertEqual(len(model.channels) , len(config.out_indices))
# Check output of last stage is taken if out_features=None, out_indices=None
__UpperCAmelCase : List[str] = copy.deepcopy(lowercase__)
__UpperCAmelCase : str = None
__UpperCAmelCase : Optional[int] = model_class(lowercase__)
model.to(lowercase__)
model.eval()
__UpperCAmelCase : Optional[Any] = model(**lowercase__)
self.assertEqual(len(result.feature_maps) , 1)
self.assertEqual(len(model.channels) , 1)
# Check backbone can be initialized with fresh weights
__UpperCAmelCase : Tuple = copy.deepcopy(lowercase__)
__UpperCAmelCase : Optional[int] = False
__UpperCAmelCase : Optional[int] = model_class(lowercase__)
model.to(lowercase__)
model.eval()
__UpperCAmelCase : List[Any] = model(**lowercase__)
| 462 | 0 |
"""simple docstring"""
from itertools import count
def _snake_case ( _snake_case : int = 50 ):
lowerCAmelCase : List[Any] = [1] * min_block_length
for n in count(_snake_case ):
fill_count_functions.append(1 )
for block_length in range(_snake_case , 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() = }""")
| 637 |
"""simple docstring"""
class snake_case_:
def __init__( self : Union[str, Any] , UpperCamelCase_ : str ):
lowerCAmelCase : Dict = val
lowerCAmelCase : str = None
lowerCAmelCase : Dict = None
def lowerCamelCase__ ( self : Union[str, Any] , UpperCamelCase_ : Dict ):
if self.val:
if val < self.val:
if self.left is None:
lowerCAmelCase : int = Node(UpperCamelCase_ )
else:
self.left.insert(UpperCamelCase_ )
elif val > self.val:
if self.right is None:
lowerCAmelCase : Any = Node(UpperCamelCase_ )
else:
self.right.insert(UpperCamelCase_ )
else:
lowerCAmelCase : Optional[Any] = val
def _snake_case ( _snake_case : Tuple , _snake_case : str ):
# Recursive traversal
if root:
inorder(root.left , _snake_case )
res.append(root.val )
inorder(root.right , _snake_case )
def _snake_case ( _snake_case : Optional[Any] ):
# Build BST
if len(_snake_case ) == 0:
return arr
lowerCAmelCase : Optional[Any] = Node(arr[0] )
for i in range(1 , len(_snake_case ) ):
root.insert(arr[i] )
# Traverse BST in order.
lowerCAmelCase : Optional[int] = []
inorder(_snake_case , _snake_case )
return res
if __name__ == "__main__":
print(tree_sort([10, 1, 3, 2, 9, 14, 13]))
| 637 | 1 |
import os
import unittest
from transformers.models.transfo_xl.tokenization_transfo_xl import VOCAB_FILES_NAMES, TransfoXLTokenizer
from ...test_tokenization_common import TokenizerTesterMixin
class UpperCAmelCase ( __UpperCAmelCase , unittest.TestCase ):
a: Union[str, Any] = TransfoXLTokenizer
a: Union[str, Any] = False
a: Optional[int] = False
def _A ( self: List[str] ):
super().setUp()
_a = [
'''<unk>''',
'''[CLS]''',
'''[SEP]''',
'''want''',
'''unwanted''',
'''wa''',
'''un''',
'''running''',
''',''',
'''low''',
'''l''',
]
_a = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
def _A ( self: Tuple , **__UpperCamelCase: Dict ):
_a = True
return TransfoXLTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def _A ( self: Optional[int] , __UpperCamelCase: int ):
_a = '''<unk> UNwanted , running'''
_a = '''<unk> unwanted, running'''
return input_text, output_text
def _A ( self: Union[str, Any] ):
_a = TransfoXLTokenizer(vocab_file=self.vocab_file , lower_case=_lowerCamelCase )
_a = tokenizer.tokenize('''<unk> UNwanted , running''' )
self.assertListEqual(_lowerCamelCase , ['''<unk>''', '''unwanted''', ''',''', '''running'''] )
self.assertListEqual(tokenizer.convert_tokens_to_ids(_lowerCamelCase ) , [0, 4, 8, 7] )
def _A ( self: Optional[Any] ):
_a = TransfoXLTokenizer(lower_case=_lowerCamelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''hello''', '''!''', '''how''', '''are''', '''you''', '''?'''] )
def _A ( self: List[str] ):
_a = TransfoXLTokenizer(lower_case=_lowerCamelCase )
self.assertListEqual(
tokenizer.tokenize(''' \tHeLLo ! how \n Are yoU ? ''' ) , ['''HeLLo''', '''!''', '''how''', '''Are''', '''yoU''', '''?'''] )
def _A ( self: List[Any] ):
_a = TransfoXLTokenizer(lower_case=_lowerCamelCase )
_a = '''Hello (bracket) and side-scrolled [and] Henry\'s $5,000 with 3.34 m. What\'s up!?'''
_a = [
'''Hello''',
'''(''',
'''bracket''',
''')''',
'''and''',
'''side''',
'''@-@''',
'''scrolled''',
'''[''',
'''and''',
''']''',
'''Henry''',
'''\'s''',
'''$''',
'''5''',
'''@,@''',
'''000''',
'''with''',
'''3''',
'''@.@''',
'''34''',
'''m''',
'''.''',
'''What''',
'''\'s''',
'''up''',
'''!''',
'''?''',
]
self.assertListEqual(tokenizer.tokenize(_lowerCamelCase ) , _lowerCamelCase )
self.assertEqual(tokenizer.convert_tokens_to_string(_lowerCamelCase ) , _lowerCamelCase )
def _A ( self: Optional[int] ):
_a = self.get_tokenizer()
_a = len(_lowerCamelCase )
tokenizer.add_tokens(['''new1''', '''new2'''] )
tokenizer.move_added_token('''new1''' , 1 )
# Check that moved token is not copied (duplicate)
self.assertEqual(len(_lowerCamelCase ) , original_len + 2 )
# Check that token is moved to specified id
self.assertEqual(tokenizer.encode('''new1''' ) , [1] )
self.assertEqual(tokenizer.decode([1] ) , '''new1''' )
| 487 |
"""simple docstring"""
import json
import os
import shutil
import tempfile
import unittest
import numpy as np
from transformers import BertTokenizerFast
from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES, BertTokenizer
from transformers.testing_utils import require_tokenizers, require_vision
from transformers.utils import IMAGE_PROCESSOR_NAME, is_vision_available
if is_vision_available():
from PIL import Image
from transformers import VisionTextDualEncoderProcessor, ViTImageProcessor
@require_tokenizers
@require_vision
class snake_case ( unittest.TestCase ):
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = tempfile.mkdtemp()
# fmt: off
__SCREAMING_SNAKE_CASE : Optional[int] = ['''[UNK]''', '''[CLS]''', '''[SEP]''', '''[PAD]''', '''[MASK]''', '''want''', '''##want''', '''##ed''', '''wa''', '''un''', '''runn''', '''##ing''', ''',''', '''low''', '''lowest''']
# fmt: on
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES['''vocab_file'''] )
with open(self.vocab_file , '''w''' , encoding='''utf-8''' ) as vocab_writer:
vocab_writer.write(''''''.join([x + '''\n''' for x in vocab_tokens] ) )
__SCREAMING_SNAKE_CASE : Optional[int] = {
'''do_resize''': True,
'''size''': {'''height''': 1_8, '''width''': 1_8},
'''do_normalize''': True,
'''image_mean''': [0.5, 0.5, 0.5],
'''image_std''': [0.5, 0.5, 0.5],
}
__SCREAMING_SNAKE_CASE : List[Any] = os.path.join(self.tmpdirname , _lowerCamelCase )
with open(self.image_processor_file , '''w''' , encoding='''utf-8''' ) as fp:
json.dump(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Union[str, Any] , **_lowerCamelCase :List[str] ):
return BertTokenizer.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[str] , **_lowerCamelCase :Optional[int] ):
return ViTImageProcessor.from_pretrained(self.tmpdirname , **_lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Optional[Any] ):
shutil.rmtree(self.tmpdirname )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = [np.random.randint(2_5_5 , size=(3, 3_0, 4_0_0) , dtype=np.uinta )]
__SCREAMING_SNAKE_CASE : Tuple = [Image.fromarray(np.moveaxis(_lowerCamelCase , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Optional[Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(self.tmpdirname )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :List[Any] ):
__SCREAMING_SNAKE_CASE : str = VisionTextDualEncoderProcessor(
tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
__SCREAMING_SNAKE_CASE : Optional[int] = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
__SCREAMING_SNAKE_CASE : List[str] = self.get_image_processor(do_normalize=_lowerCamelCase , padding_value=1.0 )
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=_lowerCamelCase , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , (BertTokenizer, BertTokenizerFast) )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :int ):
__SCREAMING_SNAKE_CASE : Union[str, Any] = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Dict = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : Optional[int] = image_processor(_lowerCamelCase , return_tensors='''np''' )
__SCREAMING_SNAKE_CASE : Tuple = processor(images=_lowerCamelCase , 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 SCREAMING_SNAKE_CASE_ ( self :Optional[int] ):
__SCREAMING_SNAKE_CASE : Any = self.get_image_processor()
__SCREAMING_SNAKE_CASE : Any = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Tuple = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Optional[int] = processor(text=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = tokenizer(_lowerCamelCase )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def SCREAMING_SNAKE_CASE_ ( self :str ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : int = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : int = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Any = '''lower newer'''
__SCREAMING_SNAKE_CASE : int = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : int = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , ['''input_ids''', '''token_type_ids''', '''attention_mask''', '''pixel_values'''] )
# test if it raises when no input is passed
with self.assertRaises(_lowerCamelCase ):
processor()
def SCREAMING_SNAKE_CASE_ ( self :Any ):
__SCREAMING_SNAKE_CASE : Dict = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[Any] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Union[str, Any] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : Union[str, Any] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
__SCREAMING_SNAKE_CASE : Tuple = processor.batch_decode(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[str] = tokenizer.batch_decode(_lowerCamelCase )
self.assertListEqual(_lowerCamelCase , _lowerCamelCase )
def SCREAMING_SNAKE_CASE_ ( self :Dict ):
__SCREAMING_SNAKE_CASE : str = self.get_image_processor()
__SCREAMING_SNAKE_CASE : List[str] = self.get_tokenizer()
__SCREAMING_SNAKE_CASE : Optional[int] = VisionTextDualEncoderProcessor(tokenizer=_lowerCamelCase , image_processor=_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = '''lower newer'''
__SCREAMING_SNAKE_CASE : Dict = self.prepare_image_inputs()
__SCREAMING_SNAKE_CASE : str = processor(text=_lowerCamelCase , images=_lowerCamelCase )
self.assertListEqual(list(inputs.keys() ) , processor.model_input_names )
| 674 | 0 |
import copy
from collections import OrderedDict
from typing import Dict, Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
from ..auto import CONFIG_MAPPING
a_ :Dict = logging.get_logger(__name__)
a_ :int = {
'facebook/detr-resnet-50': 'https://huggingface.co/facebook/detr-resnet-50/resolve/main/config.json',
# See all DETR models at https://huggingface.co/models?filter=detr
}
class lowercase ( _UpperCAmelCase ):
lowerCamelCase : Dict = '''detr'''
lowerCamelCase : List[Any] = ['''past_key_values''']
lowerCamelCase : Union[str, Any] = {
'''hidden_size''': '''d_model''',
'''num_attention_heads''': '''encoder_attention_heads''',
}
def __init__( self : int , _lowercase : List[Any]=True , _lowercase : Dict=None , _lowercase : List[str]=3 , _lowercase : Tuple=1_00 , _lowercase : Optional[int]=6 , _lowercase : Any=20_48 , _lowercase : Dict=8 , _lowercase : List[Any]=6 , _lowercase : List[Any]=20_48 , _lowercase : int=8 , _lowercase : Optional[Any]=0.0 , _lowercase : List[str]=0.0 , _lowercase : Tuple=True , _lowercase : str="relu" , _lowercase : Optional[Any]=2_56 , _lowercase : Any=0.1 , _lowercase : Union[str, Any]=0.0 , _lowercase : List[Any]=0.0 , _lowercase : str=0.02 , _lowercase : Optional[Any]=1.0 , _lowercase : Union[str, Any]=False , _lowercase : Optional[Any]="sine" , _lowercase : Union[str, Any]="resnet50" , _lowercase : int=True , _lowercase : Tuple=False , _lowercase : List[Any]=1 , _lowercase : List[Any]=5 , _lowercase : List[str]=2 , _lowercase : int=1 , _lowercase : Optional[Any]=1 , _lowercase : Optional[Any]=5 , _lowercase : Union[str, Any]=2 , _lowercase : List[Any]=0.1 , **_lowercase : List[str] , ):
if backbone_config is not None and use_timm_backbone:
raise ValueError('''You can\'t specify both `backbone_config` and `use_timm_backbone`.''' )
if not use_timm_backbone:
if backbone_config is None:
logger.info('''`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.''' )
SCREAMING_SNAKE_CASE__ : Tuple = CONFIG_MAPPING['''resnet'''](out_features=['''stage4'''] )
elif isinstance(_lowercase , _lowercase ):
SCREAMING_SNAKE_CASE__ : Any = backbone_config.get('''model_type''' )
SCREAMING_SNAKE_CASE__ : str = CONFIG_MAPPING[backbone_model_type]
SCREAMING_SNAKE_CASE__ : List[Any] = config_class.from_dict(_lowercase )
# set timm attributes to None
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[Any] = None, None, None
SCREAMING_SNAKE_CASE__ : Any = use_timm_backbone
SCREAMING_SNAKE_CASE__ : Tuple = backbone_config
SCREAMING_SNAKE_CASE__ : Tuple = num_channels
SCREAMING_SNAKE_CASE__ : Dict = num_queries
SCREAMING_SNAKE_CASE__ : int = d_model
SCREAMING_SNAKE_CASE__ : str = encoder_ffn_dim
SCREAMING_SNAKE_CASE__ : Optional[Any] = encoder_layers
SCREAMING_SNAKE_CASE__ : str = encoder_attention_heads
SCREAMING_SNAKE_CASE__ : Union[str, Any] = decoder_ffn_dim
SCREAMING_SNAKE_CASE__ : str = decoder_layers
SCREAMING_SNAKE_CASE__ : Tuple = decoder_attention_heads
SCREAMING_SNAKE_CASE__ : Optional[int] = dropout
SCREAMING_SNAKE_CASE__ : Any = attention_dropout
SCREAMING_SNAKE_CASE__ : Optional[int] = activation_dropout
SCREAMING_SNAKE_CASE__ : Union[str, Any] = activation_function
SCREAMING_SNAKE_CASE__ : Union[str, Any] = init_std
SCREAMING_SNAKE_CASE__ : Union[str, Any] = init_xavier_std
SCREAMING_SNAKE_CASE__ : Tuple = encoder_layerdrop
SCREAMING_SNAKE_CASE__ : Optional[Any] = decoder_layerdrop
SCREAMING_SNAKE_CASE__ : Optional[int] = encoder_layers
SCREAMING_SNAKE_CASE__ : Optional[Any] = auxiliary_loss
SCREAMING_SNAKE_CASE__ : Union[str, Any] = position_embedding_type
SCREAMING_SNAKE_CASE__ : List[Any] = backbone
SCREAMING_SNAKE_CASE__ : Union[str, Any] = use_pretrained_backbone
SCREAMING_SNAKE_CASE__ : Tuple = dilation
# Hungarian matcher
SCREAMING_SNAKE_CASE__ : Union[str, Any] = class_cost
SCREAMING_SNAKE_CASE__ : Tuple = bbox_cost
SCREAMING_SNAKE_CASE__ : List[Any] = giou_cost
# Loss coefficients
SCREAMING_SNAKE_CASE__ : Optional[Any] = mask_loss_coefficient
SCREAMING_SNAKE_CASE__ : Tuple = dice_loss_coefficient
SCREAMING_SNAKE_CASE__ : int = bbox_loss_coefficient
SCREAMING_SNAKE_CASE__ : List[str] = giou_loss_coefficient
SCREAMING_SNAKE_CASE__ : int = eos_coefficient
super().__init__(is_encoder_decoder=_lowercase , **_lowercase )
@property
def lowercase__ ( self : int ):
return self.encoder_attention_heads
@property
def lowercase__ ( self : str ):
return self.d_model
@classmethod
def lowercase__ ( cls : int , _lowercase : PretrainedConfig , **_lowercase : Any ):
return cls(backbone_config=_lowercase , **_lowercase )
def lowercase__ ( self : Any ):
SCREAMING_SNAKE_CASE__ : List[str] = copy.deepcopy(self.__dict__ )
if output["backbone_config"] is not None:
SCREAMING_SNAKE_CASE__ : List[Any] = self.backbone_config.to_dict()
SCREAMING_SNAKE_CASE__ : List[Any] = self.__class__.model_type
return output
class lowercase ( _UpperCAmelCase ):
lowerCamelCase : List[str] = version.parse('''1.11''' )
@property
def lowercase__ ( self : Optional[int] ):
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
('''pixel_mask''', {0: '''batch'''}),
] )
@property
def lowercase__ ( self : Tuple ):
return 1E-5
@property
def lowercase__ ( self : Optional[int] ):
return 12
| 250 |
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
a_ :str = version.parse(version.parse(torch.__version__).base_version) < version.parse('1.11')
def a ( A__ , A__ , A__ , A__ , A__ , A__ , A__ , A__=False , ) -> Optional[Any]:
'''simple docstring'''
output_path.parent.mkdir(parents=A__ , exist_ok=A__ )
# 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(
A__ , A__ , f=output_path.as_posix() , input_names=A__ , output_names=A__ , dynamic_axes=A__ , do_constant_folding=A__ , use_external_data_format=A__ , enable_onnx_checker=A__ , opset_version=A__ , )
else:
export(
A__ , A__ , f=output_path.as_posix() , input_names=A__ , output_names=A__ , dynamic_axes=A__ , do_constant_folding=A__ , opset_version=A__ , )
@torch.no_grad()
def a ( A__ , A__ , A__ , A__ = False ) -> List[Any]:
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : Any = torch.floataa if fpaa else torch.floataa
if fpaa and torch.cuda.is_available():
SCREAMING_SNAKE_CASE__ : List[str] = '''cuda'''
elif fpaa and not torch.cuda.is_available():
raise ValueError('''`float16` model export is only supported on GPUs with CUDA''' )
else:
SCREAMING_SNAKE_CASE__ : Optional[int] = '''cpu'''
SCREAMING_SNAKE_CASE__ : str = StableDiffusionPipeline.from_pretrained(A__ , torch_dtype=A__ ).to(A__ )
SCREAMING_SNAKE_CASE__ : int = Path(A__ )
# TEXT ENCODER
SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipeline.text_encoder.config.max_position_embeddings
SCREAMING_SNAKE_CASE__ : List[str] = pipeline.text_encoder.config.hidden_size
SCREAMING_SNAKE_CASE__ : Optional[Any] = pipeline.tokenizer(
'''A sample prompt''' , padding='''max_length''' , max_length=pipeline.tokenizer.model_max_length , truncation=A__ , return_tensors='''pt''' , )
onnx_export(
pipeline.text_encoder , model_args=(text_input.input_ids.to(device=A__ , 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=A__ , )
del pipeline.text_encoder
# UNET
SCREAMING_SNAKE_CASE__ : Union[str, Any] = pipeline.unet.config.in_channels
SCREAMING_SNAKE_CASE__ : Tuple = pipeline.unet.config.sample_size
SCREAMING_SNAKE_CASE__ : Dict = output_path / '''unet''' / '''model.onnx'''
onnx_export(
pipeline.unet , model_args=(
torch.randn(2 , A__ , A__ , A__ ).to(device=A__ , dtype=A__ ),
torch.randn(2 ).to(device=A__ , dtype=A__ ),
torch.randn(2 , A__ , A__ ).to(device=A__ , dtype=A__ ),
False,
) , output_path=A__ , 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=A__ , use_external_data_format=A__ , )
SCREAMING_SNAKE_CASE__ : List[str] = str(unet_path.absolute().as_posix() )
SCREAMING_SNAKE_CASE__ : List[str] = os.path.dirname(A__ )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = onnx.load(A__ )
# clean up existing tensor files
shutil.rmtree(A__ )
os.mkdir(A__ )
# collate external tensor files into one
onnx.save_model(
A__ , A__ , save_as_external_data=A__ , all_tensors_to_one_file=A__ , location='''weights.pb''' , convert_attribute=A__ , )
del pipeline.unet
# VAE ENCODER
SCREAMING_SNAKE_CASE__ : Optional[int] = pipeline.vae
SCREAMING_SNAKE_CASE__ : str = vae_encoder.config.in_channels
SCREAMING_SNAKE_CASE__ : str = vae_encoder.config.sample_size
# need to get the raw tensor output (sample) from the encoder
SCREAMING_SNAKE_CASE__ : Dict = lambda A__ , A__ : vae_encoder.encode(A__ , A__ )[0].sample()
onnx_export(
A__ , model_args=(
torch.randn(1 , A__ , A__ , A__ ).to(device=A__ , dtype=A__ ),
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=A__ , )
# VAE DECODER
SCREAMING_SNAKE_CASE__ : Tuple = pipeline.vae
SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae_decoder.config.latent_channels
SCREAMING_SNAKE_CASE__ : Dict = vae_decoder.config.out_channels
# forward only through the decoder part
SCREAMING_SNAKE_CASE__ : Union[str, Any] = vae_encoder.decode
onnx_export(
A__ , model_args=(
torch.randn(1 , A__ , A__ , A__ ).to(device=A__ , dtype=A__ ),
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=A__ , )
del pipeline.vae
# SAFETY CHECKER
if pipeline.safety_checker is not None:
SCREAMING_SNAKE_CASE__ : int = pipeline.safety_checker
SCREAMING_SNAKE_CASE__ : int = safety_checker.config.vision_config.num_channels
SCREAMING_SNAKE_CASE__ : Dict = safety_checker.config.vision_config.image_size
SCREAMING_SNAKE_CASE__ : Optional[Any] = safety_checker.forward_onnx
onnx_export(
pipeline.safety_checker , model_args=(
torch.randn(
1 , A__ , A__ , A__ , ).to(device=A__ , dtype=A__ ),
torch.randn(1 , A__ , A__ , A__ ).to(device=A__ , dtype=A__ ),
) , 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=A__ , )
del pipeline.safety_checker
SCREAMING_SNAKE_CASE__ : Optional[int] = OnnxRuntimeModel.from_pretrained(output_path / '''safety_checker''' )
SCREAMING_SNAKE_CASE__ : str = pipeline.feature_extractor
else:
SCREAMING_SNAKE_CASE__ : Tuple = None
SCREAMING_SNAKE_CASE__ : Optional[int] = None
SCREAMING_SNAKE_CASE__ : List[Any] = 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=A__ , feature_extractor=A__ , requires_safety_checker=safety_checker is not None , )
onnx_pipeline.save_pretrained(A__ )
print('''ONNX pipeline saved to''' , A__ )
del pipeline
del onnx_pipeline
SCREAMING_SNAKE_CASE__ : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained(A__ , provider='''CPUExecutionProvider''' )
print('''ONNX pipeline is loadable''' )
if __name__ == "__main__":
a_ :List[str] = 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=14,
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')
a_ :Optional[Any] = parser.parse_args()
convert_models(args.model_path, args.output_path, args.opset, args.fpaa)
| 250 | 1 |
'''simple docstring'''
import argparse
from collections import OrderedDict
from pathlib import Path
import torch
from transformers import (
VisualBertConfig,
VisualBertForMultipleChoice,
VisualBertForPreTraining,
VisualBertForQuestionAnswering,
VisualBertForVisualReasoning,
)
from transformers.utils import logging
logging.set_verbosity_info()
a__ : Tuple = logging.get_logger(__name__)
a__ : Optional[Any] = [
('bert.bert', 'visual_bert'),
('bert.cls', 'cls'),
('bert.classifier', 'cls'),
('token_type_embeddings_visual', 'visual_token_type_embeddings'),
('position_embeddings_visual', 'visual_position_embeddings'),
('projection', 'visual_projection'),
]
a__ : int = [
'nlvr2_coco_pre_trained.th',
'nlvr2_fine_tuned.th',
'nlvr2_pre_trained.th',
'vcr_coco_pre_train.th',
'vcr_fine_tune.th',
'vcr_pre_train.th',
'vqa_coco_pre_trained.th',
'vqa_fine_tuned.th',
'vqa_pre_trained.th',
]
def _lowercase ( __A ):
'''simple docstring'''
__UpperCamelCase = torch.load(__A ,map_location="""cpu""" )
return sd
def _lowercase ( __A ,__A ,__A=rename_keys_prefix ):
'''simple docstring'''
__UpperCamelCase = OrderedDict()
__UpperCamelCase = torch.arange(config.max_position_embeddings ).expand((1, -1) )
# detector_d = OrderedDict()
for key in d:
if "detector" in key:
# detector_d[key.replace('detector.','')] = d[key]
continue
__UpperCamelCase = key
for name_pair in rename_keys_prefix:
__UpperCamelCase = new_key.replace(name_pair[0] ,name_pair[1] )
__UpperCamelCase = d[key]
if key == "bert.cls.predictions.decoder.weight":
# Old bert code didn't have `decoder.bias`, but was added separately
__UpperCamelCase = new_d['''cls.predictions.bias''']
return new_d
@torch.no_grad()
def _lowercase ( __A ,__A ):
'''simple docstring'''
assert (
checkpoint_path.split("""/""" )[-1] in ACCEPTABLE_CHECKPOINTS
), f"The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}."
# Get Config
if "pre" in checkpoint_path:
__UpperCamelCase = '''pretraining'''
if "vcr" in checkpoint_path:
__UpperCamelCase = {'''visual_embedding_dim''': 512}
elif "vqa_advanced" in checkpoint_path:
__UpperCamelCase = {'''visual_embedding_dim''': 2_048}
elif "vqa" in checkpoint_path:
__UpperCamelCase = {'''visual_embedding_dim''': 2_048}
elif "nlvr" in checkpoint_path:
__UpperCamelCase = {'''visual_embedding_dim''': 1_024}
else:
raise NotImplementedError(f"No implementation found for `{checkpoint_path}`." )
else:
if "vcr" in checkpoint_path:
__UpperCamelCase = {'''visual_embedding_dim''': 512}
__UpperCamelCase = '''multichoice'''
elif "vqa_advanced" in checkpoint_path:
__UpperCamelCase = {'''visual_embedding_dim''': 2_048}
__UpperCamelCase = '''vqa_advanced'''
elif "vqa" in checkpoint_path:
__UpperCamelCase = {'''visual_embedding_dim''': 2_048, '''num_labels''': 3_129}
__UpperCamelCase = '''vqa'''
elif "nlvr" in checkpoint_path:
__UpperCamelCase = {
'''visual_embedding_dim''': 1_024,
'''num_labels''': 2,
}
__UpperCamelCase = '''nlvr'''
__UpperCamelCase = VisualBertConfig(**__A )
# Load State Dict
__UpperCamelCase = load_state_dict(__A )
__UpperCamelCase = get_new_dict(__A ,__A )
if model_type == "pretraining":
__UpperCamelCase = VisualBertForPreTraining(__A )
elif model_type == "vqa":
__UpperCamelCase = VisualBertForQuestionAnswering(__A )
elif model_type == "nlvr":
__UpperCamelCase = VisualBertForVisualReasoning(__A )
elif model_type == "multichoice":
__UpperCamelCase = VisualBertForMultipleChoice(__A )
model.load_state_dict(__A )
# Save Checkpoints
Path(__A ).mkdir(exist_ok=__A )
model.save_pretrained(__A )
if __name__ == "__main__":
a__ : List[Any] = argparse.ArgumentParser()
# Required parameters
parser.add_argument('orig_checkpoint_path', type=str, help='A path to .th on local filesystem.')
parser.add_argument('pytorch_dump_folder_path', type=str, help='Path to the output PyTorch model.')
a__ : Optional[Any] = parser.parse_args()
convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)
| 601 |
import shutil
import tempfile
import unittest
import numpy as np
import pytest
from transformers.testing_utils import require_vision
from transformers.utils import is_vision_available
if is_vision_available():
from PIL import Image
from transformers import AutoProcessor, BlipaProcessor, BlipImageProcessor, GPTaTokenizer, PreTrainedTokenizerFast
@require_vision
class a_ ( unittest.TestCase ):
def lowerCAmelCase( self : List[str] ):
"""simple docstring"""
snake_case : Tuple = tempfile.mkdtemp()
snake_case : Optional[int] = BlipImageProcessor()
snake_case : Dict = GPTaTokenizer.from_pretrained('''hf-internal-testing/tiny-random-GPT2Model''' )
snake_case : Tuple = BlipaProcessor(UpperCAmelCase__ , UpperCAmelCase__ )
processor.save_pretrained(self.tmpdirname )
def lowerCAmelCase( self : List[Any] , **UpperCAmelCase__ : Any ):
"""simple docstring"""
return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ).tokenizer
def lowerCAmelCase( self : List[str] , **UpperCAmelCase__ : Any ):
"""simple docstring"""
return AutoProcessor.from_pretrained(self.tmpdirname , **UpperCAmelCase__ ).image_processor
def lowerCAmelCase( self : Union[str, Any] ):
"""simple docstring"""
shutil.rmtree(self.tmpdirname )
def lowerCAmelCase( self : Optional[int] ):
"""simple docstring"""
snake_case : List[str] = [np.random.randint(255 , size=(3, 30, 400) , dtype=np.uinta )]
snake_case : List[Any] = [Image.fromarray(np.moveaxis(UpperCAmelCase__ , 0 , -1 ) ) for x in image_inputs]
return image_inputs
def lowerCAmelCase( self : Optional[int] ):
"""simple docstring"""
snake_case : str = BlipaProcessor(tokenizer=self.get_tokenizer() , image_processor=self.get_image_processor() )
processor.save_pretrained(self.tmpdirname )
snake_case : str = self.get_tokenizer(bos_token='''(BOS)''' , eos_token='''(EOS)''' )
snake_case : Optional[int] = self.get_image_processor(do_normalize=UpperCAmelCase__ , padding_value=1.0 )
snake_case : Optional[Any] = BlipaProcessor.from_pretrained(
self.tmpdirname , bos_token='''(BOS)''' , eos_token='''(EOS)''' , do_normalize=UpperCAmelCase__ , padding_value=1.0 )
self.assertEqual(processor.tokenizer.get_vocab() , tokenizer_add_kwargs.get_vocab() )
self.assertIsInstance(processor.tokenizer , UpperCAmelCase__ )
self.assertEqual(processor.image_processor.to_json_string() , image_processor_add_kwargs.to_json_string() )
self.assertIsInstance(processor.image_processor , UpperCAmelCase__ )
def lowerCAmelCase( self : Optional[Any] ):
"""simple docstring"""
snake_case : str = self.get_image_processor()
snake_case : Optional[Any] = self.get_tokenizer()
snake_case : int = BlipaProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ )
snake_case : int = self.prepare_image_inputs()
snake_case : Optional[int] = image_processor(UpperCAmelCase__ , return_tensors='''np''' )
snake_case : str = processor(images=UpperCAmelCase__ , 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 lowerCAmelCase( self : Optional[int] ):
"""simple docstring"""
snake_case : Optional[Any] = self.get_image_processor()
snake_case : Optional[Any] = self.get_tokenizer()
snake_case : List[Any] = BlipaProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ )
snake_case : Any = '''lower newer'''
snake_case : List[Any] = processor(text=UpperCAmelCase__ )
snake_case : Optional[int] = tokenizer(UpperCAmelCase__ , return_token_type_ids=UpperCAmelCase__ )
for key in encoded_tok.keys():
self.assertListEqual(encoded_tok[key] , encoded_processor[key] )
def lowerCAmelCase( self : Any ):
"""simple docstring"""
snake_case : List[Any] = self.get_image_processor()
snake_case : Any = self.get_tokenizer()
snake_case : Any = BlipaProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ )
snake_case : List[Any] = '''lower newer'''
snake_case : str = self.prepare_image_inputs()
snake_case : Optional[int] = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ )
self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''input_ids''', '''attention_mask'''] )
# test if it raises when no input is passed
with pytest.raises(UpperCAmelCase__ ):
processor()
def lowerCAmelCase( self : Optional[Any] ):
"""simple docstring"""
snake_case : str = self.get_image_processor()
snake_case : int = self.get_tokenizer()
snake_case : Any = BlipaProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ )
snake_case : List[str] = [[1, 4, 5, 8, 1, 0, 8], [3, 4, 3, 1, 1, 8, 9]]
snake_case : Tuple = processor.batch_decode(UpperCAmelCase__ )
snake_case : str = tokenizer.batch_decode(UpperCAmelCase__ )
self.assertListEqual(UpperCAmelCase__ , UpperCAmelCase__ )
def lowerCAmelCase( self : int ):
"""simple docstring"""
snake_case : List[Any] = self.get_image_processor()
snake_case : Any = self.get_tokenizer()
snake_case : Optional[Any] = BlipaProcessor(tokenizer=UpperCAmelCase__ , image_processor=UpperCAmelCase__ )
snake_case : Any = '''lower newer'''
snake_case : Optional[Any] = self.prepare_image_inputs()
snake_case : str = processor(text=UpperCAmelCase__ , images=UpperCAmelCase__ )
# For now the processor supports only ['pixel_values', 'input_ids', 'attention_mask']
self.assertListEqual(list(inputs.keys() ) , ['''pixel_values''', '''input_ids''', '''attention_mask'''] )
| 598 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_torch_available,
)
_lowerCamelCase : Tuple = {
'''configuration_gpt_bigcode''': ['''GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP''', '''GPTBigCodeConfig'''],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Union[str, Any] = [
'''GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''GPTBigCodeForSequenceClassification''',
'''GPTBigCodeForTokenClassification''',
'''GPTBigCodeForCausalLM''',
'''GPTBigCodeModel''',
'''GPTBigCodePreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_gpt_bigcode import GPT_BIGCODE_PRETRAINED_CONFIG_ARCHIVE_MAP, GPTBigCodeConfig
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_gpt_bigcode import (
GPT_BIGCODE_PRETRAINED_MODEL_ARCHIVE_LIST,
GPTBigCodeForCausalLM,
GPTBigCodeForSequenceClassification,
GPTBigCodeForTokenClassification,
GPTBigCodeModel,
GPTBigCodePreTrainedModel,
)
else:
import sys
_lowerCamelCase : int = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 647 | from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
_lowerCamelCase : Optional[int] = {
'''configuration_blenderbot''': [
'''BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP''',
'''BlenderbotConfig''',
'''BlenderbotOnnxConfig''',
],
'''tokenization_blenderbot''': ['''BlenderbotTokenizer'''],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : List[Any] = ['''BlenderbotTokenizerFast''']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Tuple = [
'''BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST''',
'''BlenderbotForCausalLM''',
'''BlenderbotForConditionalGeneration''',
'''BlenderbotModel''',
'''BlenderbotPreTrainedModel''',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : List[str] = [
'''TFBlenderbotForConditionalGeneration''',
'''TFBlenderbotModel''',
'''TFBlenderbotPreTrainedModel''',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Optional[int] = [
'''FlaxBlenderbotForConditionalGeneration''',
'''FlaxBlenderbotModel''',
'''FlaxBlenderbotPreTrainedModel''',
]
if TYPE_CHECKING:
from .configuration_blenderbot import (
BLENDERBOT_PRETRAINED_CONFIG_ARCHIVE_MAP,
BlenderbotConfig,
BlenderbotOnnxConfig,
)
from .tokenization_blenderbot import BlenderbotTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_blenderbot_fast import BlenderbotTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_blenderbot import (
BLENDERBOT_PRETRAINED_MODEL_ARCHIVE_LIST,
BlenderbotForCausalLM,
BlenderbotForConditionalGeneration,
BlenderbotModel,
BlenderbotPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_blenderbot import (
TFBlenderbotForConditionalGeneration,
TFBlenderbotModel,
TFBlenderbotPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_blenderbot import (
FlaxBlenderbotForConditionalGeneration,
FlaxBlenderbotModel,
FlaxBlenderbotPreTrainedModel,
)
else:
import sys
_lowerCamelCase : Dict = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)
| 647 | 1 |
'''simple docstring'''
import os
import sys
import tempfile
import torch
from .state import AcceleratorState
from .utils import PrecisionType, PrepareForLaunch, is_mps_available, patch_environment
def A_( A : Any , A : Optional[int]=() , A : int=None , A : Union[str, Any]="no" , A : Optional[Any]="29500"):
UpperCamelCase = False
UpperCamelCase = False
if any(key.startswith('KAGGLE') for key in os.environ.keys()):
UpperCamelCase = True
elif "IPython" in sys.modules:
UpperCamelCase = 'google.colab' in str(sys.modules['IPython'].get_ipython())
try:
UpperCamelCase = PrecisionType(mixed_precision.lower())
except ValueError:
raise ValueError(
f'''Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}.''')
if (in_colab or in_kaggle) and (os.environ.get('TPU_NAME' , __lowercase) is not None):
# TPU launch
import torch_xla.distributed.xla_multiprocessing as xmp
if len(AcceleratorState._shared_state) > 0:
raise ValueError(
'To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside '
'your training function. Restart your notebook and make sure no cells initializes an '
'`Accelerator`.')
if num_processes is None:
UpperCamelCase = 8
UpperCamelCase = PrepareForLaunch(__lowercase , distributed_type='TPU')
print(f'''Launching a training on {num_processes} TPU cores.''')
xmp.spawn(__lowercase , args=__lowercase , nprocs=__lowercase , start_method='fork')
elif in_colab:
# No need for a distributed launch otherwise as it's either CPU or one GPU.
if torch.cuda.is_available():
print('Launching training on one GPU.')
else:
print('Launching training on one CPU.')
function(*__lowercase)
else:
if num_processes is None:
raise ValueError(
'You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call.')
if num_processes > 1:
# Multi-GPU launch
from torch.multiprocessing import start_processes
from torch.multiprocessing.spawn import ProcessRaisedException
if len(AcceleratorState._shared_state) > 0:
raise ValueError(
'To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized '
'inside your training function. Restart your notebook and make sure no cells initializes an '
'`Accelerator`.')
if torch.cuda.is_initialized():
raise ValueError(
'To launch a multi-GPU training from your notebook, you need to avoid running any instruction '
'using `torch.cuda` in any cell. Restart your notebook and make sure no cells use any CUDA '
'function.')
# torch.distributed will expect a few environment variable to be here. We set the ones common to each
# process here (the other ones will be set be the launcher).
with patch_environment(
world_size=__lowercase , master_addr='127.0.01' , master_port=__lowercase , mixed_precision=__lowercase):
UpperCamelCase = PrepareForLaunch(__lowercase , distributed_type='MULTI_GPU')
print(f'''Launching training on {num_processes} GPUs.''')
try:
start_processes(__lowercase , args=__lowercase , nprocs=__lowercase , start_method='fork')
except ProcessRaisedException as e:
if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]:
raise RuntimeError(
'CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. '
'This likely stems from an outside import causing issues once the `notebook_launcher()` is called. '
'Please review your imports and test them when running the `notebook_launcher()` to identify '
'which one is problematic.') from e
else:
# No need for a distributed launch otherwise as it's either CPU, GPU or MPS.
if is_mps_available():
UpperCamelCase = '1'
print('Launching training on MPS.')
elif torch.cuda.is_available():
print('Launching training on one GPU.')
else:
print('Launching training on CPU.')
function(*__lowercase)
def A_( A : int , A : Union[str, Any]=() , A : List[str]=2):
from torch.multiprocessing import start_processes
with tempfile.NamedTemporaryFile() as tmp_file:
# torch.distributed will expect a few environment variable to be here. We set the ones common to each
# process here (the other ones will be set be the launcher).
with patch_environment(
world_size=__lowercase , master_addr='127.0.01' , master_port='29500' , accelerate_mixed_precision='no' , accelerate_debug_rdv_file=tmp_file.name , accelerate_use_cpu='yes' , ):
UpperCamelCase = PrepareForLaunch(__lowercase , debug=__lowercase)
start_processes(__lowercase , args=__lowercase , nprocs=__lowercase , start_method='fork')
| 3 |
def _snake_case (__lowercase):
UpperCamelCase_ = 1
for i in range(1 , num + 1):
fact *= i
return fact
def _snake_case (__lowercase):
UpperCamelCase_ = 0
while number > 0:
UpperCamelCase_ = number % 10
sum_of_digits += last_digit
UpperCamelCase_ = number // 10 # Removing the last_digit from the given number
return sum_of_digits
def _snake_case (__lowercase = 100):
UpperCamelCase_ = factorial(__lowercase)
UpperCamelCase_ = split_and_add(__lowercase)
return result
if __name__ == "__main__":
print(solution(int(input("""Enter the Number: """).strip())))
| 23 | 0 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMScheduler,
StableDiffusionAttendAndExcitePipeline,
UNetaDConditionModel,
)
from diffusers.utils import load_numpy, skip_mps, slow
from diffusers.utils.testing_utils import require_torch_gpu
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
__UpperCamelCase : Optional[Any] = False
@skip_mps
class lowerCAmelCase__( snake_case__ , snake_case__ , snake_case__ , unittest.TestCase ):
'''simple docstring'''
A_ : str = StableDiffusionAttendAndExcitePipeline
A_ : Optional[Any] = False
A_ : List[str] = TEXT_TO_IMAGE_PARAMS
A_ : Dict = TEXT_TO_IMAGE_BATCH_PARAMS.union({'token_indices'} )
A_ : Optional[int] = TEXT_TO_IMAGE_IMAGE_PARAMS
A_ : int = TEXT_TO_IMAGE_IMAGE_PARAMS
@classmethod
def _lowerCamelCase ( cls : str ):
'''simple docstring'''
super().setUpClass()
torch.use_deterministic_algorithms(__snake_case )
@classmethod
def _lowerCamelCase ( cls : int ):
'''simple docstring'''
super().tearDownClass()
torch.use_deterministic_algorithms(__snake_case )
def _lowerCamelCase ( self : Optional[int] ):
'''simple docstring'''
torch.manual_seed(0 )
UpperCAmelCase_ : str = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=1 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=__snake_case , )
UpperCAmelCase_ : Dict = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule='''scaled_linear''' , clip_sample=__snake_case , set_alpha_to_one=__snake_case , )
torch.manual_seed(0 )
UpperCAmelCase_ : Optional[int] = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , )
torch.manual_seed(0 )
UpperCAmelCase_ : Any = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , hidden_act='''gelu''' , projection_dim=512 , )
UpperCAmelCase_ : Optional[Any] = CLIPTextModel(__snake_case )
UpperCAmelCase_ : Dict = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
UpperCAmelCase_ : List[Any] = {
'''unet''': unet,
'''scheduler''': scheduler,
'''vae''': vae,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''safety_checker''': None,
'''feature_extractor''': None,
}
return components
def _lowerCamelCase ( self : List[Any] , __snake_case : Optional[Any] , __snake_case : Union[str, Any]=0 ):
'''simple docstring'''
if str(__snake_case ).startswith('''mps''' ):
UpperCAmelCase_ : int = torch.manual_seed(__snake_case )
else:
UpperCAmelCase_ : Optional[int] = torch.Generator(device=__snake_case ).manual_seed(__snake_case )
UpperCAmelCase_ : str = {
'''prompt''': '''a cat and a frog''',
'''token_indices''': [2, 5],
'''generator''': generator,
'''num_inference_steps''': 1,
'''guidance_scale''': 6.0,
'''output_type''': '''numpy''',
'''max_iter_to_alter''': 2,
'''thresholds''': {0: 0.7},
}
return inputs
def _lowerCamelCase ( self : Union[str, Any] ):
'''simple docstring'''
UpperCAmelCase_ : Optional[int] = '''cpu'''
UpperCAmelCase_ : List[Any] = self.get_dummy_components()
UpperCAmelCase_ : Dict = self.pipeline_class(**__snake_case )
pipe.to(__snake_case )
pipe.set_progress_bar_config(disable=__snake_case )
UpperCAmelCase_ : Tuple = self.get_dummy_inputs(__snake_case )
UpperCAmelCase_ : Any = pipe(**__snake_case ).images
UpperCAmelCase_ : Dict = image[0, -3:, -3:, -1]
self.assertEqual(image.shape , (1, 64, 64, 3) )
UpperCAmelCase_ : List[Any] = np.array(
[0.63_905_364, 0.62_897_307, 0.48_599_017, 0.5_133_624, 0.5_550_048, 0.45_769_516, 0.50_326_973, 0.5_023_139, 0.45_384_496] )
UpperCAmelCase_ : Any = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(__snake_case , 1E-3 )
def _lowerCamelCase ( self : Any ):
'''simple docstring'''
super().test_cpu_offload_forward_pass(expected_max_diff=5E-4 )
def _lowerCamelCase ( self : int ):
'''simple docstring'''
# NOTE: Larger batch sizes cause this test to timeout, only test on smaller batches
self._test_inference_batch_consistent(batch_sizes=[1, 2] )
def _lowerCamelCase ( self : Dict ):
'''simple docstring'''
self._test_inference_batch_single_identical(batch_size=2 , expected_max_diff=7E-4 )
def _lowerCamelCase ( self : List[Any] ):
'''simple docstring'''
super().test_dict_tuple_outputs_equivalent(expected_max_difference=3E-3 )
def _lowerCamelCase ( self : Optional[int] ):
'''simple docstring'''
super().test_pt_np_pil_outputs_equivalent(expected_max_diff=5E-4 )
def _lowerCamelCase ( self : Optional[Any] ):
'''simple docstring'''
super().test_save_load_local(expected_max_difference=5E-4 )
def _lowerCamelCase ( self : Optional[Any] ):
'''simple docstring'''
super().test_save_load_optional_components(expected_max_difference=4E-4 )
@require_torch_gpu
@slow
class lowerCAmelCase__( unittest.TestCase ):
'''simple docstring'''
@classmethod
def _lowerCamelCase ( cls : Optional[Any] ):
'''simple docstring'''
super().setUpClass()
torch.use_deterministic_algorithms(__snake_case )
@classmethod
def _lowerCamelCase ( cls : Any ):
'''simple docstring'''
super().tearDownClass()
torch.use_deterministic_algorithms(__snake_case )
def _lowerCamelCase ( self : Tuple ):
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _lowerCamelCase ( self : str ):
'''simple docstring'''
UpperCAmelCase_ : Optional[int] = torch.manual_seed(51 )
UpperCAmelCase_ : Dict = StableDiffusionAttendAndExcitePipeline.from_pretrained(
'''CompVis/stable-diffusion-v1-4''' , safety_checker=__snake_case , torch_dtype=torch.floataa )
pipe.to('''cuda''' )
UpperCAmelCase_ : Tuple = '''a painting of an elephant with glasses'''
UpperCAmelCase_ : Any = [5, 7]
UpperCAmelCase_ : Optional[Any] = pipe(
prompt=__snake_case , token_indices=__snake_case , guidance_scale=7.5 , generator=__snake_case , num_inference_steps=5 , max_iter_to_alter=5 , output_type='''numpy''' , ).images[0]
UpperCAmelCase_ : Union[str, Any] = load_numpy(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/attend-and-excite/elephant_glasses.npy''' )
assert np.abs((expected_image - image).max() ) < 5E-1 | 641 |
import fire
from utils import calculate_rouge, save_json
def snake_case_ ( __lowercase , __lowercase , __lowercase=None , **__lowercase ):
UpperCAmelCase_ : Tuple = [x.strip() for x in open(__lowercase ).readlines()]
UpperCAmelCase_ : Dict = [x.strip() for x in open(__lowercase ).readlines()][: len(__lowercase )]
UpperCAmelCase_ : int = calculate_rouge(__lowercase , __lowercase , **__lowercase )
if save_path is not None:
save_json(__lowercase , __lowercase , indent=__lowercase )
return metrics # these print nicely
if __name__ == "__main__":
fire.Fire(calculate_rouge_path) | 641 | 1 |
from typing import Optional, Tuple, Union
import torch
from einops import rearrange, reduce
from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel
from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput
SCREAMING_SNAKE_CASE : Optional[int] = 8
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_=BITS ) -> List[Any]:
_lowercase : List[str] = x.device
_lowercase : Union[str, Any] = (x * 255).int().clamp(0 , 255 )
_lowercase : List[str] = 2 ** torch.arange(bits - 1 , -1 , -1 , device=lowerCamelCase_ )
_lowercase : Union[str, Any] = rearrange(lowerCamelCase_ , 'd -> d 1 1' )
_lowercase : Union[str, Any] = rearrange(lowerCamelCase_ , 'b c h w -> b c 1 h w' )
_lowercase : Union[str, Any] = ((x & mask) != 0).float()
_lowercase : Dict = rearrange(lowerCamelCase_ , 'b c d h w -> b (c d) h w' )
_lowercase : Tuple = bits * 2 - 1
return bits
def UpperCamelCase_( lowerCamelCase_ , lowerCamelCase_=BITS ) -> Dict:
_lowercase : List[Any] = x.device
_lowercase : List[Any] = (x > 0).int()
_lowercase : Tuple = 2 ** torch.arange(bits - 1 , -1 , -1 , device=lowerCamelCase_ , dtype=torch.intaa )
_lowercase : List[str] = rearrange(lowerCamelCase_ , 'd -> d 1 1' )
_lowercase : Tuple = rearrange(lowerCamelCase_ , 'b (c d) h w -> b c d h w' , d=8 )
_lowercase : Optional[int] = reduce(x * mask , 'b c d h w -> b c h w' , 'sum' )
return (dec / 255).clamp(0.0 , 1.0 )
def UpperCamelCase_( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = 0.0 , lowerCamelCase_ = True , lowerCamelCase_=None , lowerCamelCase_ = True , ) -> Union[DDIMSchedulerOutput, Tuple]:
if self.num_inference_steps is None:
raise ValueError(
'Number of inference steps is \'None\', you need to run \'set_timesteps\' after creating the scheduler' )
# See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
# Ideally, read DDIM paper in-detail understanding
# Notation (<variable name> -> <name in paper>
# - pred_noise_t -> e_theta(x_t, t)
# - pred_original_sample -> f_theta(x_t, t) or x_0
# - std_dev_t -> sigma_t
# - eta -> η
# - pred_sample_direction -> "direction pointing to x_t"
# - pred_prev_sample -> "x_t-1"
# 1. get previous step value (=t-1)
_lowercase : Optional[int] = timestep - self.config.num_train_timesteps // self.num_inference_steps
# 2. compute alphas, betas
_lowercase : int = self.alphas_cumprod[timestep]
_lowercase : Optional[Any] = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
_lowercase : Optional[int] = 1 - alpha_prod_t
# 3. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_lowercase : List[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
# 4. Clip "predicted x_0"
_lowercase : Any = self.bit_scale
if self.config.clip_sample:
_lowercase : str = torch.clamp(lowerCamelCase_ , -scale , lowerCamelCase_ )
# 5. compute variance: "sigma_t(η)" -> see formula (16)
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
_lowercase : Dict = self._get_variance(lowerCamelCase_ , lowerCamelCase_ )
_lowercase : Union[str, Any] = eta * variance ** 0.5
if use_clipped_model_output:
# the model_output is always re-derived from the clipped x_0 in Glide
_lowercase : str = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_lowercase : Tuple = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output
# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
_lowercase : Optional[Any] = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
if eta > 0:
# randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
_lowercase : List[str] = model_output.device if torch.is_tensor(lowerCamelCase_ ) else 'cpu'
_lowercase : List[Any] = torch.randn(model_output.shape , dtype=model_output.dtype , generator=lowerCamelCase_ ).to(lowerCamelCase_ )
_lowercase : Union[str, Any] = self._get_variance(lowerCamelCase_ , lowerCamelCase_ ) ** 0.5 * eta * noise
_lowercase : Optional[Any] = prev_sample + variance
if not return_dict:
return (prev_sample,)
return DDIMSchedulerOutput(prev_sample=lowerCamelCase_ , pred_original_sample=lowerCamelCase_ )
def UpperCamelCase_( self , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_="epsilon" , lowerCamelCase_=None , lowerCamelCase_ = True , ) -> Union[DDPMSchedulerOutput, Tuple]:
_lowercase : Union[str, Any] = timestep
if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
_lowercase , _lowercase : Union[str, Any] = torch.split(lowerCamelCase_ , sample.shape[1] , dim=1 )
else:
_lowercase : Optional[int] = None
# 1. compute alphas, betas
_lowercase : Union[str, Any] = self.alphas_cumprod[t]
_lowercase : Dict = self.alphas_cumprod[t - 1] if t > 0 else self.one
_lowercase : Tuple = 1 - alpha_prod_t
_lowercase : str = 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 prediction_type == "epsilon":
_lowercase : List[Any] = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif prediction_type == "sample":
_lowercase : str = model_output
else:
raise ValueError(F'''Unsupported prediction_type {prediction_type}.''' )
# 3. Clip "predicted x_0"
_lowercase : Union[str, Any] = self.bit_scale
if self.config.clip_sample:
_lowercase : List[str] = torch.clamp(lowerCamelCase_ , -scale , lowerCamelCase_ )
# 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
_lowercase : List[Any] = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t
_lowercase : Optional[Any] = self.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
_lowercase : int = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
_lowercase : int = 0
if t > 0:
_lowercase : Union[str, Any] = torch.randn(
model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=lowerCamelCase_ ).to(model_output.device )
_lowercase : Tuple = (self._get_variance(lowerCamelCase_ , predicted_variance=lowerCamelCase_ ) ** 0.5) * noise
_lowercase : List[Any] = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample,)
return DDPMSchedulerOutput(prev_sample=lowerCamelCase_ , pred_original_sample=lowerCamelCase_ )
class _lowerCamelCase( _a ):
def __init__( self, lowerCamelCase, lowerCamelCase, lowerCamelCase = 1.0, ) -> Union[str, Any]:
"""simple docstring"""
super().__init__()
_lowercase : str = bit_scale
_lowercase : Dict = (
ddim_bit_scheduler_step if isinstance(lowerCamelCase, lowerCamelCase) else ddpm_bit_scheduler_step
)
self.register_modules(unet=lowerCamelCase, scheduler=lowerCamelCase)
@torch.no_grad()
def __call__( self, lowerCamelCase = 2_56, lowerCamelCase = 2_56, lowerCamelCase = 50, lowerCamelCase = None, lowerCamelCase = 1, lowerCamelCase = "pil", lowerCamelCase = True, **lowerCamelCase, ) -> Union[Tuple, ImagePipelineOutput]:
"""simple docstring"""
_lowercase : Optional[Any] = torch.randn(
(batch_size, self.unet.config.in_channels, height, width), generator=lowerCamelCase, )
_lowercase : Optional[int] = decimal_to_bits(lowerCamelCase) * self.bit_scale
_lowercase : Tuple = latents.to(self.device)
self.scheduler.set_timesteps(lowerCamelCase)
for t in self.progress_bar(self.scheduler.timesteps):
# predict the noise residual
_lowercase : List[str] = self.unet(lowerCamelCase, lowerCamelCase).sample
# compute the previous noisy sample x_t -> x_t-1
_lowercase : Tuple = self.scheduler.step(lowerCamelCase, lowerCamelCase, lowerCamelCase).prev_sample
_lowercase : Optional[Any] = bits_to_decimal(lowerCamelCase)
if output_type == "pil":
_lowercase : Any = self.numpy_to_pil(lowerCamelCase)
if not return_dict:
return (image,)
return ImagePipelineOutput(images=lowerCamelCase)
| 89 |
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional
import datasets
import numpy as np
import pandas as pd
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
BartForSequenceClassification,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
TapexTokenizer,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.17.0.dev0")
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/text-classification/requirements.txt")
SCREAMING_SNAKE_CASE : Dict = logging.getLogger(__name__)
@dataclass
class _lowerCamelCase:
lowercase_ : Optional[str] = field(
default="""tab_fact""", metadata={"""help""": """The name of the dataset to use (via the datasets library)."""} )
lowercase_ : Optional[str] = field(
default="""tab_fact""", metadata={"""help""": """The configuration name of the dataset to use (via the datasets library)."""}, )
lowercase_ : int = field(
default=10_24, metadata={
"""help""": (
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
)
}, )
lowercase_ : bool = field(
default=_a, metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""} )
lowercase_ : bool = field(
default=_a, metadata={
"""help""": (
"""Whether to pad all samples to `max_seq_length`. """
"""If False, will pad the samples dynamically when batching to the maximum length in the batch."""
)
}, )
lowercase_ : Optional[int] = field(
default=_a, metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of training examples to this """
"""value if set."""
)
}, )
lowercase_ : Optional[int] = field(
default=_a, metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of evaluation examples to this """
"""value if set."""
)
}, )
lowercase_ : Optional[int] = field(
default=_a, metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of prediction examples to this """
"""value if set."""
)
}, )
lowercase_ : Optional[str] = field(
default=_a, metadata={"""help""": """A csv or a json file containing the training data."""} )
lowercase_ : Optional[str] = field(
default=_a, metadata={"""help""": """A csv or a json file containing the validation data."""} )
lowercase_ : Optional[str] = field(default=_a, metadata={"""help""": """A csv or a json file containing the test data."""} )
def UpperCamelCase ( self) -> Dict:
"""simple docstring"""
if self.dataset_name is not None:
pass
elif self.train_file is None or self.validation_file is None:
raise ValueError('Need either a GLUE task, a training/validation file or a dataset name.')
else:
_lowercase : int = self.train_file.split('.')[-1]
assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file."
_lowercase : Tuple = self.validation_file.split('.')[-1]
assert (
validation_extension == train_extension
), "`validation_file` should have the same extension (csv or json) as `train_file`."
@dataclass
class _lowerCamelCase:
lowercase_ : str = field(
default=_a, metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
lowercase_ : Optional[str] = field(
default=_a, metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
lowercase_ : Optional[str] = field(
default=_a, metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
lowercase_ : Optional[str] = field(
default=_a, metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""}, )
lowercase_ : bool = field(
default=_a, metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""}, )
lowercase_ : str = field(
default="""main""", metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""}, )
lowercase_ : bool = field(
default=_a, metadata={
"""help""": (
"""Will use the token generated when running `huggingface-cli login` (necessary to use this script """
"""with private models)."""
)
}, )
def UpperCamelCase_( ) -> Optional[int]:
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
_lowercase : Optional[int] = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith('.json' ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
_lowercase , _lowercase , _lowercase : Tuple = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
_lowercase , _lowercase , _lowercase : Union[str, Any] = parser.parse_args_into_dataclasses()
# Setup logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , )
_lowercase : Union[str, Any] = training_args.get_process_log_level()
logger.setLevel(lowerCamelCase_ )
datasets.utils.logging.set_verbosity(lowerCamelCase_ )
transformers.utils.logging.set_verbosity(lowerCamelCase_ )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
+ F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' )
logger.info(F'''Training/evaluation parameters {training_args}''' )
# Detecting last checkpoint.
_lowercase : Optional[int] = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
_lowercase : Dict = get_last_checkpoint(training_args.output_dir )
if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
raise ValueError(
F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
'Use --overwrite_output_dir to overcome.' )
elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
logger.info(
F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' )
# Set seed before initializing model.
set_seed(training_args.seed )
# Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below)
# or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub).
#
# For JSON files, this script will use the `question` column for the input question and `table` column for the corresponding table.
#
# If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this
# single column. You can easily tweak this behavior (see below)
#
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
# download the dataset.
if data_args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
_lowercase : Dict = load_dataset(
data_args.dataset_name , data_args.dataset_config_name , cache_dir=model_args.cache_dir )
else:
# Loading a dataset from your local files.
# CSV/JSON training and evaluation files are needed.
_lowercase : Optional[Any] = {'train': data_args.train_file, 'validation': data_args.validation_file}
# Get the test dataset: you can provide your own CSV/JSON test file (see below)
# when you use `do_predict` without specifying a GLUE benchmark task.
if training_args.do_predict:
if data_args.test_file is not None:
_lowercase : Tuple = data_args.train_file.split('.' )[-1]
_lowercase : int = data_args.test_file.split('.' )[-1]
assert (
test_extension == train_extension
), "`test_file` should have the same extension (csv or json) as `train_file`."
_lowercase : Any = data_args.test_file
else:
raise ValueError('Need either a GLUE task or a test file for `do_predict`.' )
for key in data_files.keys():
logger.info(F'''load a local file for {key}: {data_files[key]}''' )
if data_args.train_file.endswith('.csv' ):
# Loading a dataset from local csv files
_lowercase : str = load_dataset('csv' , data_files=lowerCamelCase_ , cache_dir=model_args.cache_dir )
else:
# Loading a dataset from local json files
_lowercase : Optional[int] = load_dataset('json' , data_files=lowerCamelCase_ , cache_dir=model_args.cache_dir )
# See more about loading any type of standard or custom dataset at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Labels
_lowercase : Optional[Any] = raw_datasets['train'].features['label'].names
_lowercase : Any = len(lowerCamelCase_ )
# Load pretrained model and tokenizer
#
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
_lowercase : List[Any] = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=lowerCamelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
# load tapex tokenizer
_lowercase : str = TapexTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , add_prefix_space=lowerCamelCase_ , )
_lowercase : Tuple = BartForSequenceClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=lowerCamelCase_ , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
# Padding strategy
if data_args.pad_to_max_length:
_lowercase : int = 'max_length'
else:
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
_lowercase : str = False
# Some models have set the order of the labels to use, so let's make sure we do use it.
_lowercase : List[Any] = {'Refused': 0, 'Entailed': 1}
_lowercase : Union[str, Any] = {0: 'Refused', 1: 'Entailed'}
if data_args.max_seq_length > tokenizer.model_max_length:
logger.warning(
F'''The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the'''
F'''model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}.''' )
_lowercase : List[str] = min(data_args.max_seq_length , tokenizer.model_max_length )
def preprocess_tabfact_function(lowerCamelCase_ ):
# Tokenize the texts
def _convert_table_text_to_pandas(lowerCamelCase_ ):
_lowercase : int = [_table_row.split('#' ) for _table_row in _table_text.strip('\n' ).split('\n' )]
_lowercase : Any = pd.DataFrame.from_records(_table_content[1:] , columns=_table_content[0] )
return _table_pd
_lowercase : List[Any] = examples['statement']
_lowercase : Optional[Any] = list(map(_convert_table_text_to_pandas , examples['table_text'] ) )
_lowercase : Union[str, Any] = tokenizer(lowerCamelCase_ , lowerCamelCase_ , padding=lowerCamelCase_ , max_length=lowerCamelCase_ , truncation=lowerCamelCase_ )
_lowercase : Any = examples['label']
return result
with training_args.main_process_first(desc='dataset map pre-processing' ):
_lowercase : str = raw_datasets.map(
lowerCamelCase_ , batched=lowerCamelCase_ , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on dataset' , )
if training_args.do_train:
if "train" not in raw_datasets:
raise ValueError('--do_train requires a train dataset' )
_lowercase : Any = raw_datasets['train']
if data_args.max_train_samples is not None:
_lowercase : str = train_dataset.select(range(data_args.max_train_samples ) )
if training_args.do_eval:
if "validation" not in raw_datasets and "validation_matched" not in raw_datasets:
raise ValueError('--do_eval requires a validation dataset' )
_lowercase : str = raw_datasets['validation']
if data_args.max_eval_samples is not None:
_lowercase : List[Any] = eval_dataset.select(range(data_args.max_eval_samples ) )
if training_args.do_predict or data_args.test_file is not None:
if "test" not in raw_datasets and "test_matched" not in raw_datasets:
raise ValueError('--do_predict requires a test dataset' )
_lowercase : Optional[int] = raw_datasets['test']
if data_args.max_predict_samples is not None:
_lowercase : List[str] = predict_dataset.select(range(data_args.max_predict_samples ) )
# Log a few random samples from the training set:
if training_args.do_train:
for index in random.sample(range(len(lowerCamelCase_ ) ) , 3 ):
logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.''' )
# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
# predictions and label_ids field) and has to return a dictionary string to float.
def compute_metrics(lowerCamelCase_ ):
_lowercase : Dict = p.predictions[0] if isinstance(p.predictions , lowerCamelCase_ ) else p.predictions
_lowercase : Tuple = np.argmax(lowerCamelCase_ , axis=1 )
return {"accuracy": (preds == p.label_ids).astype(np.floataa ).mean().item()}
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
if data_args.pad_to_max_length:
_lowercase : Any = default_data_collator
elif training_args.fpaa:
_lowercase : str = DataCollatorWithPadding(lowerCamelCase_ , pad_to_multiple_of=8 )
else:
_lowercase : Optional[Any] = None
# Initialize our Trainer
_lowercase : List[str] = Trainer(
model=lowerCamelCase_ , args=lowerCamelCase_ , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=lowerCamelCase_ , tokenizer=lowerCamelCase_ , data_collator=lowerCamelCase_ , )
# Training
if training_args.do_train:
_lowercase : Optional[int] = None
if training_args.resume_from_checkpoint is not None:
_lowercase : List[Any] = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
_lowercase : Optional[Any] = last_checkpoint
_lowercase : Optional[Any] = trainer.train(resume_from_checkpoint=lowerCamelCase_ )
_lowercase : List[Any] = train_result.metrics
_lowercase : Dict = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(lowerCamelCase_ )
)
_lowercase : int = min(lowerCamelCase_ , len(lowerCamelCase_ ) )
trainer.save_model() # Saves the tokenizer too for easy upload
trainer.log_metrics('train' , lowerCamelCase_ )
trainer.save_metrics('train' , lowerCamelCase_ )
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info('*** Evaluate ***' )
_lowercase : Tuple = trainer.evaluate(eval_dataset=lowerCamelCase_ )
_lowercase : Any = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(lowerCamelCase_ )
_lowercase : Optional[int] = min(lowerCamelCase_ , len(lowerCamelCase_ ) )
trainer.log_metrics('eval' , lowerCamelCase_ )
trainer.save_metrics('eval' , lowerCamelCase_ )
if training_args.do_predict:
logger.info('*** Predict ***' )
# Removing the `label` columns because it contains -1 and Trainer won't like that.
_lowercase : Any = predict_dataset.remove_columns('label' )
_lowercase : Optional[Any] = trainer.predict(lowerCamelCase_ , metric_key_prefix='predict' ).predictions
_lowercase : Union[str, Any] = np.argmax(lowerCamelCase_ , axis=1 )
_lowercase : Dict = os.path.join(training_args.output_dir , 'predict_results_tabfact.txt' )
if trainer.is_world_process_zero():
with open(lowerCamelCase_ , 'w' ) as writer:
logger.info('***** Predict Results *****' )
writer.write('index\tprediction\n' )
for index, item in enumerate(lowerCamelCase_ ):
_lowercase : List[str] = label_list[item]
writer.write(F'''{index}\t{item}\n''' )
_lowercase : str = {'finetuned_from': model_args.model_name_or_path, 'tasks': 'text-classification'}
if training_args.push_to_hub:
trainer.push_to_hub(**lowerCamelCase_ )
else:
trainer.create_model_card(**lowerCamelCase_ )
def UpperCamelCase_( lowerCamelCase_ ) -> Dict:
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main()
| 89 | 1 |
"""simple docstring"""
import copy
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Optional, Union
@dataclass
class UpperCamelCase :
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Optional[Union[str, Path]] = None
SCREAMING_SNAKE_CASE_ : bool = False
SCREAMING_SNAKE_CASE_ : bool = False
SCREAMING_SNAKE_CASE_ : bool = False
SCREAMING_SNAKE_CASE_ : Optional[Dict] = None
SCREAMING_SNAKE_CASE_ : Optional[str] = None
SCREAMING_SNAKE_CASE_ : bool = False
SCREAMING_SNAKE_CASE_ : bool = False
SCREAMING_SNAKE_CASE_ : bool = False
SCREAMING_SNAKE_CASE_ : bool = True
SCREAMING_SNAKE_CASE_ : Optional[int] = None
SCREAMING_SNAKE_CASE_ : int = 1
SCREAMING_SNAKE_CASE_ : Optional[Union[str, bool]] = None
SCREAMING_SNAKE_CASE_ : bool = False
SCREAMING_SNAKE_CASE_ : Optional[Dict] = None
SCREAMING_SNAKE_CASE_ : Optional[str] = None
def lowerCamelCase__ ( self ):
return self.__class__(**{k: copy.deepcopy(UpperCAmelCase_ ) for k, v in self.__dict__.items()} )
| 720 |
"""simple docstring"""
from pathlib import Path
import fire
from tqdm import tqdm
def __SCREAMING_SNAKE_CASE ( __UpperCAmelCase="ro" , __UpperCAmelCase="en" , __UpperCAmelCase="wmt16" , __UpperCAmelCase=None ):
try:
import datasets
except (ModuleNotFoundError, ImportError):
raise ImportError("""run pip install datasets""" )
_lowercase : Optional[int] = F"""{src_lang}-{tgt_lang}"""
print(F"""Converting {dataset}-{pair}""" )
_lowercase : Tuple = datasets.load_dataset(__UpperCAmelCase , __UpperCAmelCase )
if save_dir is None:
_lowercase : List[str] = F"""{dataset}-{pair}"""
_lowercase : Union[str, Any] = Path(__UpperCAmelCase )
save_dir.mkdir(exist_ok=__UpperCAmelCase )
for split in ds.keys():
print(F"""Splitting {split} with {ds[split].num_rows} records""" )
# to save to val.source, val.target like summary datasets
_lowercase : List[Any] = """val""" if split == """validation""" else split
_lowercase : List[Any] = save_dir.joinpath(F"""{fn}.source""" )
_lowercase : List[Any] = save_dir.joinpath(F"""{fn}.target""" )
_lowercase : List[Any] = src_path.open("""w+""" )
_lowercase : Optional[int] = tgt_path.open("""w+""" )
# reader is the bottleneck so writing one record at a time doesn't slow things down
for x in tqdm(ds[split] ):
_lowercase : Dict = x["""translation"""]
src_fp.write(ex[src_lang] + """\n""" )
tgt_fp.write(ex[tgt_lang] + """\n""" )
print(F"""Saved {dataset} dataset to {save_dir}""" )
if __name__ == "__main__":
fire.Fire(download_wmt_dataset)
| 600 | 0 |
'''simple docstring'''
import unittest
import numpy as np
from transformers import BertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
if is_flax_available():
from transformers.models.bert.modeling_flax_bert import (
FlaxBertForMaskedLM,
FlaxBertForMultipleChoice,
FlaxBertForNextSentencePrediction,
FlaxBertForPreTraining,
FlaxBertForQuestionAnswering,
FlaxBertForSequenceClassification,
FlaxBertForTokenClassification,
FlaxBertModel,
)
class a__ ( unittest.TestCase ):
'''simple docstring'''
def __init__( self , lowerCamelCase_ , lowerCamelCase_=13 , lowerCamelCase_=7 , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=True , lowerCamelCase_=99 , lowerCamelCase_=32 , lowerCamelCase_=5 , lowerCamelCase_=4 , lowerCamelCase_=37 , lowerCamelCase_="gelu" , lowerCamelCase_=0.1 , lowerCamelCase_=0.1 , lowerCamelCase_=5_12 , lowerCamelCase_=16 , lowerCamelCase_=2 , lowerCamelCase_=0.02 , lowerCamelCase_=4 , ) -> List[Any]:
lowerCAmelCase__ = parent
lowerCAmelCase__ = batch_size
lowerCAmelCase__ = seq_length
lowerCAmelCase__ = is_training
lowerCAmelCase__ = use_attention_mask
lowerCAmelCase__ = use_token_type_ids
lowerCAmelCase__ = use_labels
lowerCAmelCase__ = vocab_size
lowerCAmelCase__ = hidden_size
lowerCAmelCase__ = num_hidden_layers
lowerCAmelCase__ = num_attention_heads
lowerCAmelCase__ = intermediate_size
lowerCAmelCase__ = hidden_act
lowerCAmelCase__ = hidden_dropout_prob
lowerCAmelCase__ = attention_probs_dropout_prob
lowerCAmelCase__ = max_position_embeddings
lowerCAmelCase__ = type_vocab_size
lowerCAmelCase__ = type_sequence_label_size
lowerCAmelCase__ = initializer_range
lowerCAmelCase__ = num_choices
def __SCREAMING_SNAKE_CASE ( self ) -> str:
lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
lowerCAmelCase__ = None
if self.use_attention_mask:
lowerCAmelCase__ = random_attention_mask([self.batch_size, self.seq_length] )
lowerCAmelCase__ = None
if self.use_token_type_ids:
lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
lowerCAmelCase__ = BertConfig(
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 , )
return config, input_ids, token_type_ids, attention_mask
def __SCREAMING_SNAKE_CASE ( self ) -> Optional[int]:
lowerCAmelCase__ = self.prepare_config_and_inputs()
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs
lowerCAmelCase__ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': attention_mask}
return config, inputs_dict
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
lowerCAmelCase__ = self.prepare_config_and_inputs()
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = config_and_inputs
lowerCAmelCase__ = True
lowerCAmelCase__ = floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
lowerCAmelCase__ = ids_tensor([self.batch_size, self.seq_length] , vocab_size=2 )
return (
config,
input_ids,
attention_mask,
encoder_hidden_states,
encoder_attention_mask,
)
@require_flax
class a__ ( a__ , unittest.TestCase ):
'''simple docstring'''
lowercase__ : Dict = True
lowercase__ : str = (
(
FlaxBertModel,
FlaxBertForPreTraining,
FlaxBertForMaskedLM,
FlaxBertForMultipleChoice,
FlaxBertForQuestionAnswering,
FlaxBertForNextSentencePrediction,
FlaxBertForSequenceClassification,
FlaxBertForTokenClassification,
FlaxBertForQuestionAnswering,
)
if is_flax_available()
else ()
)
def __SCREAMING_SNAKE_CASE ( self ) -> Tuple:
lowerCAmelCase__ = FlaxBertModelTester(self )
@slow
def __SCREAMING_SNAKE_CASE ( self ) -> str:
# Only check this for base model, not necessary for all model classes.
# This will also help speed-up tests.
lowerCAmelCase__ = FlaxBertModel.from_pretrained('''bert-base-cased''' )
lowerCAmelCase__ = model(np.ones((1, 1) ) )
self.assertIsNotNone(lowerCamelCase_ ) | 90 |
"""simple docstring"""
from ..utils import DummyObject, requires_backends
class _UpperCamelCase ( metaclass=__snake_case):
__lowerCamelCase = ["torch", "torchsde"]
def __init__(self , *lowerCamelCase__ , **lowerCamelCase__ ):
"""simple docstring"""
requires_backends(self , ["""torch""", """torchsde"""] )
@classmethod
def A (cls , *lowerCamelCase__ , **lowerCamelCase__ ):
"""simple docstring"""
requires_backends(cls , ["""torch""", """torchsde"""] )
@classmethod
def A (cls , *lowerCamelCase__ , **lowerCamelCase__ ):
"""simple docstring"""
requires_backends(cls , ["""torch""", """torchsde"""] )
| 574 | 0 |
"""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()
| 714 | """simple docstring"""
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
)
lowercase__ = {
'configuration_distilbert': [
'DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP',
'DistilBertConfig',
'DistilBertOnnxConfig',
],
'tokenization_distilbert': ['DistilBertTokenizer'],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ = ['DistilBertTokenizerFast']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ = [
'DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
'DistilBertForMaskedLM',
'DistilBertForMultipleChoice',
'DistilBertForQuestionAnswering',
'DistilBertForSequenceClassification',
'DistilBertForTokenClassification',
'DistilBertModel',
'DistilBertPreTrainedModel',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ = [
'TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFDistilBertForMaskedLM',
'TFDistilBertForMultipleChoice',
'TFDistilBertForQuestionAnswering',
'TFDistilBertForSequenceClassification',
'TFDistilBertForTokenClassification',
'TFDistilBertMainLayer',
'TFDistilBertModel',
'TFDistilBertPreTrainedModel',
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
lowercase__ = [
'FlaxDistilBertForMaskedLM',
'FlaxDistilBertForMultipleChoice',
'FlaxDistilBertForQuestionAnswering',
'FlaxDistilBertForSequenceClassification',
'FlaxDistilBertForTokenClassification',
'FlaxDistilBertModel',
'FlaxDistilBertPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_distilbert import (
DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
DistilBertConfig,
DistilBertOnnxConfig,
)
from .tokenization_distilbert import DistilBertTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_distilbert_fast import DistilBertTokenizerFast
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_distilbert import (
DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
DistilBertForMaskedLM,
DistilBertForMultipleChoice,
DistilBertForQuestionAnswering,
DistilBertForSequenceClassification,
DistilBertForTokenClassification,
DistilBertModel,
DistilBertPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_distilbert import (
TF_DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDistilBertForMaskedLM,
TFDistilBertForMultipleChoice,
TFDistilBertForQuestionAnswering,
TFDistilBertForSequenceClassification,
TFDistilBertForTokenClassification,
TFDistilBertMainLayer,
TFDistilBertModel,
TFDistilBertPreTrainedModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_distilbert import (
FlaxDistilBertForMaskedLM,
FlaxDistilBertForMultipleChoice,
FlaxDistilBertForQuestionAnswering,
FlaxDistilBertForSequenceClassification,
FlaxDistilBertForTokenClassification,
FlaxDistilBertModel,
FlaxDistilBertPreTrainedModel,
)
else:
import sys
lowercase__ = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 217 | 0 |
import heapq
import sys
import numpy as np
_lowerCamelCase : str = tuple[int, int]
class SCREAMING_SNAKE_CASE__ :
'''simple docstring'''
def __init__( self : Optional[Any] ):
'''simple docstring'''
_snake_case = []
_snake_case = set()
def A ( self : List[Any] ):
'''simple docstring'''
if not self.empty():
return self.elements[0][0]
else:
return float('inf' )
def A ( self : Any ):
'''simple docstring'''
return len(self.elements ) == 0
def A ( self : List[Any] , lowercase : Dict , lowercase : List[str] ):
'''simple docstring'''
if item not in self.set:
heapq.heappush(self.elements , (priority, item) )
self.set.add(a_ )
else:
# update
# print("update", item)
_snake_case = []
(_snake_case) = heapq.heappop(self.elements )
while x != item:
temp.append((pri, x) )
(_snake_case) = heapq.heappop(self.elements )
temp.append((priority, item) )
for pro, xxx in temp:
heapq.heappush(self.elements , (pro, xxx) )
def A ( self : List[str] , lowercase : Dict ):
'''simple docstring'''
if item in self.set:
self.set.remove(a_ )
_snake_case = []
(_snake_case) = heapq.heappop(self.elements )
while x != item:
temp.append((pro, x) )
(_snake_case) = heapq.heappop(self.elements )
for prito, yyy in temp:
heapq.heappush(self.elements , (prito, yyy) )
def A ( self : Dict ):
'''simple docstring'''
return self.elements[0][1]
def A ( self : str ):
'''simple docstring'''
(_snake_case) = heapq.heappop(self.elements )
self.set.remove(a_ )
return (priority, item)
def a_ ( __lowercase : TPos , __lowercase : TPos ) -> List[Any]:
_snake_case = np.array(lowerCAmelCase__ )
_snake_case = np.array(lowerCAmelCase__ )
return np.linalg.norm(a - b )
def a_ ( __lowercase : TPos , __lowercase : TPos ) -> Any:
return consistent_heuristic(lowerCAmelCase__ , lowerCAmelCase__ ) // t
def a_ ( __lowercase : TPos , __lowercase : TPos ) -> List[Any]:
return abs(p[0] - goal[0] ) + abs(p[1] - goal[1] )
def a_ ( __lowercase : TPos , __lowercase : int , __lowercase : TPos , __lowercase : dict[TPos, float] ) -> List[str]:
_snake_case = g_function[start] + Wa * heuristics[i](lowerCAmelCase__ , lowerCAmelCase__ )
return ans
def a_ ( __lowercase : Tuple , __lowercase : Any , __lowercase : Tuple ) -> Optional[Any]:
_snake_case = np.chararray((n, n) )
for i in range(lowerCAmelCase__ ):
for j in range(lowerCAmelCase__ ):
_snake_case = "*"
for i in range(lowerCAmelCase__ ):
for j in range(lowerCAmelCase__ ):
if (j, (n - 1) - i) in blocks:
_snake_case = "#"
_snake_case = "-"
_snake_case = back_pointer[goal]
while x != start:
(_snake_case) = x
# print(x)
_snake_case = "-"
_snake_case = back_pointer[x]
_snake_case = "-"
for i in range(lowerCAmelCase__ ):
for j in range(lowerCAmelCase__ ):
if (i, j) == (0, n - 1):
print(grid[i][j] , end=' ' )
print('<-- End position' , end=' ' )
else:
print(grid[i][j] , end=' ' )
print()
print('^' )
print('Start position' )
print()
print('# is an obstacle' )
print('- is the path taken by algorithm' )
print('PATH TAKEN BY THE ALGORITHM IS:-' )
_snake_case = back_pointer[goal]
while x != start:
print(lowerCAmelCase__ , end=' ' )
_snake_case = back_pointer[x]
print(lowerCAmelCase__ )
sys.exit()
def a_ ( __lowercase : TPos ) -> Dict:
if p[0] < 0 or p[0] > n - 1:
return False
if p[1] < 0 or p[1] > n - 1:
return False
return True
def a_ ( __lowercase : Union[str, Any] , __lowercase : List[str] , __lowercase : Tuple , __lowercase : Tuple , __lowercase : List[str] , __lowercase : List[Any] , __lowercase : Dict , __lowercase : List[str] , ) -> List[str]:
for itera in range(lowerCAmelCase__ ):
open_list[itera].remove_element(lowerCAmelCase__ )
# print("s", s)
# print("j", j)
(_snake_case) = s
_snake_case = (x - 1, y)
_snake_case = (x + 1, y)
_snake_case = (x, y + 1)
_snake_case = (x, y - 1)
for neighbours in [left, right, up, down]:
if neighbours not in blocks:
if valid(lowerCAmelCase__ ) and neighbours not in visited:
# print("neighbour", neighbours)
visited.add(lowerCAmelCase__ )
_snake_case = -1
_snake_case = float('inf' )
if valid(lowerCAmelCase__ ) and g_function[neighbours] > g_function[s] + 1:
_snake_case = g_function[s] + 1
_snake_case = s
if neighbours not in close_list_anchor:
open_list[0].put(lowerCAmelCase__ , key(lowerCAmelCase__ , 0 , lowerCAmelCase__ , lowerCAmelCase__ ) )
if neighbours not in close_list_inad:
for var in range(1 , lowerCAmelCase__ ):
if key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) <= Wa * key(
lowerCAmelCase__ , 0 , lowerCAmelCase__ , lowerCAmelCase__ ):
open_list[j].put(
lowerCAmelCase__ , key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) )
def a_ ( ) -> List[str]:
_snake_case = []
for x in range(1 , 5 ):
for y in range(1 , 6 ):
some_list.append((x, y) )
for x in range(15 , 20 ):
some_list.append((x, 17) )
for x in range(10 , 19 ):
for y in range(1 , 15 ):
some_list.append((x, y) )
# L block
for x in range(1 , 4 ):
for y in range(12 , 19 ):
some_list.append((x, y) )
for x in range(3 , 13 ):
for y in range(16 , 19 ):
some_list.append((x, y) )
return some_list
_lowerCamelCase : Optional[Any] = {0: consistent_heuristic, 1: heuristic_a, 2: heuristic_a}
_lowerCamelCase : Union[str, Any] = [
(0, 1),
(1, 1),
(2, 1),
(3, 1),
(4, 1),
(5, 1),
(6, 1),
(7, 1),
(8, 1),
(9, 1),
(10, 1),
(11, 1),
(12, 1),
(13, 1),
(14, 1),
(15, 1),
(16, 1),
(17, 1),
(18, 1),
(19, 1),
]
_lowerCamelCase : Optional[Any] = make_common_ground()
_lowerCamelCase : Optional[int] = blocks_blk
# hyper parameters
_lowerCamelCase : Dict = 1
_lowerCamelCase : str = 1
_lowerCamelCase : List[str] = 20
_lowerCamelCase : Tuple = 3 # one consistent and two other inconsistent
# start and end destination
_lowerCamelCase : Union[str, Any] = (0, 0)
_lowerCamelCase : Optional[Any] = (n - 1, n - 1)
_lowerCamelCase : List[Any] = 1
def a_ ( __lowercase : TPos , __lowercase : TPos , __lowercase : int ) -> Dict:
_snake_case = {start: 0, goal: float('inf' )}
_snake_case = {start: -1, goal: -1}
_snake_case = []
_snake_case = set()
for i in range(lowerCAmelCase__ ):
open_list.append(PriorityQueue() )
open_list[i].put(lowerCAmelCase__ , key(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ ) )
_snake_case = []
_snake_case = []
while open_list[0].minkey() < float('inf' ):
for i in range(1 , lowerCAmelCase__ ):
# print(open_list[0].minkey(), open_list[i].minkey())
if open_list[i].minkey() <= Wa * open_list[0].minkey():
global t
t += 1
if g_function[goal] <= open_list[i].minkey():
if g_function[goal] < float('inf' ):
do_something(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
else:
_snake_case = open_list[i].top_show()
visited.add(lowerCAmelCase__ )
expand_state(
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , )
close_list_inad.append(lowerCAmelCase__ )
else:
if g_function[goal] <= open_list[0].minkey():
if g_function[goal] < float('inf' ):
do_something(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
else:
_snake_case = open_list[0].top_show()
visited.add(lowerCAmelCase__ )
expand_state(
lowerCAmelCase__ , 0 , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , )
close_list_anchor.append(lowerCAmelCase__ )
print('No path found to goal' )
print()
for i in range(n - 1 , -1 , -1 ):
for j in range(lowerCAmelCase__ ):
if (j, i) in blocks:
print('#' , end=' ' )
elif (j, i) in back_pointer:
if (j, i) == (n - 1, n - 1):
print('*' , end=' ' )
else:
print('-' , end=' ' )
else:
print('*' , end=' ' )
if (j, i) == (n - 1, n - 1):
print('<-- End position' , end=' ' )
print()
print('^' )
print('Start position' )
print()
print('# is an obstacle' )
print('- is the path taken by algorithm' )
if __name__ == "__main__":
multi_a_star(start, goal, n_heuristic) | 686 |
"""simple docstring"""
import tempfile
import unittest
import numpy as np
from diffusers import (
DDIMScheduler,
DPMSolverMultistepScheduler,
EulerAncestralDiscreteScheduler,
EulerDiscreteScheduler,
LMSDiscreteScheduler,
OnnxStableDiffusionPipeline,
PNDMScheduler,
)
from diffusers.utils.testing_utils import is_onnx_available, nightly, require_onnxruntime, require_torch_gpu
from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin
if is_onnx_available():
import onnxruntime as ort
class __UpperCAmelCase ( _UpperCamelCase , unittest.TestCase ):
__lowerCamelCase : List[Any] = "hf-internal-testing/tiny-random-OnnxStableDiffusionPipeline"
def UpperCAmelCase ( self : str , a_ : Optional[Any]=0 ) -> Union[str, Any]:
'''simple docstring'''
a__ : Union[str, Any] = np.random.RandomState(a_ )
a__ : List[Any] = {
"prompt": "A painting of a squirrel eating a burger",
"generator": generator,
"num_inference_steps": 2,
"guidance_scale": 7.5,
"output_type": "numpy",
}
return inputs
def UpperCAmelCase ( self : Dict ) -> Optional[Any]:
'''simple docstring'''
a__ : Tuple = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=a_ )
a__ : Optional[int] = self.get_dummy_inputs()
a__ : Union[str, Any] = pipe(**a_ ).images
a__ : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : List[str] = np.array([0.6_5072, 0.5_8492, 0.4_8219, 0.5_5521, 0.5_3180, 0.5_5939, 0.5_0697, 0.3_9800, 0.4_6455] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Tuple ) -> Union[str, Any]:
'''simple docstring'''
a__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : List[str] = PNDMScheduler.from_config(pipe.scheduler.config , skip_prk_steps=a_ )
pipe.set_progress_bar_config(disable=a_ )
a__ : Optional[int] = self.get_dummy_inputs()
a__ : List[Any] = pipe(**a_ ).images
a__ : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : List[str] = np.array([0.6_5863, 0.5_9425, 0.4_9326, 0.5_6313, 0.5_3875, 0.5_6627, 0.5_1065, 0.3_9777, 0.4_6330] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Tuple ) -> Tuple:
'''simple docstring'''
a__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : Tuple = LMSDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a_ )
a__ : List[Any] = self.get_dummy_inputs()
a__ : Optional[Any] = pipe(**a_ ).images
a__ : int = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : Dict = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Optional[Any] ) -> Dict:
'''simple docstring'''
a__ : Union[str, Any] = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : Dict = EulerDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a_ )
a__ : Optional[int] = self.get_dummy_inputs()
a__ : int = pipe(**a_ ).images
a__ : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : str = np.array([0.5_3755, 0.6_0786, 0.4_7402, 0.4_9488, 0.5_1869, 0.4_9819, 0.4_7985, 0.3_8957, 0.4_4279] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Union[str, Any] ) -> str:
'''simple docstring'''
a__ : str = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : Dict = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a_ )
a__ : Any = self.get_dummy_inputs()
a__ : List[str] = pipe(**a_ ).images
a__ : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : Any = np.array([0.5_3817, 0.6_0812, 0.4_7384, 0.4_9530, 0.5_1894, 0.4_9814, 0.4_7984, 0.3_8958, 0.4_4271] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : Tuple ) -> Any:
'''simple docstring'''
a__ : str = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
a__ : str = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
pipe.set_progress_bar_config(disable=a_ )
a__ : Tuple = self.get_dummy_inputs()
a__ : List[str] = pipe(**a_ ).images
a__ : Any = image[0, -3:, -3:, -1]
assert image.shape == (1, 1_28, 1_28, 3)
a__ : Any = np.array([0.5_3895, 0.6_0808, 0.4_7933, 0.4_9608, 0.5_1886, 0.4_9950, 0.4_8053, 0.3_8957, 0.4_4200] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
def UpperCAmelCase ( self : str ) -> Tuple:
'''simple docstring'''
a__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=a_ )
a__ : Any = self.get_dummy_inputs()
a__ : Any = 3 * [inputs["prompt"]]
# forward
a__ : Union[str, Any] = pipe(**a_ )
a__ : int = output.images[0, -3:, -3:, -1]
a__ : Union[str, Any] = self.get_dummy_inputs()
a__ : List[Any] = 3 * [inputs.pop("prompt" )]
a__ : Optional[Any] = pipe.tokenizer(
a_ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=a_ , return_tensors="np" , )
a__ : List[str] = text_inputs["input_ids"]
a__ : int = pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0]
a__ : List[Any] = prompt_embeds
# forward
a__ : List[Any] = pipe(**a_ )
a__ : List[str] = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4
def UpperCAmelCase ( self : Dict ) -> Optional[int]:
'''simple docstring'''
a__ : Tuple = OnnxStableDiffusionPipeline.from_pretrained(self.hub_checkpoint , provider="CPUExecutionProvider" )
pipe.set_progress_bar_config(disable=a_ )
a__ : Tuple = self.get_dummy_inputs()
a__ : Dict = 3 * ["this is a negative prompt"]
a__ : Optional[Any] = negative_prompt
a__ : Any = 3 * [inputs["prompt"]]
# forward
a__ : str = pipe(**a_ )
a__ : List[str] = output.images[0, -3:, -3:, -1]
a__ : Union[str, Any] = self.get_dummy_inputs()
a__ : Union[str, Any] = 3 * [inputs.pop("prompt" )]
a__ : List[Any] = []
for p in [prompt, negative_prompt]:
a__ : int = pipe.tokenizer(
a_ , padding="max_length" , max_length=pipe.tokenizer.model_max_length , truncation=a_ , return_tensors="np" , )
a__ : Any = text_inputs["input_ids"]
embeds.append(pipe.text_encoder(input_ids=text_inputs.astype(np.intaa ) )[0] )
a__ , a__ : Union[str, Any] = embeds
# forward
a__ : Dict = pipe(**a_ )
a__ : Any = output.images[0, -3:, -3:, -1]
assert np.abs(image_slice_a.flatten() - image_slice_a.flatten() ).max() < 1E-4
@nightly
@require_onnxruntime
@require_torch_gpu
class __UpperCAmelCase ( unittest.TestCase ):
@property
def UpperCAmelCase ( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
return (
"CUDAExecutionProvider",
{
"gpu_mem_limit": "15000000000", # 15GB
"arena_extend_strategy": "kSameAsRequested",
},
)
@property
def UpperCAmelCase ( self : Optional[int] ) -> Tuple:
'''simple docstring'''
a__ : List[str] = ort.SessionOptions()
a__ : List[str] = False
return options
def UpperCAmelCase ( self : Optional[int] ) -> List[Any]:
'''simple docstring'''
a__ : Dict = OnnxStableDiffusionPipeline.from_pretrained(
"CompVis/stable-diffusion-v1-4" , revision="onnx" , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=a_ )
a__ : Optional[int] = "A painting of a squirrel eating a burger"
np.random.seed(0 )
a__ : Dict = sd_pipe([prompt] , guidance_scale=6.0 , num_inference_steps=10 , output_type="np" )
a__ : Any = output.images
a__ : Optional[int] = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
a__ : str = np.array([0.0452, 0.0390, 0.0087, 0.0350, 0.0617, 0.0364, 0.0544, 0.0523, 0.0720] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase ( self : Union[str, Any] ) -> Union[str, Any]:
'''simple docstring'''
a__ : Any = DDIMScheduler.from_pretrained(
"runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" )
a__ : str = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=a_ , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=a_ )
a__ : str = "open neural network exchange"
a__ : Tuple = np.random.RandomState(0 )
a__ : Dict = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=a_ , output_type="np" )
a__ : Dict = output.images
a__ : Union[str, Any] = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
a__ : Dict = np.array([0.2867, 0.1974, 0.1481, 0.7294, 0.7251, 0.6667, 0.4194, 0.5642, 0.6486] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase ( self : Optional[int] ) -> Dict:
'''simple docstring'''
a__ : List[Any] = LMSDiscreteScheduler.from_pretrained(
"runwayml/stable-diffusion-v1-5" , subfolder="scheduler" , revision="onnx" )
a__ : List[Any] = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , scheduler=a_ , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
sd_pipe.set_progress_bar_config(disable=a_ )
a__ : Any = "open neural network exchange"
a__ : Optional[Any] = np.random.RandomState(0 )
a__ : Optional[int] = sd_pipe([prompt] , guidance_scale=7.5 , num_inference_steps=10 , generator=a_ , output_type="np" )
a__ : int = output.images
a__ : Tuple = image[0, -3:, -3:, -1]
assert image.shape == (1, 5_12, 5_12, 3)
a__ : Dict = np.array([0.2306, 0.1959, 0.1593, 0.6549, 0.6394, 0.5408, 0.5065, 0.6010, 0.6161] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-3
def UpperCAmelCase ( self : int ) -> Optional[Any]:
'''simple docstring'''
a__ : List[str] = 0
def test_callback_fn(a_ : int , a_ : int , a_ : np.ndarray ) -> None:
a__ : Optional[int] = True
nonlocal number_of_steps
number_of_steps += 1
if step == 0:
assert latents.shape == (1, 4, 64, 64)
a__ : Any = latents[0, -3:, -3:, -1]
a__ : Union[str, Any] = np.array(
[-0.6772, -0.3835, -1.2456, 0.1905, -1.0974, 0.6967, -1.9353, 0.0178, 1.0167] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3
elif step == 5:
assert latents.shape == (1, 4, 64, 64)
a__ : Union[str, Any] = latents[0, -3:, -3:, -1]
a__ : Optional[int] = np.array(
[-0.3351, 0.2241, -0.1837, -0.2325, -0.6577, 0.3393, -0.0241, 0.5899, 1.3875] )
assert np.abs(latents_slice.flatten() - expected_slice ).max() < 1E-3
a__ : Tuple = False
a__ : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
pipe.set_progress_bar_config(disable=a_ )
a__ : List[Any] = "Andromeda galaxy in a bottle"
a__ : str = np.random.RandomState(0 )
pipe(
prompt=a_ , num_inference_steps=5 , guidance_scale=7.5 , generator=a_ , callback=a_ , callback_steps=1 , )
assert test_callback_fn.has_been_called
assert number_of_steps == 6
def UpperCAmelCase ( self : Tuple ) -> List[str]:
'''simple docstring'''
a__ : Optional[Any] = OnnxStableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5" , revision="onnx" , safety_checker=a_ , feature_extractor=a_ , provider=self.gpu_provider , sess_options=self.gpu_options , )
assert isinstance(a_ , a_ )
assert pipe.safety_checker is None
a__ : 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_ )
a__ : Optional[int] = OnnxStableDiffusionPipeline.from_pretrained(a_ )
# sanity check that the pipeline still works
assert pipe.safety_checker is None
a__ : Dict = pipe("example prompt" , num_inference_steps=2 ).images[0]
assert image is not None | 642 | 0 |
import platform
from argparse import ArgumentParser
import huggingface_hub
from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand
def UpperCAmelCase ( lowercase ):
"""simple docstring"""
return EnvironmentCommand()
class _UpperCamelCase ( _UpperCAmelCase ):
"""simple docstring"""
@staticmethod
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ) -> Optional[Any]:
'''simple docstring'''
__lowercase = parser.add_parser('''env''' )
download_parser.set_defaults(func=lowerCAmelCase__ )
def _SCREAMING_SNAKE_CASE ( self ) -> Optional[Any]:
'''simple docstring'''
__lowercase = huggingface_hub.__version__
__lowercase = '''not installed'''
__lowercase = '''NA'''
if is_torch_available():
import torch
__lowercase = torch.__version__
__lowercase = torch.cuda.is_available()
__lowercase = '''not installed'''
if is_transformers_available():
import transformers
__lowercase = transformers.__version__
__lowercase = '''not installed'''
if is_accelerate_available():
import accelerate
__lowercase = accelerate.__version__
__lowercase = '''not installed'''
if is_xformers_available():
import xformers
__lowercase = xformers.__version__
__lowercase = {
'''`diffusers` version''': version,
'''Platform''': platform.platform(),
'''Python version''': platform.python_version(),
'''PyTorch version (GPU?)''': F"{pt_version} ({pt_cuda_available})",
'''Huggingface_hub version''': hub_version,
'''Transformers version''': transformers_version,
'''Accelerate version''': accelerate_version,
'''xFormers version''': xformers_version,
'''Using GPU in script?''': '''<fill in>''',
'''Using distributed or parallel set-up in script?''': '''<fill in>''',
}
print('''\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n''' )
print(self.format_dict(lowerCAmelCase__ ) )
return info
@staticmethod
def _SCREAMING_SNAKE_CASE ( lowerCAmelCase__ ) -> int:
'''simple docstring'''
return "\n".join([F"- {prop}: {val}" for prop, val in d.items()] ) + "\n" | 700 | from math import factorial
__a : dict[str, int] = {str(digit): factorial(digit) for digit in range(1_0)}
def UpperCAmelCase ( lowercase ):
"""simple docstring"""
if not isinstance(lowercase , lowercase ):
raise TypeError('''Parameter number must be int''' )
if number < 0:
raise ValueError('''Parameter number must be greater than or equal to 0''' )
# Converts number in string to iterate on its digits and adds its factorial.
return sum(DIGIT_FACTORIAL[digit] for digit in str(lowercase ) )
def UpperCAmelCase ( lowercase = 60 , lowercase = 1000000 ):
"""simple docstring"""
if not isinstance(lowercase , lowercase ) or not isinstance(lowercase , lowercase ):
raise TypeError('''Parameters chain_length and number_limit must be int''' )
if chain_length <= 0 or number_limit <= 0:
raise ValueError(
'''Parameters chain_length and number_limit must be greater than 0''' )
# the counter for the chains with the exact desired length
__lowercase = 0
# the cached sizes of the previous chains
__lowercase = {}
for start_chain_element in range(1 , lowercase ):
# The temporary set will contain the elements of the chain
__lowercase = set()
__lowercase = 0
# Stop computing the chain when you find a cached size, a repeating item or the
# length is greater then the desired one.
__lowercase = start_chain_element
while (
chain_element not in chain_sets_lengths
and chain_element not in chain_set
and chain_set_length <= chain_length
):
chain_set.add(lowercase )
chain_set_length += 1
__lowercase = digit_factorial_sum(lowercase )
if chain_element in chain_sets_lengths:
chain_set_length += chain_sets_lengths[chain_element]
__lowercase = chain_set_length
# If chain contains the exact amount of elements increase the counter
if chain_set_length == chain_length:
chains_counter += 1
return chains_counter
if __name__ == "__main__":
import doctest
doctest.testmod()
print(F'''{solution()}''') | 522 | 0 |
from math import ceil
def a__ ( lowercase__ , lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ =list(range(0 , lowercase__ ) )
UpperCAmelCase_ =[item for sublist in list(device_map.values() ) for item in sublist]
# Duplicate check
UpperCAmelCase_ =[]
for i in device_map_blocks:
if device_map_blocks.count(lowercase__ ) > 1 and i not in duplicate_blocks:
duplicate_blocks.append(lowercase__ )
# Missing blocks
UpperCAmelCase_ =[i for i in blocks if i not in device_map_blocks]
UpperCAmelCase_ =[i for i in device_map_blocks if i not in blocks]
if len(lowercase__ ) != 0:
raise ValueError(
"Duplicate attention blocks specified in device_map. Attention blocks must be specified to one device."
" These attention blocks were specified more than once: " + str(lowercase__ ) )
if len(lowercase__ ) != 0:
raise ValueError(
"There are attention blocks for this model that are not specified in the device_map. Add these attention "
"blocks to a device on the device_map: " + str(lowercase__ ) )
if len(lowercase__ ) != 0:
raise ValueError(
"The device_map contains more attention blocks than this model has. Remove these from the device_map:"
+ str(lowercase__ ) )
def a__ ( lowercase__ , lowercase__ ):
'''simple docstring'''
UpperCAmelCase_ =list(range(lowercase__ ) )
UpperCAmelCase_ =int(ceil(n_layers / len(lowercase__ ) ) )
UpperCAmelCase_ =[layers[i : i + n_blocks] for i in range(0 , lowercase__ , lowercase__ )]
return dict(zip(lowercase__ , lowercase__ ) )
| 54 |
def _SCREAMING_SNAKE_CASE ( __lowercase : List[Any] ) -> Any:
"""simple docstring"""
stooge(__lowercase , 0 , len(__lowercase ) - 1 )
return arr
def _SCREAMING_SNAKE_CASE ( __lowercase : str , __lowercase : Dict , __lowercase : Dict ) -> int:
"""simple docstring"""
if i >= h:
return
# If first element is smaller than the last then swap them
if arr[i] > arr[h]:
__A , __A = arr[h], arr[i]
# If there are more than 2 elements in the array
if h - i + 1 > 2:
__A = (int)((h - i + 1) / 3 )
# Recursively sort first 2/3 elements
stooge(__lowercase , __lowercase , (h - t) )
# Recursively sort last 2/3 elements
stooge(__lowercase , i + t , (__lowercase) )
# Recursively sort first 2/3 elements
stooge(__lowercase , __lowercase , (h - t) )
if __name__ == "__main__":
__a : List[Any] = input("Enter numbers separated by a comma:\n").strip()
__a : List[str] = [int(item) for item in user_input.split(",")]
print(stooge_sort(unsorted))
| 637 | 0 |
from collections.abc import Iterable
from typing import Any
class lowerCamelCase__:
def __init__( self , __UpperCAmelCase = None ):
"""simple docstring"""
__lowercase = value
__lowercase = None # Added in order to delete a node easier
__lowercase = None
__lowercase = None
def __repr__( self ):
"""simple docstring"""
from pprint import pformat
if self.left is None and self.right is None:
return str(self.value )
return pformat({F'''{self.value}''': (self.left, self.right)} , indent=1 )
class lowerCamelCase__:
def __init__( self , __UpperCAmelCase = None ):
"""simple docstring"""
__lowercase = root
def __str__( self ):
"""simple docstring"""
return str(self.root )
def __magic_name__ ( self , __UpperCAmelCase , __UpperCAmelCase ):
"""simple docstring"""
if new_children is not None: # reset its kids
__lowercase = node.parent
if node.parent is not None: # reset its parent
if self.is_right(__UpperCAmelCase ): # If it is the right children
__lowercase = new_children
else:
__lowercase = new_children
else:
__lowercase = new_children
def __magic_name__ ( self , __UpperCAmelCase ):
"""simple docstring"""
if node.parent and node.parent.right:
return node == node.parent.right
return False
def __magic_name__ ( self ):
"""simple docstring"""
return self.root is None
def __magic_name__ ( self , __UpperCAmelCase ):
"""simple docstring"""
__lowercase = Node(__UpperCAmelCase ) # create a new Node
if self.empty(): # if Tree is empty
__lowercase = new_node # set its root
else: # Tree is not empty
__lowercase = self.root # from root
if parent_node is None:
return
while True: # While we don't get to a leaf
if value < parent_node.value: # We go left
if parent_node.left is None:
__lowercase = new_node # We insert the new node in a leaf
break
else:
__lowercase = parent_node.left
else:
if parent_node.right is None:
__lowercase = new_node
break
else:
__lowercase = parent_node.right
__lowercase = parent_node
def __magic_name__ ( self , *__UpperCAmelCase ):
"""simple docstring"""
for value in values:
self.__insert(__UpperCAmelCase )
def __magic_name__ ( self , __UpperCAmelCase ):
"""simple docstring"""
if self.empty():
raise IndexError("""Warning: Tree is empty! please use another.""" )
else:
__lowercase = self.root
# use lazy evaluation here to avoid NoneType Attribute error
while node is not None and node.value is not value:
__lowercase = node.left if value < node.value else node.right
return node
def __magic_name__ ( self , __UpperCAmelCase = None ):
"""simple docstring"""
if node is None:
if self.root is None:
return None
__lowercase = self.root
if not self.empty():
while node.right is not None:
__lowercase = node.right
return node
def __magic_name__ ( self , __UpperCAmelCase = None ):
"""simple docstring"""
if node is None:
__lowercase = self.root
if self.root is None:
return None
if not self.empty():
__lowercase = self.root
while node.left is not None:
__lowercase = node.left
return node
def __magic_name__ ( self , __UpperCAmelCase ):
"""simple docstring"""
__lowercase = self.search(__UpperCAmelCase ) # Look for the node with that label
if node is not None:
if node.left is None and node.right is None: # If it has no children
self.__reassign_nodes(__UpperCAmelCase , __UpperCAmelCase )
elif node.left is None: # Has only right children
self.__reassign_nodes(__UpperCAmelCase , node.right )
elif node.right is None: # Has only left children
self.__reassign_nodes(__UpperCAmelCase , node.left )
else:
__lowercase = self.get_max(
node.left ) # Gets the max value of the left branch
self.remove(tmp_node.value ) # type: ignore
__lowercase = (
tmp_node.value # type: ignore
) # Assigns the value to the node to delete and keep tree structure
def __magic_name__ ( self , __UpperCAmelCase ):
"""simple docstring"""
if node is not None:
yield node # Preorder Traversal
yield from self.preorder_traverse(node.left )
yield from self.preorder_traverse(node.right )
def __magic_name__ ( self , __UpperCAmelCase=None ):
"""simple docstring"""
if traversal_function is None:
return self.preorder_traverse(self.root )
else:
return traversal_function(self.root )
def __magic_name__ ( self , __UpperCAmelCase , __UpperCAmelCase ):
"""simple docstring"""
if node:
self.inorder(__UpperCAmelCase , node.left )
arr.append(node.value )
self.inorder(__UpperCAmelCase , node.right )
def __magic_name__ ( self , __UpperCAmelCase , __UpperCAmelCase ):
"""simple docstring"""
__lowercase = []
self.inorder(__UpperCAmelCase , __UpperCAmelCase ) # append all values to list using inorder traversal
return arr[k - 1]
def lowercase__ ( __UpperCamelCase : Node | None ):
'''simple docstring'''
__lowercase = []
if curr_node is not None:
__lowercase = postorder(curr_node.left ) + postorder(curr_node.right ) + [curr_node]
return node_list
def lowercase__ ( ):
'''simple docstring'''
__lowercase = (8, 3, 6, 1, 10, 14, 13, 4, 7)
__lowercase = BinarySearchTree()
for i in testlist:
t.insert(_lowerCamelCase )
# Prints all the elements of the list in order traversal
print(_lowerCamelCase )
if t.search(6 ) is not None:
print("""The value 6 exists""" )
else:
print("""The value 6 doesn't exist""" )
if t.search(-1 ) is not None:
print("""The value -1 exists""" )
else:
print("""The value -1 doesn't exist""" )
if not t.empty():
print("""Max Value: """ , t.get_max().value ) # type: ignore
print("""Min Value: """ , t.get_min().value ) # type: ignore
for i in testlist:
t.remove(_lowerCamelCase )
print(_lowerCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod(verbose=True)
| 704 |
'''simple docstring'''
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_tf_available,
is_torch_available,
is_vision_available,
)
snake_case : Optional[int] = {'configuration_deit': ['DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'DeiTConfig', 'DeiTOnnxConfig']}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case : List[Any] = ['DeiTFeatureExtractor']
snake_case : Any = ['DeiTImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case : List[Any] = [
'DEIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'DeiTForImageClassification',
'DeiTForImageClassificationWithTeacher',
'DeiTForMaskedImageModeling',
'DeiTModel',
'DeiTPreTrainedModel',
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
snake_case : Dict = [
'TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST',
'TFDeiTForImageClassification',
'TFDeiTForImageClassificationWithTeacher',
'TFDeiTForMaskedImageModeling',
'TFDeiTModel',
'TFDeiTPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_deit import DEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, DeiTConfig, DeiTOnnxConfig
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_deit import DeiTFeatureExtractor
from .image_processing_deit import DeiTImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_deit import (
DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
DeiTForImageClassification,
DeiTForImageClassificationWithTeacher,
DeiTForMaskedImageModeling,
DeiTModel,
DeiTPreTrainedModel,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_deit import (
TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST,
TFDeiTForImageClassification,
TFDeiTForImageClassificationWithTeacher,
TFDeiTForMaskedImageModeling,
TFDeiTModel,
TFDeiTPreTrainedModel,
)
else:
import sys
snake_case : List[str] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 339 | 0 |
'''simple docstring'''
import json
from typing import List, Optional, Tuple
from tokenizers import normalizers
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_convbert import ConvBertTokenizer
__snake_case = logging.get_logger(__name__)
__snake_case = {'''vocab_file''': '''vocab.txt'''}
__snake_case = {
'''vocab_file''': {
'''YituTech/conv-bert-base''': '''https://huggingface.co/YituTech/conv-bert-base/resolve/main/vocab.txt''',
'''YituTech/conv-bert-medium-small''': (
'''https://huggingface.co/YituTech/conv-bert-medium-small/resolve/main/vocab.txt'''
),
'''YituTech/conv-bert-small''': '''https://huggingface.co/YituTech/conv-bert-small/resolve/main/vocab.txt''',
}
}
__snake_case = {
'''YituTech/conv-bert-base''': 512,
'''YituTech/conv-bert-medium-small''': 512,
'''YituTech/conv-bert-small''': 512,
}
__snake_case = {
'''YituTech/conv-bert-base''': {'''do_lower_case''': True},
'''YituTech/conv-bert-medium-small''': {'''do_lower_case''': True},
'''YituTech/conv-bert-small''': {'''do_lower_case''': True},
}
class lowercase ( A__ ):
"""simple docstring"""
_a = VOCAB_FILES_NAMES
_a = PRETRAINED_VOCAB_FILES_MAP
_a = PRETRAINED_INIT_CONFIGURATION
_a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_a = ConvBertTokenizer
def __init__( self , UpperCamelCase_=None , UpperCamelCase_=None , UpperCamelCase_=True , UpperCamelCase_="[UNK]" , UpperCamelCase_="[SEP]" , UpperCamelCase_="[PAD]" , UpperCamelCase_="[CLS]" , UpperCamelCase_="[MASK]" , UpperCamelCase_=True , UpperCamelCase_=None , **UpperCamelCase_ , ):
'''simple docstring'''
super().__init__(
UpperCamelCase_ , tokenizer_file=UpperCamelCase_ , do_lower_case=UpperCamelCase_ , unk_token=UpperCamelCase_ , sep_token=UpperCamelCase_ , pad_token=UpperCamelCase_ , cls_token=UpperCamelCase_ , mask_token=UpperCamelCase_ , tokenize_chinese_chars=UpperCamelCase_ , strip_accents=UpperCamelCase_ , **UpperCamelCase_ , )
UpperCamelCase__ :List[Any] = json.loads(self.backend_tokenizer.normalizer.__getstate__() )
if (
normalizer_state.get('''lowercase''' , UpperCamelCase_ ) != do_lower_case
or normalizer_state.get('''strip_accents''' , UpperCamelCase_ ) != strip_accents
or normalizer_state.get('''handle_chinese_chars''' , UpperCamelCase_ ) != tokenize_chinese_chars
):
UpperCamelCase__ :Optional[int] = getattr(UpperCamelCase_ , normalizer_state.pop('''type''' ) )
UpperCamelCase__ :int = do_lower_case
UpperCamelCase__ :List[str] = strip_accents
UpperCamelCase__ :Tuple = tokenize_chinese_chars
UpperCamelCase__ :Tuple = normalizer_class(**UpperCamelCase_ )
UpperCamelCase__ :Tuple = do_lower_case
def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_=None ):
'''simple docstring'''
UpperCamelCase__ :Any = [self.cls_token_id] + token_ids_a + [self.sep_token_id]
if token_ids_a:
output += token_ids_a + [self.sep_token_id]
return output
def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ):
'''simple docstring'''
UpperCamelCase__ :str = [self.sep_token_id]
UpperCamelCase__ :List[Any] = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep ) * [0] + len(token_ids_a + sep ) * [1]
def lowerCAmelCase__ ( self , UpperCamelCase_ , UpperCamelCase_ = None ):
'''simple docstring'''
UpperCamelCase__ :int = self._tokenizer.model.save(UpperCamelCase_ , name=UpperCamelCase_ )
return tuple(UpperCamelCase_ ) | 189 |
'''simple docstring'''
from __future__ import annotations
from math import pi, sqrt
def a ( __a , __a ) -> tuple:
'''simple docstring'''
if inductance <= 0:
raise ValueError('''Inductance cannot be 0 or negative''' )
elif capacitance <= 0:
raise ValueError('''Capacitance cannot be 0 or negative''' )
else:
return (
"Resonant frequency",
float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ),
)
if __name__ == "__main__":
import doctest
doctest.testmod() | 189 | 1 |
"""simple docstring"""
from typing import List, Optional, Union
import numpy as np
import PIL
import torch
from PIL import Image
from ...models import UNetaDConditionModel, VQModel
from ...pipelines import DiffusionPipeline
from ...pipelines.pipeline_utils import ImagePipelineOutput
from ...schedulers import DDPMScheduler
from ...utils import (
is_accelerate_available,
is_accelerate_version,
logging,
randn_tensor,
replace_example_docstring,
)
lowercase__ = logging.get_logger(__name__) # pylint: disable=invalid-name
lowercase__ = "\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Img2ImgPipeline, KandinskyV22PriorPipeline\n >>> from diffusers.utils import load_image\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-prior\", torch_dtype=torch.float16\n ... )\n >>> pipe_prior.to(\"cuda\")\n\n >>> prompt = \"A red cartoon frog, 4k\"\n >>> image_emb, zero_image_emb = pipe_prior(prompt, return_dict=False)\n\n >>> pipe = KandinskyV22Img2ImgPipeline.from_pretrained(\n ... \"kandinsky-community/kandinsky-2-2-decoder\", torch_dtype=torch.float16\n ... )\n >>> pipe.to(\"cuda\")\n\n >>> init_image = load_image(\n ... \"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main\"\n ... \"/kandinsky/frog.png\"\n ... )\n\n >>> image = pipe(\n ... image=init_image,\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... strength=0.2,\n ... ).images\n\n >>> image[0].save(\"red_frog.png\")\n ```\n"
def __magic_name__ ( _lowerCamelCase : Any , _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=8 ):
__a : List[str] = height // scale_factor**2
if height % scale_factor**2 != 0:
new_height += 1
__a : Any = width // scale_factor**2
if width % scale_factor**2 != 0:
new_width += 1
return new_height * scale_factor, new_width * scale_factor
def __magic_name__ ( _lowerCamelCase : int , _lowerCamelCase : Optional[Any]=5_1_2 , _lowerCamelCase : str=5_1_2 ):
__a : Dict = pil_image.resize((w, h) , resample=Image.BICUBIC , reducing_gap=1 )
__a : Any = np.array(pil_image.convert("""RGB""" ) )
__a : Any = arr.astype(np.floataa ) / 1_27.5 - 1
__a : Any = np.transpose(_lowerCamelCase , [2, 0, 1] )
__a : Dict = torch.from_numpy(_lowerCamelCase ).unsqueeze(0 )
return image
class SCREAMING_SNAKE_CASE__ ( __snake_case ):
def __init__(self , _lowercase , _lowercase , _lowercase , ):
'''simple docstring'''
super().__init__()
self.register_modules(
unet=_lowercase , scheduler=_lowercase , movq=_lowercase , )
__a : List[str] = 2 ** (len(self.movq.config.block_out_channels ) - 1)
def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase ):
'''simple docstring'''
__a : Optional[Any] = min(int(num_inference_steps * strength ) , _lowercase )
__a : str = max(num_inference_steps - init_timestep , 0 )
__a : List[Any] = self.scheduler.timesteps[t_start:]
return timesteps, num_inference_steps - t_start
def lowerCAmelCase__(self , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase , _lowercase=None ):
'''simple docstring'''
if not isinstance(_lowercase , (torch.Tensor, PIL.Image.Image, list) ):
raise ValueError(
F'''`image` has to be of type `torch.Tensor`, `PIL.Image.Image` or list but is {type(_lowercase )}''' )
__a : Optional[Any] = image.to(device=_lowercase , dtype=_lowercase )
__a : Optional[int] = batch_size * num_images_per_prompt
if image.shape[1] == 4:
__a : int = image
else:
if isinstance(_lowercase , _lowercase ) and len(_lowercase ) != batch_size:
raise ValueError(
F'''You have passed a list of generators of length {len(_lowercase )}, but requested an effective batch'''
F''' size of {batch_size}. Make sure the batch size matches the length of the generators.''' )
elif isinstance(_lowercase , _lowercase ):
__a : int = [
self.movq.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(_lowercase )
]
__a : Optional[Any] = torch.cat(_lowercase , dim=0 )
else:
__a : Optional[Any] = self.movq.encode(_lowercase ).latent_dist.sample(_lowercase )
__a : Union[str, Any] = self.movq.config.scaling_factor * init_latents
__a : Dict = torch.cat([init_latents] , dim=0 )
__a : Dict = init_latents.shape
__a : Optional[int] = randn_tensor(_lowercase , generator=_lowercase , device=_lowercase , dtype=_lowercase )
# get latents
__a : Any = self.scheduler.add_noise(_lowercase , _lowercase , _lowercase )
__a : Any = init_latents
return latents
def lowerCAmelCase__(self , _lowercase=0 ):
'''simple docstring'''
if is_accelerate_available():
from accelerate import cpu_offload
else:
raise ImportError("""Please install accelerate via `pip install accelerate`""" )
__a : Any = torch.device(F'''cuda:{gpu_id}''' )
__a : List[Any] = [
self.unet,
self.movq,
]
for cpu_offloaded_model in models:
if cpu_offloaded_model is not None:
cpu_offload(_lowercase , _lowercase )
def lowerCAmelCase__(self , _lowercase=0 ):
'''simple docstring'''
if is_accelerate_available() and is_accelerate_version(""">=""" , """0.17.0.dev0""" ):
from accelerate import cpu_offload_with_hook
else:
raise ImportError("""`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.""" )
__a : List[Any] = torch.device(F'''cuda:{gpu_id}''' )
if self.device.type != "cpu":
self.to("""cpu""" , silence_dtype_warnings=_lowercase )
torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist)
__a : Tuple = None
for cpu_offloaded_model in [self.unet, self.movq]:
__a , __a : Optional[int] = cpu_offload_with_hook(_lowercase , _lowercase , prev_module_hook=_lowercase )
# We'll offload the last model manually.
__a : Tuple = hook
@property
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
def lowerCAmelCase__(self ):
'''simple docstring'''
if not hasattr(self.unet , """_hf_hook""" ):
return self.device
for module in self.unet.modules():
if (
hasattr(_lowercase , """_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
@torch.no_grad()
@replace_example_docstring(_lowercase )
def __call__(self , _lowercase , _lowercase , _lowercase , _lowercase = 512 , _lowercase = 512 , _lowercase = 100 , _lowercase = 4.0 , _lowercase = 0.3 , _lowercase = 1 , _lowercase = None , _lowercase = "pil" , _lowercase = True , ):
'''simple docstring'''
__a : List[Any] = self._execution_device
__a : List[str] = guidance_scale > 1.0
if isinstance(_lowercase , _lowercase ):
__a : Tuple = torch.cat(_lowercase , dim=0 )
__a : Union[str, Any] = image_embeds.shape[0]
if isinstance(_lowercase , _lowercase ):
__a : Optional[int] = torch.cat(_lowercase , dim=0 )
if do_classifier_free_guidance:
__a : int = image_embeds.repeat_interleave(_lowercase , dim=0 )
__a : Union[str, Any] = negative_image_embeds.repeat_interleave(_lowercase , dim=0 )
__a : Union[str, Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=_lowercase )
if not isinstance(_lowercase , _lowercase ):
__a : List[str] = [image]
if not all(isinstance(_lowercase , (PIL.Image.Image, torch.Tensor) ) for i in image ):
raise ValueError(
F'''Input is in incorrect format: {[type(_lowercase ) for i in image]}. Currently, we only support PIL image and pytorch tensor''' )
__a : str = torch.cat([prepare_image(_lowercase , _lowercase , _lowercase ) for i in image] , dim=0 )
__a : Optional[int] = image.to(dtype=image_embeds.dtype , device=_lowercase )
__a : Optional[Any] = self.movq.encode(_lowercase )["""latents"""]
__a : List[Any] = latents.repeat_interleave(_lowercase , dim=0 )
self.scheduler.set_timesteps(_lowercase , device=_lowercase )
__a , __a : Optional[int] = self.get_timesteps(_lowercase , _lowercase , _lowercase )
__a : Optional[int] = timesteps[:1].repeat(batch_size * num_images_per_prompt )
__a , __a : int = downscale_height_and_width(_lowercase , _lowercase , self.movq_scale_factor )
__a : List[str] = self.prepare_latents(
_lowercase , _lowercase , _lowercase , _lowercase , image_embeds.dtype , _lowercase , _lowercase )
for i, t in enumerate(self.progress_bar(_lowercase ) ):
# expand the latents if we are doing classifier free guidance
__a : Dict = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
__a : Tuple = {"""image_embeds""": image_embeds}
__a : str = self.unet(
sample=_lowercase , timestep=_lowercase , encoder_hidden_states=_lowercase , added_cond_kwargs=_lowercase , return_dict=_lowercase , )[0]
if do_classifier_free_guidance:
__a , __a : Union[str, Any] = noise_pred.split(latents.shape[1] , dim=1 )
__a , __a : int = noise_pred.chunk(2 )
__a , __a : int = variance_pred.chunk(2 )
__a : List[Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
__a : Optional[Any] = torch.cat([noise_pred, variance_pred_text] , dim=1 )
if not (
hasattr(self.scheduler.config , """variance_type""" )
and self.scheduler.config.variance_type in ["learned", "learned_range"]
):
__a , __a : Optional[int] = noise_pred.split(latents.shape[1] , dim=1 )
# compute the previous noisy sample x_t -> x_t-1
__a : Optional[int] = self.scheduler.step(
_lowercase , _lowercase , _lowercase , generator=_lowercase , )[0]
# post-processing
__a : int = self.movq.decode(_lowercase , force_not_quantize=_lowercase )["""sample"""]
if output_type not in ["pt", "np", "pil"]:
raise ValueError(F'''Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}''' )
if output_type in ["np", "pil"]:
__a : List[Any] = image * 0.5 + 0.5
__a : Union[str, Any] = image.clamp(0 , 1 )
__a : List[str] = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
if output_type == "pil":
__a : Optional[int] = self.numpy_to_pil(_lowercase )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=_lowercase )
| 63 |
"""simple docstring"""
import unittest
import numpy as np
import torch
from torch import nn
from transformers import (
CLIPImageProcessor,
CLIPTextConfig,
CLIPTextModelWithProjection,
CLIPTokenizer,
CLIPVisionConfig,
CLIPVisionModelWithProjection,
)
from diffusers import KandinskyVaaPriorPipeline, PriorTransformer, UnCLIPScheduler
from diffusers.utils import torch_device
from diffusers.utils.testing_utils import enable_full_determinism, skip_mps
from ..test_pipelines_common import PipelineTesterMixin
enable_full_determinism()
class SCREAMING_SNAKE_CASE__ ( __snake_case , unittest.TestCase ):
_lowerCAmelCase = KandinskyVaaPriorPipeline
_lowerCAmelCase = ["prompt"]
_lowerCAmelCase = ["prompt", "negative_prompt"]
_lowerCAmelCase = [
"num_images_per_prompt",
"generator",
"num_inference_steps",
"latents",
"negative_prompt",
"guidance_scale",
"output_type",
"return_dict",
]
_lowerCAmelCase = False
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
return 32
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
return 32
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
return self.time_input_dim
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
return self.time_input_dim * 4
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
return 100
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : List[str] = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" )
return tokenizer
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
torch.manual_seed(0 )
__a : str = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , )
return CLIPTextModelWithProjection(_lowercase )
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
torch.manual_seed(0 )
__a : Dict = {
"""num_attention_heads""": 2,
"""attention_head_dim""": 12,
"""embedding_dim""": self.text_embedder_hidden_size,
"""num_layers""": 1,
}
__a : Tuple = PriorTransformer(**_lowercase )
# clip_std and clip_mean is initialized to be 0 so PriorTransformer.post_process_latents will always return 0 - set clip_std to be 1 so it won't return 0
__a : int = nn.Parameter(torch.ones(model.clip_std.shape ) )
return model
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
torch.manual_seed(0 )
__a : List[str] = CLIPVisionConfig(
hidden_size=self.text_embedder_hidden_size , image_size=224 , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_channels=3 , num_hidden_layers=5 , patch_size=14 , )
__a : Optional[Any] = CLIPVisionModelWithProjection(_lowercase )
return model
@property
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Optional[Any] = CLIPImageProcessor(
crop_size=224 , do_center_crop=_lowercase , do_normalize=_lowercase , do_resize=_lowercase , image_mean=[0.4814_5466, 0.457_8275, 0.4082_1073] , image_std=[0.2686_2954, 0.2613_0258, 0.2757_7711] , resample=3 , size=224 , )
return image_processor
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Union[str, Any] = self.dummy_prior
__a : int = self.dummy_image_encoder
__a : Any = self.dummy_text_encoder
__a : int = self.dummy_tokenizer
__a : Optional[Any] = self.dummy_image_processor
__a : List[Any] = UnCLIPScheduler(
variance_type="""fixed_small_log""" , prediction_type="""sample""" , num_train_timesteps=1000 , clip_sample=_lowercase , clip_sample_range=10.0 , )
__a : List[Any] = {
"""prior""": prior,
"""image_encoder""": image_encoder,
"""text_encoder""": text_encoder,
"""tokenizer""": tokenizer,
"""scheduler""": scheduler,
"""image_processor""": image_processor,
}
return components
def lowerCAmelCase__(self , _lowercase , _lowercase=0 ):
'''simple docstring'''
if str(_lowercase ).startswith("""mps""" ):
__a : Dict = torch.manual_seed(_lowercase )
else:
__a : Union[str, Any] = torch.Generator(device=_lowercase ).manual_seed(_lowercase )
__a : Union[str, Any] = {
"""prompt""": """horse""",
"""generator""": generator,
"""guidance_scale""": 4.0,
"""num_inference_steps""": 2,
"""output_type""": """np""",
}
return inputs
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Union[str, Any] = """cpu"""
__a : Union[str, Any] = self.get_dummy_components()
__a : Dict = self.pipeline_class(**_lowercase )
__a : Tuple = pipe.to(_lowercase )
pipe.set_progress_bar_config(disable=_lowercase )
__a : Optional[int] = pipe(**self.get_dummy_inputs(_lowercase ) )
__a : str = output.image_embeds
__a : Any = pipe(
**self.get_dummy_inputs(_lowercase ) , return_dict=_lowercase , )[0]
__a : List[Any] = image[0, -10:]
__a : List[Any] = image_from_tuple[0, -10:]
assert image.shape == (1, 32)
__a : Optional[Any] = np.array(
[-0.0532, 1.7120, 0.3656, -1.0852, -0.8946, -1.1756, 0.4348, 0.2482, 0.5146, -0.1156] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2
@skip_mps
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Any = torch_device == """cpu"""
__a : Any = True
__a : Any = False
self._test_inference_batch_single_identical(
test_max_difference=_lowercase , relax_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , )
@skip_mps
def lowerCAmelCase__(self ):
'''simple docstring'''
__a : Optional[int] = torch_device == """cpu"""
__a : Union[str, Any] = False
self._test_attention_slicing_forward_pass(
test_max_difference=_lowercase , test_mean_pixel_difference=_lowercase , )
| 63 | 1 |
'''simple docstring'''
import math
import sys
import cva
import numpy as np
def lowercase (_A , _A ):
"""simple docstring"""
_lowerCAmelCase : List[str] = math.sqrt(__A )
_lowerCAmelCase : Any = 1 / (sigma * math.sqrt(2 * math.pi ))
return cons * np.exp(-((img / sigma) ** 2) * 0.5 )
def lowercase (_A , _A , _A , _A ):
"""simple docstring"""
_lowerCAmelCase : Tuple = kernel_size // 2
return img[x - half : x + half + 1, y - half : y + half + 1]
def lowercase (_A , _A ):
"""simple docstring"""
_lowerCAmelCase : Tuple = np.zeros((kernel_size, kernel_size) )
for i in range(0 , __A ):
for j in range(0 , __A ):
_lowerCAmelCase : Optional[int] = math.sqrt(
abs(i - kernel_size // 2 ) ** 2 + abs(j - kernel_size // 2 ) ** 2 )
return vec_gaussian(__A , __A )
def lowercase (_A , _A , _A , _A , ):
"""simple docstring"""
_lowerCAmelCase : Dict = np.zeros(img.shape )
_lowerCAmelCase : Any = get_gauss_kernel(__A , __A )
_lowerCAmelCase : Union[str, Any] = img.shape
for i in range(kernel_size // 2 , size_x - kernel_size // 2 ):
for j in range(kernel_size // 2 , size_y - kernel_size // 2 ):
_lowerCAmelCase : List[str] = get_slice(__A , __A , __A , __A )
_lowerCAmelCase : Union[str, Any] = img_s - img_s[kernel_size // 2, kernel_size // 2]
_lowerCAmelCase : Optional[Any] = vec_gaussian(__A , __A )
_lowerCAmelCase : Union[str, Any] = np.multiply(__A , __A )
_lowerCAmelCase : List[str] = np.multiply(__A , __A )
_lowerCAmelCase : Tuple = np.sum(__A ) / np.sum(__A )
_lowerCAmelCase : Tuple = val
return imga
def lowercase (_A ):
"""simple docstring"""
_lowerCAmelCase : Optional[int] = args[1] if args[1:] else '''../image_data/lena.jpg'''
_lowerCAmelCase : Optional[int] = float(args[2] ) if args[2:] else 1.0
_lowerCAmelCase : List[str] = float(args[3] ) if args[3:] else 1.0
if args[4:]:
_lowerCAmelCase : str = int(args[4] )
_lowerCAmelCase : Dict = kernel_size + abs(kernel_size % 2 - 1 )
else:
_lowerCAmelCase : Optional[int] = 5
return filename, spatial_variance, intensity_variance, kernel_size
if __name__ == "__main__":
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase : Any = parse_args(sys.argv)
lowerCAmelCase : int = cva.imread(filename, 0)
cva.imshow("""input image""", img)
lowerCAmelCase : Tuple = img / 2_55
lowerCAmelCase : List[str] = out.astype("""float32""")
lowerCAmelCase : Optional[int] = bilateral_filter(out, spatial_variance, intensity_variance, kernel_size)
lowerCAmelCase : str = out * 2_55
lowerCAmelCase : Dict = np.uinta(out)
cva.imshow("""output image""", out)
cva.waitKey(0)
cva.destroyAllWindows()
| 444 |
import importlib.metadata
import warnings
from copy import deepcopy
from packaging import version
from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available
if is_bitsandbytes_available():
import bitsandbytes as bnb
import torch
import torch.nn as nn
from ..pytorch_utils import ConvaD
if is_accelerate_available():
from accelerate import init_empty_weights
from accelerate.utils import find_tied_parameters
SCREAMING_SNAKE_CASE = logging.get_logger(__name__)
def _lowerCamelCase ( __A : Optional[int] , __A : Tuple , __A : Union[str, Any] , __A : List[Any]=None , __A : List[str]=None ) -> Dict:
# Recurse if needed
if "." in tensor_name:
_UpperCAmelCase : int = tensor_name.split('''.''' )
for split in splits[:-1]:
_UpperCAmelCase : Tuple = getattr(__A , __A )
if new_module is None:
raise ValueError(f'''{module} has no attribute {split}.''' )
_UpperCAmelCase : Tuple = new_module
_UpperCAmelCase : Tuple = splits[-1]
if tensor_name not in module._parameters and tensor_name not in module._buffers:
raise ValueError(f'''{module} does not have a parameter or a buffer named {tensor_name}.''' )
_UpperCAmelCase : List[str] = tensor_name in module._buffers
_UpperCAmelCase : Optional[int] = getattr(__A , __A )
if old_value.device == torch.device('''meta''' ) and device not in ["meta", torch.device('''meta''' )] and value is None:
raise ValueError(f'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.''' )
_UpperCAmelCase : Optional[Any] = False
_UpperCAmelCase : Optional[Any] = False
if is_buffer or not is_bitsandbytes_available():
_UpperCAmelCase : Optional[Any] = False
_UpperCAmelCase : Optional[int] = False
else:
_UpperCAmelCase : List[Any] = hasattr(bnb.nn , '''Params4bit''' ) and isinstance(module._parameters[tensor_name] , bnb.nn.Paramsabit )
_UpperCAmelCase : Union[str, Any] = isinstance(module._parameters[tensor_name] , bnb.nn.IntaParams )
if is_abit or is_abit:
_UpperCAmelCase : Any = module._parameters[tensor_name]
if param.device.type != "cuda":
if value is None:
_UpperCAmelCase : Any = old_value.to(__A )
elif isinstance(__A , torch.Tensor ):
_UpperCAmelCase : Tuple = value.to('''cpu''' )
if value.dtype == torch.inta:
_UpperCAmelCase : List[Any] = version.parse(importlib.metadata.version('''bitsandbytes''' ) ) > version.parse(
'''0.37.2''' )
if not is_abit_serializable:
raise ValueError(
'''Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '''
'''Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.''' )
else:
_UpperCAmelCase : List[str] = torch.tensor(__A , device='''cpu''' )
# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
# Since weights are saved in the correct "orientation", we skip transposing when loading.
if issubclass(module.source_cls , __A ) and fpaa_statistics is None:
_UpperCAmelCase : Union[str, Any] = new_value.T
_UpperCAmelCase : str = old_value.__dict__
if is_abit:
_UpperCAmelCase : Optional[int] = bnb.nn.IntaParams(__A , requires_grad=__A , **__A ).to(__A )
elif is_abit:
_UpperCAmelCase : List[str] = bnb.nn.Paramsabit(__A , requires_grad=__A , **__A ).to(__A )
_UpperCAmelCase : Optional[Any] = new_value
if fpaa_statistics is not None:
setattr(module.weight , '''SCB''' , fpaa_statistics.to(__A ) )
else:
if value is None:
_UpperCAmelCase : Union[str, Any] = old_value.to(__A )
elif isinstance(__A , torch.Tensor ):
_UpperCAmelCase : Tuple = value.to(__A )
else:
_UpperCAmelCase : Union[str, Any] = torch.tensor(__A , device=__A )
if is_buffer:
_UpperCAmelCase : Dict = new_value
else:
_UpperCAmelCase : List[str] = nn.Parameter(__A , requires_grad=old_value.requires_grad )
_UpperCAmelCase : str = new_value
def _lowerCamelCase ( __A : List[Any] , __A : Tuple=None , __A : Optional[int]=None , __A : Optional[int]=None , __A : Any=False ) -> Union[str, Any]:
for name, module in model.named_children():
if current_key_name is None:
_UpperCAmelCase : List[str] = []
current_key_name.append(__A )
if (isinstance(__A , nn.Linear ) or isinstance(__A , __A )) and name not in modules_to_not_convert:
# Check if the current key is not in the `modules_to_not_convert`
if not any(key in '''.'''.join(__A ) for key in modules_to_not_convert ):
with init_empty_weights():
if isinstance(__A , __A ):
_UpperCAmelCase , _UpperCAmelCase : Any = module.weight.shape
else:
_UpperCAmelCase : List[Any] = module.in_features
_UpperCAmelCase : Tuple = module.out_features
if quantization_config.quantization_method() == "llm_int8":
_UpperCAmelCase : Dict = bnb.nn.LinearabitLt(
__A , __A , module.bias is not None , has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight , threshold=quantization_config.llm_inta_threshold , )
_UpperCAmelCase : Union[str, Any] = True
else:
if (
quantization_config.llm_inta_skip_modules is not None
and name in quantization_config.llm_inta_skip_modules
):
pass
else:
_UpperCAmelCase : str = bnb.nn.Linearabit(
__A , __A , module.bias is not None , quantization_config.bnb_abit_compute_dtype , compress_statistics=quantization_config.bnb_abit_use_double_quant , quant_type=quantization_config.bnb_abit_quant_type , )
_UpperCAmelCase : Dict = True
# Store the module class in case we need to transpose the weight later
_UpperCAmelCase : Optional[Any] = type(__A )
# Force requires grad to False to avoid unexpected errors
model._modules[name].requires_grad_(__A )
if len(list(module.children() ) ) > 0:
_UpperCAmelCase , _UpperCAmelCase : Dict = _replace_with_bnb_linear(
__A , __A , __A , __A , has_been_replaced=__A , )
# Remove the last key for recursion
current_key_name.pop(-1 )
return model, has_been_replaced
def _lowerCamelCase ( __A : str , __A : Union[str, Any]=None , __A : Tuple=None , __A : Optional[Any]=None ) -> Optional[int]:
_UpperCAmelCase : Any = ['''lm_head'''] if modules_to_not_convert is None else modules_to_not_convert
_UpperCAmelCase , _UpperCAmelCase : Any = _replace_with_bnb_linear(
__A , __A , __A , __A )
if not has_been_replaced:
logger.warning(
'''You are loading your model in 8bit or 4bit but no linear modules were found in your model.'''
''' Please double check your model architecture, or submit an issue on github if you think this is'''
''' a bug.''' )
return model
def _lowerCamelCase ( *__A : Optional[int] , **__A : Optional[int] ) -> Dict:
warnings.warn(
'''`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead''' , __A , )
return replace_with_bnb_linear(*__A , **__A )
def _lowerCamelCase ( *__A : Tuple , **__A : List[str] ) -> List[str]:
warnings.warn(
'''`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead''' , __A , )
return set_module_quantized_tensor_to_device(*__A , **__A )
def _lowerCamelCase ( __A : Optional[int] ) -> Optional[Any]:
_UpperCAmelCase : Optional[int] = deepcopy(__A ) # this has 0 cost since it is done inside `init_empty_weights` context manager`
tied_model.tie_weights()
_UpperCAmelCase : int = find_tied_parameters(__A )
# For compatibility with Accelerate < 0.18
if isinstance(__A , __A ):
_UpperCAmelCase : Any = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() )
else:
_UpperCAmelCase : Optional[int] = sum(__A , [] )
_UpperCAmelCase : Any = len(__A ) > 0
# Check if it is a base model
_UpperCAmelCase : List[Any] = not hasattr(__A , model.base_model_prefix )
# Ignore this for base models (BertModel, GPT2Model, etc.)
if (not has_tied_params) and is_base_model:
return []
# otherwise they have an attached head
_UpperCAmelCase : Tuple = list(model.named_children() )
_UpperCAmelCase : Union[str, Any] = [list_modules[-1][0]]
# add last module together with tied weights
_UpperCAmelCase : Dict = set(__A ) - set(__A )
_UpperCAmelCase : Union[str, Any] = list(set(__A ) ) + list(__A )
# remove ".weight" from the keys
_UpperCAmelCase : List[Any] = ['''.weight''', '''.bias''']
_UpperCAmelCase : Optional[int] = []
for name in list_untouched:
for name_to_remove in names_to_remove:
if name_to_remove in name:
_UpperCAmelCase : Optional[Any] = name.replace(__A , '''''' )
filtered_module_names.append(__A )
return filtered_module_names
| 485 | 0 |
'''simple docstring'''
def A__ ( A_ = 1_000_000 ) -> int:
_lowercase = [i - 1 for i in range(limit + 1 )]
for i in range(2 , limit + 1 ):
if phi[i] == i - 1:
for j in range(2 * i , limit + 1 , A_ ):
phi[j] -= phi[j] // i
return sum(phi[2 : limit + 1] )
if __name__ == "__main__":
print(solution())
| 602 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import VivitImageProcessor
class UpperCamelCase__ ( unittest.TestCase ):
"""simple docstring"""
def __init__( self : Any , __A : Optional[int] , __A : Optional[int]=7 , __A : str=3 , __A : Dict=1_0 , __A : List[str]=1_8 , __A : Union[str, Any]=3_0 , __A : Optional[int]=4_0_0 , __A : Optional[int]=True , __A : Any=None , __A : Dict=True , __A : Union[str, Any]=[0.5, 0.5, 0.5] , __A : str=[0.5, 0.5, 0.5] , __A : int=None , ):
"""simple docstring"""
_lowercase = size if size is not None else {"shortest_edge": 1_8}
_lowercase = crop_size if crop_size is not None else {"height": 1_8, "width": 1_8}
_lowercase = parent
_lowercase = batch_size
_lowercase = num_channels
_lowercase = num_frames
_lowercase = image_size
_lowercase = min_resolution
_lowercase = max_resolution
_lowercase = do_resize
_lowercase = size
_lowercase = do_normalize
_lowercase = image_mean
_lowercase = image_std
_lowercase = crop_size
def snake_case ( self : Optional[Any] ):
"""simple docstring"""
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"size": self.size,
"crop_size": self.crop_size,
}
@require_torch
@require_vision
class UpperCamelCase__ ( lowerCamelCase__ , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase__ = VivitImageProcessor if is_vision_available() else None
def snake_case ( self : str ):
"""simple docstring"""
_lowercase = VivitImageProcessingTester(self )
@property
def snake_case ( self : Any ):
"""simple docstring"""
return self.image_processor_tester.prepare_image_processor_dict()
def snake_case ( self : Any ):
"""simple docstring"""
_lowercase = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__A , "image_mean" ) )
self.assertTrue(hasattr(__A , "image_std" ) )
self.assertTrue(hasattr(__A , "do_normalize" ) )
self.assertTrue(hasattr(__A , "do_resize" ) )
self.assertTrue(hasattr(__A , "do_center_crop" ) )
self.assertTrue(hasattr(__A , "size" ) )
def snake_case ( self : Optional[Any] ):
"""simple docstring"""
_lowercase = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size , {"shortest_edge": 1_8} )
self.assertEqual(image_processor.crop_size , {"height": 1_8, "width": 1_8} )
_lowercase = self.image_processing_class.from_dict(self.image_processor_dict , size=4_2 , crop_size=8_4 )
self.assertEqual(image_processor.size , {"shortest_edge": 4_2} )
self.assertEqual(image_processor.crop_size , {"height": 8_4, "width": 8_4} )
def snake_case ( self : Dict ):
"""simple docstring"""
# Initialize image_processing
_lowercase = self.image_processing_class(**self.image_processor_dict )
# create random PIL videos
_lowercase = prepare_video_inputs(self.image_processor_tester , equal_resolution=__A )
for video in video_inputs:
self.assertIsInstance(__A , __A )
self.assertIsInstance(video[0] , Image.Image )
# Test not batched input
_lowercase = image_processing(video_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_videos.shape , (
1,
self.image_processor_tester.num_frames,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
# Test batched
_lowercase = image_processing(__A , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_videos.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_frames,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
def snake_case ( self : Optional[Any] ):
"""simple docstring"""
# Initialize image_processing
_lowercase = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_lowercase = prepare_video_inputs(self.image_processor_tester , equal_resolution=__A , numpify=__A )
for video in video_inputs:
self.assertIsInstance(__A , __A )
self.assertIsInstance(video[0] , np.ndarray )
# Test not batched input
_lowercase = image_processing(video_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_videos.shape , (
1,
self.image_processor_tester.num_frames,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
# Test batched
_lowercase = image_processing(__A , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_videos.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_frames,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
def snake_case ( self : Tuple ):
"""simple docstring"""
# Initialize image_processing
_lowercase = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_lowercase = prepare_video_inputs(self.image_processor_tester , equal_resolution=__A , torchify=__A )
for video in video_inputs:
self.assertIsInstance(__A , __A )
self.assertIsInstance(video[0] , torch.Tensor )
# Test not batched input
_lowercase = image_processing(video_inputs[0] , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_videos.shape , (
1,
self.image_processor_tester.num_frames,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
# Test batched
_lowercase = image_processing(__A , return_tensors="pt" ).pixel_values
self.assertEqual(
encoded_videos.shape , (
self.image_processor_tester.batch_size,
self.image_processor_tester.num_frames,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["height"],
self.image_processor_tester.crop_size["width"],
) , )
| 602 | 1 |
from __future__ import annotations
def snake_case__ ( lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ ):
A : List[str] = []
A , A : Optional[Any] = input_list[low:mid], input_list[mid : high + 1]
while left and right:
result.append((left if left[0] <= right[0] else right).pop(0 ) )
A : str = result + left + right
return input_list
def snake_case__ ( lowerCamelCase_ ):
if len(lowerCamelCase_ ) <= 1:
return input_list
A : Any = list(lowerCamelCase_ )
# iteration for two-way merging
A : Any = 2
while p <= len(lowerCamelCase_ ):
# getting low, high and middle value for merge-sort of single list
for i in range(0 , len(lowerCamelCase_ ) , lowerCamelCase_ ):
A : Dict = i
A : Union[str, Any] = i + p - 1
A : Optional[int] = (low + high + 1) // 2
A : Optional[Any] = merge(lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ )
# final merge of last two parts
if p * 2 >= len(lowerCamelCase_ ):
A : Optional[int] = i
A : List[Any] = merge(lowerCamelCase_ , 0 , lowerCamelCase_ , len(lowerCamelCase_ ) - 1 )
break
p *= 2
return input_list
if __name__ == "__main__":
lowercase : Union[str, Any] = input("Enter numbers separated by a comma:\n").strip()
if user_input == "":
lowercase : List[Any] = []
else:
lowercase : str = [int(item.strip()) for item in user_input.split(",")]
print(iter_merge_sort(unsorted))
| 542 |
def snake_case__ ( lowerCamelCase_ = 1000 ):
return sum(e for e in range(3 , lowerCamelCase_ ) if e % 3 == 0 or e % 5 == 0 )
if __name__ == "__main__":
print(F"{solution() = }")
| 542 | 1 |
'''simple docstring'''
from collections import OrderedDict
from typing import Mapping
from packaging import version
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging
__a: Union[str, Any] = logging.get_logger(__name__)
__a: Optional[Any] = {
"""facebook/deit-base-distilled-patch16-224""": (
"""https://huggingface.co/facebook/deit-base-patch16-224/resolve/main/config.json"""
),
# See all DeiT models at https://huggingface.co/models?filter=deit
}
class UpperCAmelCase ( a__ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE = "deit"
def __init__( self , __lowerCAmelCase=768 , __lowerCAmelCase=12 , __lowerCAmelCase=12 , __lowerCAmelCase=3072 , __lowerCAmelCase="gelu" , __lowerCAmelCase=0.0 , __lowerCAmelCase=0.0 , __lowerCAmelCase=0.0_2 , __lowerCAmelCase=1E-12 , __lowerCAmelCase=224 , __lowerCAmelCase=16 , __lowerCAmelCase=3 , __lowerCAmelCase=True , __lowerCAmelCase=16 , **__lowerCAmelCase , ) -> List[str]:
super().__init__(**__lowerCAmelCase )
lowercase__ : List[str] = hidden_size
lowercase__ : Dict = num_hidden_layers
lowercase__ : Optional[Any] = num_attention_heads
lowercase__ : Tuple = intermediate_size
lowercase__ : Optional[int] = hidden_act
lowercase__ : int = hidden_dropout_prob
lowercase__ : Tuple = attention_probs_dropout_prob
lowercase__ : Tuple = initializer_range
lowercase__ : int = layer_norm_eps
lowercase__ : List[Any] = image_size
lowercase__ : List[str] = patch_size
lowercase__ : Dict = num_channels
lowercase__ : Optional[Any] = qkv_bias
lowercase__ : Tuple = encoder_stride
class UpperCAmelCase ( a__ ):
'''simple docstring'''
SCREAMING_SNAKE_CASE = version.parse("1.11" )
@property
def _lowerCAmelCase( self ) -> Mapping[str, Mapping[int, str]]:
return OrderedDict(
[
('''pixel_values''', {0: '''batch''', 1: '''num_channels''', 2: '''height''', 3: '''width'''}),
] )
@property
def _lowerCAmelCase( self ) -> float:
return 1E-4
| 428 | '''simple docstring'''
import unittest
from transformers import (
MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TextGenerationPipeline,
logging,
pipeline,
)
from transformers.testing_utils import (
CaptureLogger,
is_pipeline_test,
require_accelerate,
require_tf,
require_torch,
require_torch_gpu,
require_torch_or_tf,
)
from .test_pipelines_common import ANY
@is_pipeline_test
@require_torch_or_tf
class UpperCAmelCase ( unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE = MODEL_FOR_CAUSAL_LM_MAPPING
SCREAMING_SNAKE_CASE = TF_MODEL_FOR_CAUSAL_LM_MAPPING
@require_torch
def _lowerCAmelCase( self ) -> Tuple:
lowercase__ : Dict = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''pt''' )
# Using `do_sample=False` to force deterministic output
lowercase__ : Tuple = text_generator('''This is a test''' , do_sample=__lowerCAmelCase )
self.assertEqual(
__lowerCAmelCase , [
{
'''generated_text''': (
'''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.'''
''' oscope. FiliFili@@'''
)
}
] , )
lowercase__ : List[Any] = text_generator(['''This is a test''', '''This is a second test'''] )
self.assertEqual(
__lowerCAmelCase , [
[
{
'''generated_text''': (
'''This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope.'''
''' oscope. FiliFili@@'''
)
}
],
[
{
'''generated_text''': (
'''This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy'''
''' oscope. oscope. FiliFili@@'''
)
}
],
] , )
lowercase__ : List[str] = text_generator('''This is a test''' , do_sample=__lowerCAmelCase , num_return_sequences=2 , return_tensors=__lowerCAmelCase )
self.assertEqual(
__lowerCAmelCase , [
{'''generated_token_ids''': ANY(__lowerCAmelCase )},
{'''generated_token_ids''': ANY(__lowerCAmelCase )},
] , )
lowercase__ : Any = text_generator.model.config.eos_token_id
lowercase__ : List[Any] = '''<pad>'''
lowercase__ : List[str] = text_generator(
['''This is a test''', '''This is a second test'''] , do_sample=__lowerCAmelCase , num_return_sequences=2 , batch_size=2 , return_tensors=__lowerCAmelCase , )
self.assertEqual(
__lowerCAmelCase , [
[
{'''generated_token_ids''': ANY(__lowerCAmelCase )},
{'''generated_token_ids''': ANY(__lowerCAmelCase )},
],
[
{'''generated_token_ids''': ANY(__lowerCAmelCase )},
{'''generated_token_ids''': ANY(__lowerCAmelCase )},
],
] , )
@require_tf
def _lowerCAmelCase( self ) -> str:
lowercase__ : Union[str, Any] = pipeline(task='''text-generation''' , model='''sshleifer/tiny-ctrl''' , framework='''tf''' )
# Using `do_sample=False` to force deterministic output
lowercase__ : Any = text_generator('''This is a test''' , do_sample=__lowerCAmelCase )
self.assertEqual(
__lowerCAmelCase , [
{
'''generated_text''': (
'''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵'''
''' please,'''
)
}
] , )
lowercase__ : int = text_generator(['''This is a test''', '''This is a second test'''] , do_sample=__lowerCAmelCase )
self.assertEqual(
__lowerCAmelCase , [
[
{
'''generated_text''': (
'''This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵'''
''' please,'''
)
}
],
[
{
'''generated_text''': (
'''This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes'''
''' Cannes 閲閲Cannes Cannes Cannes 攵 please,'''
)
}
],
] , )
def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> List[Any]:
lowercase__ : str = TextGenerationPipeline(model=__lowerCAmelCase , tokenizer=__lowerCAmelCase )
return text_generator, ["This is a test", "Another test"]
def _lowerCAmelCase( self ) -> Optional[int]:
lowercase__ : Tuple = '''Hello I believe in'''
lowercase__ : Optional[int] = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' )
lowercase__ : Tuple = text_generator(__lowerCAmelCase )
self.assertEqual(
__lowerCAmelCase , [{'''generated_text''': '''Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe'''}] , )
lowercase__ : str = text_generator(__lowerCAmelCase , stop_sequence=''' fe''' )
self.assertEqual(__lowerCAmelCase , [{'''generated_text''': '''Hello I believe in fe'''}] )
def _lowerCAmelCase( self , __lowerCAmelCase , __lowerCAmelCase ) -> Union[str, Any]:
lowercase__ : Tuple = text_generator.model
lowercase__ : Dict = text_generator.tokenizer
lowercase__ : List[str] = text_generator('''This is a test''' )
self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] )
self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) )
lowercase__ : Any = text_generator('''This is a test''' , return_full_text=__lowerCAmelCase )
self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] )
self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] )
lowercase__ : List[str] = pipeline(task='''text-generation''' , model=__lowerCAmelCase , tokenizer=__lowerCAmelCase , return_full_text=__lowerCAmelCase )
lowercase__ : Tuple = text_generator('''This is a test''' )
self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] )
self.assertNotIn('''This is a test''' , outputs[0]['''generated_text'''] )
lowercase__ : List[str] = text_generator('''This is a test''' , return_full_text=__lowerCAmelCase )
self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] )
self.assertTrue(outputs[0]['''generated_text'''].startswith('''This is a test''' ) )
lowercase__ : Tuple = text_generator(['''This is great !''', '''Something else'''] , num_return_sequences=2 , do_sample=__lowerCAmelCase )
self.assertEqual(
__lowerCAmelCase , [
[{'''generated_text''': ANY(__lowerCAmelCase )}, {'''generated_text''': ANY(__lowerCAmelCase )}],
[{'''generated_text''': ANY(__lowerCAmelCase )}, {'''generated_text''': ANY(__lowerCAmelCase )}],
] , )
if text_generator.tokenizer.pad_token is not None:
lowercase__ : Optional[Any] = text_generator(
['''This is great !''', '''Something else'''] , num_return_sequences=2 , batch_size=2 , do_sample=__lowerCAmelCase )
self.assertEqual(
__lowerCAmelCase , [
[{'''generated_text''': ANY(__lowerCAmelCase )}, {'''generated_text''': ANY(__lowerCAmelCase )}],
[{'''generated_text''': ANY(__lowerCAmelCase )}, {'''generated_text''': ANY(__lowerCAmelCase )}],
] , )
with self.assertRaises(__lowerCAmelCase ):
lowercase__ : Tuple = text_generator('''test''' , return_full_text=__lowerCAmelCase , return_text=__lowerCAmelCase )
with self.assertRaises(__lowerCAmelCase ):
lowercase__ : Union[str, Any] = text_generator('''test''' , return_full_text=__lowerCAmelCase , return_tensors=__lowerCAmelCase )
with self.assertRaises(__lowerCAmelCase ):
lowercase__ : Tuple = text_generator('''test''' , return_text=__lowerCAmelCase , return_tensors=__lowerCAmelCase )
# Empty prompt is slighly special
# it requires BOS token to exist.
# Special case for Pegasus which will always append EOS so will
# work even without BOS.
if (
text_generator.tokenizer.bos_token_id is not None
or "Pegasus" in tokenizer.__class__.__name__
or "Git" in model.__class__.__name__
):
lowercase__ : List[str] = text_generator('''''' )
self.assertEqual(__lowerCAmelCase , [{'''generated_text''': ANY(__lowerCAmelCase )}] )
else:
with self.assertRaises((ValueError, AssertionError) ):
lowercase__ : Dict = text_generator('''''' )
if text_generator.framework == "tf":
# TF generation does not support max_new_tokens, and it's impossible
# to control long generation with only max_length without
# fancy calculation, dismissing tests for now.
return
# We don't care about infinite range models.
# They already work.
# Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly.
lowercase__ : Optional[Any] = ['''RwkvForCausalLM''', '''XGLMForCausalLM''', '''GPTNeoXForCausalLM''']
if (
tokenizer.model_max_length < 10000
and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS
):
# Handling of large generations
with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError) ):
text_generator('''This is a test''' * 500 , max_new_tokens=20 )
lowercase__ : str = text_generator('''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=20 )
# Hole strategy cannot work
with self.assertRaises(__lowerCAmelCase ):
text_generator(
'''This is a test''' * 500 , handle_long_generation='''hole''' , max_new_tokens=tokenizer.model_max_length + 10 , )
@require_torch
@require_accelerate
@require_torch_gpu
def _lowerCAmelCase( self ) -> Optional[int]:
import torch
# Classic `model_kwargs`
lowercase__ : str = pipeline(
model='''hf-internal-testing/tiny-random-bloom''' , model_kwargs={'''device_map''': '''auto''', '''torch_dtype''': torch.bfloataa} , )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa )
lowercase__ : Optional[int] = pipe('''This is a test''' )
self.assertEqual(
__lowerCAmelCase , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
# Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.)
lowercase__ : List[Any] = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.bfloataa )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.bfloataa )
lowercase__ : int = pipe('''This is a test''' )
self.assertEqual(
__lowerCAmelCase , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
# torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602
lowercase__ : List[str] = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' )
self.assertEqual(pipe.model.device , torch.device(0 ) )
self.assertEqual(pipe.model.lm_head.weight.dtype , torch.floataa )
lowercase__ : Optional[int] = pipe('''This is a test''' )
self.assertEqual(
__lowerCAmelCase , [
{
'''generated_text''': (
'''This is a test test test test test test test test test test test test test test test test'''
''' test'''
)
}
] , )
@require_torch
@require_torch_gpu
def _lowerCAmelCase( self ) -> Dict:
import torch
lowercase__ : str = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device=0 , torch_dtype=torch.floataa )
pipe('''This is a test''' )
@require_torch
@require_accelerate
@require_torch_gpu
def _lowerCAmelCase( self ) -> List[str]:
import torch
lowercase__ : int = pipeline(model='''hf-internal-testing/tiny-random-bloom''' , device_map='''auto''' , torch_dtype=torch.floataa )
pipe('''This is a test''' , do_sample=__lowerCAmelCase , top_p=0.5 )
def _lowerCAmelCase( self ) -> Optional[Any]:
lowercase__ : Union[str, Any] = '''Hello world'''
lowercase__ : Optional[Any] = pipeline('''text-generation''' , model='''hf-internal-testing/tiny-random-gpt2''' )
if text_generator.model.framework == "tf":
lowercase__ : List[str] = logging.get_logger('''transformers.generation.tf_utils''' )
else:
lowercase__ : List[str] = logging.get_logger('''transformers.generation.utils''' )
lowercase__ : Any = '''Both `max_new_tokens`''' # The beggining of the message to be checked in this test
# Both are set by the user -> log warning
with CaptureLogger(__lowerCAmelCase ) as cl:
lowercase__ : Dict = text_generator(__lowerCAmelCase , max_length=10 , max_new_tokens=1 )
self.assertIn(__lowerCAmelCase , cl.out )
# The user only sets one -> no warning
with CaptureLogger(__lowerCAmelCase ) as cl:
lowercase__ : Union[str, Any] = text_generator(__lowerCAmelCase , max_new_tokens=1 )
self.assertNotIn(__lowerCAmelCase , cl.out )
with CaptureLogger(__lowerCAmelCase ) as cl:
lowercase__ : str = text_generator(__lowerCAmelCase , max_length=10 )
self.assertNotIn(__lowerCAmelCase , cl.out )
| 428 | 1 |
"""simple docstring"""
import argparse
import json
import os
import re
import torch
from transformers import BloomConfig, BloomModel
from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME
from transformers.utils import logging
logging.set_verbosity_info()
lowerCamelCase__ = [
"word_embeddings_layernorm.weight",
"word_embeddings_layernorm.bias",
"input_layernorm.weight",
"input_layernorm.bias",
"post_attention_layernorm.weight",
"post_attention_layernorm.bias",
"self_attention.dense.bias",
"mlp.dense_4h_to_h.bias",
"ln_f.weight",
"ln_f.bias",
]
lowerCamelCase__ = [
"mlp.dense_4h_to_h.weight",
"self_attention.dense.weight",
]
def lowercase__ ( lowercase_ ,lowercase_ ) -> Union[str, Any]:
"""simple docstring"""
_UpperCamelCase : Dict = {
"word_embeddings.weight": "word_embeddings.weight",
"word_embeddings.norm.weight": "word_embeddings_layernorm.weight",
"word_embeddings.norm.bias": "word_embeddings_layernorm.bias",
"weight": "ln_f.weight",
"bias": "ln_f.bias",
}
if key in layer_rename_map:
return layer_rename_map[key]
# Handle transformer blocks
_UpperCamelCase : Any = int(re.match(r".*layer_(\d*).*" ,lowercase_ )[1] )
layer_number -= 3
return F'''h.{layer_number}.''' + key
def lowercase__ ( lowercase_ ) -> Optional[Any]:
"""simple docstring"""
if dtype == torch.bool:
return 1 / 8
_UpperCamelCase : Optional[int] = re.search(r"[^\d](\d+)$" ,str(lowercase_ ) )
if bit_search is None:
raise ValueError(F'''`dtype` is not a valid dtype: {dtype}.''' )
_UpperCamelCase : str = int(bit_search.groups()[0] )
return bit_size // 8
def lowercase__ ( lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ,lowercase_ ) -> Tuple:
"""simple docstring"""
if bloom_config_file == "":
_UpperCamelCase : Optional[Any] = BloomConfig()
else:
_UpperCamelCase : List[Any] = BloomConfig.from_json_file(lowercase_ )
if shard_model:
_UpperCamelCase : Dict = os.listdir(lowercase_ )
_UpperCamelCase : Optional[Any] = sorted(filter(lambda lowercase_ : s.startswith("layer" ) and "model_00" in s ,lowercase_ ) )
_UpperCamelCase : Optional[Any] = {"weight_map": {}, "metadata": {}}
_UpperCamelCase : int = 0
_UpperCamelCase : Dict = None
_UpperCamelCase : Optional[int] = BloomConfig()
for j, file in enumerate(lowercase_ ):
print("Processing file: {}".format(lowercase_ ) )
_UpperCamelCase : Dict = None
for i in range(lowercase_ ):
# load all TP files
_UpperCamelCase : Tuple = file.replace("model_00" ,F'''model_0{i}''' )
_UpperCamelCase : Optional[int] = torch.load(os.path.join(lowercase_ ,lowercase_ ) ,map_location="cpu" )
# Rename keys in the transformers names
_UpperCamelCase : List[Any] = list(temp.keys() )
for key in keys:
_UpperCamelCase : Any = temp.pop(lowercase_ )
if tensors is None:
_UpperCamelCase : Optional[Any] = temp
else:
for key in tensors.keys():
if any(key.endswith(lowercase_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
tensors[key] += temp[key]
else:
# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
_UpperCamelCase : str = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0
# We concatenate these weights accross TP ranks
_UpperCamelCase : Tuple = torch.cat([tensors[key], temp[key]] ,dim=lowercase_ )
# Divide by the number of TP the weights we want to average
for key in tensors.keys():
if any(key.endswith(lowercase_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
_UpperCamelCase : str = tensors[key] / pretraining_tp
torch.save(
lowercase_ ,os.path.join(
lowercase_ ,"pytorch_model_{}-of-{}.bin".format(str(j + 1 ).zfill(5 ) ,str(len(lowercase_ ) ).zfill(5 ) ) ,) ,)
for key in tensors.keys():
_UpperCamelCase : int = tensors[key]
total_size += value.numel() * get_dtype_size(value.dtype )
if key not in index_dict["weight_map"]:
_UpperCamelCase : List[Any] = "pytorch_model_{}-of-{}.bin".format(
str(j + 1 ).zfill(5 ) ,str(len(lowercase_ ) ).zfill(5 ) )
_UpperCamelCase : Optional[Any] = BloomConfig()
_UpperCamelCase : int = pytorch_dump_folder_path + "/" + CONFIG_NAME
_UpperCamelCase : str = total_size
with open(lowercase_ ,"w" ,encoding="utf-8" ) as f:
f.write(config.to_json_string() )
with open(os.path.join(lowercase_ ,WEIGHTS_NAME + ".index.json" ) ,"w" ,encoding="utf-8" ) as f:
_UpperCamelCase : Any = json.dumps(lowercase_ ,indent=2 ,sort_keys=lowercase_ ) + "\n"
f.write(lowercase_ )
else:
_UpperCamelCase : Optional[int] = BloomModel(lowercase_ )
_UpperCamelCase : Optional[int] = os.listdir(lowercase_ )
_UpperCamelCase : Any = sorted(filter(lambda lowercase_ : s.startswith("layer" ) and "model_00" in s ,lowercase_ ) )
_UpperCamelCase : List[Any] = None
for i, file in enumerate(lowercase_ ):
_UpperCamelCase : Any = None
for i in range(lowercase_ ):
# load all TP files
_UpperCamelCase : Dict = file.replace("model_00" ,F'''model_0{i}''' )
_UpperCamelCase : Optional[Any] = torch.load(os.path.join(lowercase_ ,lowercase_ ) ,map_location="cpu" )
# Rename keys in the transformers names
_UpperCamelCase : List[Any] = list(temp.keys() )
for key in keys:
_UpperCamelCase : Dict = temp.pop(lowercase_ )
if tensors is None:
_UpperCamelCase : Any = temp
else:
for key in tensors.keys():
# We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
if any(key.endswith(lowercase_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
tensors[key] += temp[key]
else:
# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
_UpperCamelCase : Union[str, Any] = 1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN ) else 0
# We concatenate these weights accross TP ranks
_UpperCamelCase : Optional[int] = torch.cat([tensors[key], temp[key]] ,dim=lowercase_ )
# Divide by the number of TP the weights we want to average
for key in tensors.keys():
if any(key.endswith(lowercase_ ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH ):
_UpperCamelCase : List[str] = tensors[key] / pretraining_tp
_UpperCamelCase : Dict = model.load_state_dict(lowercase_ ,strict=lowercase_ )
assert not other_keys.unexpected_keys, F'''The keys {other_keys.unexpected_keys} are unexpected'''
if missing_keys is None:
_UpperCamelCase : str = set(other_keys.missing_keys )
else:
_UpperCamelCase : int = missing_keys.intersection(set(other_keys.missing_keys ) )
assert not missing_keys, F'''The keys {missing_keys} are missing'''
# Save pytorch-model
os.makedirs(lowercase_ ,exist_ok=lowercase_ )
_UpperCamelCase : List[str] = pytorch_dump_folder_path + "/" + WEIGHTS_NAME
_UpperCamelCase : Optional[Any] = pytorch_dump_folder_path + "/" + CONFIG_NAME
print(F'''Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}''' )
if config.torch_dtype is not None:
_UpperCamelCase : List[str] = model.to(config.torch_dtype )
torch.save(model.state_dict() ,lowercase_ )
print(F'''Save configuration file to {pytorch_config_dump_path}''' )
with open(lowercase_ ,"w" ,encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
lowerCamelCase__ = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--bloom_checkpoint_path",
default=None,
type=str,
required=True,
help="Path to the Megatron-LM 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(
"--bloom_config_file",
default="",
type=str,
help=(
"An optional config json file corresponding to the pre-trained model. \n"
"This specifies the model architecture."
),
)
parser.add_argument(
"--shard_model",
action="store_true",
help="An optional setting to shard the output model \nThis enables sharding the converted checkpoint",
)
parser.add_argument(
"--pretraining_tp",
default=4,
type=int,
help="Pretraining TP rank that has been used when training the model in Megatron-LM \n",
)
lowerCamelCase__ = parser.parse_args()
convert_bloom_checkpoint_to_pytorch(
args.bloom_checkpoint_path,
args.bloom_config_file,
args.pytorch_dump_folder_path,
args.shard_model,
args.pretraining_tp,
)
| 624 |
"""simple docstring"""
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import GLPNImageProcessor
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
def __init__( self : Any , __a : Any , __a : Optional[Any]=7 , __a : Tuple=3 , __a : int=18 , __a : Optional[Any]=30 , __a : Optional[Any]=400 , __a : List[str]=True , __a : Any=32 , __a : Tuple=True , ) -> List[str]:
_UpperCamelCase : List[str] = parent
_UpperCamelCase : int = batch_size
_UpperCamelCase : List[str] = num_channels
_UpperCamelCase : Union[str, Any] = image_size
_UpperCamelCase : Optional[Any] = min_resolution
_UpperCamelCase : Union[str, Any] = max_resolution
_UpperCamelCase : Optional[Any] = do_resize
_UpperCamelCase : str = size_divisor
_UpperCamelCase : Optional[Any] = do_rescale
def __SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]:
return {
"do_resize": self.do_resize,
"size_divisor": self.size_divisor,
"do_rescale": self.do_rescale,
}
@require_torch
@require_vision
class __SCREAMING_SNAKE_CASE ( _UpperCamelCase , unittest.TestCase ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ :Any = GLPNImageProcessor if is_vision_available() else None
def __SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Any:
_UpperCamelCase : Optional[Any] = GLPNImageProcessingTester(self )
@property
def __SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Dict:
return self.image_processor_tester.prepare_image_processor_dict()
def __SCREAMING_SNAKE_CASE ( self : str ) -> Union[str, Any]:
_UpperCamelCase : int = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(__a , "do_resize" ) )
self.assertTrue(hasattr(__a , "size_divisor" ) )
self.assertTrue(hasattr(__a , "resample" ) )
self.assertTrue(hasattr(__a , "do_rescale" ) )
def __SCREAMING_SNAKE_CASE ( self : Dict ) -> List[Any]:
pass
def __SCREAMING_SNAKE_CASE ( self : int ) -> Optional[Any]:
# Initialize image_processing
_UpperCamelCase : Optional[Any] = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
_UpperCamelCase : List[str] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a )
for image in image_inputs:
self.assertIsInstance(__a , Image.Image )
# Test not batched input (GLPNImageProcessor doesn't support batching)
_UpperCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
def __SCREAMING_SNAKE_CASE ( self : str ) -> Dict:
# Initialize image_processing
_UpperCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
_UpperCamelCase : List[str] = 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 (GLPNImageProcessor doesn't support batching)
_UpperCamelCase : Dict = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
def __SCREAMING_SNAKE_CASE ( self : Any ) -> Union[str, Any]:
# Initialize image_processing
_UpperCamelCase : Optional[int] = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
_UpperCamelCase : Dict = 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 (GLPNImageProcessor doesn't support batching)
_UpperCamelCase : Optional[int] = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values
self.assertTrue(encoded_images.shape[-1] % self.image_processor_tester.size_divisor == 0 )
self.assertTrue(encoded_images.shape[-2] % self.image_processor_tester.size_divisor == 0 )
| 624 | 1 |
"""simple docstring"""
def _lowerCamelCase ( UpperCAmelCase_ : int = 1000 ) -> int:
"""simple docstring"""
A__ = 2**power
A__ = 0
while n:
A__ , A__ = r + n % 10, n // 10
return r
if __name__ == "__main__":
print(solution(int(str(input()).strip())))
| 562 |
"""simple docstring"""
import sys
from typing import Tuple
import numpy as np
import torch
from PIL import Image
from torch import nn
from transformers.image_utils import PILImageResampling
from utils import img_tensorize
class UpperCamelCase__ :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=sys.maxsize ) -> str:
A__ = "bilinear"
A__ = max_size
A__ = short_edge_length
def __call__( self , SCREAMING_SNAKE_CASE__ ) -> Optional[Any]:
A__ = []
for img in imgs:
A__ , A__ = img.shape[:2]
# later: provide list and randomly choose index for resize
A__ = np.random.randint(self.short_edge_length[0] , self.short_edge_length[1] + 1 )
if size == 0:
return img
A__ = size * 1.0 / min(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if h < w:
A__ , A__ = size, scale * w
else:
A__ , A__ = scale * h, size
if max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) > self.max_size:
A__ = self.max_size * 1.0 / max(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
A__ = newh * scale
A__ = neww * scale
A__ = int(neww + 0.5 )
A__ = int(newh + 0.5 )
if img.dtype == np.uinta:
A__ = Image.fromarray(SCREAMING_SNAKE_CASE__ )
A__ = pil_image.resize((neww, newh) , PILImageResampling.BILINEAR )
A__ = np.asarray(SCREAMING_SNAKE_CASE__ )
else:
A__ = img.permute(2 , 0 , 1 ).unsqueeze(0 ) # 3, 0, 1) # hw(c) -> nchw
A__ = nn.functional.interpolate(
SCREAMING_SNAKE_CASE__ , (newh, neww) , mode=self.interp_method , align_corners=SCREAMING_SNAKE_CASE__ ).squeeze(0 )
img_augs.append(SCREAMING_SNAKE_CASE__ )
return img_augs
class UpperCamelCase__ :
"""simple docstring"""
def __init__( self , SCREAMING_SNAKE_CASE__ ) -> str:
A__ = ResizeShortestEdge([cfg.INPUT.MIN_SIZE_TEST, cfg.INPUT.MIN_SIZE_TEST] , cfg.INPUT.MAX_SIZE_TEST )
A__ = cfg.INPUT.FORMAT
A__ = cfg.SIZE_DIVISIBILITY
A__ = cfg.PAD_VALUE
A__ = cfg.INPUT.MAX_SIZE_TEST
A__ = cfg.MODEL.DEVICE
A__ = torch.tensor(cfg.MODEL.PIXEL_STD ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 )
A__ = torch.tensor(cfg.MODEL.PIXEL_MEAN ).to(self.device ).view(len(cfg.MODEL.PIXEL_STD ) , 1 , 1 )
A__ = lambda SCREAMING_SNAKE_CASE__ : (x - self.pixel_mean) / self.pixel_std
def snake_case__ ( self , SCREAMING_SNAKE_CASE__ ) -> Union[str, Any]:
A__ = tuple(max(SCREAMING_SNAKE_CASE__ ) for s in zip(*[img.shape for img in images] ) )
A__ = [im.shape[-2:] for im in images]
A__ = [
nn.functional.pad(
SCREAMING_SNAKE_CASE__ , [0, max_size[-1] - size[1], 0, max_size[-2] - size[0]] , value=self.pad_value , )
for size, im in zip(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
]
return torch.stack(SCREAMING_SNAKE_CASE__ ), torch.tensor(SCREAMING_SNAKE_CASE__ )
def __call__( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__=False ) -> Optional[int]:
with torch.no_grad():
if not isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ):
A__ = [images]
if single_image:
assert len(SCREAMING_SNAKE_CASE__ ) == 1
for i in range(len(SCREAMING_SNAKE_CASE__ ) ):
if isinstance(images[i] , torch.Tensor ):
images.insert(SCREAMING_SNAKE_CASE__ , images.pop(SCREAMING_SNAKE_CASE__ ).to(self.device ).float() )
elif not isinstance(images[i] , torch.Tensor ):
images.insert(
SCREAMING_SNAKE_CASE__ , torch.as_tensor(img_tensorize(images.pop(SCREAMING_SNAKE_CASE__ ) , input_format=self.input_format ) )
.to(self.device )
.float() , )
# resize smallest edge
A__ = torch.tensor([im.shape[:2] for im in images] )
A__ = self.aug(SCREAMING_SNAKE_CASE__ )
# transpose images and convert to torch tensors
# images = [torch.as_tensor(i.astype("float32")).permute(2, 0, 1).to(self.device) for i in images]
# now normalize before pad to avoid useless arithmetic
A__ = [self.normalizer(SCREAMING_SNAKE_CASE__ ) for x in images]
# now pad them to do the following operations
A__ , A__ = self.pad(SCREAMING_SNAKE_CASE__ )
# Normalize
if self.size_divisibility > 0:
raise NotImplementedError()
# pad
A__ = torch.true_divide(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
if single_image:
return images[0], sizes[0], scales_yx[0]
else:
return images, sizes, scales_yx
def _lowerCamelCase ( UpperCAmelCase_ : List[Any], UpperCAmelCase_ : List[str] ) -> List[Any]:
"""simple docstring"""
boxes[:, 0::2] *= scale_yx[:, 1]
boxes[:, 1::2] *= scale_yx[:, 0]
return boxes
def _lowerCamelCase ( UpperCAmelCase_ : List[str], UpperCAmelCase_ : Tuple[int, int] ) -> str:
"""simple docstring"""
assert torch.isfinite(UpperCAmelCase_ ).all(), "Box tensor contains infinite or NaN!"
A__ , A__ = box_size
tensor[:, 0].clamp_(min=0, max=UpperCAmelCase_ )
tensor[:, 1].clamp_(min=0, max=UpperCAmelCase_ )
tensor[:, 2].clamp_(min=0, max=UpperCAmelCase_ )
tensor[:, 3].clamp_(min=0, max=UpperCAmelCase_ )
| 562 | 1 |
from typing import TYPE_CHECKING
from ...utils import _LazyModule
lowercase_: Dict = {'tokenization_byt5': ['ByT5Tokenizer']}
if TYPE_CHECKING:
from .tokenization_byta import ByTaTokenizer
else:
import sys
lowercase_: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 648 |
import torch
from diffusers import DiffusionPipeline
class lowercase__ (__snake_case ):
"""simple docstring"""
def __init__( self : List[Any] , __a : Optional[Any] , __a : List[str] ):
super().__init__()
self.register_modules(unet=__a , scheduler=__a )
def __call__( self : Union[str, Any] ):
snake_case__ : int = torch.randn(
(1, self.unet.config.in_channels, self.unet.config.sample_size, self.unet.config.sample_size) , )
snake_case__ : Dict = 1
snake_case__ : str = self.unet(__a , __a ).sample
snake_case__ : Tuple = self.scheduler.step(__a , __a , __a ).prev_sample
snake_case__ : Optional[int] = scheduler_output - scheduler_output + torch.ones_like(__a )
return result
| 648 | 1 |
from __future__ import annotations
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: str ):
'''simple docstring'''
return [ord(__lowerCamelCase ) - 96 for elem in plain]
def SCREAMING_SNAKE_CASE_ ( __lowerCamelCase: list[int] ):
'''simple docstring'''
return "".join(chr(elem + 96 ) for elem in encoded )
def SCREAMING_SNAKE_CASE_ ( ):
'''simple docstring'''
lowercase_ = encode(input("-> " ).strip().lower() )
print("Encoded: " , __lowerCamelCase )
print("Decoded:" , decode(__lowerCamelCase ) )
if __name__ == "__main__":
main()
| 714 |
import gc
import unittest
import torch
from parameterized import parameterized
from diffusers import AutoencoderKL
from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import enable_full_determinism
from .test_modeling_common import ModelTesterMixin, UNetTesterMixin
enable_full_determinism()
class __lowerCamelCase ( snake_case_ , snake_case_ , unittest.TestCase ):
"""simple docstring"""
lowerCAmelCase__ = AutoencoderKL
lowerCAmelCase__ = "sample"
lowerCAmelCase__ = 1E-2
@property
def A__ ( self ) -> int:
'''simple docstring'''
lowercase_ = 4
lowercase_ = 3
lowercase_ = (32, 32)
lowercase_ = floats_tensor((batch_size, num_channels) + sizes ).to(UpperCAmelCase )
return {"sample": image}
@property
def A__ ( self ) -> Tuple:
'''simple docstring'''
return (3, 32, 32)
@property
def A__ ( self ) -> List[Any]:
'''simple docstring'''
return (3, 32, 32)
def A__ ( self ) -> str:
'''simple docstring'''
lowercase_ = {
"block_out_channels": [32, 64],
"in_channels": 3,
"out_channels": 3,
"down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"],
"up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"],
"latent_channels": 4,
}
lowercase_ = self.dummy_input
return init_dict, inputs_dict
def A__ ( self ) -> Any:
'''simple docstring'''
pass
def A__ ( self ) -> Tuple:
'''simple docstring'''
pass
@unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" )
def A__ ( self ) -> str:
'''simple docstring'''
lowercase_ , lowercase_ = self.prepare_init_args_and_inputs_for_common()
lowercase_ = self.model_class(**UpperCAmelCase )
model.to(UpperCAmelCase )
assert not model.is_gradient_checkpointing and model.training
lowercase_ = model(**UpperCAmelCase ).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model.zero_grad()
lowercase_ = torch.randn_like(UpperCAmelCase )
lowercase_ = (out - labels).mean()
loss.backward()
# re-instantiate the model now enabling gradient checkpointing
lowercase_ = self.model_class(**UpperCAmelCase )
# clone model
model_a.load_state_dict(model.state_dict() )
model_a.to(UpperCAmelCase )
model_a.enable_gradient_checkpointing()
assert model_a.is_gradient_checkpointing and model_a.training
lowercase_ = model_a(**UpperCAmelCase ).sample
# run the backwards pass on the model. For backwards pass, for simplicity purpose,
# we won't calculate the loss and rather backprop on out.sum()
model_a.zero_grad()
lowercase_ = (out_a - labels).mean()
loss_a.backward()
# compare the output and parameters gradients
self.assertTrue((loss - loss_a).abs() < 1e-5 )
lowercase_ = dict(model.named_parameters() )
lowercase_ = dict(model_a.named_parameters() )
for name, param in named_params.items():
self.assertTrue(torch_all_close(param.grad.data , named_params_a[name].grad.data , atol=5e-5 ) )
def A__ ( self ) -> List[str]:
'''simple docstring'''
lowercase_ , lowercase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=UpperCAmelCase )
self.assertIsNotNone(UpperCAmelCase )
self.assertEqual(len(loading_info["missing_keys"] ) , 0 )
model.to(UpperCAmelCase )
lowercase_ = model(**self.dummy_input )
assert image is not None, "Make sure output is not None"
def A__ ( self ) -> List[str]:
'''simple docstring'''
lowercase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" )
lowercase_ = model.to(UpperCAmelCase )
model.eval()
if torch_device == "mps":
lowercase_ = torch.manual_seed(0 )
else:
lowercase_ = torch.Generator(device=UpperCAmelCase ).manual_seed(0 )
lowercase_ = torch.randn(
1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , )
lowercase_ = image.to(UpperCAmelCase )
with torch.no_grad():
lowercase_ = model(UpperCAmelCase , sample_posterior=UpperCAmelCase , generator=UpperCAmelCase ).sample
lowercase_ = output[0, -1, -3:, -3:].flatten().cpu()
# Since the VAE Gaussian prior's generator is seeded on the appropriate device,
# the expected output slices are not the same for CPU and GPU.
if torch_device == "mps":
lowercase_ = torch.tensor(
[
-4.0_078e-01,
-3.8_323e-04,
-1.2_681e-01,
-1.1_462e-01,
2.0_095e-01,
1.0_893e-01,
-8.8_247e-02,
-3.0_361e-01,
-9.8_644e-03,
] )
elif torch_device == "cpu":
lowercase_ = torch.tensor(
[-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026] )
else:
lowercase_ = torch.tensor(
[-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485] )
self.assertTrue(torch_all_close(UpperCAmelCase , UpperCAmelCase , rtol=1e-2 ) )
@slow
class __lowerCamelCase ( unittest.TestCase ):
"""simple docstring"""
def A__ ( self , UpperCAmelCase , UpperCAmelCase ) -> Union[str, Any]:
'''simple docstring'''
return F'gaussian_noise_s={seed}_shape={"_".join([str(UpperCAmelCase ) for s in shape] )}.npy'
def A__ ( self ) -> Optional[int]:
'''simple docstring'''
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def A__ ( self , UpperCAmelCase=0 , UpperCAmelCase=(4, 3, 512, 512) , UpperCAmelCase=False ) -> str:
'''simple docstring'''
lowercase_ = torch.floataa if fpaa else torch.floataa
lowercase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(UpperCAmelCase , UpperCAmelCase ) ) ).to(UpperCAmelCase ).to(UpperCAmelCase )
return image
def A__ ( self , UpperCAmelCase="CompVis/stable-diffusion-v1-4" , UpperCAmelCase=False ) -> List[str]:
'''simple docstring'''
lowercase_ = "fp16" if fpaa else None
lowercase_ = torch.floataa if fpaa else torch.floataa
lowercase_ = AutoencoderKL.from_pretrained(
UpperCAmelCase , subfolder="vae" , torch_dtype=UpperCAmelCase , revision=UpperCAmelCase , )
model.to(UpperCAmelCase ).eval()
return model
def A__ ( self , UpperCAmelCase=0 ) -> int:
'''simple docstring'''
if torch_device == "mps":
return torch.manual_seed(UpperCAmelCase )
return torch.Generator(device=UpperCAmelCase ).manual_seed(UpperCAmelCase )
@parameterized.expand(
[
# fmt: off
[33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
[47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
# fmt: on
] )
def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> Union[str, Any]:
'''simple docstring'''
lowercase_ = self.get_sd_vae_model()
lowercase_ = self.get_sd_image(UpperCAmelCase )
lowercase_ = self.get_generator(UpperCAmelCase )
with torch.no_grad():
lowercase_ = model(UpperCAmelCase , generator=UpperCAmelCase , sample_posterior=UpperCAmelCase ).sample
assert sample.shape == image.shape
lowercase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu()
lowercase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice )
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , atol=3e-3 )
@parameterized.expand(
[
# fmt: off
[33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
[47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
# fmt: on
] )
@require_torch_gpu
def A__ ( self , UpperCAmelCase , UpperCAmelCase ) -> List[str]:
'''simple docstring'''
lowercase_ = self.get_sd_vae_model(fpaa=UpperCAmelCase )
lowercase_ = self.get_sd_image(UpperCAmelCase , fpaa=UpperCAmelCase )
lowercase_ = self.get_generator(UpperCAmelCase )
with torch.no_grad():
lowercase_ = model(UpperCAmelCase , generator=UpperCAmelCase , sample_posterior=UpperCAmelCase ).sample
assert sample.shape == image.shape
lowercase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu()
lowercase_ = torch.tensor(UpperCAmelCase )
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , atol=1e-2 )
@parameterized.expand(
[
# fmt: off
[33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],
[47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],
# fmt: on
] )
def A__ ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) -> str:
'''simple docstring'''
lowercase_ = self.get_sd_vae_model()
lowercase_ = self.get_sd_image(UpperCAmelCase )
with torch.no_grad():
lowercase_ = model(UpperCAmelCase ).sample
assert sample.shape == image.shape
lowercase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu()
lowercase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice )
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , atol=3e-3 )
@parameterized.expand(
[
# fmt: off
[13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
[37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
# fmt: on
] )
@require_torch_gpu
def A__ ( self , UpperCAmelCase , UpperCAmelCase ) -> Dict:
'''simple docstring'''
lowercase_ = self.get_sd_vae_model()
lowercase_ = self.get_sd_image(UpperCAmelCase , shape=(3, 4, 64, 64) )
with torch.no_grad():
lowercase_ = model.decode(UpperCAmelCase ).sample
assert list(sample.shape ) == [3, 3, 512, 512]
lowercase_ = sample[-1, -2:, :2, -2:].flatten().cpu()
lowercase_ = torch.tensor(UpperCAmelCase )
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , atol=1e-3 )
@parameterized.expand(
[
# fmt: off
[27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
[16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
# fmt: on
] )
@require_torch_gpu
def A__ ( self , UpperCAmelCase , UpperCAmelCase ) -> Tuple:
'''simple docstring'''
lowercase_ = self.get_sd_vae_model(fpaa=UpperCAmelCase )
lowercase_ = self.get_sd_image(UpperCAmelCase , shape=(3, 4, 64, 64) , fpaa=UpperCAmelCase )
with torch.no_grad():
lowercase_ = model.decode(UpperCAmelCase ).sample
assert list(sample.shape ) == [3, 3, 512, 512]
lowercase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu()
lowercase_ = torch.tensor(UpperCAmelCase )
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , atol=5e-3 )
@parameterized.expand([(13,), (16,), (27,)] )
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." )
def A__ ( self , UpperCAmelCase ) -> Union[str, Any]:
'''simple docstring'''
lowercase_ = self.get_sd_vae_model(fpaa=UpperCAmelCase )
lowercase_ = self.get_sd_image(UpperCAmelCase , shape=(3, 4, 64, 64) , fpaa=UpperCAmelCase )
with torch.no_grad():
lowercase_ = model.decode(UpperCAmelCase ).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
lowercase_ = model.decode(UpperCAmelCase ).sample
assert list(sample.shape ) == [3, 3, 512, 512]
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , atol=1e-1 )
@parameterized.expand([(13,), (16,), (37,)] )
@require_torch_gpu
@unittest.skipIf(not is_xformers_available() , reason="xformers is not required when using PyTorch 2.0." )
def A__ ( self , UpperCAmelCase ) -> Tuple:
'''simple docstring'''
lowercase_ = self.get_sd_vae_model()
lowercase_ = self.get_sd_image(UpperCAmelCase , shape=(3, 4, 64, 64) )
with torch.no_grad():
lowercase_ = model.decode(UpperCAmelCase ).sample
model.enable_xformers_memory_efficient_attention()
with torch.no_grad():
lowercase_ = model.decode(UpperCAmelCase ).sample
assert list(sample.shape ) == [3, 3, 512, 512]
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , atol=1e-2 )
@parameterized.expand(
[
# fmt: off
[33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
[47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
# fmt: on
] )
def A__ ( self , UpperCAmelCase , UpperCAmelCase ) -> str:
'''simple docstring'''
lowercase_ = self.get_sd_vae_model()
lowercase_ = self.get_sd_image(UpperCAmelCase )
lowercase_ = self.get_generator(UpperCAmelCase )
with torch.no_grad():
lowercase_ = model.encode(UpperCAmelCase ).latent_dist
lowercase_ = dist.sample(generator=UpperCAmelCase )
assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]
lowercase_ = sample[0, -1, -3:, -3:].flatten().cpu()
lowercase_ = torch.tensor(UpperCAmelCase )
lowercase_ = 3e-3 if torch_device != "mps" else 1e-2
assert torch_all_close(UpperCAmelCase , UpperCAmelCase , atol=UpperCAmelCase )
| 601 | 0 |
'''simple docstring'''
import unittest
import numpy as np
def _lowerCAmelCase ( __magic_name__ : np.ndarray , __magic_name__ : np.ndarray , __magic_name__ : np.ndarray , __magic_name__ : np.ndarray | None = None , ) -> np.ndarray:
lowercase : List[str] =np.shape(__magic_name__ )
lowercase : Optional[Any] =np.shape(__magic_name__ )
lowercase : Dict =np.shape(__magic_name__ )
if shape_a[0] != shape_b[0]:
lowercase : Optional[Any] =(
'''Expected the same number of rows for A and B. '''
f'''Instead found A of size {shape_a} and B of size {shape_b}'''
)
raise ValueError(__magic_name__ )
if shape_b[1] != shape_c[1]:
lowercase : Optional[Any] =(
'''Expected the same number of columns for B and C. '''
f'''Instead found B of size {shape_b} and C of size {shape_c}'''
)
raise ValueError(__magic_name__ )
lowercase : List[str] =pseudo_inv
if a_inv is None:
try:
lowercase : Optional[Any] =np.linalg.inv(__magic_name__ )
except np.linalg.LinAlgError:
raise ValueError(
'''Input matrix A is not invertible. Cannot compute Schur complement.''' )
return mat_c - mat_b.T @ a_inv @ mat_b
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
lowercase : Optional[Any] =np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
lowercase : Dict =np.array([[0, 3], [3, 0], [2, 3]] )
lowercase : Union[str, Any] =np.array([[2, 1], [6, 3]] )
lowercase : Union[str, Any] =schur_complement(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
lowercase : Optional[Any] =np.block([[a, b], [b.T, c]] )
lowercase : Union[str, Any] =np.linalg.det(UpperCAmelCase__ )
lowercase : List[Any] =np.linalg.det(UpperCAmelCase__ )
lowercase : List[str] =np.linalg.det(UpperCAmelCase__ )
self.assertAlmostEqual(UpperCAmelCase__ , det_a * det_s )
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
lowercase : Any =np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
lowercase : Optional[Any] =np.array([[0, 3], [3, 0], [2, 3]] )
lowercase : Tuple =np.array([[2, 1], [6, 3]] )
with self.assertRaises(UpperCAmelCase__ ):
schur_complement(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
lowercase : List[Any] =np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]] )
lowercase : Optional[int] =np.array([[0, 3], [3, 0], [2, 3]] )
lowercase : Optional[Any] =np.array([[2, 1, 3], [6, 3, 5]] )
with self.assertRaises(UpperCAmelCase__ ):
schur_complement(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
unittest.main()
| 92 |
'''simple docstring'''
import inspect
import unittest
from transformers import ConvNextVaConfig
from transformers.models.auto import get_values
from transformers.models.auto.modeling_auto import MODEL_FOR_BACKBONE_MAPPING_NAMES, MODEL_MAPPING_NAMES
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 ConvNextVaBackbone, ConvNextVaForImageClassification, ConvNextVaModel
from transformers.models.convnextva.modeling_convnextva import CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class __SCREAMING_SNAKE_CASE :
def __init__( self : str , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : List[str]=13 , UpperCAmelCase__ : Any=32 , UpperCAmelCase__ : List[str]=3 , UpperCAmelCase__ : Any=4 , UpperCAmelCase__ : List[str]=[10, 20, 30, 40] , UpperCAmelCase__ : Any=[2, 2, 3, 2] , UpperCAmelCase__ : Optional[Any]=True , UpperCAmelCase__ : Tuple=True , UpperCAmelCase__ : Optional[Any]=37 , UpperCAmelCase__ : Union[str, Any]="gelu" , UpperCAmelCase__ : Optional[Any]=10 , UpperCAmelCase__ : Any=0.02 , UpperCAmelCase__ : Optional[int]=["stage2", "stage3", "stage4"] , UpperCAmelCase__ : Dict=[2, 3, 4] , UpperCAmelCase__ : Optional[int]=None , ):
'''simple docstring'''
lowercase : List[Any] =parent
lowercase : Tuple =batch_size
lowercase : List[str] =image_size
lowercase : List[Any] =num_channels
lowercase : Union[str, Any] =num_stages
lowercase : int =hidden_sizes
lowercase : Any =depths
lowercase : Tuple =is_training
lowercase : str =use_labels
lowercase : List[Any] =intermediate_size
lowercase : int =hidden_act
lowercase : Union[str, Any] =num_labels
lowercase : Optional[int] =initializer_range
lowercase : int =out_features
lowercase : List[str] =out_indices
lowercase : str =scope
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
lowercase : str =floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
lowercase : Dict =None
if self.use_labels:
lowercase : List[Any] =ids_tensor([self.batch_size] , self.num_labels )
lowercase : Dict =self.get_config()
return config, pixel_values, labels
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
return ConvNextVaConfig(
num_channels=self.num_channels , hidden_sizes=self.hidden_sizes , depths=self.depths , num_stages=self.num_stages , hidden_act=self.hidden_act , is_decoder=UpperCAmelCase__ , initializer_range=self.initializer_range , out_features=self.out_features , out_indices=self.out_indices , num_labels=self.num_labels , )
def lowerCamelCase_ ( self : List[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Optional[Any] ):
'''simple docstring'''
lowercase : Dict =ConvNextVaModel(config=UpperCAmelCase__ )
model.to(UpperCAmelCase__ )
model.eval()
lowercase : Optional[Any] =model(UpperCAmelCase__ )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , )
def lowerCamelCase_ ( self : Any , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Dict , UpperCAmelCase__ : int ):
'''simple docstring'''
lowercase : Dict =ConvNextVaForImageClassification(UpperCAmelCase__ )
model.to(UpperCAmelCase__ )
model.eval()
lowercase : str =model(UpperCAmelCase__ , labels=UpperCAmelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def lowerCamelCase_ ( self : Dict , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : int ):
'''simple docstring'''
lowercase : Union[str, Any] =ConvNextVaBackbone(config=UpperCAmelCase__ )
model.to(UpperCAmelCase__ )
model.eval()
lowercase : Optional[int] =model(UpperCAmelCase__ )
# verify hidden states
self.parent.assertEqual(len(result.feature_maps ) , len(config.out_features ) )
self.parent.assertListEqual(list(result.feature_maps[0].shape ) , [self.batch_size, self.hidden_sizes[1], 4, 4] )
# 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
lowercase : Optional[Any] =None
lowercase : str =ConvNextVaBackbone(config=UpperCAmelCase__ )
model.to(UpperCAmelCase__ )
model.eval()
lowercase : Optional[Any] =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.hidden_sizes[-1], 1, 1] )
# verify channels
self.parent.assertEqual(len(model.channels ) , 1 )
self.parent.assertListEqual(model.channels , [config.hidden_sizes[-1]] )
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
lowercase : Any =self.prepare_config_and_inputs()
lowercase , lowercase , lowercase : str =config_and_inputs
lowercase : Any ={'''pixel_values''': pixel_values}
return config, inputs_dict
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
lowercase : str =self.prepare_config_and_inputs()
lowercase , lowercase , lowercase : List[str] =config_and_inputs
lowercase : Optional[Any] ={'''pixel_values''': pixel_values, '''labels''': labels}
return config, inputs_dict
@require_torch
class __SCREAMING_SNAKE_CASE ( lowercase__ , lowercase__ , unittest.TestCase ):
lowerCamelCase_ = (
(
ConvNextVaModel,
ConvNextVaForImageClassification,
ConvNextVaBackbone,
)
if is_torch_available()
else ()
)
lowerCamelCase_ = (
{'feature-extraction': ConvNextVaModel, 'image-classification': ConvNextVaForImageClassification}
if is_torch_available()
else {}
)
lowerCamelCase_ = False
lowerCamelCase_ = False
lowerCamelCase_ = False
lowerCamelCase_ = False
lowerCamelCase_ = False
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
lowercase : Dict =ConvNextVaModelTester(self )
lowercase : str =ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__ , hidden_size=37 )
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
self.create_and_test_config_common_properties()
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def lowerCamelCase_ ( self : Any ):
'''simple docstring'''
return
@unittest.skip(reason='''ConvNextV2 does not use inputs_embeds''' )
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
pass
@unittest.skip(reason='''ConvNextV2 does not support input and output embeddings''' )
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
pass
@unittest.skip(reason='''ConvNextV2 does not use feedforward chunking''' )
def lowerCamelCase_ ( self : Tuple ):
'''simple docstring'''
pass
def lowerCamelCase_ ( self : List[Any] ):
'''simple docstring'''
if not self.model_tester.is_training:
return
for model_class in self.all_model_classes:
lowercase , lowercase : Union[str, Any] =self.model_tester.prepare_config_and_inputs_with_labels()
lowercase : Optional[int] =True
if model_class.__name__ in [
*get_values(UpperCAmelCase__ ),
*get_values(UpperCAmelCase__ ),
]:
continue
lowercase : Dict =model_class(UpperCAmelCase__ )
model.to(UpperCAmelCase__ )
model.train()
lowercase : Optional[Any] =self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ )
lowercase : List[Any] =model(**UpperCAmelCase__ ).loss
loss.backward()
def lowerCamelCase_ ( self : Union[str, Any] ):
'''simple docstring'''
if not self.model_tester.is_training:
return
for model_class in self.all_model_classes:
lowercase , lowercase : Any =self.model_tester.prepare_config_and_inputs_with_labels()
lowercase : List[Any] =False
lowercase : Any =True
if (
model_class.__name__
in [*get_values(UpperCAmelCase__ ), *get_values(UpperCAmelCase__ )]
or not model_class.supports_gradient_checkpointing
):
continue
lowercase : Any =model_class(UpperCAmelCase__ )
model.to(UpperCAmelCase__ )
model.gradient_checkpointing_enable()
model.train()
lowercase : Optional[Any] =self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ , return_labels=UpperCAmelCase__ )
lowercase : int =model(**UpperCAmelCase__ ).loss
loss.backward()
def lowerCamelCase_ ( self : Tuple ):
'''simple docstring'''
lowercase , lowercase : int =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase : Dict =model_class(UpperCAmelCase__ )
lowercase : Union[str, Any] =inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
lowercase : int =[*signature.parameters.keys()]
lowercase : Optional[Any] =['''pixel_values''']
self.assertListEqual(arg_names[:1] , UpperCAmelCase__ )
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
lowercase : Tuple =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCAmelCase__ )
def lowerCamelCase_ ( self : int ):
'''simple docstring'''
def check_hidden_states_output(UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : Tuple ):
lowercase : int =model_class(UpperCAmelCase__ )
model.to(UpperCAmelCase__ )
model.eval()
with torch.no_grad():
lowercase : Any =model(**self._prepare_for_class(UpperCAmelCase__ , UpperCAmelCase__ ) )
lowercase : Dict =outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
lowercase : List[Any] =self.model_tester.num_stages
self.assertEqual(len(UpperCAmelCase__ ) , expected_num_stages + 1 )
# ConvNextV2's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 4, self.model_tester.image_size // 4] , )
lowercase , lowercase : List[str] =self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
lowercase : List[str] =True
check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
lowercase : Tuple =True
check_hidden_states_output(UpperCAmelCase__ , UpperCAmelCase__ , UpperCAmelCase__ )
def lowerCamelCase_ ( self : Dict ):
'''simple docstring'''
lowercase : str =self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__ )
@slow
def lowerCamelCase_ ( self : Optional[int] ):
'''simple docstring'''
for model_name in CONVNEXTV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
lowercase : List[Any] =ConvNextVaModel.from_pretrained(UpperCAmelCase__ )
self.assertIsNotNone(UpperCAmelCase__ )
def _lowerCAmelCase ( ) -> List[Any]:
lowercase : Union[str, Any] =Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
@require_vision
class __SCREAMING_SNAKE_CASE ( unittest.TestCase ):
@cached_property
def lowerCamelCase_ ( self : List[str] ):
'''simple docstring'''
return AutoImageProcessor.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ) if is_vision_available() else None
@slow
def lowerCamelCase_ ( self : Optional[Any] ):
'''simple docstring'''
lowercase : Tuple =ConvNextVaForImageClassification.from_pretrained('''facebook/convnextv2-tiny-1k-224''' ).to(UpperCAmelCase__ )
lowercase : int =self.default_image_processor
lowercase : List[str] =prepare_img()
lowercase : List[Any] =preprocessor(images=UpperCAmelCase__ , return_tensors='''pt''' ).to(UpperCAmelCase__ )
# forward pass
with torch.no_grad():
lowercase : Dict =model(**UpperCAmelCase__ )
# verify the logits
lowercase : Optional[Any] =torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , UpperCAmelCase__ )
lowercase : Tuple =torch.tensor([0.99_96, 0.19_66, -0.43_86] ).to(UpperCAmelCase__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , UpperCAmelCase__ , atol=1E-4 ) )
| 92 | 1 |
'''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 : List[str] = logging.get_logger(__name__)
def A__ ( __lowerCAmelCase : List[str] , __lowerCAmelCase : Union[str, Any] ):
lowerCamelCase__ = b.T
lowerCamelCase__ = np.sum(np.square(__lowerCAmelCase ) , axis=1 )
lowerCamelCase__ = np.sum(np.square(__lowerCAmelCase ) , axis=0 )
lowerCamelCase__ = np.matmul(__lowerCAmelCase , __lowerCAmelCase )
lowerCamelCase__ = aa[:, None] - 2 * ab + ba[None, :]
return d
def A__ ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : str ):
lowerCamelCase__ = x.reshape(-1 , 3 )
lowerCamelCase__ = squared_euclidean_distance(__lowerCAmelCase , __lowerCAmelCase )
return np.argmin(__lowerCAmelCase , axis=1 )
class UpperCamelCase__ (a ):
'''simple docstring'''
_UpperCamelCase = ['pixel_values']
def __init__( self ,_lowerCAmelCase = None ,_lowerCAmelCase = True ,_lowerCAmelCase = None ,_lowerCAmelCase = PILImageResampling.BILINEAR ,_lowerCAmelCase = True ,_lowerCAmelCase = True ,**_lowerCAmelCase ,):
super().__init__(**_lowerCAmelCase )
lowerCamelCase__ = size if size is not None else {"""height""": 2_56, """width""": 2_56}
lowerCamelCase__ = get_size_dict(_lowerCAmelCase )
lowerCamelCase__ = np.array(_lowerCAmelCase ) if clusters is not None else None
lowerCamelCase__ = do_resize
lowerCamelCase__ = size
lowerCamelCase__ = resample
lowerCamelCase__ = do_normalize
lowerCamelCase__ = do_color_quantize
def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase ,_lowerCAmelCase = PILImageResampling.BILINEAR ,_lowerCAmelCase = None ,**_lowerCAmelCase ,):
lowerCamelCase__ = 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 UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase = None ,):
lowerCamelCase__ = rescale(image=_lowerCAmelCase ,scale=1 / 127.5 ,data_format=_lowerCAmelCase )
lowerCamelCase__ = image - 1
return image
def UpperCamelCase_ ( self ,_lowerCAmelCase ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = None ,_lowerCAmelCase = ChannelDimension.FIRST ,**_lowerCAmelCase ,):
lowerCamelCase__ = do_resize if do_resize is not None else self.do_resize
lowerCamelCase__ = size if size is not None else self.size
lowerCamelCase__ = get_size_dict(_lowerCAmelCase )
lowerCamelCase__ = resample if resample is not None else self.resample
lowerCamelCase__ = do_normalize if do_normalize is not None else self.do_normalize
lowerCamelCase__ = do_color_quantize if do_color_quantize is not None else self.do_color_quantize
lowerCamelCase__ = clusters if clusters is not None else self.clusters
lowerCamelCase__ = np.array(_lowerCAmelCase )
lowerCamelCase__ = make_list_of_images(_lowerCAmelCase )
if not valid_images(_lowerCAmelCase ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
if do_resize and size is None or resample is None:
raise ValueError("""Size and resample must be specified if do_resize is True.""" )
if do_color_quantize and clusters is None:
raise ValueError("""Clusters must be specified if do_color_quantize is True.""" )
# All transformations expect numpy arrays.
lowerCamelCase__ = [to_numpy_array(_lowerCAmelCase ) for image in images]
if do_resize:
lowerCamelCase__ = [self.resize(image=_lowerCAmelCase ,size=_lowerCAmelCase ,resample=_lowerCAmelCase ) for image in images]
if do_normalize:
lowerCamelCase__ = [self.normalize(image=_lowerCAmelCase ) for image in images]
if do_color_quantize:
lowerCamelCase__ = [to_channel_dimension_format(_lowerCAmelCase ,ChannelDimension.LAST ) for image in images]
# color quantize from (batch_size, height, width, 3) to (batch_size, height, width)
lowerCamelCase__ = np.array(_lowerCAmelCase )
lowerCamelCase__ = color_quantize(_lowerCAmelCase ,_lowerCAmelCase ).reshape(images.shape[:-1] )
# flatten to (batch_size, height*width)
lowerCamelCase__ = images.shape[0]
lowerCamelCase__ = images.reshape(_lowerCAmelCase ,-1 )
# We need to convert back to a list of images to keep consistent behaviour across processors.
lowerCamelCase__ = list(_lowerCAmelCase )
else:
lowerCamelCase__ = [to_channel_dimension_format(_lowerCAmelCase ,_lowerCAmelCase ) for image in images]
lowerCamelCase__ = {"""input_ids""": images}
return BatchFeature(data=_lowerCAmelCase ,tensor_type=_lowerCAmelCase )
| 9 |
'''simple docstring'''
import unittest
import numpy as np
from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available
from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
from transformers import LevitImageProcessor
class UpperCamelCase__ (unittest.TestCase ):
'''simple docstring'''
def __init__( self ,_lowerCAmelCase ,_lowerCAmelCase=7 ,_lowerCAmelCase=3 ,_lowerCAmelCase=18 ,_lowerCAmelCase=30 ,_lowerCAmelCase=4_00 ,_lowerCAmelCase=True ,_lowerCAmelCase=None ,_lowerCAmelCase=True ,_lowerCAmelCase=None ,_lowerCAmelCase=True ,_lowerCAmelCase=[0.5, 0.5, 0.5] ,_lowerCAmelCase=[0.5, 0.5, 0.5] ,):
lowerCamelCase__ = size if size is not None else {"""shortest_edge""": 18}
lowerCamelCase__ = crop_size if crop_size is not None else {"""height""": 18, """width""": 18}
lowerCamelCase__ = parent
lowerCamelCase__ = batch_size
lowerCamelCase__ = num_channels
lowerCamelCase__ = image_size
lowerCamelCase__ = min_resolution
lowerCamelCase__ = max_resolution
lowerCamelCase__ = do_resize
lowerCamelCase__ = size
lowerCamelCase__ = do_center_crop
lowerCamelCase__ = crop_size
lowerCamelCase__ = do_normalize
lowerCamelCase__ = image_mean
lowerCamelCase__ = image_std
def UpperCamelCase_ ( self ):
return {
"image_mean": self.image_mean,
"image_std": self.image_std,
"do_normalize": self.do_normalize,
"do_resize": self.do_resize,
"do_center_crop": self.do_center_crop,
"size": self.size,
"crop_size": self.crop_size,
}
@require_torch
@require_vision
class UpperCamelCase__ (a ,unittest.TestCase ):
'''simple docstring'''
_UpperCamelCase = LevitImageProcessor if is_vision_available() else None
def UpperCamelCase_ ( self ):
lowerCamelCase__ = LevitImageProcessingTester(self )
@property
def UpperCamelCase_ ( self ):
return self.image_processor_tester.prepare_image_processor_dict()
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.image_processing_class(**self.image_processor_dict )
self.assertTrue(hasattr(_lowerCAmelCase ,"""image_mean""" ) )
self.assertTrue(hasattr(_lowerCAmelCase ,"""image_std""" ) )
self.assertTrue(hasattr(_lowerCAmelCase ,"""do_normalize""" ) )
self.assertTrue(hasattr(_lowerCAmelCase ,"""do_resize""" ) )
self.assertTrue(hasattr(_lowerCAmelCase ,"""do_center_crop""" ) )
self.assertTrue(hasattr(_lowerCAmelCase ,"""size""" ) )
def UpperCamelCase_ ( self ):
lowerCamelCase__ = self.image_processing_class.from_dict(self.image_processor_dict )
self.assertEqual(image_processor.size ,{"""shortest_edge""": 18} )
self.assertEqual(image_processor.crop_size ,{"""height""": 18, """width""": 18} )
lowerCamelCase__ = self.image_processing_class.from_dict(self.image_processor_dict ,size=42 ,crop_size=84 )
self.assertEqual(image_processor.size ,{"""shortest_edge""": 42} )
self.assertEqual(image_processor.crop_size ,{"""height""": 84, """width""": 84} )
def UpperCamelCase_ ( self ):
pass
def UpperCamelCase_ ( self ):
# Initialize image_processing
lowerCamelCase__ = self.image_processing_class(**self.image_processor_dict )
# create random PIL images
lowerCamelCase__ = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCAmelCase ,Image.Image )
# Test not batched input
lowerCamelCase__ = image_processing(image_inputs[0] ,return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape ,(
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) ,)
# Test batched
lowerCamelCase__ = image_processing(_lowerCAmelCase ,return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape ,(
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) ,)
def UpperCamelCase_ ( self ):
# Initialize image_processing
lowerCamelCase__ = self.image_processing_class(**self.image_processor_dict )
# create random numpy tensors
lowerCamelCase__ = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_lowerCAmelCase ,numpify=_lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCAmelCase ,np.ndarray )
# Test not batched input
lowerCamelCase__ = image_processing(image_inputs[0] ,return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape ,(
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) ,)
# Test batched
lowerCamelCase__ = image_processing(_lowerCAmelCase ,return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape ,(
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) ,)
def UpperCamelCase_ ( self ):
# Initialize image_processing
lowerCamelCase__ = self.image_processing_class(**self.image_processor_dict )
# create random PyTorch tensors
lowerCamelCase__ = prepare_image_inputs(self.image_processor_tester ,equal_resolution=_lowerCAmelCase ,torchify=_lowerCAmelCase )
for image in image_inputs:
self.assertIsInstance(_lowerCAmelCase ,torch.Tensor )
# Test not batched input
lowerCamelCase__ = image_processing(image_inputs[0] ,return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape ,(
1,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) ,)
# Test batched
lowerCamelCase__ = image_processing(_lowerCAmelCase ,return_tensors="""pt""" ).pixel_values
self.assertEqual(
encoded_images.shape ,(
self.image_processor_tester.batch_size,
self.image_processor_tester.num_channels,
self.image_processor_tester.crop_size["""height"""],
self.image_processor_tester.crop_size["""width"""],
) ,)
| 9 | 1 |
'''simple docstring'''
def lowerCamelCase__ ( _A ):
a : List[str] = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def lowerCamelCase__ ( _A = 5000 ):
a : int = [(i * (3 * i - 1)) // 2 for i in range(1 , _A )]
for i, pentagonal_i in enumerate(_A ):
for j in range(_A , len(_A ) ):
a : Union[str, Any] = pentagonal_nums[j]
a : List[Any] = pentagonal_i + pentagonal_j
a : List[Any] = pentagonal_j - pentagonal_i
if is_pentagonal(_A ) and is_pentagonal(_A ):
return b
return -1
if __name__ == "__main__":
print(F"{solution() = }") | 526 |
'''simple docstring'''
from __future__ import annotations
lowerCAmelCase: str = 'Muhammad Umer Farooq'
lowerCAmelCase: List[str] = 'MIT'
lowerCAmelCase: Tuple = '1.0.0'
lowerCAmelCase: List[Any] = 'Muhammad Umer Farooq'
lowerCAmelCase: Optional[Any] = 'contact@muhammadumerfarooq.me'
lowerCAmelCase: Dict = 'Alpha'
import re
from html.parser import HTMLParser
from urllib import parse
import requests
class a__( lowerCamelCase__ ):
def __init__( self : Dict , __snake_case : str ):
super().__init__()
a : list[str] = []
a : List[Any] = domain
def lowercase_ ( self : Dict , __snake_case : str , __snake_case : list[tuple[str, str | None]] ):
# Only parse the 'anchor' tag.
if tag == "a":
# Check the list of defined attributes.
for name, value in attrs:
# If href is defined, and not empty nor # print it.
if name == "href" and value != "#" and value != "":
# If not already in urls.
if value not in self.urls:
a : Tuple = parse.urljoin(self.domain , __snake_case )
self.urls.append(__snake_case )
def lowerCamelCase__ ( _A ):
return ".".join(get_sub_domain_name(_A ).split('.' )[-2:] )
def lowerCamelCase__ ( _A ):
return parse.urlparse(_A ).netloc
def lowerCamelCase__ ( _A = "https://github.com" ):
a : Any = get_domain_name(_A )
# Initialize the parser
a : Tuple = Parser(_A )
try:
# Open URL
a : List[Any] = requests.get(_A )
# pass the raw HTML to the parser to get links
parser.feed(r.text )
# Get links and loop through
a : Union[str, Any] = set()
for link in parser.urls:
# open URL.
# read = requests.get(link)
try:
a : int = requests.get(_A )
# Get the valid email.
a : Optional[Any] = re.findall('[a-zA-Z0-9]+@' + domain , read.text )
# If not in list then append it.
for email in emails:
valid_emails.add(_A )
except ValueError:
pass
except ValueError:
raise SystemExit(1 )
# Finally return a sorted list of email addresses with no duplicates.
return sorted(_A )
if __name__ == "__main__":
lowerCAmelCase: Any = emails_from_url('https://github.com')
print(F"{len(emails)} emails found:")
print('\n'.join(sorted(emails))) | 526 | 1 |
import argparse
from collections import defaultdict
import yaml
__SCREAMING_SNAKE_CASE : str = 'docs/source/en/_toctree.yml'
def snake_case (__lowercase ) -> Any:
'''simple docstring'''
_snake_case : List[Any] = defaultdict(__lowercase )
for doc in model_doc:
counts[doc["local"]] += 1
_snake_case : str = [key for key, value in counts.items() if value > 1]
_snake_case : Tuple = []
for duplicate_key in duplicates:
_snake_case : Union[str, Any] = list({doc["title"] for doc in model_doc if doc["local"] == duplicate_key} )
if len(__lowercase ) > 1:
raise ValueError(
F"""{duplicate_key} is present several times in the documentation table of content at """
"`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the "
"others." )
# Only add this once
new_doc.append({"local": duplicate_key, "title": titles[0]} )
# Add none duplicate-keys
new_doc.extend([doc for doc in model_doc if counts[doc["local"]] == 1] )
# Sort
return sorted(__lowercase , key=lambda __lowercase : s["title"].lower() )
def snake_case (__lowercase=False ) -> Tuple:
'''simple docstring'''
with open(__lowercase , encoding="utf-8" ) as f:
_snake_case : Optional[Any] = yaml.safe_load(f.read() )
# Get to the API doc
_snake_case : int = 0
while content[api_idx]["title"] != "API":
api_idx += 1
_snake_case : List[str] = content[api_idx]["sections"]
# Then to the model doc
_snake_case : str = 0
while api_doc[model_idx]["title"] != "Models":
model_idx += 1
_snake_case : Union[str, Any] = api_doc[model_idx]["sections"]
_snake_case : List[str] = [(idx, section) for idx, section in enumerate(__lowercase ) if "sections" in section]
_snake_case : str = False
for idx, modality_doc in modalities_docs:
_snake_case : int = modality_doc["sections"]
_snake_case : Optional[Any] = clean_model_doc_toc(__lowercase )
if old_modality_doc != new_modality_doc:
_snake_case : int = True
if overwrite:
_snake_case : Optional[Any] = new_modality_doc
if diff:
if overwrite:
_snake_case : Dict = model_doc
_snake_case : Optional[int] = api_doc
with open(__lowercase , "w" , encoding="utf-8" ) as f:
f.write(yaml.dump(__lowercase , allow_unicode=__lowercase ) )
else:
raise ValueError(
"The model doc part of the table of content is not properly sorted, run `make style` to fix this." )
if __name__ == "__main__":
__SCREAMING_SNAKE_CASE : str = argparse.ArgumentParser()
parser.add_argument('--fix_and_overwrite', action='store_true', help='Whether to fix inconsistencies.')
__SCREAMING_SNAKE_CASE : int = parser.parse_args()
check_model_doc(args.fix_and_overwrite) | 580 | import unittest
from transformers import BigBirdTokenizer, BigBirdTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
__SCREAMING_SNAKE_CASE : Tuple = '▁'
__SCREAMING_SNAKE_CASE : Optional[Any] = get_tests_dir('fixtures/test_sentencepiece.model')
@require_sentencepiece
@require_tokenizers
class lowercase_ ( __snake_case , unittest.TestCase ):
_lowerCamelCase = BigBirdTokenizer
_lowerCamelCase = BigBirdTokenizerFast
_lowerCamelCase = True
_lowerCamelCase = True
def UpperCamelCase ( self ):
super().setUp()
_snake_case : List[str] = self.tokenizer_class(lowercase_ , keep_accents=lowercase_ )
tokenizer.save_pretrained(self.tmpdirname )
def UpperCamelCase ( self ):
_snake_case : Any = "<s>"
_snake_case : Union[str, Any] = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ) , lowercase_ )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ) , lowercase_ )
def UpperCamelCase ( self ):
_snake_case : Any = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , "<unk>" )
self.assertEqual(vocab_keys[1] , "<s>" )
self.assertEqual(vocab_keys[-1] , "[MASK]" )
self.assertEqual(len(lowercase_ ) , 1_004 )
def UpperCamelCase ( self ):
self.assertEqual(self.get_tokenizer().vocab_size , 1_000 )
def UpperCamelCase ( self ):
if not self.test_rust_tokenizer:
return
_snake_case : Tuple = self.get_tokenizer()
_snake_case : List[str] = self.get_rust_tokenizer()
_snake_case : Optional[Any] = "I was born in 92000, and this is falsé."
_snake_case : str = tokenizer.tokenize(lowercase_ )
_snake_case : Optional[Any] = rust_tokenizer.tokenize(lowercase_ )
self.assertListEqual(lowercase_ , lowercase_ )
_snake_case : str = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ )
_snake_case : Any = rust_tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ )
self.assertListEqual(lowercase_ , lowercase_ )
_snake_case : List[Any] = self.get_rust_tokenizer()
_snake_case : str = tokenizer.encode(lowercase_ )
_snake_case : Optional[Any] = rust_tokenizer.encode(lowercase_ )
self.assertListEqual(lowercase_ , lowercase_ )
def UpperCamelCase ( self ):
_snake_case : Tuple = BigBirdTokenizer(lowercase_ , keep_accents=lowercase_ )
_snake_case : Union[str, Any] = tokenizer.tokenize("This is a test" )
self.assertListEqual(lowercase_ , ["▁This", "▁is", "▁a", "▁t", "est"] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(lowercase_ ) , [285, 46, 10, 170, 382] , )
_snake_case : Any = tokenizer.tokenize("I was born in 92000, and this is falsé." )
self.assertListEqual(
lowercase_ , [
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",
"é",
".",
] , )
_snake_case : str = tokenizer.convert_tokens_to_ids(lowercase_ )
self.assertListEqual(
lowercase_ , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , )
_snake_case : Any = tokenizer.convert_ids_to_tokens(lowercase_ )
self.assertListEqual(
lowercase_ , [
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 UpperCamelCase ( self ):
return BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" )
@slow
def UpperCamelCase ( self ):
_snake_case : Optional[Any] = "Hello World!"
_snake_case : Tuple = [65, 18_536, 2_260, 101, 66]
self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_ ) )
@slow
def UpperCamelCase ( self ):
_snake_case : 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
_snake_case : List[str] = [65, 871, 419, 358, 946, 991, 2_521, 452, 358, 1_357, 387, 7_751, 3_536, 112, 985, 456, 126, 865, 938, 5_400, 5_734, 458, 1_368, 467, 786, 2_462, 5_246, 1_159, 633, 865, 4_519, 457, 582, 852, 2_557, 427, 916, 508, 405, 34_324, 497, 391, 408, 11_342, 1_244, 385, 100, 938, 985, 456, 574, 362, 12_597, 3_200, 3_129, 1_172, 66] # noqa: E231
# fmt: on
self.assertListEqual(lowercase_ , self.big_tokenizer.encode(lowercase_ ) )
@require_torch
@slow
def UpperCamelCase ( self ):
import torch
from transformers import BigBirdConfig, BigBirdModel
# Build sequence
_snake_case : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10]
_snake_case : Optional[Any] = " ".join(lowercase_ )
_snake_case : Tuple = self.big_tokenizer.encode_plus(lowercase_ , return_tensors="pt" , return_token_type_ids=lowercase_ )
_snake_case : Optional[int] = self.big_tokenizer.batch_encode_plus(
[sequence + " " + sequence] , return_tensors="pt" , return_token_type_ids=lowercase_ )
_snake_case : Optional[Any] = BigBirdConfig(attention_type="original_full" )
_snake_case : int = BigBirdModel(lowercase_ )
assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size
with torch.no_grad():
model(**lowercase_ )
model(**lowercase_ )
@slow
def UpperCamelCase ( self ):
_snake_case : Optional[int] = BigBirdTokenizer.from_pretrained("google/bigbird-roberta-base" )
_snake_case : Tuple = tokenizer.decode(tokenizer("Paris is the [MASK]." ).input_ids )
self.assertTrue(decoded_text == "[CLS] Paris is the[MASK].[SEP]" )
@slow
def UpperCamelCase ( self ):
# fmt: off
_snake_case : List[Any] = {"input_ids": [[65, 39_286, 458, 36_335, 2_001, 456, 13_073, 13_266, 455, 113, 7_746, 1_741, 11_157, 391, 13_073, 13_266, 455, 113, 3_967, 35_412, 113, 4_936, 109, 3_870, 2_377, 113, 30_084, 45_720, 458, 134, 17_496, 112, 503, 11_672, 113, 118, 112, 5_665, 13_347, 38_687, 112, 1_496, 31_389, 112, 3_268, 47_264, 134, 962, 112, 16_377, 8_035, 23_130, 430, 12_169, 15_518, 28_592, 458, 146, 41_697, 109, 391, 12_169, 15_518, 16_689, 458, 146, 41_358, 109, 452, 726, 4_034, 111, 763, 35_412, 5_082, 388, 1_903, 111, 9_051, 391, 2_870, 48_918, 1_900, 1_123, 550, 998, 112, 9_586, 15_985, 455, 391, 410, 22_955, 37_636, 114, 66], [65, 448, 17_496, 419, 3_663, 385, 763, 113, 27_533, 2_870, 3_283, 13_043, 1_639, 24_713, 523, 656, 24_013, 18_550, 2_521, 517, 27_014, 21_244, 420, 1_212, 1_465, 391, 927, 4_833, 388, 578, 11_786, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 484, 2_169, 7_687, 21_932, 18_146, 726, 363, 17_032, 3_391, 114, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=lowercase_ , model_name="google/bigbird-roberta-base" , revision="215c99f1600e06f83acce68422f2035b2b5c3510" , ) | 580 | 1 |
'''simple docstring'''
import argparse
import torch
from transformers import FunnelBaseModel, FunnelConfig, FunnelModel, load_tf_weights_in_funnel
from transformers.utils import logging
logging.set_verbosity_info()
def __a(SCREAMING_SNAKE_CASE_ : List[str] , SCREAMING_SNAKE_CASE_ : Any , SCREAMING_SNAKE_CASE_ : int , SCREAMING_SNAKE_CASE_ : List[Any] ):
'''simple docstring'''
_lowerCAmelCase = FunnelConfig.from_json_file(SCREAMING_SNAKE_CASE_ )
print(F'''Building PyTorch model from configuration: {config}''' )
_lowerCAmelCase = FunnelBaseModel(SCREAMING_SNAKE_CASE_ ) if base_model else FunnelModel(SCREAMING_SNAKE_CASE_ )
# Load weights from tf checkpoint
load_tf_weights_in_funnel(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
# Save pytorch-model
print(F'''Save PyTorch model to {pytorch_dump_path}''' )
torch.save(model.state_dict() , SCREAMING_SNAKE_CASE_ )
if __name__ == "__main__":
_SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--tf_checkpoint_path", default=None, type=str, required=True, help="Path to the TensorFlow checkpoint path."
)
parser.add_argument(
"--config_file",
default=None,
type=str,
required=True,
help="The config json file corresponding to the pre-trained model. \nThis specifies the model architecture.",
)
parser.add_argument(
"--pytorch_dump_path", default=None, type=str, required=True, help="Path to the output PyTorch model."
)
parser.add_argument(
"--base_model", action="store_true", help="Whether you want just the base model (no decoder) or not."
)
_SCREAMING_SNAKE_CASE = parser.parse_args()
convert_tf_checkpoint_to_pytorch(
args.tf_checkpoint_path, args.config_file, args.pytorch_dump_path, args.base_model
)
| 18 |
'''simple docstring'''
import argparse
import os
import torch
from transformers import (
XLNetConfig,
XLNetForQuestionAnswering,
XLNetForSequenceClassification,
XLNetLMHeadModel,
load_tf_weights_in_xlnet,
)
from transformers.utils import CONFIG_NAME, WEIGHTS_NAME, logging
lowercase__ = {
'''cola''': 2,
'''mnli''': 3,
'''mrpc''': 2,
'''sst-2''': 2,
'''sts-b''': 1,
'''qqp''': 2,
'''qnli''': 2,
'''rte''': 2,
'''wnli''': 2,
}
logging.set_verbosity_info()
def __snake_case ( lowercase : Dict , lowercase : Optional[int] , lowercase : Tuple , lowercase : List[str]=None ):
# Initialise PyTorch model
snake_case_ = XLNetConfig.from_json_file(lowercase )
snake_case_ = finetuning_task.lower() if finetuning_task is not None else ""
if finetuning_task in GLUE_TASKS_NUM_LABELS:
print(f'''Building PyTorch XLNetForSequenceClassification model from configuration: {config}''' )
snake_case_ = finetuning_task
snake_case_ = GLUE_TASKS_NUM_LABELS[finetuning_task]
snake_case_ = XLNetForSequenceClassification(lowercase )
elif "squad" in finetuning_task:
snake_case_ = finetuning_task
snake_case_ = XLNetForQuestionAnswering(lowercase )
else:
snake_case_ = XLNetLMHeadModel(lowercase )
# Load weights from tf checkpoint
load_tf_weights_in_xlnet(lowercase , lowercase , lowercase )
# Save pytorch-model
snake_case_ = os.path.join(lowercase , lowercase )
snake_case_ = os.path.join(lowercase , lowercase )
print(f'''Save PyTorch model to {os.path.abspath(lowercase )}''' )
torch.save(model.state_dict() , lowercase )
print(f'''Save configuration file to {os.path.abspath(lowercase )}''' )
with open(lowercase , "w" , encoding="utf-8" ) as f:
f.write(config.to_json_string() )
if __name__ == "__main__":
lowercase__ = 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(
'''--xlnet_config_file''',
default=None,
type=str,
required=True,
help=(
'''The config json file corresponding to the pre-trained XLNet model. \n'''
'''This specifies the model architecture.'''
),
)
parser.add_argument(
'''--pytorch_dump_folder_path''',
default=None,
type=str,
required=True,
help='''Path to the folder to store the PyTorch model or dataset/vocab.''',
)
parser.add_argument(
'''--finetuning_task''',
default=None,
type=str,
help='''Name of a task on which the XLNet TensorFlow model was fine-tuned''',
)
lowercase__ = parser.parse_args()
print(args)
convert_xlnet_checkpoint_to_pytorch(
args.tf_checkpoint_path, args.xlnet_config_file, args.pytorch_dump_folder_path, args.finetuning_task
)
| 508 | 0 |
'''simple docstring'''
import copy
import unittest
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, 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, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import (
MODEL_FOR_MULTIPLE_CHOICE_MAPPING,
MODEL_FOR_QUESTION_ANSWERING_MAPPING,
MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
LayoutLMvaConfig,
LayoutLMvaForQuestionAnswering,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaModel,
)
from transformers.models.layoutlmva.modeling_layoutlmva import LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import LayoutLMvaImageProcessor
class lowerCamelCase_ :
def __init__( self : Union[str, Any] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : str=2 , lowerCAmelCase__ : List[Any]=3 , lowerCAmelCase__ : Union[str, Any]=4 , lowerCAmelCase__ : Dict=2 , lowerCAmelCase__ : List[Any]=7 , lowerCAmelCase__ : List[str]=True , lowerCAmelCase__ : Optional[Any]=True , lowerCAmelCase__ : List[Any]=True , lowerCAmelCase__ : Optional[int]=True , lowerCAmelCase__ : Tuple=99 , lowerCAmelCase__ : Optional[int]=36 , lowerCAmelCase__ : List[Any]=3 , lowerCAmelCase__ : Optional[int]=4 , lowerCAmelCase__ : Optional[Any]=37 , lowerCAmelCase__ : Dict="gelu" , lowerCAmelCase__ : str=0.1 , lowerCAmelCase__ : Optional[int]=0.1 , lowerCAmelCase__ : Any=5_12 , lowerCAmelCase__ : Tuple=16 , lowerCAmelCase__ : List[Any]=2 , lowerCAmelCase__ : Union[str, Any]=0.02 , lowerCAmelCase__ : Any=6 , lowerCAmelCase__ : Tuple=6 , lowerCAmelCase__ : Optional[Any]=3 , lowerCAmelCase__ : str=4 , lowerCAmelCase__ : str=None , lowerCAmelCase__ : Optional[int]=10_00 , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = parent
SCREAMING_SNAKE_CASE : Any = batch_size
SCREAMING_SNAKE_CASE : List[str] = num_channels
SCREAMING_SNAKE_CASE : int = image_size
SCREAMING_SNAKE_CASE : Union[str, Any] = patch_size
SCREAMING_SNAKE_CASE : int = text_seq_length
SCREAMING_SNAKE_CASE : str = is_training
SCREAMING_SNAKE_CASE : Tuple = use_input_mask
SCREAMING_SNAKE_CASE : Union[str, Any] = use_token_type_ids
SCREAMING_SNAKE_CASE : Dict = use_labels
SCREAMING_SNAKE_CASE : List[str] = vocab_size
SCREAMING_SNAKE_CASE : Optional[int] = hidden_size
SCREAMING_SNAKE_CASE : Any = num_hidden_layers
SCREAMING_SNAKE_CASE : List[Any] = num_attention_heads
SCREAMING_SNAKE_CASE : Optional[int] = intermediate_size
SCREAMING_SNAKE_CASE : Any = hidden_act
SCREAMING_SNAKE_CASE : Union[str, Any] = hidden_dropout_prob
SCREAMING_SNAKE_CASE : Optional[Any] = attention_probs_dropout_prob
SCREAMING_SNAKE_CASE : List[Any] = max_position_embeddings
SCREAMING_SNAKE_CASE : Any = type_vocab_size
SCREAMING_SNAKE_CASE : List[Any] = type_sequence_label_size
SCREAMING_SNAKE_CASE : Union[str, Any] = initializer_range
SCREAMING_SNAKE_CASE : Dict = coordinate_size
SCREAMING_SNAKE_CASE : str = shape_size
SCREAMING_SNAKE_CASE : Tuple = num_labels
SCREAMING_SNAKE_CASE : Optional[Any] = num_choices
SCREAMING_SNAKE_CASE : Optional[int] = scope
SCREAMING_SNAKE_CASE : Tuple = range_bbox
# LayoutLMv3's sequence length equals the number of text tokens + number of patches + 1 (we add 1 for the CLS token)
SCREAMING_SNAKE_CASE : List[str] = text_seq_length
SCREAMING_SNAKE_CASE : str = (image_size // patch_size) ** 2 + 1
SCREAMING_SNAKE_CASE : Tuple = self.text_seq_length + self.image_seq_length
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = ids_tensor([self.batch_size, self.text_seq_length] , self.vocab_size )
SCREAMING_SNAKE_CASE : Tuple = ids_tensor([self.batch_size, self.text_seq_length, 4] , self.range_bbox )
# Ensure that bbox is legal
for i in range(bbox.shape[0] ):
for j in range(bbox.shape[1] ):
if bbox[i, j, 3] < bbox[i, j, 1]:
SCREAMING_SNAKE_CASE : Dict = bbox[i, j, 3]
SCREAMING_SNAKE_CASE : Tuple = bbox[i, j, 1]
SCREAMING_SNAKE_CASE : str = t
if bbox[i, j, 2] < bbox[i, j, 0]:
SCREAMING_SNAKE_CASE : Any = bbox[i, j, 2]
SCREAMING_SNAKE_CASE : List[str] = bbox[i, j, 0]
SCREAMING_SNAKE_CASE : Union[str, Any] = t
SCREAMING_SNAKE_CASE : Dict = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
SCREAMING_SNAKE_CASE : List[str] = None
if self.use_input_mask:
SCREAMING_SNAKE_CASE : Optional[Any] = random_attention_mask([self.batch_size, self.text_seq_length] )
SCREAMING_SNAKE_CASE : Optional[int] = None
if self.use_token_type_ids:
SCREAMING_SNAKE_CASE : Dict = ids_tensor([self.batch_size, self.text_seq_length] , self.type_vocab_size )
SCREAMING_SNAKE_CASE : Dict = None
SCREAMING_SNAKE_CASE : List[str] = None
if self.use_labels:
SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size] , self.type_sequence_label_size )
SCREAMING_SNAKE_CASE : Union[str, Any] = ids_tensor([self.batch_size, self.text_seq_length] , self.num_labels )
SCREAMING_SNAKE_CASE : Optional[int] = LayoutLMvaConfig(
vocab_size=self.vocab_size , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , coordinate_size=self.coordinate_size , shape_size=self.shape_size , input_size=self.image_size , patch_size=self.patch_size , )
return config, input_ids, bbox, pixel_values, token_type_ids, input_mask, sequence_labels, token_labels
def __lowercase ( self : List[str] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : str , lowerCAmelCase__ : int , lowerCAmelCase__ : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = LayoutLMvaModel(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
# text + image
SCREAMING_SNAKE_CASE : Dict = model(UpperCamelCase__ , pixel_values=UpperCamelCase__ )
SCREAMING_SNAKE_CASE : List[str] = model(
UpperCamelCase__ , bbox=UpperCamelCase__ , pixel_values=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = model(UpperCamelCase__ , bbox=UpperCamelCase__ , pixel_values=UpperCamelCase__ , token_type_ids=UpperCamelCase__ )
SCREAMING_SNAKE_CASE : Tuple = model(UpperCamelCase__ , bbox=UpperCamelCase__ , pixel_values=UpperCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) )
# text only
SCREAMING_SNAKE_CASE : Any = model(UpperCamelCase__ )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.text_seq_length, self.hidden_size) )
# image only
SCREAMING_SNAKE_CASE : List[Any] = model(pixel_values=UpperCamelCase__ )
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.image_seq_length, self.hidden_size) )
def __lowercase ( self : Optional[int] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = self.num_labels
SCREAMING_SNAKE_CASE : Optional[Any] = LayoutLMvaForSequenceClassification(UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
SCREAMING_SNAKE_CASE : Optional[Any] = model(
UpperCamelCase__ , bbox=UpperCamelCase__ , pixel_values=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowercase ( self : Dict , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : List[str] , lowerCAmelCase__ : Any , lowerCAmelCase__ : List[Any] , lowerCAmelCase__ : Any , lowerCAmelCase__ : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = self.num_labels
SCREAMING_SNAKE_CASE : Optional[int] = LayoutLMvaForTokenClassification(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
SCREAMING_SNAKE_CASE : List[Any] = model(
UpperCamelCase__ , bbox=UpperCamelCase__ , pixel_values=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , labels=UpperCamelCase__ , )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.text_seq_length, self.num_labels) )
def __lowercase ( self : Optional[int] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = LayoutLMvaForQuestionAnswering(config=UpperCamelCase__ )
model.to(UpperCamelCase__ )
model.eval()
SCREAMING_SNAKE_CASE : List[str] = model(
UpperCamelCase__ , bbox=UpperCamelCase__ , pixel_values=UpperCamelCase__ , attention_mask=UpperCamelCase__ , token_type_ids=UpperCamelCase__ , start_positions=UpperCamelCase__ , end_positions=UpperCamelCase__ , )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def __lowercase ( self : List[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = self.prepare_config_and_inputs()
(
(
SCREAMING_SNAKE_CASE
) ,(
SCREAMING_SNAKE_CASE
) ,(
SCREAMING_SNAKE_CASE
) ,(
SCREAMING_SNAKE_CASE
) ,(
SCREAMING_SNAKE_CASE
) ,(
SCREAMING_SNAKE_CASE
) ,(
SCREAMING_SNAKE_CASE
) ,(
SCREAMING_SNAKE_CASE
) ,
) : Dict = config_and_inputs
SCREAMING_SNAKE_CASE : Optional[int] = {
'''input_ids''': input_ids,
'''bbox''': bbox,
'''pixel_values''': pixel_values,
'''token_type_ids''': token_type_ids,
'''attention_mask''': input_mask,
}
return config, inputs_dict
@require_torch
class lowerCamelCase_ ( snake_case_ , snake_case_ , unittest.TestCase ):
_lowerCAmelCase : str = False
_lowerCAmelCase : str = False
_lowerCAmelCase : int = False
_lowerCAmelCase : List[Any] = (
(
LayoutLMvaModel,
LayoutLMvaForSequenceClassification,
LayoutLMvaForTokenClassification,
LayoutLMvaForQuestionAnswering,
)
if is_torch_available()
else ()
)
_lowerCAmelCase : Union[str, Any] = (
{"document-question-answering": LayoutLMvaForQuestionAnswering, "feature-extraction": LayoutLMvaModel}
if is_torch_available()
else {}
)
def __lowercase ( self : str , lowerCAmelCase__ : int , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Any , lowerCAmelCase__ : Optional[int] , lowerCAmelCase__ : Optional[Any] ):
"""simple docstring"""
return True
def __lowercase ( self : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = LayoutLMvaModelTester(self )
SCREAMING_SNAKE_CASE : str = ConfigTester(self , config_class=UpperCamelCase__ , hidden_size=37 )
def __lowercase ( self : List[Any] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Dict , lowerCAmelCase__ : List[str]=False ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[int] = copy.deepcopy(UpperCamelCase__ )
if model_class in get_values(UpperCamelCase__ ):
SCREAMING_SNAKE_CASE : int = {
k: v.unsqueeze(1 ).expand(-1 , self.model_tester.num_choices , -1 ).contiguous()
if isinstance(UpperCamelCase__ , torch.Tensor ) and v.ndim > 1
else v
for k, v in inputs_dict.items()
}
if return_labels:
if model_class in get_values(UpperCamelCase__ ):
SCREAMING_SNAKE_CASE : Optional[Any] = torch.ones(self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase__ )
elif model_class in get_values(UpperCamelCase__ ):
SCREAMING_SNAKE_CASE : str = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase__ )
SCREAMING_SNAKE_CASE : Dict = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase__ )
elif model_class in [
*get_values(UpperCamelCase__ ),
]:
SCREAMING_SNAKE_CASE : Optional[Any] = torch.zeros(
self.model_tester.batch_size , dtype=torch.long , device=UpperCamelCase__ )
elif model_class in [
*get_values(UpperCamelCase__ ),
]:
SCREAMING_SNAKE_CASE : Optional[Any] = torch.zeros(
(self.model_tester.batch_size, self.model_tester.text_seq_length) , dtype=torch.long , device=UpperCamelCase__ , )
return inputs_dict
def __lowercase ( self : Optional[int] ):
"""simple docstring"""
self.config_tester.run_common_tests()
def __lowercase ( self : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def __lowercase ( self : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs()
for type in ["absolute", "relative_key", "relative_key_query"]:
SCREAMING_SNAKE_CASE : Optional[int] = type
self.model_tester.create_and_check_model(*UpperCamelCase__ )
def __lowercase ( self : Optional[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__ )
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__ )
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[int] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__ )
@slow
def __lowercase ( self : Optional[int] ):
"""simple docstring"""
for model_name in LAYOUTLMV3_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE : Tuple = LayoutLMvaModel.from_pretrained(UpperCamelCase__ )
self.assertIsNotNone(UpperCamelCase__ )
def UpperCAmelCase ( ):
'''simple docstring'''
SCREAMING_SNAKE_CASE : int = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_torch
class lowerCamelCase_ ( unittest.TestCase ):
@cached_property
def __lowercase ( self : Optional[Any] ):
"""simple docstring"""
return LayoutLMvaImageProcessor(apply_ocr=UpperCamelCase__ ) if is_vision_available() else None
@slow
def __lowercase ( self : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Union[str, Any] = LayoutLMvaModel.from_pretrained('''microsoft/layoutlmv3-base''' ).to(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : Optional[Any] = self.default_image_processor
SCREAMING_SNAKE_CASE : List[str] = prepare_img()
SCREAMING_SNAKE_CASE : Any = image_processor(images=UpperCamelCase__ , return_tensors='''pt''' ).pixel_values.to(UpperCamelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[1, 2]] )
SCREAMING_SNAKE_CASE : List[Any] = torch.tensor([[1, 2, 3, 4], [5, 6, 7, 8]] ).unsqueeze(0 )
# forward pass
SCREAMING_SNAKE_CASE : List[str] = model(
input_ids=input_ids.to(UpperCamelCase__ ) , bbox=bbox.to(UpperCamelCase__ ) , pixel_values=pixel_values.to(UpperCamelCase__ ) , )
# verify the logits
SCREAMING_SNAKE_CASE : Any = torch.Size((1, 1_99, 7_68) )
self.assertEqual(outputs.last_hidden_state.shape , UpperCamelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = torch.tensor(
[[-0.0529, 0.3618, 0.1632], [-0.1587, -0.1667, -0.0400], [-0.1557, -0.1671, -0.0505]] ).to(UpperCamelCase__ )
self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , UpperCamelCase__ , atol=1e-4 ) )
| 700 |
'''simple docstring'''
import warnings
from typing import List, Optional, Union
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class lowerCamelCase_ ( snake_case_ ):
_lowerCAmelCase : int = ['image_processor', 'tokenizer']
_lowerCAmelCase : Union[str, Any] = 'LayoutLMv3ImageProcessor'
_lowerCAmelCase : List[Any] = ('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast')
def __init__( self : str , lowerCAmelCase__ : int=None , lowerCAmelCase__ : str=None , **lowerCAmelCase__ : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = None
if "feature_extractor" in kwargs:
warnings.warn(
'''The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`'''
''' instead.''' , lowerCAmelCase__ , )
SCREAMING_SNAKE_CASE : List[str] = kwargs.pop('''feature_extractor''' )
SCREAMING_SNAKE_CASE : 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__(lowerCAmelCase__ , lowerCAmelCase__ )
def __call__( self : Dict , lowerCAmelCase__ : Any , lowerCAmelCase__ : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , lowerCAmelCase__ : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , lowerCAmelCase__ : Union[List[List[int]], List[List[List[int]]]] = None , lowerCAmelCase__ : Optional[Union[List[int], List[List[int]]]] = None , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : Union[bool, str, PaddingStrategy] = False , lowerCAmelCase__ : Union[bool, str, TruncationStrategy] = None , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : int = 0 , lowerCAmelCase__ : Optional[int] = None , lowerCAmelCase__ : Optional[bool] = None , lowerCAmelCase__ : Optional[bool] = None , lowerCAmelCase__ : bool = False , lowerCAmelCase__ : bool = False , lowerCAmelCase__ : bool = False , lowerCAmelCase__ : bool = False , lowerCAmelCase__ : bool = True , lowerCAmelCase__ : Optional[Union[str, TensorType]] = None , **lowerCAmelCase__ : Any , ):
"""simple docstring"""
# verify input
if self.image_processor.apply_ocr and (boxes is not None):
raise ValueError(
'''You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True.''' )
if self.image_processor.apply_ocr and (word_labels is not None):
raise ValueError(
'''You cannot provide word labels if you initialized the image processor with apply_ocr set to True.''' )
# first, apply the image processor
SCREAMING_SNAKE_CASE : List[Any] = self.image_processor(images=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ )
# second, apply the tokenizer
if text is not None and self.image_processor.apply_ocr and text_pair is None:
if isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
SCREAMING_SNAKE_CASE : List[Any] = [text] # add batch dimension (as the image processor always adds a batch dimension)
SCREAMING_SNAKE_CASE : Optional[Any] = features['''words''']
SCREAMING_SNAKE_CASE : Tuple = self.tokenizer(
text=text if text is not None else features['''words'''] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features['''boxes'''] , word_labels=lowerCAmelCase__ , add_special_tokens=lowerCAmelCase__ , padding=lowerCAmelCase__ , truncation=lowerCAmelCase__ , max_length=lowerCAmelCase__ , stride=lowerCAmelCase__ , pad_to_multiple_of=lowerCAmelCase__ , return_token_type_ids=lowerCAmelCase__ , return_attention_mask=lowerCAmelCase__ , return_overflowing_tokens=lowerCAmelCase__ , return_special_tokens_mask=lowerCAmelCase__ , return_offsets_mapping=lowerCAmelCase__ , return_length=lowerCAmelCase__ , verbose=lowerCAmelCase__ , return_tensors=lowerCAmelCase__ , **lowerCAmelCase__ , )
# add pixel values
SCREAMING_SNAKE_CASE : List[Any] = features.pop('''pixel_values''' )
if return_overflowing_tokens is True:
SCREAMING_SNAKE_CASE : Any = self.get_overflowing_images(lowerCAmelCase__ , encoded_inputs['''overflow_to_sample_mapping'''] )
SCREAMING_SNAKE_CASE : Any = images
return encoded_inputs
def __lowercase ( self : str , lowerCAmelCase__ : Optional[Any] , lowerCAmelCase__ : Optional[int] ):
"""simple docstring"""
# in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image
SCREAMING_SNAKE_CASE : Dict = []
for sample_idx in overflow_to_sample_mapping:
images_with_overflow.append(images[sample_idx] )
if len(lowerCAmelCase__ ) != len(lowerCAmelCase__ ):
raise ValueError(
'''Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got'''
F""" {len(lowerCAmelCase__ )} and {len(lowerCAmelCase__ )}""" )
return images_with_overflow
def __lowercase ( self : Any , *lowerCAmelCase__ : Union[str, Any] , **lowerCAmelCase__ : List[Any] ):
"""simple docstring"""
return self.tokenizer.batch_decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
def __lowercase ( self : Optional[int] , *lowerCAmelCase__ : Optional[Any] , **lowerCAmelCase__ : Tuple ):
"""simple docstring"""
return self.tokenizer.decode(*lowerCAmelCase__ , **lowerCAmelCase__ )
@property
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
return ["input_ids", "bbox", "attention_mask", "pixel_values"]
@property
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
warnings.warn(
'''`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.''' , lowerCAmelCase__ , )
return self.image_processor_class
@property
def __lowercase ( self : List[Any] ):
"""simple docstring"""
warnings.warn(
'''`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.''' , lowerCAmelCase__ , )
return self.image_processor
| 464 | 0 |
#
# This a `torch.distributed` diagnostics script that checks that all GPUs in the cluster (one or
# many nodes) can talk to each other via nccl and allocate gpu memory.
#
# To run first adjust the number of processes and nodes:
#
# python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# You may need to add --master_addr $MASTER_ADDR --master_port $MASTER_PORT if using a custom addr:port
#
# You can also use the rdzv API: --rdzv_endpoint $MASTER_ADDR:$MASTER_PORT --rdzv_backend c10d
#
# use torch.distributed.launch instead of torch.distributed.run for torch < 1.9
#
# If you get a hanging in `barrier` calls you have some network issues, you may try to debug this with:
#
# NCCL_DEBUG=INFO python -m torch.distributed.run --nproc_per_node 2 --nnodes 1 torch-distributed-gpu-test.py
#
# which should tell you what's going on behind the scenes.
#
#
# This script can be run via `srun` in the SLURM environment as well. Here is a SLURM script that
# runs on 2 nodes of 4 gpus per node:
#
# #SBATCH --job-name=test-nodes # name
# #SBATCH --nodes=2 # nodes
# #SBATCH --ntasks-per-node=1 # crucial - only 1 task per dist per node!
# #SBATCH --cpus-per-task=10 # number of cores per tasks
# #SBATCH --gres=gpu:4 # number of gpus
# #SBATCH --time 0:05:00 # maximum execution time (HH:MM:SS)
# #SBATCH --output=%x-%j.out # output file name
#
# GPUS_PER_NODE=4
# MASTER_ADDR=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1)
# MASTER_PORT=6000
#
# srun --jobid $SLURM_JOBID bash -c 'python -m torch.distributed.run \
# --nproc_per_node $GPUS_PER_NODE --nnodes $SLURM_NNODES --node_rank $SLURM_PROCID \
# --master_addr $MASTER_ADDR --master_port $MASTER_PORT \
# torch-distributed-gpu-test.py'
#
import fcntl
import os
import socket
import torch
import torch.distributed as dist
def _a ( *lowercase__ : List[str] ):
'''simple docstring'''
with open(lowercase__ , 'r' ) as fh:
fcntl.flock(lowercase__ , fcntl.LOCK_EX )
try:
print(*lowercase__ )
finally:
fcntl.flock(lowercase__ , fcntl.LOCK_UN )
SCREAMING_SNAKE_CASE__ : int = int(os.environ["LOCAL_RANK"])
torch.cuda.set_device(local_rank)
SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.device("cuda", local_rank)
SCREAMING_SNAKE_CASE__ : Dict = socket.gethostname()
SCREAMING_SNAKE_CASE__ : str = F"""[{hostname}-{local_rank}]"""
try:
# test distributed
dist.init_process_group("nccl")
dist.all_reduce(torch.ones(1).to(device), op=dist.ReduceOp.SUM)
dist.barrier()
# test cuda is available and can allocate memory
torch.cuda.is_available()
torch.ones(1).cuda(local_rank)
# global rank
SCREAMING_SNAKE_CASE__ : str = dist.get_rank()
SCREAMING_SNAKE_CASE__ : List[str] = dist.get_world_size()
printflock(F"""{gpu} is OK (global rank: {rank}/{world_size})""")
dist.barrier()
if rank == 0:
printflock(F"""pt={torch.__version__}, cuda={torch.version.cuda}, nccl={torch.cuda.nccl.version()}""")
except Exception:
printflock(F"""{gpu} is broken""")
raise
| 85 |
'''simple docstring'''
import datasets
import faiss
import numpy as np
import streamlit as st
import torch
from elasticsearch import Elasticsearch
from elia_utils import (
embed_questions_for_retrieval,
make_qa_sas_model,
qa_sas_generate,
query_es_index,
query_qa_dense_index,
)
import transformers
from transformers import AutoModel, AutoModelForSeqaSeqLM, AutoTokenizer
__UpperCamelCase = "bart"
__UpperCamelCase = True
@st.cache(allow_output_mutation=_lowerCamelCase )
def _a ( ) -> Union[str, Any]:
"""simple docstring"""
if LOAD_DENSE_INDEX:
__snake_case : int = AutoTokenizer.from_pretrained("""yjernite/retribert-base-uncased""" )
__snake_case : Tuple = AutoModel.from_pretrained("""yjernite/retribert-base-uncased""" ).to("""cuda:0""" )
__snake_case : List[Any] = qar_model.eval()
else:
__snake_case , __snake_case : Optional[Any] = (None, None)
if MODEL_TYPE == "bart":
__snake_case : List[str] = AutoTokenizer.from_pretrained("""yjernite/bart_eli5""" )
__snake_case : Any = AutoModelForSeqaSeqLM.from_pretrained("""yjernite/bart_eli5""" ).to("""cuda:0""" )
__snake_case : int = torch.load("""seq2seq_models/eli5_bart_model_blm_2.pth""" )
sas_model.load_state_dict(save_dict["""model"""] )
__snake_case : int = sas_model.eval()
else:
__snake_case , __snake_case : Dict = make_qa_sas_model(
model_name="""t5-small""" , from_file="""seq2seq_models/eli5_t5_model_1024_4.pth""" , device="""cuda:0""" )
return (qar_tokenizer, qar_model, sas_tokenizer, sas_model)
@st.cache(allow_output_mutation=_lowerCamelCase )
def _a ( ) -> Tuple:
"""simple docstring"""
if LOAD_DENSE_INDEX:
__snake_case : Tuple = faiss.StandardGpuResources()
__snake_case : Optional[Any] = datasets.load_dataset(path="""wiki_snippets""" , name="""wiki40b_en_100_0""" )["""train"""]
__snake_case : str = np.memmap(
"""wiki40b_passages_reps_32_l-8_h-768_b-512-512.dat""" , dtype="""float32""" , mode="""r""" , shape=(wikiaab_passages.num_rows, 128) , )
__snake_case : Optional[int] = faiss.IndexFlatIP(128 )
__snake_case : Any = faiss.index_cpu_to_gpu(_lowerCamelCase , 1 , _lowerCamelCase )
wikiaab_gpu_index_flat.add(_lowerCamelCase ) # TODO fix for larger GPU
else:
__snake_case , __snake_case : Tuple = (None, None)
__snake_case : List[str] = Elasticsearch([{"""host""": """localhost""", """port""": """9200"""}] )
return (wikiaab_passages, wikiaab_gpu_index_flat, es_client)
@st.cache(allow_output_mutation=_lowerCamelCase )
def _a ( ) -> List[Any]:
"""simple docstring"""
__snake_case : Tuple = datasets.load_dataset("""eli5""" , name="""LFQA_reddit""" )
__snake_case : Dict = elia["""train_eli5"""]
__snake_case : int = np.memmap(
"""eli5_questions_reps.dat""" , dtype="""float32""" , mode="""r""" , shape=(elia_train.num_rows, 128) )
__snake_case : Dict = faiss.IndexFlatIP(128 )
eli5_train_q_index.add(_lowerCamelCase )
return (elia_train, eli5_train_q_index)
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase = load_indexes()
__UpperCamelCase , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = load_models()
__UpperCamelCase , __UpperCamelCase = load_train_data()
def _a ( _lowerCamelCase , _lowerCamelCase=10 ) -> int:
"""simple docstring"""
__snake_case : Optional[int] = embed_questions_for_retrieval([question] , _lowerCamelCase , _lowerCamelCase )
__snake_case , __snake_case : Tuple = eli5_train_q_index.search(_lowerCamelCase , _lowerCamelCase )
__snake_case : Tuple = [elia_train[int(_lowerCamelCase )] for i in I[0]]
return nn_examples
def _a ( _lowerCamelCase , _lowerCamelCase="wiki40b" , _lowerCamelCase="dense" , _lowerCamelCase=10 ) -> Optional[Any]:
"""simple docstring"""
if source == "none":
__snake_case , __snake_case : Dict = (""" <P> """.join(["""""" for _ in range(11 )] ).strip(), [])
else:
if method == "dense":
__snake_case , __snake_case : Dict = query_qa_dense_index(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
else:
__snake_case , __snake_case : str = query_es_index(
_lowerCamelCase , _lowerCamelCase , index_name="""english_wiki40b_snippets_100w""" , n_results=_lowerCamelCase , )
__snake_case : Optional[int] = [
(res["""article_title"""], res["""section_title"""].strip(), res["""score"""], res["""passage_text"""]) for res in hit_lst
]
__snake_case : Optional[Any] = """question: {} context: {}""".format(_lowerCamelCase , _lowerCamelCase )
return question_doc, support_list
@st.cache(
hash_funcs={
torch.Tensor: (lambda _lowerCamelCase : None),
transformers.models.bart.tokenization_bart.BartTokenizer: (lambda _lowerCamelCase : None),
} )
def _a ( _lowerCamelCase , _lowerCamelCase , _lowerCamelCase , _lowerCamelCase=64 , _lowerCamelCase=256 , _lowerCamelCase=False , _lowerCamelCase=2 , _lowerCamelCase=0.95 , _lowerCamelCase=0.8 ) -> List[str]:
"""simple docstring"""
with torch.no_grad():
__snake_case : Union[str, Any] = qa_sas_generate(
_lowerCamelCase , _lowerCamelCase , _lowerCamelCase , num_answers=1 , num_beams=_lowerCamelCase , min_len=_lowerCamelCase , max_len=_lowerCamelCase , do_sample=_lowerCamelCase , temp=_lowerCamelCase , top_p=_lowerCamelCase , top_k=_lowerCamelCase , max_input_length=1024 , device="""cuda:0""" , )[0]
return (answer, support_list)
st.title("Long Form Question Answering with ELI5")
# Start sidebar
__UpperCamelCase = "<img src='https://huggingface.co/front/assets/huggingface_logo.svg'>"
__UpperCamelCase = "\n<html>\n <head>\n <style>\n .img-container {\n padding-left: 90px;\n padding-right: 90px;\n padding-top: 50px;\n padding-bottom: 50px;\n background-color: #f0f3f9;\n }\n </style>\n </head>\n <body>\n <span class=\"img-container\"> <!-- Inline parent element -->\n %s\n </span>\n </body>\n</html>\n" % (
header_html,
)
st.sidebar.markdown(
header_full,
unsafe_allow_html=True,
)
# Long Form QA with ELI5 and Wikipedia
__UpperCamelCase = "\nThis demo presents a model trained to [provide long-form answers to open-domain questions](https://yjernite.github.io/lfqa.html).\nFirst, a document retriever fetches a set of relevant Wikipedia passages given the question from the [Wiki40b](https://research.google/pubs/pub49029/) dataset,\na pre-processed fixed snapshot of Wikipedia.\n"
st.sidebar.markdown(description, unsafe_allow_html=True)
__UpperCamelCase = [
"Answer the question",
"View the retrieved document only",
"View the most similar ELI5 question and answer",
"Show me everything, please!",
]
__UpperCamelCase = st.sidebar.checkbox("Demo options")
if demo_options:
__UpperCamelCase = st.sidebar.selectbox(
"",
action_list,
index=3,
)
__UpperCamelCase = action_list.index(action_st)
__UpperCamelCase = st.sidebar.selectbox(
"",
["Show full text of passages", "Show passage section titles"],
index=0,
)
__UpperCamelCase = show_type == "Show full text of passages"
else:
__UpperCamelCase = 3
__UpperCamelCase = True
__UpperCamelCase = st.sidebar.checkbox("Retrieval options")
if retrieval_options:
__UpperCamelCase = "\n ### Information retriever options\n\n The **sparse** retriever uses ElasticSearch, while the **dense** retriever uses max-inner-product search between a question and passage embedding\n trained using the [ELI5](https://arxiv.org/abs/1907.09190) questions-answer pairs.\n The answer is then generated by sequence to sequence model which takes the question and retrieved document as input.\n "
st.sidebar.markdown(retriever_info)
__UpperCamelCase = st.sidebar.selectbox("Which Wikipedia format should the model use?", ["wiki40b", "none"])
__UpperCamelCase = st.sidebar.selectbox("Which Wikipedia indexer should the model use?", ["dense", "sparse", "mixed"])
else:
__UpperCamelCase = "wiki40b"
__UpperCamelCase = "dense"
__UpperCamelCase = "beam"
__UpperCamelCase = 2
__UpperCamelCase = 64
__UpperCamelCase = 256
__UpperCamelCase = None
__UpperCamelCase = None
__UpperCamelCase = st.sidebar.checkbox("Generation options")
if generate_options:
__UpperCamelCase = "\n ### Answer generation options\n\n The sequence-to-sequence model was initialized with [BART](https://huggingface.co/facebook/bart-large)\n weights and fine-tuned on the ELI5 QA pairs and retrieved documents. You can use the model for greedy decoding with\n **beam** search, or **sample** from the decoder's output probabilities.\n "
st.sidebar.markdown(generate_info)
__UpperCamelCase = st.sidebar.selectbox("Would you like to use beam search or sample an answer?", ["beam", "sampled"])
__UpperCamelCase = st.sidebar.slider(
"Minimum generation length", min_value=8, max_value=256, value=64, step=8, format=None, key=None
)
__UpperCamelCase = st.sidebar.slider(
"Maximum generation length", min_value=64, max_value=512, value=256, step=16, format=None, key=None
)
if sampled == "beam":
__UpperCamelCase = st.sidebar.slider("Beam size", min_value=1, max_value=8, value=2, step=None, format=None, key=None)
else:
__UpperCamelCase = st.sidebar.slider(
"Nucleus sampling p", min_value=0.1, max_value=1.0, value=0.95, step=0.01, format=None, key=None
)
__UpperCamelCase = st.sidebar.slider(
"Temperature", min_value=0.1, max_value=1.0, value=0.7, step=0.01, format=None, key=None
)
__UpperCamelCase = None
# start main text
__UpperCamelCase = [
"<MY QUESTION>",
"How do people make chocolate?",
"Why do we get a fever when we are sick?",
"How can different animals perceive different colors?",
"What is natural language processing?",
"What's the best way to treat a sunburn?",
"What exactly are vitamins ?",
"How does nuclear energy provide electricity?",
"What's the difference between viruses and bacteria?",
"Why are flutes classified as woodwinds when most of them are made out of metal ?",
"Why do people like drinking coffee even though it tastes so bad?",
"What happens when wine ages? How does it make the wine taste better?",
"If an animal is an herbivore, where does it get the protein that it needs to survive if it only eats grass?",
"How can we set a date to the beginning or end of an artistic period? Doesn't the change happen gradually?",
"How does New Zealand have so many large bird predators?",
]
__UpperCamelCase = st.selectbox(
"What would you like to ask? ---- select <MY QUESTION> to enter a new query",
questions_list,
index=1,
)
if question_s == "<MY QUESTION>":
__UpperCamelCase = st.text_input("Enter your question here:", "")
else:
__UpperCamelCase = question_s
if st.button("Show me!"):
if action in [0, 1, 3]:
if index_type == "mixed":
__UpperCamelCase , __UpperCamelCase = make_support(question, source=wiki_source, method="dense", n_results=10)
__UpperCamelCase , __UpperCamelCase = make_support(question, source=wiki_source, method="sparse", n_results=10)
__UpperCamelCase = []
for res_d, res_s in zip(support_list_dense, support_list_sparse):
if tuple(res_d) not in support_list:
support_list += [tuple(res_d)]
if tuple(res_s) not in support_list:
support_list += [tuple(res_s)]
__UpperCamelCase = support_list[:10]
__UpperCamelCase = "<P> " + " <P> ".join([res[-1] for res in support_list])
else:
__UpperCamelCase , __UpperCamelCase = make_support(question, source=wiki_source, method=index_type, n_results=10)
if action in [0, 3]:
__UpperCamelCase , __UpperCamelCase = answer_question(
question_doc,
sas_model,
sas_tokenizer,
min_len=min_len,
max_len=int(max_len),
sampling=(sampled == "sampled"),
n_beams=n_beams,
top_p=top_p,
temp=temp,
)
st.markdown("### The model generated answer is:")
st.write(answer)
if action in [0, 1, 3] and wiki_source != "none":
st.markdown("--- \n ### The model is drawing information from the following Wikipedia passages:")
for i, res in enumerate(support_list):
__UpperCamelCase = "https://en.wikipedia.org/wiki/{}".format(res[0].replace(" ", "_"))
__UpperCamelCase = res[1].strip()
if sec_titles == "":
__UpperCamelCase = "[{}]({})".format(res[0], wiki_url)
else:
__UpperCamelCase = sec_titles.split(" & ")
__UpperCamelCase = " & ".join(
["[{}]({}#{})".format(sec.strip(), wiki_url, sec.strip().replace(" ", "_")) for sec in sec_list]
)
st.markdown(
"{0:02d} - **Article**: {1:<18} <br> _Section_: {2}".format(i + 1, res[0], sections),
unsafe_allow_html=True,
)
if show_passages:
st.write(
"> <span style=\"font-family:arial; font-size:10pt;\">" + res[-1] + "</span>", unsafe_allow_html=True
)
if action in [2, 3]:
__UpperCamelCase = find_nearest_training(question)
__UpperCamelCase = nn_train_list[0]
st.markdown(
"--- \n ### The most similar question in the ELI5 training set was: \n\n {}".format(train_exple["title"])
)
__UpperCamelCase = [
"{}. {}".format(i + 1, " \n".join([line.strip() for line in ans.split("\n") if line.strip() != ""]))
for i, (ans, sc) in enumerate(zip(train_exple["answers"]["text"], train_exple["answers"]["score"]))
if i == 0 or sc > 2
]
st.markdown("##### Its answers were: \n\n {}".format("\n".join(answers_st)))
__UpperCamelCase = "\n---\n\n**Disclaimer**\n\n*The intent of this app is to provide some (hopefully entertaining) insights into the behavior of a current LFQA system.\nEvaluating biases of such a model and ensuring factual generations are still very much open research problems.\nTherefore, until some significant progress is achieved, we caution against using the generated answers for practical purposes.*\n"
st.sidebar.markdown(disclaimer, unsafe_allow_html=True)
| 26 | 0 |
import gc
import unittest
import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, XLMRobertaTokenizer
from diffusers import AltDiffusionPipeline, AutoencoderKL, DDIMScheduler, PNDMScheduler, UNetaDConditionModel
from diffusers.pipelines.alt_diffusion.modeling_roberta_series import (
RobertaSeriesConfig,
RobertaSeriesModelWithTransformation,
)
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
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
enable_full_determinism()
class SCREAMING_SNAKE_CASE_ (a__ , a__ , a__ , unittest.TestCase ):
'''simple docstring'''
_a = AltDiffusionPipeline
_a = TEXT_TO_IMAGE_PARAMS
_a = TEXT_TO_IMAGE_BATCH_PARAMS
_a = TEXT_TO_IMAGE_IMAGE_PARAMS
_a = TEXT_TO_IMAGE_IMAGE_PARAMS
def _lowerCAmelCase ( self : int ) ->Optional[int]:
torch.manual_seed(0 )
lowerCamelCase_ : Optional[int] = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , )
lowerCamelCase_ : Optional[Any] = DDIMScheduler(
beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=UpperCamelCase_ , set_alpha_to_one=UpperCamelCase_ , )
torch.manual_seed(0 )
lowerCamelCase_ : Optional[int] = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , )
# TODO: address the non-deterministic text encoder (fails for save-load tests)
# torch.manual_seed(0)
# text_encoder_config = RobertaSeriesConfig(
# hidden_size=32,
# project_dim=32,
# intermediate_size=37,
# layer_norm_eps=1e-05,
# num_attention_heads=4,
# num_hidden_layers=5,
# vocab_size=5002,
# )
# text_encoder = RobertaSeriesModelWithTransformation(text_encoder_config)
torch.manual_seed(0 )
lowerCamelCase_ : Any = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=5_002 , )
lowerCamelCase_ : str = CLIPTextModel(UpperCamelCase_ )
lowerCamelCase_ : str = XLMRobertaTokenizer.from_pretrained("""hf-internal-testing/tiny-xlm-roberta""" )
lowerCamelCase_ : Union[str, Any] = 77
lowerCamelCase_ : Union[str, Any] = {
'unet': unet,
'scheduler': scheduler,
'vae': vae,
'text_encoder': text_encoder,
'tokenizer': tokenizer,
'safety_checker': None,
'feature_extractor': None,
}
return components
def _lowerCAmelCase ( self : Optional[int] , __a : Optional[Any] , __a : List[Any]=0 ) ->Optional[int]:
if str(UpperCamelCase_ ).startswith("""mps""" ):
lowerCamelCase_ : Union[str, Any] = torch.manual_seed(UpperCamelCase_ )
else:
lowerCamelCase_ : Any = torch.Generator(device=UpperCamelCase_ ).manual_seed(UpperCamelCase_ )
lowerCamelCase_ : List[Any] = {
'prompt': 'A painting of a squirrel eating a burger',
'generator': generator,
'num_inference_steps': 2,
'guidance_scale': 6.0,
'output_type': 'numpy',
}
return inputs
def _lowerCAmelCase ( self : List[str] ) ->int:
super().test_attention_slicing_forward_pass(expected_max_diff=3e-3 )
def _lowerCAmelCase ( self : Optional[int] ) ->Any:
super().test_inference_batch_single_identical(expected_max_diff=3e-3 )
def _lowerCAmelCase ( self : Optional[Any] ) ->Dict:
lowerCamelCase_ : Dict = 'cpu' # ensure determinism for the device-dependent torch.Generator
lowerCamelCase_ : List[Any] = self.get_dummy_components()
torch.manual_seed(0 )
lowerCamelCase_ : List[Any] = RobertaSeriesConfig(
hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_002 , )
# TODO: remove after fixing the non-deterministic text encoder
lowerCamelCase_ : Optional[Any] = RobertaSeriesModelWithTransformation(UpperCamelCase_ )
lowerCamelCase_ : str = text_encoder
lowerCamelCase_ : str = AltDiffusionPipeline(**UpperCamelCase_ )
lowerCamelCase_ : List[Any] = alt_pipe.to(UpperCamelCase_ )
alt_pipe.set_progress_bar_config(disable=UpperCamelCase_ )
lowerCamelCase_ : Any = self.get_dummy_inputs(UpperCamelCase_ )
lowerCamelCase_ : int = 'A photo of an astronaut'
lowerCamelCase_ : Optional[int] = alt_pipe(**UpperCamelCase_ )
lowerCamelCase_ : List[str] = output.images
lowerCamelCase_ : Dict = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
lowerCamelCase_ : Union[str, Any] = np.array(
[0.5_748_162, 0.60_447_145, 0.48_821_217, 0.50_100_636, 0.5_431_185, 0.45_763_683, 0.49_657_696, 0.48_132_733, 0.47_573_093] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def _lowerCAmelCase ( self : Optional[int] ) ->List[str]:
lowerCamelCase_ : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator
lowerCamelCase_ : List[Any] = self.get_dummy_components()
lowerCamelCase_ : int = PNDMScheduler(skip_prk_steps=UpperCamelCase_ )
torch.manual_seed(0 )
lowerCamelCase_ : Dict = RobertaSeriesConfig(
hidden_size=32 , project_dim=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=5_002 , )
# TODO: remove after fixing the non-deterministic text encoder
lowerCamelCase_ : Optional[int] = RobertaSeriesModelWithTransformation(UpperCamelCase_ )
lowerCamelCase_ : Tuple = text_encoder
lowerCamelCase_ : str = AltDiffusionPipeline(**UpperCamelCase_ )
lowerCamelCase_ : List[Any] = alt_pipe.to(UpperCamelCase_ )
alt_pipe.set_progress_bar_config(disable=UpperCamelCase_ )
lowerCamelCase_ : Dict = self.get_dummy_inputs(UpperCamelCase_ )
lowerCamelCase_ : List[str] = alt_pipe(**UpperCamelCase_ )
lowerCamelCase_ : Any = output.images
lowerCamelCase_ : int = image[0, -3:, -3:, -1]
assert image.shape == (1, 64, 64, 3)
lowerCamelCase_ : str = np.array(
[0.51_605_093, 0.5_707_241, 0.47_365_507, 0.50_578_886, 0.5_633_877, 0.4_642_503, 0.5_182_081, 0.48_763_484, 0.49_084_237] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
@slow
@require_torch_gpu
class SCREAMING_SNAKE_CASE_ (unittest.TestCase ):
'''simple docstring'''
def _lowerCAmelCase ( self : List[str] ) ->Union[str, Any]:
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _lowerCAmelCase ( self : str ) ->int:
lowerCamelCase_ : int = AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion""" , safety_checker=UpperCamelCase_ )
lowerCamelCase_ : List[Any] = alt_pipe.to(UpperCamelCase_ )
alt_pipe.set_progress_bar_config(disable=UpperCamelCase_ )
lowerCamelCase_ : Any = 'A painting of a squirrel eating a burger'
lowerCamelCase_ : int = torch.manual_seed(0 )
lowerCamelCase_ : Dict = alt_pipe([prompt] , generator=UpperCamelCase_ , guidance_scale=6.0 , num_inference_steps=20 , output_type="""np""" )
lowerCamelCase_ : List[Any] = output.images
lowerCamelCase_ : str = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
lowerCamelCase_ : Optional[int] = np.array([0.1_010, 0.0_800, 0.0_794, 0.0_885, 0.0_843, 0.0_762, 0.0_769, 0.0_729, 0.0_586] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
def _lowerCAmelCase ( self : List[str] ) ->int:
lowerCamelCase_ : Union[str, Any] = DDIMScheduler.from_pretrained("""BAAI/AltDiffusion""" , subfolder="""scheduler""" )
lowerCamelCase_ : Optional[Any] = AltDiffusionPipeline.from_pretrained("""BAAI/AltDiffusion""" , scheduler=UpperCamelCase_ , safety_checker=UpperCamelCase_ )
lowerCamelCase_ : str = alt_pipe.to(UpperCamelCase_ )
alt_pipe.set_progress_bar_config(disable=UpperCamelCase_ )
lowerCamelCase_ : int = 'A painting of a squirrel eating a burger'
lowerCamelCase_ : Any = torch.manual_seed(0 )
lowerCamelCase_ : Optional[Any] = alt_pipe([prompt] , generator=UpperCamelCase_ , num_inference_steps=2 , output_type="""numpy""" )
lowerCamelCase_ : List[Any] = output.images
lowerCamelCase_ : List[str] = image[0, -3:, -3:, -1]
assert image.shape == (1, 512, 512, 3)
lowerCamelCase_ : str = np.array([0.4_019, 0.4_052, 0.3_810, 0.4_119, 0.3_916, 0.3_982, 0.4_651, 0.4_195, 0.5_323] )
assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
| 704 |
import argparse
snake_case__ : Dict = 'docs/source/_static/js/custom.js'
def __lowerCamelCase ( A__ : List[str] ) -> int:
with open(A__ , encoding="""utf-8""" , newline="""\n""" ) as f:
lowerCamelCase_ : List[Any] = f.readlines()
lowerCamelCase_ : Dict = 0
# First let's put the right version
while not lines[index].startswith("""const stableVersion =""" ):
index += 1
lowerCamelCase_ : int = f'''const stableVersion = "v{version}"\n'''
# Then update the dictionary
while not lines[index].startswith("""const versionMapping = {""" ):
index += 1
# We go until the end
while not lines[index].startswith("""}""" ):
index += 1
# We add the new version at the end
lines[index - 1] += f''' "v{version}": "v{version}",\n'''
with open(A__ , """w""" , encoding="""utf-8""" , newline="""\n""" ) as f:
f.writelines(A__ )
if __name__ == "__main__":
snake_case__ : int = argparse.ArgumentParser()
parser.add_argument('--version', help='Release version.')
snake_case__ : Tuple = parser.parse_args()
update_custom_js(args.version)
| 171 | 0 |
"""simple docstring"""
import inspect
from typing import Callable, List, Optional, Union
import torch
from transformers import CLIPImageProcessor, CLIPTextModel, CLIPTokenizer
from diffusers import DiffusionPipeline
from diffusers.models import AutoencoderKL, UNetaDConditionModel
from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker
from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
from diffusers.utils import logging
_UpperCamelCase = logging.get_logger(__name__) # pylint: disable=invalid-name
class __UpperCAmelCase (__A ):
'''simple docstring'''
def __init__( self , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ , ):
'''simple docstring'''
super().__init__()
self.register_modules(
vae=snake_case_ , text_encoder=snake_case_ , tokenizer=snake_case_ , unet=snake_case_ , scheduler=snake_case_ , safety_checker=snake_case_ , feature_extractor=snake_case_ , )
def lowerCamelCase ( self , snake_case_ = "auto" ):
'''simple docstring'''
if slice_size == "auto":
# half the attention head size is usually a good trade-off between
# speed and memory
A__ : List[str] = self.unet.config.attention_head_dim // 2
self.unet.set_attention_slice(snake_case_ )
def lowerCamelCase ( self ):
'''simple docstring'''
self.enable_attention_slicing(snake_case_ )
@torch.no_grad()
def __call__( self , snake_case_ , snake_case_ = 512 , snake_case_ = 512 , snake_case_ = 50 , snake_case_ = 7.5 , snake_case_ = None , snake_case_ = 1 , snake_case_ = 0.0 , snake_case_ = None , snake_case_ = None , snake_case_ = "pil" , snake_case_ = True , snake_case_ = None , snake_case_ = 1 , snake_case_ = None , **snake_case_ , ):
'''simple docstring'''
if isinstance(snake_case_ , snake_case_ ):
A__ : Optional[int] = 1
elif isinstance(snake_case_ , snake_case_ ):
A__ : List[Any] = len(snake_case_ )
else:
raise ValueError(F'''`prompt` has to be of type `str` or `list` but is {type(snake_case_ )}''' )
if height % 8 != 0 or width % 8 != 0:
raise ValueError(F'''`height` and `width` have to be divisible by 8 but are {height} and {width}.''' )
if (callback_steps is None) or (
callback_steps is not None and (not isinstance(snake_case_ , snake_case_ ) or callback_steps <= 0)
):
raise ValueError(
F'''`callback_steps` has to be a positive integer but is {callback_steps} of type'''
F''' {type(snake_case_ )}.''' )
# get prompt text embeddings
A__ : List[str] = self.tokenizer(
snake_case_ , padding="""max_length""" , max_length=self.tokenizer.model_max_length , return_tensors="""pt""" , )
A__ : List[Any] = text_inputs.input_ids
if text_input_ids.shape[-1] > self.tokenizer.model_max_length:
A__ : int = self.tokenizer.batch_decode(text_input_ids[:, self.tokenizer.model_max_length :] )
logger.warning(
"""The following part of your input was truncated because CLIP can only handle sequences up to"""
F''' {self.tokenizer.model_max_length} tokens: {removed_text}''' )
A__ : Tuple = text_input_ids[:, : self.tokenizer.model_max_length]
if text_embeddings is None:
A__ : Any = self.text_encoder(text_input_ids.to(self.device ) )[0]
# duplicate text embeddings for each generation per prompt, using mps friendly method
A__ , A__ , A__ : str = text_embeddings.shape
A__ : List[str] = text_embeddings.repeat(1 , snake_case_ , 1 )
A__ : int = text_embeddings.view(bs_embed * num_images_per_prompt , snake_case_ , -1 )
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
# corresponds to doing no classifier free guidance.
A__ : str = guidance_scale > 1.0
# get unconditional embeddings for classifier free guidance
if do_classifier_free_guidance:
A__ : List[str]
if negative_prompt is None:
A__ : List[str] = [""""""]
elif type(snake_case_ ) is not type(snake_case_ ):
raise TypeError(
F'''`negative_prompt` should be the same type to `prompt`, but got {type(snake_case_ )} !='''
F''' {type(snake_case_ )}.''' )
elif isinstance(snake_case_ , snake_case_ ):
A__ : int = [negative_prompt]
elif batch_size != len(snake_case_ ):
raise ValueError(
F'''`negative_prompt`: {negative_prompt} has batch size {len(snake_case_ )}, but `prompt`:'''
F''' {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches'''
""" the batch size of `prompt`.""" )
else:
A__ : Tuple = negative_prompt
A__ : Any = text_input_ids.shape[-1]
A__ : Any = self.tokenizer(
snake_case_ , padding="""max_length""" , max_length=snake_case_ , truncation=snake_case_ , return_tensors="""pt""" , )
A__ : Optional[Any] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0]
# duplicate unconditional embeddings for each generation per prompt, using mps friendly method
A__ : Union[str, Any] = uncond_embeddings.shape[1]
A__ : List[str] = uncond_embeddings.repeat(snake_case_ , snake_case_ , 1 )
A__ : Optional[Any] = uncond_embeddings.view(batch_size * num_images_per_prompt , snake_case_ , -1 )
# 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
A__ : Tuple = torch.cat([uncond_embeddings, text_embeddings] )
# get the initial random noise unless the user supplied it
# Unlike in other pipelines, latents need to be generated in the target device
# for 1-to-1 results reproducibility with the CompVis implementation.
# However this currently doesn't work in `mps`.
A__ : Dict = (batch_size * num_images_per_prompt, self.unet.config.in_channels, height // 8, width // 8)
A__ : Union[str, Any] = (batch_size * num_images_per_prompt, self.unet.config.in_channels, 64, 64)
A__ : Union[str, Any] = text_embeddings.dtype
if latents is None:
if self.device.type == "mps":
# randn does not exist on mps
A__ : str = torch.randn(
snake_case_ , generator=snake_case_ , device="""cpu""" , dtype=snake_case_ ).to(self.device )
A__ : Optional[int] = torch.randn(snake_case_ , generator=snake_case_ , device="""cpu""" , dtype=snake_case_ ).to(
self.device )
else:
A__ : Dict = torch.randn(
snake_case_ , generator=snake_case_ , device=self.device , dtype=snake_case_ )
A__ : Optional[int] = torch.randn(snake_case_ , generator=snake_case_ , device=self.device , dtype=snake_case_ )
else:
if latents_reference.shape != latents_shape:
raise ValueError(F'''Unexpected latents shape, got {latents.shape}, expected {latents_shape}''' )
A__ : List[str] = latents_reference.to(self.device )
A__ : Union[str, Any] = latents.to(self.device )
# This is the key part of the pipeline where we
# try to ensure that the generated images w/ the same seed
# but different sizes actually result in similar images
A__ : int = (latents_shape[3] - latents_shape_reference[3]) // 2
A__ : List[Any] = (latents_shape[2] - latents_shape_reference[2]) // 2
A__ : Dict = latents_shape_reference[3] if dx >= 0 else latents_shape_reference[3] + 2 * dx
A__ : int = latents_shape_reference[2] if dy >= 0 else latents_shape_reference[2] + 2 * dy
A__ : Optional[int] = 0 if dx < 0 else dx
A__ : List[str] = 0 if dy < 0 else dy
A__ : List[Any] = max(-dx , 0 )
A__ : Any = max(-dy , 0 )
# import pdb
# pdb.set_trace()
A__ : int = latents_reference[:, :, dy : dy + h, dx : dx + w]
# set timesteps
self.scheduler.set_timesteps(snake_case_ )
# Some schedulers like PNDM have timesteps as arrays
# It's more optimized to move all timesteps to correct device beforehand
A__ : Optional[Any] = self.scheduler.timesteps.to(self.device )
# scale the initial noise by the standard deviation required by the scheduler
A__ : int = latents * self.scheduler.init_noise_sigma
# prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
# eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
# eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
# and should be between [0, 1]
A__ : int = """eta""" in set(inspect.signature(self.scheduler.step ).parameters.keys() )
A__ : Optional[int] = {}
if accepts_eta:
A__ : Union[str, Any] = eta
for i, t in enumerate(self.progress_bar(snake_case_ ) ):
# expand the latents if we are doing classifier free guidance
A__ : List[Any] = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents
A__ : Optional[int] = self.scheduler.scale_model_input(snake_case_ , snake_case_ )
# predict the noise residual
A__ : Any = self.unet(snake_case_ , snake_case_ , encoder_hidden_states=snake_case_ ).sample
# perform guidance
if do_classifier_free_guidance:
A__ , A__ : int = noise_pred.chunk(2 )
A__ : int = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
# compute the previous noisy sample x_t -> x_t-1
A__ : Optional[int] = self.scheduler.step(snake_case_ , snake_case_ , snake_case_ , **snake_case_ ).prev_sample
# call the callback, if provided
if callback is not None and i % callback_steps == 0:
callback(snake_case_ , snake_case_ , snake_case_ )
A__ : Optional[Any] = 1 / 0.1_82_15 * latents
A__ : Union[str, Any] = self.vae.decode(snake_case_ ).sample
A__ : Tuple = (image / 2 + 0.5).clamp(0 , 1 )
# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
A__ : Dict = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy()
if self.safety_checker is not None:
A__ : Dict = self.feature_extractor(self.numpy_to_pil(snake_case_ ) , return_tensors="""pt""" ).to(
self.device )
A__ , A__ : Union[str, Any] = self.safety_checker(
images=snake_case_ , clip_input=safety_checker_input.pixel_values.to(text_embeddings.dtype ) )
else:
A__ : Dict = None
if output_type == "pil":
A__ : Any = self.numpy_to_pil(snake_case_ )
if not return_dict:
return (image, has_nsfw_concept)
return StableDiffusionPipelineOutput(images=snake_case_ , nsfw_content_detected=snake_case_ )
| 363 | """simple docstring"""
import argparse
import os
import re
import numpy as np
import PIL
import torch
from timm import create_model
from torch.optim.lr_scheduler import OneCycleLR
from torch.utils.data import DataLoader, Dataset
from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor
from accelerate import Accelerator
def _A( lowerCAmelCase ):
A__ : int = fname.split(os.path.sep )[-1]
return re.search(r"""^(.*)_\d+\.jpg$""" , lowerCAmelCase ).groups()[0]
class __UpperCAmelCase (__A ):
'''simple docstring'''
def __init__( self , snake_case_ , snake_case_=None , snake_case_=None ):
'''simple docstring'''
A__ : Dict = file_names
A__ : str = image_transform
A__ : Dict = label_to_id
def __len__( self ):
'''simple docstring'''
return len(self.file_names )
def __getitem__( self , snake_case_ ):
'''simple docstring'''
A__ : Optional[Any] = self.file_names[idx]
A__ : Optional[Any] = PIL.Image.open(snake_case_ )
A__ : str = raw_image.convert("""RGB""" )
if self.image_transform is not None:
A__ : Optional[int] = self.image_transform(snake_case_ )
A__ : Dict = extract_label(snake_case_ )
if self.label_to_id is not None:
A__ : List[Any] = self.label_to_id[label]
return {"image": image, "label": label}
def _A( lowerCAmelCase , lowerCAmelCase ):
# Initialize accelerator
if args.with_tracking:
A__ : List[Any] = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with="""all""" , project_dir=args.project_dir )
else:
A__ : Optional[Any] = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
A__ : List[Any] = config["""lr"""]
A__ : Any = int(config["""num_epochs"""] )
A__ : List[Any] = int(config["""seed"""] )
A__ : Tuple = int(config["""batch_size"""] )
A__ : List[str] = config["""image_size"""]
if not isinstance(lowerCAmelCase , (list, tuple) ):
A__ : List[str] = (image_size, image_size)
# Parse out whether we are saving every epoch or after a certain number of batches
if hasattr(args.checkpointing_steps , """isdigit""" ):
if args.checkpointing_steps == "epoch":
A__ : List[Any] = args.checkpointing_steps
elif args.checkpointing_steps.isdigit():
A__ : int = int(args.checkpointing_steps )
else:
raise ValueError(
F'''Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed.''' )
else:
A__ : Any = None
# We need to initialize the trackers we use, and also store our configuration
if args.with_tracking:
A__ : int = os.path.split(lowerCAmelCase )[-1].split(""".""" )[0]
accelerator.init_trackers(lowerCAmelCase , lowerCAmelCase )
# Grab all the image filenames
A__ : Union[str, Any] = [os.path.join(args.data_dir , lowerCAmelCase ) for fname in os.listdir(args.data_dir ) if fname.endswith(""".jpg""" )]
# Build the label correspondences
A__ : int = [extract_label(lowerCAmelCase ) for fname in file_names]
A__ : Dict = list(set(lowerCAmelCase ) )
id_to_label.sort()
A__ : int = {lbl: i for i, lbl in enumerate(lowerCAmelCase )}
# Set the seed before splitting the data.
np.random.seed(lowerCAmelCase )
torch.manual_seed(lowerCAmelCase )
torch.cuda.manual_seed_all(lowerCAmelCase )
# Split our filenames between train and validation
A__ : str = np.random.permutation(len(lowerCAmelCase ) )
A__ : Optional[int] = int(0.8 * len(lowerCAmelCase ) )
A__ : Union[str, Any] = random_perm[:cut]
A__ : Optional[int] = random_perm[cut:]
# For training we use a simple RandomResizedCrop
A__ : Union[str, Any] = Compose([RandomResizedCrop(lowerCAmelCase , scale=(0.5, 1.0) ), ToTensor()] )
A__ : Dict = PetsDataset(
[file_names[i] for i in train_split] , image_transform=lowerCAmelCase , label_to_id=lowerCAmelCase )
# For evaluation, we use a deterministic Resize
A__ : Optional[int] = Compose([Resize(lowerCAmelCase ), ToTensor()] )
A__ : Optional[Any] = PetsDataset([file_names[i] for i in eval_split] , image_transform=lowerCAmelCase , label_to_id=lowerCAmelCase )
# Instantiate dataloaders.
A__ : List[Any] = DataLoader(lowerCAmelCase , shuffle=lowerCAmelCase , batch_size=lowerCAmelCase , num_workers=4 )
A__ : str = DataLoader(lowerCAmelCase , shuffle=lowerCAmelCase , batch_size=lowerCAmelCase , num_workers=4 )
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
A__ : Dict = create_model("""resnet50d""" , pretrained=lowerCAmelCase , num_classes=len(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__ : Tuple = model.to(accelerator.device )
# Freezing the base model
for param in model.parameters():
A__ : Any = False
for param in model.get_classifier().parameters():
A__ : Dict = True
# We normalize the batches of images to be a bit faster.
A__ : List[Any] = torch.tensor(model.default_cfg["""mean"""] )[None, :, None, None].to(accelerator.device )
A__ : int = torch.tensor(model.default_cfg["""std"""] )[None, :, None, None].to(accelerator.device )
# Instantiate optimizer
A__ : str = torch.optim.Adam(params=model.parameters() , lr=lr / 25 )
# Instantiate learning rate scheduler
A__ : Optional[int] = OneCycleLR(optimizer=lowerCAmelCase , max_lr=lowerCAmelCase , epochs=lowerCAmelCase , steps_per_epoch=len(lowerCAmelCase ) )
# 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__ : Dict = accelerator.prepare(
lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase )
# We need to keep track of how many total steps we have iterated over
A__ : str = 0
# We also need to keep track of the starting epoch so files are named properly
A__ : Union[str, Any] = 0
# Potentially load in the weights and states from a previous save
if args.resume_from_checkpoint:
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
accelerator.print(F'''Resumed from checkpoint: {args.resume_from_checkpoint}''' )
accelerator.load_state(args.resume_from_checkpoint )
A__ : Dict = os.path.basename(args.resume_from_checkpoint )
else:
# Get the most recent checkpoint
A__ : Tuple = [f.name for f in os.scandir(os.getcwd() ) if f.is_dir()]
dirs.sort(key=os.path.getctime )
A__ : Optional[Any] = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
# Extract `epoch_{i}` or `step_{i}`
A__ : Optional[Any] = os.path.splitext(lowerCAmelCase )[0]
if "epoch" in training_difference:
A__ : Optional[Any] = int(training_difference.replace("""epoch_""" , """""" ) ) + 1
A__ : int = None
else:
A__ : Optional[Any] = int(training_difference.replace("""step_""" , """""" ) )
A__ : Union[str, Any] = resume_step // len(lowerCAmelCase )
resume_step -= starting_epoch * len(lowerCAmelCase )
# Now we train the model
for epoch in range(lowerCAmelCase , lowerCAmelCase ):
model.train()
if args.with_tracking:
A__ : List[Any] = 0
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
# We need to skip steps until we reach the resumed step
A__ : int = accelerator.skip_first_batches(lowerCAmelCase , lowerCAmelCase )
overall_step += resume_step
else:
# After the first iteration though, we need to go back to the original dataloader
A__ : Optional[int] = train_dataloader
for batch in active_dataloader:
# We could avoid this line since we set the accelerator with `device_placement=True`.
A__ : Union[str, Any] = {k: v.to(accelerator.device ) for k, v in batch.items()}
A__ : Any = (batch["""image"""] - mean) / std
A__ : Tuple = model(lowerCAmelCase )
A__ : int = torch.nn.functional.cross_entropy(lowerCAmelCase , batch["""label"""] )
# We keep track of the loss at each epoch
if args.with_tracking:
total_loss += loss.detach().float()
accelerator.backward(lowerCAmelCase )
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
overall_step += 1
if isinstance(lowerCAmelCase , lowerCAmelCase ):
A__ : Union[str, Any] = F'''step_{overall_step}'''
if overall_step % checkpointing_steps == 0:
if args.output_dir is not None:
A__ : List[str] = os.path.join(args.output_dir , lowerCAmelCase )
accelerator.save_state(lowerCAmelCase )
model.eval()
A__ : Any = 0
A__ : Tuple = 0
for step, batch in enumerate(lowerCAmelCase ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
A__ : List[Any] = {k: v.to(accelerator.device ) for k, v in batch.items()}
A__ : Any = (batch["""image"""] - mean) / std
with torch.no_grad():
A__ : Optional[int] = model(lowerCAmelCase )
A__ : Tuple = outputs.argmax(dim=-1 )
A__ , A__ : Tuple = accelerator.gather_for_metrics((predictions, batch["""label"""]) )
A__ : int = predictions == references
num_elems += accurate_preds.shape[0]
accurate += accurate_preds.long().sum()
A__ : List[Any] = accurate.item() / num_elems
# Use accelerator.print to print only on the main process.
accelerator.print(F'''epoch {epoch}: {100 * eval_metric:.2f}''' )
if args.with_tracking:
accelerator.log(
{
"""accuracy""": 100 * eval_metric,
"""train_loss""": total_loss.item() / len(lowerCAmelCase ),
"""epoch""": epoch,
} , step=lowerCAmelCase , )
if checkpointing_steps == "epoch":
A__ : Any = F'''epoch_{epoch}'''
if args.output_dir is not None:
A__ : Any = os.path.join(args.output_dir , lowerCAmelCase )
accelerator.save_state(lowerCAmelCase )
if args.with_tracking:
accelerator.end_training()
def _A( ):
A__ : Union[str, Any] = argparse.ArgumentParser(description="""Simple example of training script.""" )
parser.add_argument("""--data_dir""" , required=lowerCAmelCase , help="""The data folder on disk.""" )
parser.add_argument("""--fp16""" , action="""store_true""" , help="""If passed, will use FP16 training.""" )
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.""" )
parser.add_argument(
"""--checkpointing_steps""" , type=lowerCAmelCase , default=lowerCAmelCase , help="""Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.""" , )
parser.add_argument(
"""--output_dir""" , type=lowerCAmelCase , default=""".""" , help="""Optional save directory where all checkpoint folders will be stored. Default is the current working directory.""" , )
parser.add_argument(
"""--resume_from_checkpoint""" , type=lowerCAmelCase , default=lowerCAmelCase , help="""If the training should continue from a checkpoint folder.""" , )
parser.add_argument(
"""--with_tracking""" , action="""store_true""" , help="""Whether to load in all available experiment trackers from the environment and use them for logging.""" , )
parser.add_argument(
"""--project_dir""" , type=lowerCAmelCase , default="""logs""" , help="""Location on where to store experiment tracking logs` and relevent project information""" , )
A__ : Optional[Any] = parser.parse_args()
A__ : Any = {"""lr""": 3E-2, """num_epochs""": 3, """seed""": 42, """batch_size""": 64, """image_size""": 224}
training_function(lowerCAmelCase , lowerCAmelCase )
if __name__ == "__main__":
main()
| 363 | 1 |
import json
import sys
def __UpperCamelCase (_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) -> Union[str, Any]:
with open(_SCREAMING_SNAKE_CASE , encoding='utf-8' ) as f:
lowercase__ = json.load(_SCREAMING_SNAKE_CASE )
lowercase__ = ['<details>', '<summary>Show updated benchmarks!</summary>', ' ']
for benchmark_name in sorted(_SCREAMING_SNAKE_CASE ):
lowercase__ = results[benchmark_name]
lowercase__ = benchmark_name.split('/' )[-1]
output_md.append(F"""### Benchmark: {benchmark_file_name}""" )
lowercase__ = '| metric |'
lowercase__ = '|--------|'
lowercase__ = '| new / old (diff) |'
for metric_name in sorted(_SCREAMING_SNAKE_CASE ):
lowercase__ = benchmark_res[metric_name]
lowercase__ = metric_vals['new']
lowercase__ = metric_vals.get('old' , _SCREAMING_SNAKE_CASE )
lowercase__ = metric_vals.get('diff' , _SCREAMING_SNAKE_CASE )
lowercase__ = 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__":
lowercase_ = sys.argv[1]
lowercase_ = sys.argv[2]
format_json_to_md(input_json_file, output_md_file)
| 706 |
def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> bool:
if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
raise ValueError('Input series is not valid, valid series - [2, 4, 6]' )
if len(_SCREAMING_SNAKE_CASE ) == 0:
raise ValueError('Input list must be a non empty list' )
if len(_SCREAMING_SNAKE_CASE ) == 1:
return True
lowercase__ = series[1] - series[0]
for index in range(len(_SCREAMING_SNAKE_CASE ) - 1 ):
if series[index + 1] - series[index] != common_diff:
return False
return True
def __UpperCamelCase (_SCREAMING_SNAKE_CASE ) -> float:
if not isinstance(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ):
raise ValueError('Input series is not valid, valid series - [2, 4, 6]' )
if len(_SCREAMING_SNAKE_CASE ) == 0:
raise ValueError('Input list must be a non empty list' )
lowercase__ = 0
for val in series:
answer += val
return answer / len(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 45 | 0 |
from ...configuration_utils import PretrainedConfig
from ...utils import logging
lowerCamelCase :Optional[int] = logging.get_logger(__name__)
lowerCamelCase :Optional[Any] = {
"naver-clova-ix/donut-base": "https://huggingface.co/naver-clova-ix/donut-base/resolve/main/config.json",
# See all Donut models at https://huggingface.co/models?filter=donut-swin
}
class UpperCAmelCase ( _a ):
a: Union[str, Any] = "donut-swin"
a: Union[str, Any] = {
"num_attention_heads": "num_heads",
"num_hidden_layers": "num_layers",
}
def __init__( self: Union[str, Any] , __UpperCamelCase: Dict=224 , __UpperCamelCase: Union[str, Any]=4 , __UpperCamelCase: Union[str, Any]=3 , __UpperCamelCase: Any=96 , __UpperCamelCase: int=[2, 2, 6, 2] , __UpperCamelCase: Optional[int]=[3, 6, 12, 24] , __UpperCamelCase: Dict=7 , __UpperCamelCase: int=4.0 , __UpperCamelCase: Optional[int]=True , __UpperCamelCase: str=0.0 , __UpperCamelCase: List[Any]=0.0 , __UpperCamelCase: Optional[Any]=0.1 , __UpperCamelCase: Any="gelu" , __UpperCamelCase: Dict=False , __UpperCamelCase: Dict=0.0_2 , __UpperCamelCase: List[str]=1E-5 , **__UpperCamelCase: List[str] , ):
super().__init__(**_UpperCAmelCase )
_a = image_size
_a = patch_size
_a = num_channels
_a = embed_dim
_a = depths
_a = len(_UpperCAmelCase )
_a = num_heads
_a = window_size
_a = mlp_ratio
_a = qkv_bias
_a = hidden_dropout_prob
_a = attention_probs_dropout_prob
_a = drop_path_rate
_a = hidden_act
_a = use_absolute_embeddings
_a = layer_norm_eps
_a = initializer_range
# we set the hidden_size attribute in order to make Swin work with VisionEncoderDecoderModel
# this indicates the channel dimension after the last stage of the model
_a = int(embed_dim * 2 ** (len(_UpperCAmelCase ) - 1) )
| 487 |
import unittest
from transformers import BertGenerationTokenizer
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_torch, slow
from transformers.utils import cached_property
from ...test_tokenization_common import TokenizerTesterMixin
_lowerCamelCase : Union[str, Any] = "▁"
_lowerCamelCase : Dict = get_tests_dir("fixtures/test_sentencepiece.model")
@require_sentencepiece
class __snake_case (_a , unittest.TestCase ):
lowerCAmelCase__ = BertGenerationTokenizer
lowerCAmelCase__ = False
lowerCAmelCase__ = True
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Dict:
'''simple docstring'''
super().setUp()
_lowerCAmelCase : Dict = BertGenerationTokenizer(_UpperCAmelCase , keep_accents=_UpperCAmelCase )
tokenizer.save_pretrained(self.tmpdirname )
def SCREAMING_SNAKE_CASE ( self : Tuple ) -> Optional[int]:
'''simple docstring'''
_lowerCAmelCase : Dict = """<s>"""
_lowerCAmelCase : int = 1
self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCAmelCase ) , _UpperCAmelCase )
self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCAmelCase ) , _UpperCAmelCase )
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[int]:
'''simple docstring'''
_lowerCAmelCase : Union[str, Any] = list(self.get_tokenizer().get_vocab().keys() )
self.assertEqual(vocab_keys[0] , """<unk>""" )
self.assertEqual(vocab_keys[1] , """<s>""" )
self.assertEqual(vocab_keys[-1] , """<pad>""" )
self.assertEqual(len(_UpperCAmelCase ) , 1002 )
def SCREAMING_SNAKE_CASE ( self : Dict ) -> List[str]:
'''simple docstring'''
self.assertEqual(self.get_tokenizer().vocab_size , 1000 )
def SCREAMING_SNAKE_CASE ( self : str ) -> List[Any]:
'''simple docstring'''
_lowerCAmelCase : Dict = BertGenerationTokenizer(_UpperCAmelCase , keep_accents=_UpperCAmelCase )
_lowerCAmelCase : List[Any] = tokenizer.tokenize("""This is a test""" )
self.assertListEqual(_UpperCAmelCase , ["""▁This""", """▁is""", """▁a""", """▁t""", """est"""] )
self.assertListEqual(
tokenizer.convert_tokens_to_ids(_UpperCAmelCase ) , [285, 46, 10, 170, 382] , )
_lowerCAmelCase : int = tokenizer.tokenize("""I was born in 92000, and this is falsé.""" )
self.assertListEqual(
_UpperCAmelCase , [
SPIECE_UNDERLINE + """I""",
SPIECE_UNDERLINE + """was""",
SPIECE_UNDERLINE + """b""",
"""or""",
"""n""",
SPIECE_UNDERLINE + """in""",
SPIECE_UNDERLINE + """""",
"""9""",
"""2""",
"""0""",
"""0""",
"""0""",
""",""",
SPIECE_UNDERLINE + """and""",
SPIECE_UNDERLINE + """this""",
SPIECE_UNDERLINE + """is""",
SPIECE_UNDERLINE + """f""",
"""al""",
"""s""",
"""é""",
""".""",
] , )
_lowerCAmelCase : Optional[Any] = tokenizer.convert_tokens_to_ids(_UpperCAmelCase )
self.assertListEqual(
_UpperCAmelCase , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , )
_lowerCAmelCase : Optional[int] = tokenizer.convert_ids_to_tokens(_UpperCAmelCase )
self.assertListEqual(
_UpperCAmelCase , [
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 SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> str:
'''simple docstring'''
return BertGenerationTokenizer.from_pretrained("""google/bert_for_seq_generation_L-24_bbc_encoder""" )
@slow
def SCREAMING_SNAKE_CASE ( self : Union[str, Any] ) -> Optional[Any]:
'''simple docstring'''
_lowerCAmelCase : int = """Hello World!"""
_lowerCAmelCase : List[Any] = [1_8536, 2260, 101]
self.assertListEqual(_UpperCAmelCase , self.big_tokenizer.encode(_UpperCAmelCase ) )
@slow
def SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Tuple:
'''simple docstring'''
_lowerCAmelCase : Optional[Any] = (
"""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"""
)
_lowerCAmelCase : Union[str, Any] = [
871,
419,
358,
946,
991,
2521,
452,
358,
1357,
387,
7751,
3536,
112,
985,
456,
126,
865,
938,
5400,
5734,
458,
1368,
467,
786,
2462,
5246,
1159,
633,
865,
4519,
457,
582,
852,
2557,
427,
916,
508,
405,
3_4324,
497,
391,
408,
1_1342,
1244,
385,
100,
938,
985,
456,
574,
362,
1_2597,
3200,
3129,
1172,
]
self.assertListEqual(_UpperCAmelCase , self.big_tokenizer.encode(_UpperCAmelCase ) )
@require_torch
@slow
def SCREAMING_SNAKE_CASE ( self : Optional[Any] ) -> Tuple:
'''simple docstring'''
import torch
from transformers import BertGenerationConfig, BertGenerationEncoder
# Build sequence
_lowerCAmelCase : Tuple = list(self.big_tokenizer.get_vocab().keys() )[:10]
_lowerCAmelCase : Optional[Any] = """ """.join(_UpperCAmelCase )
_lowerCAmelCase : Union[str, Any] = self.big_tokenizer.encode_plus(_UpperCAmelCase , return_tensors="""pt""" , return_token_type_ids=_UpperCAmelCase )
_lowerCAmelCase : Optional[Any] = self.big_tokenizer.batch_encode_plus(
[sequence + """ """ + sequence] , return_tensors="""pt""" , return_token_type_ids=_UpperCAmelCase )
_lowerCAmelCase : str = BertGenerationConfig()
_lowerCAmelCase : Dict = BertGenerationEncoder(_UpperCAmelCase )
assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size
with torch.no_grad():
model(**_UpperCAmelCase )
model(**_UpperCAmelCase )
@slow
def SCREAMING_SNAKE_CASE ( self : List[str] ) -> str:
'''simple docstring'''
_lowerCAmelCase : Optional[Any] = {"""input_ids""": [[3_9286, 458, 3_6335, 2001, 456, 1_3073, 1_3266, 455, 113, 7746, 1741, 1_1157, 391, 1_3073, 1_3266, 455, 113, 3967, 3_5412, 113, 4936, 109, 3870, 2377, 113, 3_0084, 4_5720, 458, 134, 1_7496, 112, 503, 1_1672, 113, 118, 112, 5665, 1_3347, 3_8687, 112, 1496, 3_1389, 112, 3268, 4_7264, 134, 962, 112, 1_6377, 8035, 2_3130, 430, 1_2169, 1_5518, 2_8592, 458, 146, 4_1697, 109, 391, 1_2169, 1_5518, 1_6689, 458, 146, 4_1358, 109, 452, 726, 4034, 111, 763, 3_5412, 5082, 388, 1903, 111, 9051, 391, 2870, 4_8918, 1900, 1123, 550, 998, 112, 9586, 1_5985, 455, 391, 410, 2_2955, 3_7636, 114], [448, 1_7496, 419, 3663, 385, 763, 113, 2_7533, 2870, 3283, 1_3043, 1639, 2_4713, 523, 656, 2_4013, 1_8550, 2521, 517, 2_7014, 2_1244, 420, 1212, 1465, 391, 927, 4833, 388, 578, 1_1786, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [484, 2169, 7687, 2_1932, 1_8146, 726, 363, 1_7032, 3391, 114, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], """attention_mask""": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501
# fmt: on
self.tokenizer_integration_test_util(
expected_encoding=_UpperCAmelCase , model_name="""google/bert_for_seq_generation_L-24_bbc_encoder""" , revision="""c817d1fd1be2ffa69431227a1fe320544943d4db""" , )
| 429 | 0 |
"""simple docstring"""
from ...utils import (
OptionalDependencyNotAvailable,
is_torch_available,
is_transformers_available,
is_transformers_version,
)
try:
if not (is_transformers_available() and is_torch_available()):
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
from ...utils.dummy_torch_and_transformers_objects import (
ImageTextPipelineOutput,
UniDiffuserPipeline,
)
else:
from .modeling_text_decoder import UniDiffuserTextDecoder
from .modeling_uvit import UniDiffuserModel, UTransformeraDModel
from .pipeline_unidiffuser import ImageTextPipelineOutput, UniDiffuserPipeline
| 237 | """simple docstring"""
lowerCamelCase : Optional[Any] ={
'''A''': '''.-''', '''B''': '''-...''', '''C''': '''-.-.''', '''D''': '''-..''', '''E''': '''.''', '''F''': '''..-.''', '''G''': '''--.''',
'''H''': '''....''', '''I''': '''..''', '''J''': '''.---''', '''K''': '''-.-''', '''L''': '''.-..''', '''M''': '''--''', '''N''': '''-.''',
'''O''': '''---''', '''P''': '''.--.''', '''Q''': '''--.-''', '''R''': '''.-.''', '''S''': '''...''', '''T''': '''-''', '''U''': '''..-''',
'''V''': '''...-''', '''W''': '''.--''', '''X''': '''-..-''', '''Y''': '''-.--''', '''Z''': '''--..''', '''1''': '''.----''',
'''2''': '''..---''', '''3''': '''...--''', '''4''': '''....-''', '''5''': '''.....''', '''6''': '''-....''', '''7''': '''--...''',
'''8''': '''---..''', '''9''': '''----.''', '''0''': '''-----''', '''&''': '''.-...''', '''@''': '''.--.-.''',
''':''': '''---...''', ''',''': '''--..--''', '''.''': '''.-.-.-''', '''\'''': '''.----.''', '''"''': '''.-..-.''',
'''?''': '''..--..''', '''/''': '''-..-.''', '''=''': '''-...-''', '''+''': '''.-.-.''', '''-''': '''-....-''',
'''(''': '''-.--.''', ''')''': '''-.--.-''', '''!''': '''-.-.--''', ''' ''': '''/'''
} # Exclamation mark is not in ITU-R recommendation
# fmt: on
lowerCamelCase : str ={value: key for key, value in MORSE_CODE_DICT.items()}
def _lowercase ( _SCREAMING_SNAKE_CASE : str ) -> str:
'''simple docstring'''
return " ".join(MORSE_CODE_DICT[char] for char in message.upper() )
def _lowercase ( _SCREAMING_SNAKE_CASE : str ) -> str:
'''simple docstring'''
return "".join(REVERSE_DICT[char] for char in message.split() )
def _lowercase ( ) -> None:
'''simple docstring'''
__A : Union[str, Any] = 'Morse code here!'
print(_SCREAMING_SNAKE_CASE )
__A : Any = encrypt(_SCREAMING_SNAKE_CASE )
print(_SCREAMING_SNAKE_CASE )
__A : str = decrypt(_SCREAMING_SNAKE_CASE )
print(_SCREAMING_SNAKE_CASE )
if __name__ == "__main__":
main()
| 237 | 1 |
import collections
import gzip
import os
import urllib
import numpy
from tensorflow.python.framework import dtypes, random_seed
from tensorflow.python.platform import gfile
from tensorflow.python.util.deprecation import deprecated
a_ = collections.namedtuple('_Datasets', ['train', 'validation', 'test'])
# CVDF mirror of http://yann.lecun.com/exdb/mnist/
a_ = 'https://storage.googleapis.com/cvdf-datasets/mnist/'
def lowerCamelCase__ ( _a):
SCREAMING_SNAKE_CASE : Union[str, Any] = numpy.dtype(numpy.uintaa).newbyteorder(">")
return numpy.frombuffer(bytestream.read(4) , dtype=lowerCAmelCase__)[0]
@deprecated(lowerCAmelCase__ , "Please use tf.data to implement this functionality.")
def lowerCamelCase__ ( _a):
print("Extracting" , f.name)
with gzip.GzipFile(fileobj=lowerCAmelCase__) as bytestream:
SCREAMING_SNAKE_CASE : Dict = _readaa(lowerCAmelCase__)
if magic != 2051:
raise ValueError(
"Invalid magic number %d in MNIST image file: %s" % (magic, f.name))
SCREAMING_SNAKE_CASE : Any = _readaa(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Optional[int] = _readaa(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Tuple = _readaa(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Any = bytestream.read(rows * cols * num_images)
SCREAMING_SNAKE_CASE : Union[str, Any] = numpy.frombuffer(lowerCAmelCase__ , dtype=numpy.uinta)
SCREAMING_SNAKE_CASE : str = data.reshape(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , 1)
return data
@deprecated(lowerCAmelCase__ , "Please use tf.one_hot on tensors.")
def lowerCamelCase__ ( _a , _a):
SCREAMING_SNAKE_CASE : Optional[Any] = labels_dense.shape[0]
SCREAMING_SNAKE_CASE : Tuple = numpy.arange(lowerCAmelCase__) * num_classes
SCREAMING_SNAKE_CASE : Tuple = numpy.zeros((num_labels, num_classes))
SCREAMING_SNAKE_CASE : List[Any] = 1
return labels_one_hot
@deprecated(lowerCAmelCase__ , "Please use tf.data to implement this functionality.")
def lowerCamelCase__ ( _a , _a=False , _a=10):
print("Extracting" , f.name)
with gzip.GzipFile(fileobj=lowerCAmelCase__) as bytestream:
SCREAMING_SNAKE_CASE : Optional[int] = _readaa(lowerCAmelCase__)
if magic != 2049:
raise ValueError(
"Invalid magic number %d in MNIST label file: %s" % (magic, f.name))
SCREAMING_SNAKE_CASE : Dict = _readaa(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : List[str] = bytestream.read(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : List[Any] = numpy.frombuffer(lowerCAmelCase__ , dtype=numpy.uinta)
if one_hot:
return _dense_to_one_hot(lowerCAmelCase__ , lowerCAmelCase__)
return labels
class _UpperCamelCase :
'''simple docstring'''
@deprecated(
A__ , "Please use alternatives such as official/mnist/_DataSet.py"
" from tensorflow/models." , )
def __init__( self : Optional[Any] , a : Union[str, Any] , a : Union[str, Any] , a : List[Any]=False , a : str=False , a : Dict=dtypes.floataa , a : Tuple=True , a : str=None , ) -> Optional[int]:
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = random_seed.get_seed(A__ )
# If op level seed is not set, use whatever graph level seed is returned
numpy.random.seed(seeda if seed is None else seeda )
SCREAMING_SNAKE_CASE : Any = dtypes.as_dtype(A__ ).base_dtype
if dtype not in (dtypes.uinta, dtypes.floataa):
raise TypeError("Invalid image dtype %r, expected uint8 or float32" % dtype )
if fake_data:
SCREAMING_SNAKE_CASE : Tuple = 1_0000
SCREAMING_SNAKE_CASE : Any = one_hot
else:
assert (
images.shape[0] == labels.shape[0]
), F"images.shape: {images.shape} labels.shape: {labels.shape}"
SCREAMING_SNAKE_CASE : List[str] = images.shape[0]
# Convert shape from [num examples, rows, columns, depth]
# to [num examples, rows*columns] (assuming depth == 1)
if reshape:
assert images.shape[3] == 1
SCREAMING_SNAKE_CASE : Optional[Any] = images.reshape(
images.shape[0] , images.shape[1] * images.shape[2] )
if dtype == dtypes.floataa:
# Convert from [0, 255] -> [0.0, 1.0].
SCREAMING_SNAKE_CASE : Union[str, Any] = images.astype(numpy.floataa )
SCREAMING_SNAKE_CASE : Optional[Any] = numpy.multiply(A__ , 1.0 / 255.0 )
SCREAMING_SNAKE_CASE : Dict = images
SCREAMING_SNAKE_CASE : List[Any] = labels
SCREAMING_SNAKE_CASE : int = 0
SCREAMING_SNAKE_CASE : Optional[Any] = 0
@property
def __UpperCamelCase ( self : int ) -> int:
"""simple docstring"""
return self._images
@property
def __UpperCamelCase ( self : Dict ) -> Optional[int]:
"""simple docstring"""
return self._labels
@property
def __UpperCamelCase ( self : Union[str, Any] ) -> Optional[int]:
"""simple docstring"""
return self._num_examples
@property
def __UpperCamelCase ( self : int ) -> List[str]:
"""simple docstring"""
return self._epochs_completed
def __UpperCamelCase ( self : List[Any] , a : int , a : Tuple=False , a : Optional[Any]=True ) -> Any:
"""simple docstring"""
if fake_data:
SCREAMING_SNAKE_CASE : str = [1] * 784
SCREAMING_SNAKE_CASE : List[Any] = [1] + [0] * 9 if self.one_hot else 0
return (
[fake_image for _ in range(A__ )],
[fake_label for _ in range(A__ )],
)
SCREAMING_SNAKE_CASE : int = self._index_in_epoch
# Shuffle for the first epoch
if self._epochs_completed == 0 and start == 0 and shuffle:
SCREAMING_SNAKE_CASE : Dict = numpy.arange(self._num_examples )
numpy.random.shuffle(A__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = self.images[perma]
SCREAMING_SNAKE_CASE : str = self.labels[perma]
# Go to the next epoch
if start + batch_size > self._num_examples:
# Finished epoch
self._epochs_completed += 1
# Get the rest examples in this epoch
SCREAMING_SNAKE_CASE : Optional[Any] = self._num_examples - start
SCREAMING_SNAKE_CASE : List[Any] = self._images[start : self._num_examples]
SCREAMING_SNAKE_CASE : List[Any] = self._labels[start : self._num_examples]
# Shuffle the data
if shuffle:
SCREAMING_SNAKE_CASE : Optional[Any] = numpy.arange(self._num_examples )
numpy.random.shuffle(A__ )
SCREAMING_SNAKE_CASE : Any = self.images[perm]
SCREAMING_SNAKE_CASE : int = self.labels[perm]
# Start next epoch
SCREAMING_SNAKE_CASE : List[Any] = 0
SCREAMING_SNAKE_CASE : int = batch_size - rest_num_examples
SCREAMING_SNAKE_CASE : List[str] = self._index_in_epoch
SCREAMING_SNAKE_CASE : Union[str, Any] = self._images[start:end]
SCREAMING_SNAKE_CASE : Union[str, Any] = self._labels[start:end]
return (
numpy.concatenate((images_rest_part, images_new_part) , axis=0 ),
numpy.concatenate((labels_rest_part, labels_new_part) , axis=0 ),
)
else:
self._index_in_epoch += batch_size
SCREAMING_SNAKE_CASE : List[str] = self._index_in_epoch
return self._images[start:end], self._labels[start:end]
@deprecated(lowerCAmelCase__ , "Please write your own downloading logic.")
def lowerCamelCase__ ( _a , _a , _a):
if not gfile.Exists(lowerCAmelCase__):
gfile.MakeDirs(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : List[Any] = os.path.join(lowerCAmelCase__ , lowerCAmelCase__)
if not gfile.Exists(lowerCAmelCase__):
urllib.request.urlretrieve(lowerCAmelCase__ , lowerCAmelCase__) # noqa: S310
with gfile.GFile(lowerCAmelCase__) as f:
SCREAMING_SNAKE_CASE : str = f.size()
print("Successfully downloaded" , lowerCAmelCase__ , lowerCAmelCase__ , "bytes.")
return filepath
@deprecated(
lowerCAmelCase__ , "Please use alternatives such as:" " tensorflow_datasets.load(\'mnist\')")
def lowerCamelCase__ ( _a , _a=False , _a=False , _a=dtypes.floataa , _a=True , _a=5000 , _a=None , _a=DEFAULT_SOURCE_URL , ):
if fake_data:
def fake():
return _DataSet(
[] , [] , fake_data=lowerCAmelCase__ , one_hot=lowerCAmelCase__ , dtype=lowerCAmelCase__ , seed=lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Optional[Any] = fake()
SCREAMING_SNAKE_CASE : List[str] = fake()
SCREAMING_SNAKE_CASE : int = fake()
return _Datasets(train=lowerCAmelCase__ , validation=lowerCAmelCase__ , test=lowerCAmelCase__)
if not source_url: # empty string check
SCREAMING_SNAKE_CASE : Optional[Any] = DEFAULT_SOURCE_URL
SCREAMING_SNAKE_CASE : Optional[int] = '''train-images-idx3-ubyte.gz'''
SCREAMING_SNAKE_CASE : int = '''train-labels-idx1-ubyte.gz'''
SCREAMING_SNAKE_CASE : Dict = '''t10k-images-idx3-ubyte.gz'''
SCREAMING_SNAKE_CASE : Tuple = '''t10k-labels-idx1-ubyte.gz'''
SCREAMING_SNAKE_CASE : List[str] = _maybe_download(
lowerCAmelCase__ , lowerCAmelCase__ , source_url + train_images_file)
with gfile.Open(lowerCAmelCase__ , "rb") as f:
SCREAMING_SNAKE_CASE : Dict = _extract_images(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Dict = _maybe_download(
lowerCAmelCase__ , lowerCAmelCase__ , source_url + train_labels_file)
with gfile.Open(lowerCAmelCase__ , "rb") as f:
SCREAMING_SNAKE_CASE : Optional[Any] = _extract_labels(lowerCAmelCase__ , one_hot=lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Any = _maybe_download(
lowerCAmelCase__ , lowerCAmelCase__ , source_url + test_images_file)
with gfile.Open(lowerCAmelCase__ , "rb") as f:
SCREAMING_SNAKE_CASE : Dict = _extract_images(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Optional[int] = _maybe_download(
lowerCAmelCase__ , lowerCAmelCase__ , source_url + test_labels_file)
with gfile.Open(lowerCAmelCase__ , "rb") as f:
SCREAMING_SNAKE_CASE : List[Any] = _extract_labels(lowerCAmelCase__ , one_hot=lowerCAmelCase__)
if not 0 <= validation_size <= len(lowerCAmelCase__):
SCREAMING_SNAKE_CASE : Any = (
'''Validation size should be between 0 and '''
f"{len(lowerCAmelCase__)}. Received: {validation_size}."
)
raise ValueError(lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Any = train_images[:validation_size]
SCREAMING_SNAKE_CASE : List[Any] = train_labels[:validation_size]
SCREAMING_SNAKE_CASE : Dict = train_images[validation_size:]
SCREAMING_SNAKE_CASE : Optional[int] = train_labels[validation_size:]
SCREAMING_SNAKE_CASE : List[Any] = {'''dtype''': dtype, '''reshape''': reshape, '''seed''': seed}
SCREAMING_SNAKE_CASE : Any = _DataSet(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Tuple = _DataSet(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__)
SCREAMING_SNAKE_CASE : Optional[int] = _DataSet(lowerCAmelCase__ , lowerCAmelCase__ , **lowerCAmelCase__)
return _Datasets(train=lowerCAmelCase__ , validation=lowerCAmelCase__ , test=lowerCAmelCase__) | 25 |
'''simple docstring'''
# Lint as: python3
import os
import re
import urllib.parse
from pathlib import Path
from typing import Callable, List, Optional, Union
from zipfile import ZipFile
from ..utils.file_utils import cached_path, hf_github_url
from ..utils.logging import get_logger
from ..utils.version import Version
__SCREAMING_SNAKE_CASE = get_logger(__name__)
class lowerCAmelCase__ :
"""simple docstring"""
__UpperCamelCase = "dummy_data"
__UpperCamelCase = "datasets"
__UpperCamelCase = False
def __init__( self : Any , A__ : str , A__ : str , A__ : Union[Version, str] , A__ : Optional[str] = None , A__ : bool = False , A__ : bool = True , A__ : Optional[List[Callable]] = None , ) -> int:
'''simple docstring'''
a__ : Tuple = 0
a__ : Any = dataset_name
a__ : int = cache_dir
a__ : str = use_local_dummy_data
a__ : List[str] = config
# download_callbacks take a single url as input
a__ : List[Callable] = download_callbacks or []
# if False, it doesn't load existing files and it returns the paths of the dummy files relative
# to the dummy_data zip file root
a__ : str = load_existing_dummy_data
# TODO(PVP, QL) might need to make this more general
a__ : Optional[Any] = str(A__ )
# to be downloaded
a__ : Tuple = None
a__ : Tuple = None
@property
def __lowerCAmelCase ( self : Optional[Any] ) -> List[Any]:
'''simple docstring'''
if self._dummy_file is None:
a__ : Dict = self.download_dummy_data()
return self._dummy_file
@property
def __lowerCAmelCase ( self : Any ) -> Optional[int]:
'''simple docstring'''
if self.config is not None:
# structure is dummy / config_name / version_name
return os.path.join('''dummy''' , self.config.name , self.version_name )
# structure is dummy / version_name
return os.path.join('''dummy''' , self.version_name )
@property
def __lowerCAmelCase ( self : Optional[Any] ) -> Dict:
'''simple docstring'''
return os.path.join(self.dummy_data_folder , '''dummy_data.zip''' )
def __lowerCAmelCase ( self : str ) -> Union[str, Any]:
'''simple docstring'''
a__ : int = (
self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data
)
a__ : str = cached_path(
A__ , cache_dir=self.cache_dir , extract_compressed_file=A__ , force_extract=A__ )
return os.path.join(A__ , self.dummy_file_name )
@property
def __lowerCAmelCase ( self : int ) -> Optional[int]:
'''simple docstring'''
return os.path.join(self.datasets_scripts_dir , self.dataset_name , self.dummy_zip_file )
@property
def __lowerCAmelCase ( self : Optional[Any] ) -> Optional[int]:
'''simple docstring'''
if self._bucket_url is None:
a__ : int = hf_github_url(self.dataset_name , self.dummy_zip_file.replace(os.sep , '''/''' ) )
return self._bucket_url
@property
def __lowerCAmelCase ( self : List[Any] ) -> Dict:
'''simple docstring'''
if os.path.isdir(self.dummy_file ):
return self.dummy_file
# else cut off path to file -> example `xsum`.
return "/".join(self.dummy_file.replace(os.sep , '''/''' ).split('''/''' )[:-1] )
def __lowerCAmelCase ( self : Union[str, Any] , A__ : Optional[int] , *A__ : int ) -> Union[str, Any]:
'''simple docstring'''
if self.load_existing_dummy_data:
# dummy data is downloaded and tested
a__ : Tuple = self.dummy_file
else:
# dummy data cannot be downloaded and only the path to dummy file is returned
a__ : Union[str, Any] = self.dummy_file_name
# special case when data_url is a dict
if isinstance(A__ , A__ ):
return self.create_dummy_data_dict(A__ , A__ )
elif isinstance(A__ , (list, tuple) ):
return self.create_dummy_data_list(A__ , A__ )
else:
return self.create_dummy_data_single(A__ , A__ )
def __lowerCAmelCase ( self : List[str] , A__ : Any , *A__ : int ) -> Any:
'''simple docstring'''
return self.download_and_extract(A__ )
def __lowerCAmelCase ( self : Any , A__ : Optional[int] , A__ : Optional[Any] ) -> int:
'''simple docstring'''
return self.download_and_extract(A__ )
def __lowerCAmelCase ( self : Union[str, Any] , A__ : int , *A__ : List[Any] , **A__ : str ) -> Optional[Any]:
'''simple docstring'''
return path
def __lowerCAmelCase ( self : List[Any] ) -> str:
'''simple docstring'''
return {}
def __lowerCAmelCase ( self : int , A__ : Union[str, Any] , A__ : List[str] ) -> Any:
'''simple docstring'''
a__ : int = {}
for key, single_urls in data_url.items():
for download_callback in self.download_callbacks:
if isinstance(A__ , A__ ):
for single_url in single_urls:
download_callback(A__ )
else:
a__ : Dict = single_urls
download_callback(A__ )
# we force the name of each key to be the last file / folder name of the url path
# if the url has arguments, we need to encode them with urllib.parse.quote_plus
if isinstance(A__ , A__ ):
a__ : Optional[int] = [os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) ) for x in single_urls]
else:
a__ : Optional[Any] = single_urls
a__ : Tuple = os.path.join(A__ , urllib.parse.quote_plus(Path(A__ ).name ) )
a__ : List[str] = value
# make sure that values are unique
if all(isinstance(A__ , A__ ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len(
dummy_data_dict.values() ):
# append key to value to make its name unique
a__ : Optional[int] = {key: value + key for key, value in dummy_data_dict.items()}
return dummy_data_dict
def __lowerCAmelCase ( self : Dict , A__ : str , A__ : Optional[int] ) -> Optional[int]:
'''simple docstring'''
a__ : str = []
# trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one
a__ : Union[str, Any] = all(bool(re.findall('''[0-9]{3,}-of-[0-9]{3,}''' , A__ ) ) for url in data_url )
a__ : Optional[Any] = all(
url.startswith('''https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed''' ) for url in data_url )
if data_url and (is_tf_records or is_pubmed_records):
a__ : Dict = [data_url[0]] * len(A__ )
for single_url in data_url:
for download_callback in self.download_callbacks:
download_callback(A__ )
# we force the name of each key to be the last file / folder name of the url path
# if the url has arguments, we need to encode them with urllib.parse.quote_plus
a__ : Optional[int] = os.path.join(A__ , urllib.parse.quote_plus(single_url.split('''/''' )[-1] ) )
dummy_data_list.append(A__ )
return dummy_data_list
def __lowerCAmelCase ( self : Dict , A__ : Dict , A__ : str ) -> Optional[int]:
'''simple docstring'''
for download_callback in self.download_callbacks:
download_callback(A__ )
# we force the name of each key to be the last file / folder name of the url path
# if the url has arguments, we need to encode them with urllib.parse.quote_plus
a__ : Union[str, Any] = os.path.join(A__ , urllib.parse.quote_plus(data_url.split('''/''' )[-1] ) )
if os.path.exists(A__ ) or not self.load_existing_dummy_data:
return value
else:
# Backward compatibility, maybe deprecate at one point.
# For many datasets with single url calls to dl_manager.download_and_extract,
# the dummy_data.zip file is actually the zipped downloaded file
# while now we expected the dummy_data.zip file to be a directory containing
# the downloaded file.
return path_to_dummy_data
def __lowerCAmelCase ( self : int ) -> str:
'''simple docstring'''
pass
def __lowerCAmelCase ( self : Optional[Any] ) -> Tuple:
'''simple docstring'''
pass
def __lowerCAmelCase ( self : Any , A__ : Tuple ) -> Any:
'''simple docstring'''
def _iter_archive_members(A__ : str ):
# this preserves the order of the members inside the ZIP archive
a__ : Dict = Path(self.dummy_file ).parent
a__ : Tuple = path.relative_to(A__ )
with ZipFile(self.local_path_to_dummy_data ) as zip_file:
a__ : Optional[Any] = zip_file.namelist()
for member in members:
if member.startswith(relative_path.as_posix() ):
yield dummy_parent_path.joinpath(A__ )
a__ : str = Path(A__ )
a__ : Optional[Any] = _iter_archive_members(A__ ) if self.use_local_dummy_data else path.rglob('''*''' )
for file_path in file_paths:
if file_path.is_file() and not file_path.name.startswith(('''.''', '''__''') ):
yield file_path.relative_to(A__ ).as_posix(), file_path.open('''rb''' )
def __lowerCAmelCase ( self : Tuple , A__ : Tuple ) -> Tuple:
'''simple docstring'''
if not isinstance(A__ , A__ ):
a__ : int = [paths]
for path in paths:
if os.path.isfile(A__ ):
if os.path.basename(A__ ).startswith(('''.''', '''__''') ):
return
yield path
else:
for dirpath, dirnames, filenames in os.walk(A__ ):
if os.path.basename(A__ ).startswith(('''.''', '''__''') ):
continue
dirnames.sort()
for filename in sorted(A__ ):
if filename.startswith(('''.''', '''__''') ):
continue
yield os.path.join(A__ , A__ )
| 688 | 0 |
"""simple docstring"""
def _a ( _snake_case , _snake_case , _snake_case = 0 , _snake_case = 0 ):
"""simple docstring"""
UpperCAmelCase = right or len(_snake_case ) - 1
if left > right:
return -1
elif list_data[left] == key:
return left
elif list_data[right] == key:
return right
else:
return search(_snake_case , _snake_case , left + 1 , right - 1 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 719 |
"""simple docstring"""
import math
def _a ( _snake_case ):
"""simple docstring"""
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(_snake_case ) + 1 ) , 6 ):
if number % i == 0 or number % (i + 2) == 0:
return False
return True
def _a ( _snake_case = 0.1 ):
"""simple docstring"""
UpperCAmelCase = 3
UpperCAmelCase = 3
while primes / (2 * j - 1) >= ratio:
for i in range(j * j + j + 1 , (j + 2) * (j + 2) , j + 1 ):
primes += is_prime(_snake_case )
j += 2
return j
if __name__ == "__main__":
import doctest
doctest.testmod()
| 74 | 0 |
def _A( UpperCamelCase__ : int ) -> int:
'''simple docstring'''
__lowercase = 0
while num > 0:
digit_sum += num % 10
num //= 10
return digit_sum
def _A( UpperCamelCase__ : int = 100 ) -> int:
'''simple docstring'''
__lowercase = 1
__lowercase = 2
for i in range(2 , max_n + 1 ):
__lowercase = pre_numerator
__lowercase = 2 * i // 3 if i % 3 == 0 else 1
__lowercase = cur_numerator
__lowercase = e_cont * pre_numerator + temp
return sum_digits(UpperCamelCase__ )
if __name__ == "__main__":
print(F"""{solution() = }""")
| 332 |
import argparse
import os
import evaluate
import torch
from datasets import load_dataset
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
from accelerate import Accelerator, DistributedType
########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing the experiment tracking capability,
# 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
#
########################################################################
UpperCAmelCase__ = 16
UpperCAmelCase__ = 32
def _A( UpperCamelCase__ : Accelerator , UpperCamelCase__ : int = 16 ) -> int:
'''simple docstring'''
__lowercase = AutoTokenizer.from_pretrained('''bert-base-cased''' )
__lowercase = load_dataset('''glue''' , '''mrpc''' )
def tokenize_function(UpperCamelCase__ : Tuple ):
# max_length=None => use the model max length (it's actually the default)
__lowercase = tokenizer(examples['''sentence1'''] , examples['''sentence2'''] , truncation=UpperCamelCase__ , max_length=UpperCamelCase__ )
return outputs
# Apply the method we just defined to all the examples in all the splits of the dataset
# starting with the main process first:
with accelerator.main_process_first():
__lowercase = datasets.map(
UpperCamelCase__ , batched=UpperCamelCase__ , remove_columns=['''idx''', '''sentence1''', '''sentence2'''] , )
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
# transformers library
__lowercase = tokenized_datasets.rename_column('''label''' , '''labels''' )
def collate_fn(UpperCamelCase__ : str ):
# On TPU it's best to pad everything to the same length or training will be very slow.
__lowercase = 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":
__lowercase = 16
elif accelerator.mixed_precision != "no":
__lowercase = 8
else:
__lowercase = None
return tokenizer.pad(
UpperCamelCase__ , padding='''longest''' , max_length=UpperCamelCase__ , pad_to_multiple_of=UpperCamelCase__ , return_tensors='''pt''' , )
# Instantiate dataloaders.
__lowercase = DataLoader(
tokenized_datasets['''train'''] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ )
__lowercase = DataLoader(
tokenized_datasets['''validation'''] , shuffle=UpperCamelCase__ , collate_fn=UpperCamelCase__ , batch_size=UpperCamelCase__ )
return train_dataloader, eval_dataloader
# For testing only
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
from accelerate.test_utils.training import mocked_dataloaders
UpperCAmelCase__ = mocked_dataloaders # noqa: F811
def _A( UpperCamelCase__ : str , UpperCamelCase__ : Tuple ) -> Optional[int]:
'''simple docstring'''
if os.environ.get('''TESTING_MOCKED_DATALOADERS''' , UpperCamelCase__ ) == "1":
__lowercase = 2
# Initialize Accelerator
# New Code #
# We pass in "all" to `log_with` to grab all available trackers in the environment
# Note: If using a custom `Tracker` class, should be passed in here such as:
# >>> log_with = ["all", MyCustomTrackerClassInstance()]
if args.with_tracking:
__lowercase = Accelerator(
cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='''all''' , project_dir=args.project_dir )
else:
__lowercase = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision )
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
__lowercase = config['''lr''']
__lowercase = int(config['''num_epochs'''] )
__lowercase = int(config['''seed'''] )
__lowercase = int(config['''batch_size'''] )
set_seed(UpperCamelCase__ )
__lowercase , __lowercase = get_dataloaders(UpperCamelCase__ , UpperCamelCase__ )
__lowercase = evaluate.load('''glue''' , '''mrpc''' )
# If the batch size is too big we use gradient accumulation
__lowercase = 1
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
__lowercase = batch_size // MAX_GPU_BATCH_SIZE
__lowercase = MAX_GPU_BATCH_SIZE
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
__lowercase = AutoModelForSequenceClassification.from_pretrained('''bert-base-cased''' , return_dict=UpperCamelCase__ )
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
__lowercase = model.to(accelerator.device )
# Instantiate optimizer
__lowercase = AdamW(params=model.parameters() , lr=UpperCamelCase__ )
# Instantiate scheduler
__lowercase = get_linear_schedule_with_warmup(
optimizer=UpperCamelCase__ , num_warmup_steps=100 , num_training_steps=(len(UpperCamelCase__ ) * num_epochs) // gradient_accumulation_steps , )
# Prepare everything
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
# prepare method.
__lowercase , __lowercase , __lowercase , __lowercase , __lowercase = accelerator.prepare(
UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ , UpperCamelCase__ )
# New Code #
# We need to initialize the trackers we use. Overall configurations can also be stored
if args.with_tracking:
__lowercase = os.path.split(UpperCamelCase__ )[-1].split('''.''' )[0]
accelerator.init_trackers(UpperCamelCase__ , UpperCamelCase__ )
# Now we train the model
for epoch in range(UpperCamelCase__ ):
model.train()
# New Code #
# For our tracking example, we will log the total loss of each epoch
if args.with_tracking:
__lowercase = 0
for step, batch in enumerate(UpperCamelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True`.
batch.to(accelerator.device )
__lowercase = model(**UpperCamelCase__ )
__lowercase = outputs.loss
# New Code #
if args.with_tracking:
total_loss += loss.detach().float()
__lowercase = loss / gradient_accumulation_steps
accelerator.backward(UpperCamelCase__ )
if step % gradient_accumulation_steps == 0:
optimizer.step()
lr_scheduler.step()
optimizer.zero_grad()
model.eval()
for step, batch in enumerate(UpperCamelCase__ ):
# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
batch.to(accelerator.device )
with torch.no_grad():
__lowercase = model(**UpperCamelCase__ )
__lowercase = outputs.logits.argmax(dim=-1 )
__lowercase , __lowercase = accelerator.gather_for_metrics((predictions, batch['''labels''']) )
metric.add_batch(
predictions=UpperCamelCase__ , references=UpperCamelCase__ , )
__lowercase = metric.compute()
# Use accelerator.print to print only on the main process.
accelerator.print(F'epoch {epoch}:' , UpperCamelCase__ )
# New Code #
# To actually log, we call `Accelerator.log`
# The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int`
if args.with_tracking:
accelerator.log(
{
'''accuracy''': eval_metric['''accuracy'''],
'''f1''': eval_metric['''f1'''],
'''train_loss''': total_loss.item() / len(UpperCamelCase__ ),
'''epoch''': epoch,
} , step=UpperCamelCase__ , )
# New Code #
# When a run is finished, you should call `accelerator.end_training()`
# to close all of the open trackers
if args.with_tracking:
accelerator.end_training()
def _A( ) -> str:
'''simple docstring'''
__lowercase = argparse.ArgumentParser(description='''Simple example of training script.''' )
parser.add_argument(
'''--mixed_precision''' , type=UpperCamelCase__ , default=UpperCamelCase__ , choices=['''no''', '''fp16''', '''bf16''', '''fp8'''] , help='''Whether to use mixed precision. Choose'''
'''between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.'''
'''and an Nvidia Ampere GPU.''' , )
parser.add_argument('''--cpu''' , action='''store_true''' , help='''If passed, will train on the CPU.''' )
parser.add_argument(
'''--with_tracking''' , action='''store_true''' , help='''Whether to load in all available experiment trackers from the environment and use them for logging.''' , )
parser.add_argument(
'''--project_dir''' , type=UpperCamelCase__ , default='''logs''' , help='''Location on where to store experiment tracking logs` and relevent project information''' , )
__lowercase = parser.parse_args()
__lowercase = {'''lr''': 2e-5, '''num_epochs''': 3, '''seed''': 42, '''batch_size''': 16}
training_function(UpperCamelCase__ , UpperCamelCase__ )
if __name__ == "__main__":
main()
| 332 | 1 |
from math import factorial
def snake_case_ ( SCREAMING_SNAKE_CASE_ : List[str] = 1_00 ) -> int:
return sum(map(SCREAMING_SNAKE_CASE_ ,str(factorial(SCREAMING_SNAKE_CASE_ ) ) ) )
if __name__ == "__main__":
print(solution(int(input('''Enter the Number: ''').strip()))) | 718 |
import inspect
import os
import unittest
import torch
import accelerate
from accelerate import debug_launcher
from accelerate.test_utils import (
execute_subprocess_async,
require_cpu,
require_huggingface_suite,
require_multi_gpu,
require_single_gpu,
)
from accelerate.utils import patch_environment
@require_huggingface_suite
class UpperCAmelCase( unittest.TestCase ):
"""simple docstring"""
def __a ( self ) -> Optional[Any]:
"""simple docstring"""
lowercase__ : Optional[int] = inspect.getfile(accelerate.test_utils )
lowercase__ : Union[str, Any] = os.path.sep.join(
mod_file.split(os.path.sep )[:-1] + ["scripts", "external_deps", "test_metrics.py"] )
from accelerate.test_utils.scripts.external_deps import test_metrics # noqa: F401
lowercase__ : Optional[int] = test_metrics
@require_cpu
def __a ( self ) -> List[Any]:
"""simple docstring"""
debug_launcher(self.test_metrics.main , num_processes=1 )
@require_cpu
def __a ( self ) -> Union[str, Any]:
"""simple docstring"""
debug_launcher(self.test_metrics.main )
@require_single_gpu
def __a ( self ) -> Dict:
"""simple docstring"""
self.test_metrics.main()
@require_multi_gpu
def __a ( self ) -> str:
"""simple docstring"""
print(f"""Found {torch.cuda.device_count()} devices.""" )
lowercase__ : Optional[Any] = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path]
with patch_environment(omp_num_threads=1 ):
execute_subprocess_async(lowerCamelCase , env=os.environ.copy() ) | 298 | 0 |
SCREAMING_SNAKE_CASE__ : int = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
def _a ( lowercase__ : bytes ):
'''simple docstring'''
if not isinstance(lowercase__ , lowercase__ ):
SCREAMING_SNAKE_CASE__ : Optional[int] = f'''a bytes-like object is required, not \'{data.__class__.__name__}\''''
raise TypeError(lowercase__ )
SCREAMING_SNAKE_CASE__ : Optional[Any] = ''.join(bin(lowercase__ )[2:].zfill(8 ) for byte in data )
SCREAMING_SNAKE_CASE__ : Any = len(lowercase__ ) % 6 != 0
if padding_needed:
# The padding that will be added later
SCREAMING_SNAKE_CASE__ : List[Any] = b'=' * ((6 - len(lowercase__ ) % 6) // 2)
# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream += "0" * (6 - len(lowercase__ ) % 6)
else:
SCREAMING_SNAKE_CASE__ : Optional[int] = b''
# Encode every 6 binary digits to their corresponding Base64 character
return (
"".join(
B64_CHARSET[int(binary_stream[index : index + 6] , 2 )]
for index in range(0 , len(lowercase__ ) , 6 ) ).encode()
+ padding
)
def _a ( lowercase__ : str ):
'''simple docstring'''
if not isinstance(lowercase__ , lowercase__ ) and not isinstance(lowercase__ , lowercase__ ):
SCREAMING_SNAKE_CASE__ : List[str] = (
'argument should be a bytes-like object or ASCII string, '
f'''not \'{encoded_data.__class__.__name__}\''''
)
raise TypeError(lowercase__ )
# In case encoded_data is a bytes-like object, make sure it contains only
# ASCII characters so we convert it to a string object
if isinstance(lowercase__ , lowercase__ ):
try:
SCREAMING_SNAKE_CASE__ : str = encoded_data.decode('utf-8' )
except UnicodeDecodeError:
raise ValueError('base64 encoded data should only contain ASCII characters' )
SCREAMING_SNAKE_CASE__ : int = encoded_data.count('=' )
# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found."
else:
assert all(
char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found."
# Check the padding
assert len(lowercase__ ) % 4 == 0 and padding < 3, "Incorrect padding"
if padding:
# Remove padding if there is one
SCREAMING_SNAKE_CASE__ : int = encoded_data[:-padding]
SCREAMING_SNAKE_CASE__ : List[str] = ''.join(
bin(B64_CHARSET.index(lowercase__ ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2]
else:
SCREAMING_SNAKE_CASE__ : List[str] = ''.join(
bin(B64_CHARSET.index(lowercase__ ) )[2:].zfill(6 ) for char in encoded_data )
SCREAMING_SNAKE_CASE__ : Optional[int] = [
int(binary_stream[index : index + 8] , 2 )
for index in range(0 , len(lowercase__ ) , 8 )
]
return bytes(lowercase__ )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 85 | def _a ( lowercase__ : int , lowercase__ : list ):
'''simple docstring'''
_enforce_args(lowercase__ , lowercase__ )
if n == 0:
return 0
SCREAMING_SNAKE_CASE__ : str = float('-inf' )
for i in range(1 , n + 1 ):
SCREAMING_SNAKE_CASE__ : int = max(
lowercase__ , prices[i - 1] + naive_cut_rod_recursive(n - i , lowercase__ ) )
return max_revue
def _a ( lowercase__ : int , lowercase__ : list ):
'''simple docstring'''
_enforce_args(lowercase__ , lowercase__ )
SCREAMING_SNAKE_CASE__ : str = [float('-inf' ) for _ in range(n + 1 )]
return _top_down_cut_rod_recursive(lowercase__ , lowercase__ , lowercase__ )
def _a ( lowercase__ : int , lowercase__ : list , lowercase__ : list ):
'''simple docstring'''
if max_rev[n] >= 0:
return max_rev[n]
elif n == 0:
return 0
else:
SCREAMING_SNAKE_CASE__ : List[str] = float('-inf' )
for i in range(1 , n + 1 ):
SCREAMING_SNAKE_CASE__ : Any = max(
lowercase__ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , lowercase__ , lowercase__ ) , )
SCREAMING_SNAKE_CASE__ : Tuple = max_revenue
return max_rev[n]
def _a ( lowercase__ : int , lowercase__ : list ):
'''simple docstring'''
_enforce_args(lowercase__ , lowercase__ )
# length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of
# length 0.
SCREAMING_SNAKE_CASE__ : Optional[int] = [float('-inf' ) for _ in range(n + 1 )]
SCREAMING_SNAKE_CASE__ : int = 0
for i in range(1 , n + 1 ):
SCREAMING_SNAKE_CASE__ : Optional[Any] = max_rev[i]
for j in range(1 , i + 1 ):
SCREAMING_SNAKE_CASE__ : Union[str, Any] = max(lowercase__ , prices[j - 1] + max_rev[i - j] )
SCREAMING_SNAKE_CASE__ : Dict = max_revenue_i
return max_rev[n]
def _a ( lowercase__ : int , lowercase__ : list ):
'''simple docstring'''
if n < 0:
SCREAMING_SNAKE_CASE__ : Tuple = f'''n must be greater than or equal to 0. Got n = {n}'''
raise ValueError(lowercase__ )
if n > len(lowercase__ ):
SCREAMING_SNAKE_CASE__ : Tuple = (
'Each integral piece of rod must have a corresponding price. '
f'''Got n = {n} but length of prices = {len(lowercase__ )}'''
)
raise ValueError(lowercase__ )
def _a ( ):
'''simple docstring'''
SCREAMING_SNAKE_CASE__ : str = [6, 10, 12, 15, 20, 23]
SCREAMING_SNAKE_CASE__ : Optional[int] = len(lowercase__ )
# the best revenue comes from cutting the rod into 6 pieces, each
# of length 1 resulting in a revenue of 6 * 6 = 36.
SCREAMING_SNAKE_CASE__ : Optional[Any] = 36
SCREAMING_SNAKE_CASE__ : Tuple = top_down_cut_rod(lowercase__ , lowercase__ )
SCREAMING_SNAKE_CASE__ : Optional[int] = bottom_up_cut_rod(lowercase__ , lowercase__ )
SCREAMING_SNAKE_CASE__ : List[str] = naive_cut_rod_recursive(lowercase__ , lowercase__ )
assert expected_max_revenue == max_rev_top_down
assert max_rev_top_down == max_rev_bottom_up
assert max_rev_bottom_up == max_rev_naive
if __name__ == "__main__":
main()
| 85 | 1 |
import os
from shutil import copyfile
from typing import List, Optional, Tuple
from tokenizers import processors
from ...tokenization_utils import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import is_sentencepiece_available, logging
if is_sentencepiece_available():
from .tokenization_nllb import NllbTokenizer
else:
SCREAMING_SNAKE_CASE_ : Dict = None
SCREAMING_SNAKE_CASE_ : int = logging.get_logger(__name__)
SCREAMING_SNAKE_CASE_ : int = {'''vocab_file''': '''sentencepiece.bpe.model''', '''tokenizer_file''': '''tokenizer.json'''}
SCREAMING_SNAKE_CASE_ : Optional[int] = {
'''vocab_file''': {
'''facebook/nllb-200-distilled-600M''': (
'''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/sentencepiece.bpe.model'''
),
},
'''tokenizer_file''': {
'''facebook/nllb-200-distilled-600M''': (
'''https://huggingface.co/facebook/nllb-200-distilled-600M/resolve/main/tokenizer.json'''
),
},
}
SCREAMING_SNAKE_CASE_ : Any = {
'''facebook/nllb-large-en-ro''': 1024,
'''facebook/nllb-200-distilled-600M''': 1024,
}
# fmt: off
SCREAMING_SNAKE_CASE_ : Optional[int] = ['''ace_Arab''', '''ace_Latn''', '''acm_Arab''', '''acq_Arab''', '''aeb_Arab''', '''afr_Latn''', '''ajp_Arab''', '''aka_Latn''', '''amh_Ethi''', '''apc_Arab''', '''arb_Arab''', '''ars_Arab''', '''ary_Arab''', '''arz_Arab''', '''asm_Beng''', '''ast_Latn''', '''awa_Deva''', '''ayr_Latn''', '''azb_Arab''', '''azj_Latn''', '''bak_Cyrl''', '''bam_Latn''', '''ban_Latn''', '''bel_Cyrl''', '''bem_Latn''', '''ben_Beng''', '''bho_Deva''', '''bjn_Arab''', '''bjn_Latn''', '''bod_Tibt''', '''bos_Latn''', '''bug_Latn''', '''bul_Cyrl''', '''cat_Latn''', '''ceb_Latn''', '''ces_Latn''', '''cjk_Latn''', '''ckb_Arab''', '''crh_Latn''', '''cym_Latn''', '''dan_Latn''', '''deu_Latn''', '''dik_Latn''', '''dyu_Latn''', '''dzo_Tibt''', '''ell_Grek''', '''eng_Latn''', '''epo_Latn''', '''est_Latn''', '''eus_Latn''', '''ewe_Latn''', '''fao_Latn''', '''pes_Arab''', '''fij_Latn''', '''fin_Latn''', '''fon_Latn''', '''fra_Latn''', '''fur_Latn''', '''fuv_Latn''', '''gla_Latn''', '''gle_Latn''', '''glg_Latn''', '''grn_Latn''', '''guj_Gujr''', '''hat_Latn''', '''hau_Latn''', '''heb_Hebr''', '''hin_Deva''', '''hne_Deva''', '''hrv_Latn''', '''hun_Latn''', '''hye_Armn''', '''ibo_Latn''', '''ilo_Latn''', '''ind_Latn''', '''isl_Latn''', '''ita_Latn''', '''jav_Latn''', '''jpn_Jpan''', '''kab_Latn''', '''kac_Latn''', '''kam_Latn''', '''kan_Knda''', '''kas_Arab''', '''kas_Deva''', '''kat_Geor''', '''knc_Arab''', '''knc_Latn''', '''kaz_Cyrl''', '''kbp_Latn''', '''kea_Latn''', '''khm_Khmr''', '''kik_Latn''', '''kin_Latn''', '''kir_Cyrl''', '''kmb_Latn''', '''kon_Latn''', '''kor_Hang''', '''kmr_Latn''', '''lao_Laoo''', '''lvs_Latn''', '''lij_Latn''', '''lim_Latn''', '''lin_Latn''', '''lit_Latn''', '''lmo_Latn''', '''ltg_Latn''', '''ltz_Latn''', '''lua_Latn''', '''lug_Latn''', '''luo_Latn''', '''lus_Latn''', '''mag_Deva''', '''mai_Deva''', '''mal_Mlym''', '''mar_Deva''', '''min_Latn''', '''mkd_Cyrl''', '''plt_Latn''', '''mlt_Latn''', '''mni_Beng''', '''khk_Cyrl''', '''mos_Latn''', '''mri_Latn''', '''zsm_Latn''', '''mya_Mymr''', '''nld_Latn''', '''nno_Latn''', '''nob_Latn''', '''npi_Deva''', '''nso_Latn''', '''nus_Latn''', '''nya_Latn''', '''oci_Latn''', '''gaz_Latn''', '''ory_Orya''', '''pag_Latn''', '''pan_Guru''', '''pap_Latn''', '''pol_Latn''', '''por_Latn''', '''prs_Arab''', '''pbt_Arab''', '''quy_Latn''', '''ron_Latn''', '''run_Latn''', '''rus_Cyrl''', '''sag_Latn''', '''san_Deva''', '''sat_Beng''', '''scn_Latn''', '''shn_Mymr''', '''sin_Sinh''', '''slk_Latn''', '''slv_Latn''', '''smo_Latn''', '''sna_Latn''', '''snd_Arab''', '''som_Latn''', '''sot_Latn''', '''spa_Latn''', '''als_Latn''', '''srd_Latn''', '''srp_Cyrl''', '''ssw_Latn''', '''sun_Latn''', '''swe_Latn''', '''swh_Latn''', '''szl_Latn''', '''tam_Taml''', '''tat_Cyrl''', '''tel_Telu''', '''tgk_Cyrl''', '''tgl_Latn''', '''tha_Thai''', '''tir_Ethi''', '''taq_Latn''', '''taq_Tfng''', '''tpi_Latn''', '''tsn_Latn''', '''tso_Latn''', '''tuk_Latn''', '''tum_Latn''', '''tur_Latn''', '''twi_Latn''', '''tzm_Tfng''', '''uig_Arab''', '''ukr_Cyrl''', '''umb_Latn''', '''urd_Arab''', '''uzn_Latn''', '''vec_Latn''', '''vie_Latn''', '''war_Latn''', '''wol_Latn''', '''xho_Latn''', '''ydd_Hebr''', '''yor_Latn''', '''yue_Hant''', '''zho_Hans''', '''zho_Hant''', '''zul_Latn''']
class _A ( __a ):
__a = VOCAB_FILES_NAMES
__a = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
__a = PRETRAINED_VOCAB_FILES_MAP
__a = ['input_ids', 'attention_mask']
__a = NllbTokenizer
__a = []
__a = []
def __init__( self , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="</s>" , SCREAMING_SNAKE_CASE__="<s>" , SCREAMING_SNAKE_CASE__="<unk>" , SCREAMING_SNAKE_CASE__="<pad>" , SCREAMING_SNAKE_CASE__="<mask>" , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=None , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ , ) -> Any:
# Mask token behave like a normal word, i.e. include the space before it
lowerCamelCase__ = AddedToken(SCREAMING_SNAKE_CASE__ , lstrip=SCREAMING_SNAKE_CASE__ , rstrip=SCREAMING_SNAKE_CASE__ ) if isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) else mask_token
lowerCamelCase__ = legacy_behaviour
super().__init__(
vocab_file=SCREAMING_SNAKE_CASE__ , tokenizer_file=SCREAMING_SNAKE_CASE__ , bos_token=SCREAMING_SNAKE_CASE__ , eos_token=SCREAMING_SNAKE_CASE__ , sep_token=SCREAMING_SNAKE_CASE__ , cls_token=SCREAMING_SNAKE_CASE__ , unk_token=SCREAMING_SNAKE_CASE__ , pad_token=SCREAMING_SNAKE_CASE__ , mask_token=SCREAMING_SNAKE_CASE__ , src_lang=SCREAMING_SNAKE_CASE__ , tgt_lang=SCREAMING_SNAKE_CASE__ , additional_special_tokens=SCREAMING_SNAKE_CASE__ , legacy_behaviour=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ , )
lowerCamelCase__ = vocab_file
lowerCamelCase__ = False if not self.vocab_file else True
lowerCamelCase__ = FAIRSEQ_LANGUAGE_CODES.copy()
if additional_special_tokens is not None:
# Only add those special tokens if they are not already there.
_additional_special_tokens.extend(
[t for t in additional_special_tokens if t not in _additional_special_tokens] )
self.add_special_tokens({"additional_special_tokens": _additional_special_tokens} )
lowerCamelCase__ = {
lang_code: self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ ) for lang_code in FAIRSEQ_LANGUAGE_CODES
}
lowerCamelCase__ = src_lang if src_lang is not None else "eng_Latn"
lowerCamelCase__ = self.convert_tokens_to_ids(self._src_lang )
lowerCamelCase__ = tgt_lang
self.set_src_lang_special_tokens(self._src_lang )
@property
def _lowerCamelCase ( self ) -> str:
return self._src_lang
@src_lang.setter
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ) -> None:
lowerCamelCase__ = new_src_lang
self.set_src_lang_special_tokens(self._src_lang )
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> List[int]:
if token_ids_a is None:
return self.prefix_tokens + token_ids_a + self.suffix_tokens
# We don't expect to process pairs, but leave the pair logic for API consistency
return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> List[int]:
lowerCamelCase__ = [self.sep_token_id]
lowerCamelCase__ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep ) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ ) -> Any:
if src_lang is None or tgt_lang is None:
raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" )
lowerCamelCase__ = src_lang
lowerCamelCase__ = self(SCREAMING_SNAKE_CASE__ , add_special_tokens=SCREAMING_SNAKE_CASE__ , return_tensors=SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ )
lowerCamelCase__ = tgt_lang_id
return inputs
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = "eng_Latn" , SCREAMING_SNAKE_CASE__ = None , SCREAMING_SNAKE_CASE__ = "fra_Latn" , **SCREAMING_SNAKE_CASE__ , ) -> BatchEncoding:
lowerCamelCase__ = src_lang
lowerCamelCase__ = tgt_lang
return super().prepare_seqaseq_batch(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , **SCREAMING_SNAKE_CASE__ )
def _lowerCamelCase ( self ) -> Any:
return self.set_src_lang_special_tokens(self.src_lang )
def _lowerCamelCase ( self ) -> Tuple:
return self.set_tgt_lang_special_tokens(self.tgt_lang )
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ) -> None:
lowerCamelCase__ = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ )
if self.legacy_behaviour:
lowerCamelCase__ = []
lowerCamelCase__ = [self.eos_token_id, self.cur_lang_code]
else:
lowerCamelCase__ = [self.cur_lang_code]
lowerCamelCase__ = [self.eos_token_id]
lowerCamelCase__ = self.convert_ids_to_tokens(self.prefix_tokens )
lowerCamelCase__ = self.convert_ids_to_tokens(self.suffix_tokens )
lowerCamelCase__ = processors.TemplateProcessing(
single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , )
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ ) -> None:
lowerCamelCase__ = self.convert_tokens_to_ids(SCREAMING_SNAKE_CASE__ )
if self.legacy_behaviour:
lowerCamelCase__ = []
lowerCamelCase__ = [self.eos_token_id, self.cur_lang_code]
else:
lowerCamelCase__ = [self.cur_lang_code]
lowerCamelCase__ = [self.eos_token_id]
lowerCamelCase__ = self.convert_ids_to_tokens(self.prefix_tokens )
lowerCamelCase__ = self.convert_ids_to_tokens(self.suffix_tokens )
lowerCamelCase__ = processors.TemplateProcessing(
single=prefix_tokens_str + ["$A"] + suffix_tokens_str , pair=prefix_tokens_str + ["$A", "$B"] + suffix_tokens_str , special_tokens=list(zip(prefix_tokens_str + suffix_tokens_str , self.prefix_tokens + self.suffix_tokens ) ) , )
def _lowerCamelCase ( self , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ = None ) -> Tuple[str]:
if not self.can_save_slow_tokenizer:
raise ValueError(
"Your fast tokenizer does not have the necessary information to save the vocabulary for a slow "
"tokenizer." )
if not os.path.isdir(SCREAMING_SNAKE_CASE__ ):
logger.error(f'Vocabulary path ({save_directory}) should be a directory.' )
return
lowerCamelCase__ = os.path.join(
SCREAMING_SNAKE_CASE__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(SCREAMING_SNAKE_CASE__ ):
copyfile(self.vocab_file , SCREAMING_SNAKE_CASE__ )
return (out_vocab_file,)
| 704 |
"""simple docstring"""
import logging
import os
import sys
from dataclasses import dataclass, field
from typing import Optional
from seqaseq_trainer import SeqaSeqTrainer
from seqaseq_training_args import SeqaSeqTrainingArguments
import transformers
from transformers import (
AutoConfig,
AutoModelForSeqaSeqLM,
AutoTokenizer,
HfArgumentParser,
MBartTokenizer,
MBartTokenizerFast,
set_seed,
)
from transformers.trainer_utils import EvaluationStrategy, is_main_process
from transformers.training_args import ParallelMode
from utils import (
SeqaSeqDataCollator,
SeqaSeqDataset,
assert_all_frozen,
build_compute_metrics_fn,
check_output_dir,
freeze_embeds,
freeze_params,
lmap,
save_json,
use_task_specific_params,
write_txt_file,
)
SCREAMING_SNAKE_CASE_ : Optional[Any] = logging.getLogger(__name__)
@dataclass
class _A :
__a = field(
metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'} )
__a = field(
default=__a , metadata={'help': 'Pretrained config name or path if not the same as model_name'} )
__a = field(
default=__a , metadata={'help': 'Pretrained tokenizer name or path if not the same as model_name'} )
__a = field(
default=__a , metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'} , )
__a = field(default=__a , metadata={'help': 'Whether tp freeze the encoder.'} )
__a = field(default=__a , metadata={'help': 'Whether to freeze the embeddings.'} )
@dataclass
class _A :
__a = field(
metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'} )
__a = field(
default='summarization' , metadata={'help': 'Task name, summarization (or summarization_{dataset} for pegasus) or translation'} , )
__a = field(
default=1024 , metadata={
'help': (
'The maximum total input sequence length after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
__a = field(
default=128 , metadata={
'help': (
'The maximum total sequence length for target text after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
__a = field(
default=142 , metadata={
'help': (
'The maximum total sequence length for validation target text after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded. '
'This argument is also used to override the ``max_length`` param of ``model.generate``, which is used '
'during ``evaluate`` and ``predict``.'
)
} , )
__a = field(
default=142 , metadata={
'help': (
'The maximum total sequence length for test target text after tokenization. Sequences longer '
'than this will be truncated, sequences shorter will be padded.'
)
} , )
__a = field(default=-1 , metadata={'help': '# training examples. -1 means use all.'} )
__a = field(default=-1 , metadata={'help': '# validation examples. -1 means use all.'} )
__a = field(default=-1 , metadata={'help': '# test examples. -1 means use all.'} )
__a = field(default=__a , metadata={'help': 'Source language id for translation.'} )
__a = field(default=__a , metadata={'help': 'Target language id for translation.'} )
__a = field(default=__a , metadata={'help': '# num_beams to use for evaluation.'} )
__a = field(
default=__a , metadata={'help': 'If only pad tokens should be ignored. This assumes that `config.pad_token_id` is defined.'} , )
def UpperCAmelCase__ ( A__ , A__ , A__ ) -> Union[str, Any]:
"""simple docstring"""
logger.info(f'***** {split} metrics *****' )
for key in sorted(metrics.keys() ):
logger.info(f' {key} = {metrics[key]}' )
save_json(A__ , os.path.join(A__ , f'{split}_results.json' ) )
def UpperCAmelCase__ ( ) -> List[str]:
"""simple docstring"""
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
lowerCamelCase__ = HfArgumentParser((ModelArguments, DataTrainingArguments, SeqaSeqTrainingArguments) )
if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ):
# If we pass only one argument to the script and it's the path to a json file,
# let's parse it to get our arguments.
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) )
else:
lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ = parser.parse_args_into_dataclasses()
check_output_dir(A__ )
# Setup logging
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , )
logger.warning(
"Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s" , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.parallel_mode == ParallelMode.DISTRIBUTED ) , training_args.fpaa , )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Set the verbosity to info of the Transformers logger (on main process only):
if is_main_process(training_args.local_rank ):
transformers.utils.logging.set_verbosity_info()
logger.info("Training/evaluation parameters %s" , A__ )
# Set seed
set_seed(training_args.seed )
# Load pretrained model and tokenizer
#
# Distributed training:
# The .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
lowerCamelCase__ = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , )
lowerCamelCase__ = ("encoder_layerdrop", "decoder_layerdrop", "dropout", "attention_dropout")
for p in extra_model_params:
if getattr(A__ , A__ , A__ ):
assert hasattr(A__ , A__ ), f'({config.__class__.__name__}) doesn\'t have a `{p}` attribute'
setattr(A__ , A__ , getattr(A__ , A__ ) )
lowerCamelCase__ = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , )
lowerCamelCase__ = AutoModelForSeqaSeqLM.from_pretrained(
model_args.model_name_or_path , from_tf=".ckpt" in model_args.model_name_or_path , config=A__ , cache_dir=model_args.cache_dir , )
# use task specific params
use_task_specific_params(A__ , data_args.task )
# set num_beams for evaluation
if data_args.eval_beams is None:
lowerCamelCase__ = model.config.num_beams
# set decoder_start_token_id for MBart
if model.config.decoder_start_token_id is None and isinstance(A__ , (MBartTokenizer, MBartTokenizerFast) ):
assert (
data_args.tgt_lang is not None and data_args.src_lang is not None
), "mBart requires --tgt_lang and --src_lang"
if isinstance(A__ , A__ ):
lowerCamelCase__ = tokenizer.lang_code_to_id[data_args.tgt_lang]
else:
lowerCamelCase__ = tokenizer.convert_tokens_to_ids(data_args.tgt_lang )
if model_args.freeze_embeds:
freeze_embeds(A__ )
if model_args.freeze_encoder:
freeze_params(model.get_encoder() )
assert_all_frozen(model.get_encoder() )
lowerCamelCase__ = SeqaSeqDataset
# Get datasets
lowerCamelCase__ = (
dataset_class(
A__ , type_path="train" , data_dir=data_args.data_dir , n_obs=data_args.n_train , max_target_length=data_args.max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , )
if training_args.do_train
else None
)
lowerCamelCase__ = (
dataset_class(
A__ , type_path="val" , data_dir=data_args.data_dir , n_obs=data_args.n_val , max_target_length=data_args.val_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , )
if training_args.do_eval or training_args.evaluation_strategy != EvaluationStrategy.NO
else None
)
lowerCamelCase__ = (
dataset_class(
A__ , type_path="test" , data_dir=data_args.data_dir , n_obs=data_args.n_test , max_target_length=data_args.test_max_target_length , max_source_length=data_args.max_source_length , prefix=model.config.prefix or "" , )
if training_args.do_predict
else None
)
# Initialize our Trainer
lowerCamelCase__ = (
build_compute_metrics_fn(data_args.task , A__ ) if training_args.predict_with_generate else None
)
lowerCamelCase__ = SeqaSeqTrainer(
model=A__ , args=A__ , data_args=A__ , train_dataset=A__ , eval_dataset=A__ , data_collator=SeqaSeqDataCollator(
A__ , A__ , model.config.decoder_start_token_id , training_args.tpu_num_cores ) , compute_metrics=A__ , tokenizer=A__ , )
lowerCamelCase__ = {}
# Training
if training_args.do_train:
logger.info("*** Train ***" )
lowerCamelCase__ = trainer.train(
model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None )
lowerCamelCase__ = train_result.metrics
lowerCamelCase__ = data_args.n_train
trainer.save_model() # this also saves the tokenizer
if trainer.is_world_process_zero():
handle_metrics("train" , A__ , training_args.output_dir )
all_metrics.update(A__ )
# Need to save the state, since Trainer.save_model saves only the tokenizer with the model
trainer.state.save_to_json(os.path.join(training_args.output_dir , "trainer_state.json" ) )
# For convenience, we also re-save the tokenizer to the same directory,
# so that you can share your model easily on huggingface.co/models =)
tokenizer.save_pretrained(training_args.output_dir )
# Evaluation
if training_args.do_eval:
logger.info("*** Evaluate ***" )
lowerCamelCase__ = trainer.evaluate(metric_key_prefix="val" )
lowerCamelCase__ = data_args.n_val
lowerCamelCase__ = round(metrics["val_loss"] , 4 )
if trainer.is_world_process_zero():
handle_metrics("val" , A__ , training_args.output_dir )
all_metrics.update(A__ )
if training_args.do_predict:
logger.info("*** Predict ***" )
lowerCamelCase__ = trainer.predict(test_dataset=A__ , metric_key_prefix="test" )
lowerCamelCase__ = test_output.metrics
lowerCamelCase__ = data_args.n_test
if trainer.is_world_process_zero():
lowerCamelCase__ = round(metrics["test_loss"] , 4 )
handle_metrics("test" , A__ , training_args.output_dir )
all_metrics.update(A__ )
if training_args.predict_with_generate:
lowerCamelCase__ = tokenizer.batch_decode(
test_output.predictions , skip_special_tokens=A__ , clean_up_tokenization_spaces=A__ )
lowerCamelCase__ = lmap(str.strip , A__ )
write_txt_file(A__ , os.path.join(training_args.output_dir , "test_generations.txt" ) )
if trainer.is_world_process_zero():
save_json(A__ , os.path.join(training_args.output_dir , "all_results.json" ) )
return all_metrics
def UpperCAmelCase__ ( A__ ) -> Any:
"""simple docstring"""
# For xla_spawn (TPUs)
main()
if __name__ == "__main__":
main()
| 274 | 0 |
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
_lowercase : List[str] =logging.get_logger(__name__)
_lowercase : Dict ={
"""sail/poolformer_s12""": """https://huggingface.co/sail/poolformer_s12/resolve/main/config.json""",
# See all PoolFormer models at https://huggingface.co/models?filter=poolformer
}
class UpperCamelCase_ ( snake_case__ ):
_a : Any = 'poolformer'
def __init__( self : List[str] , lowerCamelCase : int=3 , lowerCamelCase : Any=16 , lowerCamelCase : str=16 , lowerCamelCase : Optional[int]=3 , lowerCamelCase : Optional[Any]=4.0 , lowerCamelCase : int=[2, 2, 6, 2] , lowerCamelCase : str=[64, 1_28, 3_20, 5_12] , lowerCamelCase : Any=[7, 3, 3, 3] , lowerCamelCase : int=[4, 2, 2, 2] , lowerCamelCase : List[str]=[2, 1, 1, 1] , lowerCamelCase : List[Any]=4 , lowerCamelCase : int=0.0 , lowerCamelCase : int="gelu" , lowerCamelCase : Optional[Any]=True , lowerCamelCase : int=1E-5 , lowerCamelCase : str=0.02 , **lowerCamelCase : Tuple , ):
lowerCamelCase_ : str = num_channels
lowerCamelCase_ : int = patch_size
lowerCamelCase_ : Optional[int] = stride
lowerCamelCase_ : Optional[Any] = padding
lowerCamelCase_ : str = pool_size
lowerCamelCase_ : Any = hidden_sizes
lowerCamelCase_ : Dict = mlp_ratio
lowerCamelCase_ : Tuple = depths
lowerCamelCase_ : Any = patch_sizes
lowerCamelCase_ : Any = strides
lowerCamelCase_ : Dict = num_encoder_blocks
lowerCamelCase_ : Optional[int] = drop_path_rate
lowerCamelCase_ : List[Any] = hidden_act
lowerCamelCase_ : Dict = use_layer_scale
lowerCamelCase_ : Optional[Any] = layer_scale_init_value
lowerCamelCase_ : List[Any] = initializer_range
super().__init__(**lowerCamelCase )
class UpperCamelCase_ ( snake_case__ ):
_a : Dict = version.parse('1.11' )
@property
def __a ( self : List[str] ):
return OrderedDict(
[
('pixel_values', {0: 'batch', 1: 'num_channels', 2: 'height', 3: 'width'}),
] )
@property
def __a ( self : List[Any] ):
return 2E-3
| 364 |
import numpy as np
from transformers import BatchFeature
from transformers.testing_utils import require_tf, require_torch
from .test_feature_extraction_common import FeatureExtractionSavingTestMixin
class UpperCamelCase_ ( snake_case__ ):
# to overwrite at feature extractactor specific tests
_a : str = None
_a : Tuple = None
@property
def __a ( self : str ):
return self.feat_extract_tester.prepare_feat_extract_dict()
def __a ( self : int ):
lowerCamelCase_ : List[str] = self.feature_extraction_class(**self.feat_extract_dict )
self.assertTrue(hasattr(lowerCamelCase , 'feature_size' ) )
self.assertTrue(hasattr(lowerCamelCase , 'sampling_rate' ) )
self.assertTrue(hasattr(lowerCamelCase , 'padding_value' ) )
def __a ( self : List[Any] ):
lowerCamelCase_ : Dict = self.feat_extract_tester.prepare_inputs_for_common()
lowerCamelCase_ : str = self.feature_extraction_class(**self.feat_extract_dict )
lowerCamelCase_ : int = feat_extract.model_input_names[0]
lowerCamelCase_ : Optional[int] = BatchFeature({input_name: speech_inputs} )
self.assertTrue(all(len(lowerCamelCase ) == len(lowerCamelCase ) for x, y in zip(lowerCamelCase , processed_features[input_name] ) ) )
lowerCamelCase_ : Tuple = self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCamelCase )
lowerCamelCase_ : Union[str, Any] = BatchFeature({input_name: speech_inputs} , tensor_type='np' )
lowerCamelCase_ : int = processed_features[input_name]
if len(batch_features_input.shape ) < 3:
lowerCamelCase_ : Union[str, Any] = batch_features_input[:, :, None]
self.assertTrue(
batch_features_input.shape
== (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) )
@require_torch
def __a ( self : Dict ):
lowerCamelCase_ : Any = self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCamelCase )
lowerCamelCase_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict )
lowerCamelCase_ : Tuple = feat_extract.model_input_names[0]
lowerCamelCase_ : Any = BatchFeature({input_name: speech_inputs} , tensor_type='pt' )
lowerCamelCase_ : Optional[int] = processed_features[input_name]
if len(batch_features_input.shape ) < 3:
lowerCamelCase_ : Optional[int] = batch_features_input[:, :, None]
self.assertTrue(
batch_features_input.shape
== (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) )
@require_tf
def __a ( self : Tuple ):
lowerCamelCase_ : int = self.feat_extract_tester.prepare_inputs_for_common(equal_length=lowerCamelCase )
lowerCamelCase_ : List[str] = self.feature_extraction_class(**self.feat_extract_dict )
lowerCamelCase_ : int = feat_extract.model_input_names[0]
lowerCamelCase_ : List[str] = BatchFeature({input_name: speech_inputs} , tensor_type='tf' )
lowerCamelCase_ : Union[str, Any] = processed_features[input_name]
if len(batch_features_input.shape ) < 3:
lowerCamelCase_ : Any = batch_features_input[:, :, None]
self.assertTrue(
batch_features_input.shape
== (self.feat_extract_tester.batch_size, len(speech_inputs[0] ), self.feat_extract_tester.feature_size) )
def __a ( self : Optional[Any] , lowerCamelCase : int=False ):
def _inputs_have_equal_length(lowerCamelCase : Union[str, Any] ):
lowerCamelCase_ : Any = len(input[0] )
for input_slice in input[1:]:
if len(lowerCamelCase ) != length:
return False
return True
def _inputs_are_equal(lowerCamelCase : List[str] , lowerCamelCase : Dict ):
if len(lowerCamelCase ) != len(lowerCamelCase ):
return False
for input_slice_a, input_slice_a in zip(lowerCamelCase , lowerCamelCase ):
if not np.allclose(np.asarray(lowerCamelCase ) , np.asarray(lowerCamelCase ) , atol=1E-3 ):
return False
return True
lowerCamelCase_ : List[str] = self.feature_extraction_class(**self.feat_extract_dict )
lowerCamelCase_ : str = self.feat_extract_tester.prepare_inputs_for_common(numpify=lowerCamelCase )
lowerCamelCase_ : List[Any] = feat_extract.model_input_names[0]
lowerCamelCase_ : List[Any] = BatchFeature({input_name: speech_inputs} )
lowerCamelCase_ : Optional[int] = self.feat_extract_tester.seq_length_diff
lowerCamelCase_ : int = self.feat_extract_tester.max_seq_length + pad_diff
lowerCamelCase_ : Optional[int] = self.feat_extract_tester.min_seq_length
lowerCamelCase_ : List[Any] = self.feat_extract_tester.batch_size
lowerCamelCase_ : int = self.feat_extract_tester.feature_size
# test padding for List[int] + numpy
lowerCamelCase_ : int = feat_extract.pad(lowerCamelCase , padding=lowerCamelCase )
lowerCamelCase_ : Tuple = input_a[input_name]
lowerCamelCase_ : List[str] = feat_extract.pad(lowerCamelCase , padding='longest' )
lowerCamelCase_ : Optional[Any] = input_a[input_name]
lowerCamelCase_ : List[Any] = feat_extract.pad(lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[-1] ) )
lowerCamelCase_ : List[str] = input_a[input_name]
lowerCamelCase_ : Union[str, Any] = feat_extract.pad(lowerCamelCase , padding='longest' , return_tensors='np' )
lowerCamelCase_ : int = input_a[input_name]
# max_length parameter has to be provided when setting `padding="max_length"`
with self.assertRaises(lowerCamelCase ):
feat_extract.pad(lowerCamelCase , padding='max_length' )[input_name]
lowerCamelCase_ : Union[str, Any] = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=lowerCamelCase , return_tensors='np' )
lowerCamelCase_ : Dict = input_a[input_name]
self.assertFalse(_inputs_have_equal_length(lowerCamelCase ) )
self.assertTrue(_inputs_have_equal_length(lowerCamelCase ) )
self.assertTrue(_inputs_have_equal_length(lowerCamelCase ) )
self.assertTrue(_inputs_are_equal(lowerCamelCase , lowerCamelCase ) )
self.assertTrue(len(input_a[0] ) == pad_min_length )
self.assertTrue(len(input_a[1] ) == pad_min_length + pad_diff )
self.assertTrue(input_a.shape[:2] == (batch_size, len(input_a[0] )) )
self.assertTrue(input_a.shape[:2] == (batch_size, pad_max_length) )
if feature_size > 1:
self.assertTrue(input_a.shape[2] == input_a.shape[2] == feature_size )
# test padding for `pad_to_multiple_of` for List[int] + numpy
lowerCamelCase_ : Optional[Any] = feat_extract.pad(lowerCamelCase , pad_to_multiple_of=10 )
lowerCamelCase_ : Dict = input_a[input_name]
lowerCamelCase_ : List[Any] = feat_extract.pad(lowerCamelCase , padding='longest' , pad_to_multiple_of=10 )
lowerCamelCase_ : Union[str, Any] = input_a[input_name]
lowerCamelCase_ : str = feat_extract.pad(
lowerCamelCase , padding='max_length' , pad_to_multiple_of=10 , max_length=lowerCamelCase )
lowerCamelCase_ : List[str] = input_a[input_name]
lowerCamelCase_ : Any = feat_extract.pad(
lowerCamelCase , padding='max_length' , pad_to_multiple_of=10 , max_length=lowerCamelCase , return_tensors='np' , )
lowerCamelCase_ : str = input_a[input_name]
self.assertTrue(all(len(lowerCamelCase ) % 10 == 0 for x in input_a ) )
self.assertTrue(_inputs_are_equal(lowerCamelCase , lowerCamelCase ) )
lowerCamelCase_ : Dict = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10
self.assertTrue(all(len(lowerCamelCase ) == expected_mult_pad_length for x in input_a ) )
self.assertEqual(input_a.shape[:2] , (batch_size, expected_mult_pad_length) )
if feature_size > 1:
self.assertTrue(input_a.shape[2] == feature_size )
# Check padding value is correct
lowerCamelCase_ : Dict = (np.ones(self.feat_extract_tester.feature_size ) * feat_extract.padding_value).sum()
self.assertTrue(
abs(np.asarray(input_a[0] )[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) )
< 1E-3 )
self.assertTrue(
abs(
np.asarray(input_a[1] )[pad_min_length + pad_diff :].sum()
- padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) )
< 1E-3 )
self.assertTrue(
abs(
np.asarray(input_a[2] )[pad_min_length + 2 * pad_diff :].sum()
- padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) )
< 1E-3 )
self.assertTrue(
abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length) ) < 1E-3 )
self.assertTrue(
abs(input_a[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length) )
< 1E-3 )
def __a ( self : Optional[Any] , lowerCamelCase : Any=False ):
def _inputs_have_equal_length(lowerCamelCase : Dict ):
lowerCamelCase_ : Dict = len(input[0] )
for input_slice in input[1:]:
if len(lowerCamelCase ) != length:
return False
return True
def _inputs_are_equal(lowerCamelCase : int , lowerCamelCase : List[str] ):
if len(lowerCamelCase ) != len(lowerCamelCase ):
return False
for input_slice_a, input_slice_a in zip(lowerCamelCase , lowerCamelCase ):
if not np.allclose(np.asarray(lowerCamelCase ) , np.asarray(lowerCamelCase ) , atol=1E-3 ):
return False
return True
lowerCamelCase_ : List[str] = self.feature_extraction_class(**self.feat_extract_dict )
lowerCamelCase_ : str = self.feat_extract_tester.prepare_inputs_for_common(numpify=lowerCamelCase )
lowerCamelCase_ : Any = feat_extract.model_input_names[0]
lowerCamelCase_ : str = BatchFeature({input_name: speech_inputs} )
# truncate to smallest
lowerCamelCase_ : Dict = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[0] ) , truncation=lowerCamelCase )
lowerCamelCase_ : int = input_a[input_name]
lowerCamelCase_ : str = feat_extract.pad(lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[0] ) )
lowerCamelCase_ : Union[str, Any] = input_a[input_name]
self.assertTrue(_inputs_have_equal_length(lowerCamelCase ) )
self.assertFalse(_inputs_have_equal_length(lowerCamelCase ) )
# truncate to smallest with np
lowerCamelCase_ : Optional[int] = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[0] ) , return_tensors='np' , truncation=lowerCamelCase , )
lowerCamelCase_ : List[str] = input_a[input_name]
lowerCamelCase_ : int = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[0] ) , return_tensors='np' )
lowerCamelCase_ : Tuple = input_a[input_name]
self.assertTrue(_inputs_have_equal_length(lowerCamelCase ) )
self.assertTrue(input_a.shape[1] == len(speech_inputs[0] ) )
# since truncation forces padding to be smaller than longest input
# function can't return `np.ndarray`, but has to return list
self.assertFalse(_inputs_have_equal_length(lowerCamelCase ) )
# truncate to middle
lowerCamelCase_ : Tuple = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[1] ) , truncation=lowerCamelCase , return_tensors='np' , )
lowerCamelCase_ : Union[str, Any] = input_a[input_name]
lowerCamelCase_ : str = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[1] ) , truncation=lowerCamelCase )
lowerCamelCase_ : Any = input_a[input_name]
lowerCamelCase_ : int = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[1] ) , return_tensors='np' )
lowerCamelCase_ : Optional[int] = input_a[input_name]
self.assertTrue(input_a.shape[1] == len(speech_inputs[1] ) )
self.assertTrue(_inputs_have_equal_length(lowerCamelCase ) )
self.assertTrue(_inputs_have_equal_length(lowerCamelCase ) )
self.assertTrue(_inputs_are_equal(lowerCamelCase , lowerCamelCase ) )
# since truncation forces padding to be smaller than longest input
# function can't return `np.ndarray`, but has to return list
self.assertFalse(_inputs_have_equal_length(lowerCamelCase ) )
self.assertTrue(len(input_a[-1] ) == len(speech_inputs[-1] ) )
# padding has to be max_length when setting `truncation=True`
with self.assertRaises(lowerCamelCase ):
feat_extract.pad(lowerCamelCase , truncation=lowerCamelCase )[input_name]
# padding has to be max_length when setting `truncation=True`
with self.assertRaises(lowerCamelCase ):
feat_extract.pad(lowerCamelCase , padding='longest' , truncation=lowerCamelCase )[input_name]
# padding has to be max_length when setting `truncation=True`
with self.assertRaises(lowerCamelCase ):
feat_extract.pad(lowerCamelCase , padding='longest' , truncation=lowerCamelCase )[input_name]
# max_length parameter has to be provided when setting `truncation=True` and padding="max_length"
with self.assertRaises(lowerCamelCase ):
feat_extract.pad(lowerCamelCase , padding='max_length' , truncation=lowerCamelCase )[input_name]
# test truncation for `pad_to_multiple_of` for List[int] + numpy
lowerCamelCase_ : str = 12
lowerCamelCase_ : List[Any] = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=lowerCamelCase , truncation=lowerCamelCase , )
lowerCamelCase_ : List[str] = input_a[input_name]
lowerCamelCase_ : List[Any] = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=len(speech_inputs[0] ) , pad_to_multiple_of=lowerCamelCase , )
lowerCamelCase_ : Dict = input_a[input_name]
# retrieve expected_length as multiple of pad_to_multiple_of
lowerCamelCase_ : Optional[Any] = len(speech_inputs[0] )
if expected_length % pad_to_multiple_of != 0:
lowerCamelCase_ : str = ((len(speech_inputs[0] ) // pad_to_multiple_of) + 1) * pad_to_multiple_of
self.assertTrue(len(input_a[0] ) == expected_length )
self.assertTrue(_inputs_have_equal_length(lowerCamelCase ) )
self.assertFalse(_inputs_have_equal_length(lowerCamelCase ) )
def __a ( self : Any ):
self._check_padding(numpify=lowerCamelCase )
def __a ( self : List[Any] ):
self._check_padding(numpify=lowerCamelCase )
def __a ( self : int ):
self._check_truncation(numpify=lowerCamelCase )
def __a ( self : Optional[int] ):
self._check_truncation(numpify=lowerCamelCase )
@require_torch
def __a ( self : str ):
lowerCamelCase_ : List[Any] = self.feature_extraction_class(**self.feat_extract_dict )
lowerCamelCase_ : str = self.feat_extract_tester.prepare_inputs_for_common()
lowerCamelCase_ : Optional[Any] = feat_extract.model_input_names[0]
lowerCamelCase_ : Optional[Any] = BatchFeature({input_name: speech_inputs} )
lowerCamelCase_ : int = feat_extract.pad(lowerCamelCase , padding='longest' , return_tensors='np' )[input_name]
lowerCamelCase_ : Dict = feat_extract.pad(lowerCamelCase , padding='longest' , return_tensors='pt' )[input_name]
self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_pt.numpy().astype(np.floataa ).sum() ) < 1E-2 )
@require_tf
def __a ( self : Any ):
lowerCamelCase_ : Union[str, Any] = self.feature_extraction_class(**self.feat_extract_dict )
lowerCamelCase_ : List[str] = self.feat_extract_tester.prepare_inputs_for_common()
lowerCamelCase_ : Tuple = feat_extract.model_input_names[0]
lowerCamelCase_ : Tuple = BatchFeature({input_name: speech_inputs} )
lowerCamelCase_ : Dict = feat_extract.pad(lowerCamelCase , padding='longest' , return_tensors='np' )[input_name]
lowerCamelCase_ : List[str] = feat_extract.pad(lowerCamelCase , padding='longest' , return_tensors='tf' )[input_name]
self.assertTrue(abs(input_np.astype(np.floataa ).sum() - input_tf.numpy().astype(np.floataa ).sum() ) < 1E-2 )
def __a ( self : str ):
lowerCamelCase_ : Any = self.feat_extract_dict
lowerCamelCase_ : Optional[Any] = True
lowerCamelCase_ : Dict = self.feature_extraction_class(**lowerCamelCase )
lowerCamelCase_ : Optional[int] = self.feat_extract_tester.prepare_inputs_for_common()
lowerCamelCase_ : List[str] = [len(lowerCamelCase ) for x in speech_inputs]
lowerCamelCase_ : List[Any] = feat_extract.model_input_names[0]
lowerCamelCase_ : List[str] = BatchFeature({input_name: speech_inputs} )
lowerCamelCase_ : Tuple = feat_extract.pad(lowerCamelCase , padding='longest' , return_tensors='np' )
self.assertIn('attention_mask' , lowerCamelCase )
self.assertListEqual(list(processed.attention_mask.shape ) , list(processed[input_name].shape[:2] ) )
self.assertListEqual(processed.attention_mask.sum(-1 ).tolist() , lowerCamelCase )
def __a ( self : Dict ):
lowerCamelCase_ : int = self.feat_extract_dict
lowerCamelCase_ : Any = True
lowerCamelCase_ : int = self.feature_extraction_class(**lowerCamelCase )
lowerCamelCase_ : List[str] = self.feat_extract_tester.prepare_inputs_for_common()
lowerCamelCase_ : str = [len(lowerCamelCase ) for x in speech_inputs]
lowerCamelCase_ : Optional[Any] = feat_extract.model_input_names[0]
lowerCamelCase_ : Any = BatchFeature({input_name: speech_inputs} )
lowerCamelCase_ : Optional[Any] = min(lowerCamelCase )
lowerCamelCase_ : List[Any] = feat_extract.pad(
lowerCamelCase , padding='max_length' , max_length=lowerCamelCase , truncation=lowerCamelCase , return_tensors='np' )
self.assertIn('attention_mask' , lowerCamelCase )
self.assertListEqual(
list(processed_pad.attention_mask.shape ) , [processed_pad[input_name].shape[0], max_length] )
self.assertListEqual(
processed_pad.attention_mask[:, :max_length].sum(-1 ).tolist() , [max_length for x in speech_inputs] )
| 364 | 1 |
def _UpperCAmelCase ( UpperCAmelCase : int ):
"""simple docstring"""
__lowerCamelCase : List[str] = (1 + 24 * n) ** 0.5
return ((1 + root) / 6) % 1 == 0
def _UpperCAmelCase ( UpperCAmelCase : int = 5_000 ):
"""simple docstring"""
__lowerCamelCase : int = [(i * (3 * i - 1)) // 2 for i in range(1 , UpperCAmelCase )]
for i, pentagonal_i in enumerate(UpperCAmelCase ):
for j in range(UpperCAmelCase , len(UpperCAmelCase ) ):
__lowerCamelCase : List[str] = pentagonal_nums[j]
__lowerCamelCase : Tuple = pentagonal_i + pentagonal_j
__lowerCamelCase : Union[str, Any] = pentagonal_j - pentagonal_i
if is_pentagonal(UpperCAmelCase ) and is_pentagonal(UpperCAmelCase ):
return b
return -1
if __name__ == "__main__":
print(F'''{solution() = }''')
| 458 |
import re
import warnings
from contextlib import contextmanager
from ...processing_utils import ProcessorMixin
class _UpperCamelCase ( A ):
'''simple docstring'''
a_ : List[Any] = ["image_processor", "tokenizer"]
a_ : Tuple = "AutoImageProcessor"
a_ : Tuple = "AutoTokenizer"
def __init__( self : Union[str, Any] , _lowerCamelCase : List[Any]=None , _lowerCamelCase : Any=None , **_lowerCamelCase : List[str] ):
'''simple docstring'''
__lowerCamelCase : Tuple = None
if "feature_extractor" in kwargs:
warnings.warn(
"""The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"""
""" instead.""" , _lowerCamelCase , )
__lowerCamelCase : List[Any] = kwargs.pop("""feature_extractor""" )
__lowerCamelCase : Optional[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__(_lowerCamelCase , _lowerCamelCase )
__lowerCamelCase : List[Any] = self.image_processor
__lowerCamelCase : Any = False
def __call__( self : Union[str, Any] , *_lowerCamelCase : str , **_lowerCamelCase : Dict ):
'''simple docstring'''
if self._in_target_context_manager:
return self.current_processor(*_lowerCamelCase , **_lowerCamelCase )
__lowerCamelCase : List[str] = kwargs.pop("""images""" , _lowerCamelCase )
__lowerCamelCase : List[str] = kwargs.pop("""text""" , _lowerCamelCase )
if len(_lowerCamelCase ) > 0:
__lowerCamelCase : Tuple = args[0]
__lowerCamelCase : List[Any] = args[1:]
if images is None and text is None:
raise ValueError("""You need to specify either an `images` or `text` input to process.""" )
if images is not None:
__lowerCamelCase : Tuple = self.image_processor(_lowerCamelCase , *_lowerCamelCase , **_lowerCamelCase )
if text is not None:
__lowerCamelCase : int = self.tokenizer(_lowerCamelCase , **_lowerCamelCase )
if text is None:
return inputs
elif images is None:
return encodings
else:
__lowerCamelCase : Optional[int] = encodings["""input_ids"""]
return inputs
def _snake_case ( self : List[Any] , *_lowerCamelCase : Tuple , **_lowerCamelCase : Union[str, Any] ):
'''simple docstring'''
return self.tokenizer.batch_decode(*_lowerCamelCase , **_lowerCamelCase )
def _snake_case ( self : List[str] , *_lowerCamelCase : Optional[int] , **_lowerCamelCase : int ):
'''simple docstring'''
return self.tokenizer.decode(*_lowerCamelCase , **_lowerCamelCase )
@contextmanager
def _snake_case ( self : Optional[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 images inputs, or in a separate call.""" )
__lowerCamelCase : Any = True
__lowerCamelCase : int = self.tokenizer
yield
__lowerCamelCase : Dict = self.image_processor
__lowerCamelCase : List[Any] = False
def _snake_case ( self : List[str] , _lowerCamelCase : str , _lowerCamelCase : List[str]=False , _lowerCamelCase : List[Any]=None ):
'''simple docstring'''
if added_vocab is None:
__lowerCamelCase : List[str] = self.tokenizer.get_added_vocab()
__lowerCamelCase : List[Any] = {}
while tokens:
__lowerCamelCase : Dict = re.search(R"""<s_(.*?)>""" , _lowerCamelCase , re.IGNORECASE )
if start_token is None:
break
__lowerCamelCase : Dict = start_token.group(1 )
__lowerCamelCase : List[str] = re.search(RF"""</s_{key}>""" , _lowerCamelCase , re.IGNORECASE )
__lowerCamelCase : Optional[int] = start_token.group()
if end_token is None:
__lowerCamelCase : int = tokens.replace(_lowerCamelCase , """""" )
else:
__lowerCamelCase : Dict = end_token.group()
__lowerCamelCase : Optional[Any] = re.escape(_lowerCamelCase )
__lowerCamelCase : List[str] = re.escape(_lowerCamelCase )
__lowerCamelCase : Any = re.search(F"""{start_token_escaped}(.*?){end_token_escaped}""" , _lowerCamelCase , re.IGNORECASE )
if content is not None:
__lowerCamelCase : Union[str, Any] = content.group(1 ).strip()
if r"<s_" in content and r"</s_" in content: # non-leaf node
__lowerCamelCase : Union[str, Any] = self.tokenajson(_lowerCamelCase , is_inner_value=_lowerCamelCase , added_vocab=_lowerCamelCase )
if value:
if len(_lowerCamelCase ) == 1:
__lowerCamelCase : Optional[int] = value[0]
__lowerCamelCase : Union[str, Any] = value
else: # leaf nodes
__lowerCamelCase : List[Any] = []
for leaf in content.split(R"""<sep/>""" ):
__lowerCamelCase : Optional[Any] = leaf.strip()
if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
__lowerCamelCase : str = leaf[1:-2] # for categorical special tokens
output[key].append(_lowerCamelCase )
if len(output[key] ) == 1:
__lowerCamelCase : Tuple = output[key][0]
__lowerCamelCase : Tuple = tokens[tokens.find(_lowerCamelCase ) + len(_lowerCamelCase ) :].strip()
if tokens[:6] == r"<sep/>": # non-leaf nodes
return [output] + self.tokenajson(tokens[6:] , is_inner_value=_lowerCamelCase , added_vocab=_lowerCamelCase )
if len(_lowerCamelCase ):
return [output] if is_inner_value else output
else:
return [] if is_inner_value else {"text_sequence": tokens}
@property
def _snake_case ( self : Tuple ):
'''simple docstring'''
warnings.warn(
"""`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead.""" , _lowerCamelCase , )
return self.image_processor_class
@property
def _snake_case ( self : List[Any] ):
'''simple docstring'''
warnings.warn(
"""`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead.""" , _lowerCamelCase , )
return self.image_processor
| 458 | 1 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_lowerCamelCase : str = {
'configuration_bridgetower': [
'BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP',
'BridgeTowerConfig',
'BridgeTowerTextConfig',
'BridgeTowerVisionConfig',
],
'processing_bridgetower': ['BridgeTowerProcessor'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : str = ['BridgeTowerImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : Union[str, Any] = [
'BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST',
'BridgeTowerForContrastiveLearning',
'BridgeTowerForImageAndTextRetrieval',
'BridgeTowerForMaskedLM',
'BridgeTowerModel',
'BridgeTowerPreTrainedModel',
]
if TYPE_CHECKING:
from .configuration_bridgetower import (
BRIDGETOWER_PRETRAINED_CONFIG_ARCHIVE_MAP,
BridgeTowerConfig,
BridgeTowerTextConfig,
BridgeTowerVisionConfig,
)
from .processing_bridgetower import BridgeTowerProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_bridgetower import BridgeTowerImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_bridgetower import (
BRIDGETOWER_PRETRAINED_MODEL_ARCHIVE_LIST,
BridgeTowerForContrastiveLearning,
BridgeTowerForImageAndTextRetrieval,
BridgeTowerForMaskedLM,
BridgeTowerModel,
BridgeTowerPreTrainedModel,
)
else:
import sys
_lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure)
| 121 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available
_lowerCamelCase : str = {
'configuration_jukebox': [
'JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP',
'JukeboxConfig',
'JukeboxPriorConfig',
'JukeboxVQVAEConfig',
],
'tokenization_jukebox': ['JukeboxTokenizer'],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_lowerCamelCase : str = [
'JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST',
'JukeboxModel',
'JukeboxPreTrainedModel',
'JukeboxVQVAE',
'JukeboxPrior',
]
if TYPE_CHECKING:
from .configuration_jukebox import (
JUKEBOX_PRETRAINED_CONFIG_ARCHIVE_MAP,
JukeboxConfig,
JukeboxPriorConfig,
JukeboxVQVAEConfig,
)
from .tokenization_jukebox import JukeboxTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_jukebox import (
JUKEBOX_PRETRAINED_MODEL_ARCHIVE_LIST,
JukeboxModel,
JukeboxPreTrainedModel,
JukeboxPrior,
JukeboxVQVAE,
)
else:
import sys
_lowerCamelCase : Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 121 | 1 |
'''simple docstring'''
import argparse
from diffusers.pipelines.stable_diffusion.convert_from_ckpt import download_controlnet_from_original_ckpt
if __name__ == "__main__":
lowerCAmelCase_ : List[str] = argparse.ArgumentParser()
parser.add_argument(
'--checkpoint_path', default=None, type=str, required=True, help='Path to the checkpoint to convert.'
)
parser.add_argument(
'--original_config_file',
type=str,
required=True,
help='The YAML config file corresponding to the original architecture.',
)
parser.add_argument(
'--num_in_channels',
default=None,
type=int,
help='The number of input channels. If `None` number of input channels will be automatically inferred.',
)
parser.add_argument(
'--image_size',
default=512,
type=int,
help=(
'The image size that the model was trained on. Use 512 for Stable Diffusion v1.X and Stable Siffusion v2'
' Base. Use 768 for Stable Diffusion v2.'
),
)
parser.add_argument(
'--extract_ema',
action='store_true',
help=(
'Only relevant for checkpoints that have both EMA and non-EMA weights. Whether to extract the EMA weights'
' or not. Defaults to `False`. Add `--extract_ema` to extract the EMA weights. EMA weights usually yield'
' higher quality images for inference. Non-EMA weights are usually better to continue fine-tuning.'
),
)
parser.add_argument(
'--upcast_attention',
action='store_true',
help=(
'Whether the attention computation should always be upcasted. This is necessary when running stable'
' diffusion 2.1.'
),
)
parser.add_argument(
'--from_safetensors',
action='store_true',
help='If `--checkpoint_path` is in `safetensors` format, load checkpoint with safetensors instead of PyTorch.',
)
parser.add_argument(
'--to_safetensors',
action='store_true',
help='Whether to store pipeline in safetensors format or not.',
)
parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.')
parser.add_argument('--device', type=str, help='Device to use (e.g. cpu, cuda:0, cuda:1, etc.)')
def UpperCAmelCase ( A : Tuple ):
if string == "True":
return True
elif string == "False":
return False
else:
raise ValueError(F"""could not parse string as bool {string}""" )
parser.add_argument(
'--use_linear_projection', help='Override for use linear projection', required=False, type=parse_bool
)
parser.add_argument('--cross_attention_dim', help='Override for cross attention_dim', required=False, type=int)
lowerCAmelCase_ : int = parser.parse_args()
lowerCAmelCase_ : Any = download_controlnet_from_original_ckpt(
checkpoint_path=args.checkpoint_path,
original_config_file=args.original_config_file,
image_size=args.image_size,
extract_ema=args.extract_ema,
num_in_channels=args.num_in_channels,
upcast_attention=args.upcast_attention,
from_safetensors=args.from_safetensors,
device=args.device,
use_linear_projection=args.use_linear_projection,
cross_attention_dim=args.cross_attention_dim,
)
controlnet.save_pretrained(args.dump_path, safe_serialization=args.to_safetensors)
| 464 |
'''simple docstring'''
from __future__ import annotations
import inspect
import unittest
from typing import List, Tuple
from transformers import RegNetConfig
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 TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class lowerCamelCase_ :
def __init__( self : Optional[Any] , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : int=3 , lowerCAmelCase__ : Tuple=32 , lowerCAmelCase__ : Union[str, Any]=3 , lowerCAmelCase__ : Dict=10 , lowerCAmelCase__ : List[Any]=[10, 20, 30, 40] , lowerCAmelCase__ : List[Any]=[1, 1, 2, 1] , lowerCAmelCase__ : Optional[int]=True , lowerCAmelCase__ : Any=True , lowerCAmelCase__ : List[str]="relu" , lowerCAmelCase__ : int=3 , lowerCAmelCase__ : Tuple=None , ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = parent
SCREAMING_SNAKE_CASE : Optional[int] = batch_size
SCREAMING_SNAKE_CASE : List[Any] = image_size
SCREAMING_SNAKE_CASE : Optional[int] = num_channels
SCREAMING_SNAKE_CASE : str = embeddings_size
SCREAMING_SNAKE_CASE : str = hidden_sizes
SCREAMING_SNAKE_CASE : Tuple = depths
SCREAMING_SNAKE_CASE : Dict = is_training
SCREAMING_SNAKE_CASE : Optional[int] = use_labels
SCREAMING_SNAKE_CASE : Optional[int] = hidden_act
SCREAMING_SNAKE_CASE : str = num_labels
SCREAMING_SNAKE_CASE : List[Any] = scope
SCREAMING_SNAKE_CASE : List[Any] = len(lowerCAmelCase__ )
def __lowercase ( self : str ):
"""simple docstring"""
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.num_labels )
SCREAMING_SNAKE_CASE : Optional[int] = self.get_config()
return config, pixel_values, labels
def __lowercase ( self : Any ):
"""simple docstring"""
return RegNetConfig(
num_channels=self.num_channels , embeddings_size=self.embeddings_size , hidden_sizes=self.hidden_sizes , depths=self.depths , hidden_act=self.hidden_act , num_labels=self.num_labels , )
def __lowercase ( self : Dict , lowerCAmelCase__ : Tuple , lowerCAmelCase__ : Union[str, Any] , lowerCAmelCase__ : Optional[int] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : int = TFRegNetModel(config=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : int = model(lowerCAmelCase__ , training=lowerCAmelCase__ )
# expected last hidden states: B, C, H // 32, W // 32
self.parent.assertEqual(
result.last_hidden_state.shape , (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) , )
def __lowercase ( self : int , lowerCAmelCase__ : str , lowerCAmelCase__ : int , lowerCAmelCase__ : List[str] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = self.num_labels
SCREAMING_SNAKE_CASE : Any = TFRegNetForImageClassification(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Dict = model(lowerCAmelCase__ , labels=lowerCAmelCase__ , training=lowerCAmelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __lowercase ( self : List[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : int = self.prepare_config_and_inputs()
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : List[str] = config_and_inputs
SCREAMING_SNAKE_CASE : Tuple = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_tf
class lowerCamelCase_ ( snake_case_ , snake_case_ , unittest.TestCase ):
_lowerCAmelCase : str = (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
_lowerCAmelCase : str = (
{'feature-extraction': TFRegNetModel, 'image-classification': TFRegNetForImageClassification}
if is_tf_available()
else {}
)
_lowerCAmelCase : Tuple = False
_lowerCAmelCase : List[Any] = False
_lowerCAmelCase : List[str] = False
_lowerCAmelCase : str = False
_lowerCAmelCase : str = False
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Tuple = TFRegNetModelTester(self )
SCREAMING_SNAKE_CASE : Dict = ConfigTester(self , config_class=lowerCAmelCase__ , has_text_modality=lowerCAmelCase__ )
def __lowercase ( self : List[str] ):
"""simple docstring"""
return
@unittest.skip(reason='''RegNet does not use inputs_embeds''' )
def __lowercase ( self : Optional[int] ):
"""simple docstring"""
pass
@unittest.skipIf(
not is_tf_available() or len(tf.config.list_physical_devices('''GPU''' ) ) == 0 , reason='''TF does not support backprop for grouped convolutions on CPU.''' , )
@slow
def __lowercase ( self : int ):
"""simple docstring"""
super().test_keras_fit()
@unittest.skip(reason='''RegNet does not support input and output embeddings''' )
def __lowercase ( self : Dict ):
"""simple docstring"""
pass
def __lowercase ( self : int ):
"""simple docstring"""
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE : int = model_class(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = inspect.signature(model.call )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
SCREAMING_SNAKE_CASE : Tuple = [*signature.parameters.keys()]
SCREAMING_SNAKE_CASE : Optional[Any] = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , lowerCAmelCase__ )
def __lowercase ( self : Any ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCAmelCase__ )
def __lowercase ( self : Dict ):
"""simple docstring"""
def check_hidden_states_output(lowerCAmelCase__ : Any , lowerCAmelCase__ : int , lowerCAmelCase__ : Tuple ):
SCREAMING_SNAKE_CASE : List[Any] = model_class(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Dict = model(**self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ ) , training=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : int = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
SCREAMING_SNAKE_CASE : int = self.model_tester.num_stages
self.assertEqual(len(lowerCAmelCase__ ) , expected_num_stages + 1 )
# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
self.assertListEqual(
list(hidden_states[0].shape[-2:] ) , [self.model_tester.image_size // 2, self.model_tester.image_size // 2] , )
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
SCREAMING_SNAKE_CASE : Union[str, Any] = ['''basic''', '''bottleneck''']
for model_class in self.all_model_classes:
for layer_type in layers_type:
SCREAMING_SNAKE_CASE : Union[str, Any] = layer_type
SCREAMING_SNAKE_CASE : Tuple = 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 : Optional[int] = True
check_hidden_states_output(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
def __lowercase ( self : Union[str, Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE ,SCREAMING_SNAKE_CASE : Union[str, Any] = self.model_tester.prepare_config_and_inputs_for_common()
def check_equivalence(lowerCAmelCase__ : Tuple , lowerCAmelCase__ : int , lowerCAmelCase__ : Dict , lowerCAmelCase__ : str={} ):
SCREAMING_SNAKE_CASE : Union[str, Any] = model(lowerCAmelCase__ , return_dict=lowerCAmelCase__ , **lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Any = model(lowerCAmelCase__ , return_dict=lowerCAmelCase__ , **lowerCAmelCase__ ).to_tuple()
def recursive_check(lowerCAmelCase__ : Dict , lowerCAmelCase__ : str ):
if isinstance(lowerCAmelCase__ , (List, Tuple) ):
for tuple_iterable_value, dict_iterable_value in zip(lowerCAmelCase__ , lowerCAmelCase__ ):
recursive_check(lowerCAmelCase__ , lowerCAmelCase__ )
elif tuple_object is None:
return
else:
self.assertTrue(
all(tf.equal(lowerCAmelCase__ , lowerCAmelCase__ ) ) , msg=(
'''Tuple and dict output are not equal. Difference:'''
F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object ) )}"""
) , )
recursive_check(lowerCAmelCase__ , lowerCAmelCase__ )
for model_class in self.all_model_classes:
SCREAMING_SNAKE_CASE : List[Any] = model_class(lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : int = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Union[str, Any] = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ )
check_equivalence(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Optional[int] = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ , return_labels=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : str = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ , return_labels=lowerCAmelCase__ )
check_equivalence(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Tuple = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : Dict = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ )
check_equivalence(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , {'''output_hidden_states''': True} )
SCREAMING_SNAKE_CASE : Any = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ , return_labels=lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[Any] = self._prepare_for_class(lowerCAmelCase__ , lowerCAmelCase__ , return_labels=lowerCAmelCase__ )
check_equivalence(lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ , {'''output_hidden_states''': True} )
def __lowercase ( self : List[Any] ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : Dict = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__ )
@slow
def __lowercase ( self : Any ):
"""simple docstring"""
for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE : Optional[Any] = TFRegNetModel.from_pretrained(lowerCAmelCase__ )
self.assertIsNotNone(lowerCAmelCase__ )
def UpperCAmelCase ( ):
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 __lowercase ( self : List[str] ):
"""simple docstring"""
return (
AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
if is_vision_available()
else None
)
@slow
def __lowercase ( self : str ):
"""simple docstring"""
SCREAMING_SNAKE_CASE : str = TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )
SCREAMING_SNAKE_CASE : Dict = self.default_image_processor
SCREAMING_SNAKE_CASE : int = prepare_img()
SCREAMING_SNAKE_CASE : List[str] = image_processor(images=lowerCAmelCase__ , return_tensors='''tf''' )
# forward pass
SCREAMING_SNAKE_CASE : Union[str, Any] = model(**lowerCAmelCase__ , training=lowerCAmelCase__ )
# verify the logits
SCREAMING_SNAKE_CASE : List[str] = tf.TensorShape((1, 10_00) )
self.assertEqual(outputs.logits.shape , lowerCAmelCase__ )
SCREAMING_SNAKE_CASE : List[str] = tf.constant([-0.4180, -1.5051, -3.4836] )
tf.debugging.assert_near(outputs.logits[0, :3] , lowerCAmelCase__ , atol=1e-4 )
| 464 | 1 |
def __a ( A__ : int ):
if not isinstance(A__ , A__ ):
raise ValueError("Input must be an integer" )
if input_num <= 0:
raise ValueError("Input must be positive" )
return sum(
divisor for divisor in range(1 , input_num // 2 + 1 ) if input_num % divisor == 0 )
if __name__ == "__main__":
import doctest
doctest.testmod() | 16 |
'''simple docstring'''
import argparse
from pathlib import Path
from typing import Dict, OrderedDict, Tuple
import torch
from audiocraft.models import MusicGen
from transformers import (
AutoFeatureExtractor,
AutoTokenizer,
EncodecModel,
MusicgenDecoderConfig,
MusicgenForConditionalGeneration,
MusicgenProcessor,
TaEncoderModel,
)
from transformers.models.musicgen.modeling_musicgen import MusicgenForCausalLM
from transformers.utils import logging
logging.set_verbosity_info()
lowercase : str = logging.get_logger(__name__)
lowercase : Any = ["model.decoder.embed_positions.weights"]
def SCREAMING_SNAKE_CASE__ ( __A ) -> List[Any]:
if "emb" in name:
_snake_case = name.replace('emb' , 'model.decoder.embed_tokens' )
if "transformer" in name:
_snake_case = name.replace('transformer' , 'model.decoder' )
if "cross_attention" in name:
_snake_case = name.replace('cross_attention' , 'encoder_attn' )
if "linear1" in name:
_snake_case = name.replace('linear1' , 'fc1' )
if "linear2" in name:
_snake_case = name.replace('linear2' , 'fc2' )
if "norm1" in name:
_snake_case = name.replace('norm1' , 'self_attn_layer_norm' )
if "norm_cross" in name:
_snake_case = name.replace('norm_cross' , 'encoder_attn_layer_norm' )
if "norm2" in name:
_snake_case = name.replace('norm2' , 'final_layer_norm' )
if "out_norm" in name:
_snake_case = name.replace('out_norm' , 'model.decoder.layer_norm' )
if "linears" in name:
_snake_case = name.replace('linears' , 'lm_heads' )
if "condition_provider.conditioners.description.output_proj" in name:
_snake_case = name.replace('condition_provider.conditioners.description.output_proj' , 'enc_to_dec_proj' )
return name
def SCREAMING_SNAKE_CASE__ ( __A , __A ) -> Tuple[Dict, Dict]:
_snake_case = list(state_dict.keys() )
_snake_case = {}
for key in keys:
_snake_case = state_dict.pop(__A )
_snake_case = rename_keys(__A )
if "in_proj_weight" in key:
# split fused qkv proj
_snake_case = val[:hidden_size, :]
_snake_case = val[hidden_size : 2 * hidden_size, :]
_snake_case = val[-hidden_size:, :]
elif "enc_to_dec_proj" in key:
_snake_case = val
else:
_snake_case = val
return state_dict, enc_dec_proj_state_dict
def SCREAMING_SNAKE_CASE__ ( __A ) -> MusicgenDecoderConfig:
if checkpoint == "small":
# default config values
_snake_case = 1_024
_snake_case = 24
_snake_case = 16
elif checkpoint == "medium":
_snake_case = 1_536
_snake_case = 48
_snake_case = 24
elif checkpoint == "large":
_snake_case = 2_048
_snake_case = 48
_snake_case = 32
else:
raise ValueError(F'Checkpoint should be one of `[\'small\', \'medium\', \'large\']`, got {checkpoint}.' )
_snake_case = MusicgenDecoderConfig(
hidden_size=__A , ffn_dim=hidden_size * 4 , num_hidden_layers=__A , num_attention_heads=__A , )
return config
@torch.no_grad()
def SCREAMING_SNAKE_CASE__ ( __A , __A=None , __A=None , __A="cpu" ) -> Any:
_snake_case = MusicGen.get_pretrained(__A , device=__A )
_snake_case = decoder_config_from_checkpoint(__A )
_snake_case = fairseq_model.lm.state_dict()
_snake_case , _snake_case = rename_state_dict(
__A , hidden_size=decoder_config.hidden_size )
_snake_case = TaEncoderModel.from_pretrained('t5-base' )
_snake_case = EncodecModel.from_pretrained('facebook/encodec_32khz' )
_snake_case = MusicgenForCausalLM(__A ).eval()
# load all decoder weights - expect that we'll be missing embeddings and enc-dec projection
_snake_case , _snake_case = decoder.load_state_dict(__A , strict=__A )
for key in missing_keys.copy():
if key.startswith(('text_encoder', 'audio_encoder') ) or key in EXPECTED_MISSING_KEYS:
missing_keys.remove(__A )
if len(__A ) > 0:
raise ValueError(F'Missing key(s) in state_dict: {missing_keys}' )
if len(__A ) > 0:
raise ValueError(F'Unexpected key(s) in state_dict: {unexpected_keys}' )
# init the composite model
_snake_case = MusicgenForConditionalGeneration(text_encoder=__A , audio_encoder=__A , decoder=__A )
# load the pre-trained enc-dec projection (from the decoder state dict)
model.enc_to_dec_proj.load_state_dict(__A )
# check we can do a forward pass
_snake_case = torch.arange(0 , 8 , dtype=torch.long ).reshape(2 , -1 )
_snake_case = input_ids.reshape(2 * 4 , -1 )
with torch.no_grad():
_snake_case = model(input_ids=__A , decoder_input_ids=__A ).logits
if logits.shape != (8, 1, 2_048):
raise ValueError('Incorrect shape for logits' )
# now construct the processor
_snake_case = AutoTokenizer.from_pretrained('t5-base' )
_snake_case = AutoFeatureExtractor.from_pretrained('facebook/encodec_32khz' , padding_side='left' )
_snake_case = MusicgenProcessor(feature_extractor=__A , tokenizer=__A )
# set the appropriate bos/pad token ids
_snake_case = 2_048
_snake_case = 2_048
# set other default generation config params
_snake_case = int(30 * audio_encoder.config.frame_rate )
_snake_case = True
_snake_case = 3.0
if pytorch_dump_folder is not None:
Path(__A ).mkdir(exist_ok=__A )
logger.info(F'Saving model {checkpoint} to {pytorch_dump_folder}' )
model.save_pretrained(__A )
processor.save_pretrained(__A )
if repo_id:
logger.info(F'Pushing model {checkpoint} to {repo_id}' )
model.push_to_hub(__A )
processor.push_to_hub(__A )
if __name__ == "__main__":
lowercase : List[str] = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--checkpoint",
default="small",
type=str,
help="Checkpoint size of the MusicGen model you'd like to convert. Can be one of: `['small', 'medium', 'large']`.",
)
parser.add_argument(
"--pytorch_dump_folder",
required=True,
default=None,
type=str,
help="Path to the output PyTorch model directory.",
)
parser.add_argument(
"--push_to_hub", default=None, type=str, help="Where to upload the converted model on the 🤗 hub."
)
parser.add_argument(
"--device", default="cpu", type=str, help="Torch device to run the conversion, either cpu or cuda."
)
lowercase : List[Any] = parser.parse_args()
convert_musicgen_checkpoint(args.checkpoint, args.pytorch_dump_folder, args.push_to_hub)
| 495 | 0 |
from __future__ import annotations
def _a ( UpperCamelCase_ : list[float] , UpperCamelCase_ : str ) -> Dict:
"""simple docstring"""
print(F"Vertex\tShortest Distance from vertex {src}" )
for i, d in enumerate(UpperCamelCase_ ):
print(F"{i}\t\t{d}" )
def _a ( UpperCamelCase_ : list[dict[str, int]] , UpperCamelCase_ : list[float] , UpperCamelCase_ : int ) -> List[str]:
"""simple docstring"""
for j in range(UpperCamelCase_ ):
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = (graph[j][k] for k in ["src", "dst", "weight"])
if distance[u] != float("inf" ) and distance[u] + w < distance[v]:
return True
return False
def _a ( UpperCamelCase_ : list[dict[str, int]] , UpperCamelCase_ : int , UpperCamelCase_ : int , UpperCamelCase_ : int ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase__ = [float("inf" )] * vertex_count
lowerCAmelCase__ = 0.0
for _ in range(vertex_count - 1 ):
for j in range(UpperCamelCase_ ):
lowerCAmelCase__ , lowerCAmelCase__ , lowerCAmelCase__ = (graph[j][k] for k in ["src", "dst", "weight"])
if distance[u] != float("inf" ) and distance[u] + w < distance[v]:
lowerCAmelCase__ = distance[u] + w
lowerCAmelCase__ = check_negative_cycle(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ )
if negative_cycle_exists:
raise Exception("Negative cycle found" )
return distance
if __name__ == "__main__":
import doctest
doctest.testmod()
a_ = int(input('''Enter number of vertices: ''').strip())
a_ = int(input('''Enter number of edges: ''').strip())
a_ = [{} for _ in range(E)]
for i in range(E):
print('''Edge ''', i + 1)
a_, a_, a_ = (
int(x)
for x in input('''Enter source, destination, weight: ''').strip().split(''' ''')
)
a_ = {'''src''': src, '''dst''': dest, '''weight''': weight}
a_ = int(input('''\nEnter shortest path source:''').strip())
a_ = bellman_ford(graph, V, E, source)
print_distance(shortest_distance, 0)
| 702 |
import math
from collections import defaultdict
from typing import List, Optional, Tuple, Union
import numpy as np
import torch
from ..configuration_utils import ConfigMixin, register_to_config
from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput
def _a ( UpperCamelCase_ : Union[str, Any] , UpperCamelCase_ : Tuple=0.999 , UpperCamelCase_ : Union[str, Any]="cosine" , ) -> str:
"""simple docstring"""
if alpha_transform_type == "cosine":
def alpha_bar_fn(UpperCamelCase_ : List[Any] ):
return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2
elif alpha_transform_type == "exp":
def alpha_bar_fn(UpperCamelCase_ : int ):
return math.exp(t * -12.0 )
else:
raise ValueError(F"Unsupported alpha_tranform_type: {alpha_transform_type}" )
lowerCAmelCase__ = []
for i in range(UpperCamelCase_ ):
lowerCAmelCase__ = i / num_diffusion_timesteps
lowerCAmelCase__ = (i + 1) / num_diffusion_timesteps
betas.append(min(1 - alpha_bar_fn(UpperCamelCase_ ) / alpha_bar_fn(UpperCamelCase_ ) , UpperCamelCase_ ) )
return torch.tensor(UpperCamelCase_ , dtype=torch.floataa )
class lowercase__ ( _UpperCAmelCase, _UpperCAmelCase ):
a_ =[e.name for e in KarrasDiffusionSchedulers]
a_ =2
@register_to_config
def __init__( self , __UpperCAmelCase = 1000 , __UpperCAmelCase = 0.00_085 , __UpperCAmelCase = 0.012 , __UpperCAmelCase = "linear" , __UpperCAmelCase = None , __UpperCAmelCase = "epsilon" , __UpperCAmelCase = "linspace" , __UpperCAmelCase = 0 , )-> int:
'''simple docstring'''
if trained_betas is not None:
lowerCAmelCase__ = torch.tensor(__UpperCAmelCase , dtype=torch.floataa )
elif beta_schedule == "linear":
lowerCAmelCase__ = torch.linspace(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , dtype=torch.floataa )
elif beta_schedule == "scaled_linear":
# this schedule is very specific to the latent diffusion model.
lowerCAmelCase__ = (
torch.linspace(beta_start**0.5 , beta_end**0.5 , __UpperCAmelCase , dtype=torch.floataa ) ** 2
)
elif beta_schedule == "squaredcos_cap_v2":
# Glide cosine schedule
lowerCAmelCase__ = betas_for_alpha_bar(__UpperCAmelCase )
else:
raise NotImplementedError(F"{beta_schedule} does is not implemented for {self.__class__}" )
lowerCAmelCase__ = 1.0 - self.betas
lowerCAmelCase__ = torch.cumprod(self.alphas , dim=0 )
# set all values
self.set_timesteps(__UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase )
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase=None )-> str:
'''simple docstring'''
if schedule_timesteps is None:
lowerCAmelCase__ = self.timesteps
lowerCAmelCase__ = (schedule_timesteps == timestep).nonzero()
# The sigma index that is taken for the **very** first `step`
# is always the second index (or the last index if there is only 1)
# This way we can ensure we don't accidentally skip a sigma in
# case we start in the middle of the denoising schedule (e.g. for image-to-image)
if len(self._index_counter ) == 0:
lowerCAmelCase__ = 1 if len(__UpperCAmelCase ) > 1 else 0
else:
lowerCAmelCase__ = timestep.cpu().item() if torch.is_tensor(__UpperCAmelCase ) else timestep
lowerCAmelCase__ = self._index_counter[timestep_int]
return indices[pos].item()
@property
def UpperCAmelCase ( self )-> List[str]:
'''simple docstring'''
if self.config.timestep_spacing in ["linspace", "trailing"]:
return self.sigmas.max()
return (self.sigmas.max() ** 2 + 1) ** 0.5
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , )-> torch.FloatTensor:
'''simple docstring'''
lowerCAmelCase__ = self.index_for_timestep(__UpperCAmelCase )
if self.state_in_first_order:
lowerCAmelCase__ = self.sigmas[step_index]
else:
lowerCAmelCase__ = self.sigmas_interpol[step_index]
lowerCAmelCase__ = sample / ((sigma**2 + 1) ** 0.5)
return sample
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase = None , __UpperCAmelCase = None , )-> Optional[int]:
'''simple docstring'''
lowerCAmelCase__ = num_inference_steps
lowerCAmelCase__ = num_train_timesteps or self.config.num_train_timesteps
# "linspace", "leading", "trailing" corresponds to annotation of Table 2. of https://arxiv.org/abs/2305.08891
if self.config.timestep_spacing == "linspace":
lowerCAmelCase__ = np.linspace(0 , num_train_timesteps - 1 , __UpperCAmelCase , dtype=__UpperCAmelCase )[::-1].copy()
elif self.config.timestep_spacing == "leading":
lowerCAmelCase__ = num_train_timesteps // self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
lowerCAmelCase__ = (np.arange(0 , __UpperCAmelCase ) * step_ratio).round()[::-1].copy().astype(__UpperCAmelCase )
timesteps += self.config.steps_offset
elif self.config.timestep_spacing == "trailing":
lowerCAmelCase__ = num_train_timesteps / self.num_inference_steps
# creates integer timesteps by multiplying by ratio
# casting to int to avoid issues when num_inference_step is power of 3
lowerCAmelCase__ = (np.arange(__UpperCAmelCase , 0 , -step_ratio )).round().copy().astype(__UpperCAmelCase )
timesteps -= 1
else:
raise ValueError(
F"{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'." )
lowerCAmelCase__ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 )
lowerCAmelCase__ = torch.from_numpy(np.log(__UpperCAmelCase ) ).to(__UpperCAmelCase )
lowerCAmelCase__ = np.interp(__UpperCAmelCase , np.arange(0 , len(__UpperCAmelCase ) ) , __UpperCAmelCase )
lowerCAmelCase__ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa )
lowerCAmelCase__ = torch.from_numpy(__UpperCAmelCase ).to(device=__UpperCAmelCase )
# interpolate sigmas
lowerCAmelCase__ = sigmas.log().lerp(sigmas.roll(1 ).log() , 0.5 ).exp()
lowerCAmelCase__ = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] )
lowerCAmelCase__ = torch.cat(
[sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] )
if str(__UpperCAmelCase ).startswith("mps" ):
# mps does not support float64
lowerCAmelCase__ = torch.from_numpy(__UpperCAmelCase ).to(__UpperCAmelCase , dtype=torch.floataa )
else:
lowerCAmelCase__ = torch.from_numpy(__UpperCAmelCase ).to(__UpperCAmelCase )
# interpolate timesteps
lowerCAmelCase__ = self.sigma_to_t(__UpperCAmelCase ).to(__UpperCAmelCase , dtype=timesteps.dtype )
lowerCAmelCase__ = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) , dim=-1 ).flatten()
lowerCAmelCase__ = torch.cat([timesteps[:1], interleaved_timesteps] )
lowerCAmelCase__ = None
# for exp beta schedules, such as the one for `pipeline_shap_e.py`
# we need an index counter
lowerCAmelCase__ = defaultdict(__UpperCAmelCase )
def UpperCAmelCase ( self , __UpperCAmelCase )-> Tuple:
'''simple docstring'''
lowerCAmelCase__ = sigma.log()
# get distribution
lowerCAmelCase__ = log_sigma - self.log_sigmas[:, None]
# get sigmas range
lowerCAmelCase__ = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 )
lowerCAmelCase__ = low_idx + 1
lowerCAmelCase__ = self.log_sigmas[low_idx]
lowerCAmelCase__ = self.log_sigmas[high_idx]
# interpolate sigmas
lowerCAmelCase__ = (low - log_sigma) / (low - high)
lowerCAmelCase__ = w.clamp(0 , 1 )
# transform interpolation to time range
lowerCAmelCase__ = (1 - w) * low_idx + w * high_idx
lowerCAmelCase__ = t.view(sigma.shape )
return t
@property
def UpperCAmelCase ( self )-> List[str]:
'''simple docstring'''
return self.sample is None
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase = True , )-> Union[SchedulerOutput, Tuple]:
'''simple docstring'''
lowerCAmelCase__ = self.index_for_timestep(__UpperCAmelCase )
# advance index counter by 1
lowerCAmelCase__ = timestep.cpu().item() if torch.is_tensor(__UpperCAmelCase ) else timestep
self._index_counter[timestep_int] += 1
if self.state_in_first_order:
lowerCAmelCase__ = self.sigmas[step_index]
lowerCAmelCase__ = self.sigmas_interpol[step_index + 1]
lowerCAmelCase__ = self.sigmas[step_index + 1]
else:
# 2nd order / KDPM2's method
lowerCAmelCase__ = self.sigmas[step_index - 1]
lowerCAmelCase__ = self.sigmas_interpol[step_index]
lowerCAmelCase__ = self.sigmas[step_index]
# currently only gamma=0 is supported. This usually works best anyways.
# We can support gamma in the future but then need to scale the timestep before
# passing it to the model which requires a change in API
lowerCAmelCase__ = 0
lowerCAmelCase__ = sigma * (gamma + 1) # Note: sigma_hat == sigma for now
# 1. compute predicted original sample (x_0) from sigma-scaled predicted noise
if self.config.prediction_type == "epsilon":
lowerCAmelCase__ = sigma_hat if self.state_in_first_order else sigma_interpol
lowerCAmelCase__ = sample - sigma_input * model_output
elif self.config.prediction_type == "v_prediction":
lowerCAmelCase__ = sigma_hat if self.state_in_first_order else sigma_interpol
lowerCAmelCase__ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + (
sample / (sigma_input**2 + 1)
)
elif self.config.prediction_type == "sample":
raise NotImplementedError("prediction_type not implemented yet: sample" )
else:
raise ValueError(
F"prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`" )
if self.state_in_first_order:
# 2. Convert to an ODE derivative for 1st order
lowerCAmelCase__ = (sample - pred_original_sample) / sigma_hat
# 3. delta timestep
lowerCAmelCase__ = sigma_interpol - sigma_hat
# store for 2nd order step
lowerCAmelCase__ = sample
else:
# DPM-Solver-2
# 2. Convert to an ODE derivative for 2nd order
lowerCAmelCase__ = (sample - pred_original_sample) / sigma_interpol
# 3. delta timestep
lowerCAmelCase__ = sigma_next - sigma_hat
lowerCAmelCase__ = self.sample
lowerCAmelCase__ = None
lowerCAmelCase__ = sample + derivative * dt
if not return_dict:
return (prev_sample,)
return SchedulerOutput(prev_sample=__UpperCAmelCase )
def UpperCAmelCase ( self , __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase , )-> torch.FloatTensor:
'''simple docstring'''
lowerCAmelCase__ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype )
if original_samples.device.type == "mps" and torch.is_floating_point(__UpperCAmelCase ):
# mps does not support float64
lowerCAmelCase__ = self.timesteps.to(original_samples.device , dtype=torch.floataa )
lowerCAmelCase__ = timesteps.to(original_samples.device , dtype=torch.floataa )
else:
lowerCAmelCase__ = self.timesteps.to(original_samples.device )
lowerCAmelCase__ = timesteps.to(original_samples.device )
lowerCAmelCase__ = [self.index_for_timestep(__UpperCAmelCase , __UpperCAmelCase ) for t in timesteps]
lowerCAmelCase__ = sigmas[step_indices].flatten()
while len(sigma.shape ) < len(original_samples.shape ):
lowerCAmelCase__ = sigma.unsqueeze(-1 )
lowerCAmelCase__ = original_samples + noise * sigma
return noisy_samples
def __len__( self )-> List[Any]:
'''simple docstring'''
return self.config.num_train_timesteps
| 115 | 0 |
import logging
import os
from dataclasses import dataclass
from typing import List, Optional, Union
import tqdm
from filelock import FileLock
from transformers import (
BartTokenizer,
BartTokenizerFast,
DataProcessor,
PreTrainedTokenizer,
RobertaTokenizer,
RobertaTokenizerFast,
XLMRobertaTokenizer,
is_tf_available,
is_torch_available,
)
__a : Union[str, Any] = logging.getLogger(__name__)
@dataclass(frozen=snake_case__ )
class __UpperCAmelCase :
"""simple docstring"""
lowercase = 42
lowercase = 42
lowercase = None
lowercase = None
lowercase = None
@dataclass(frozen=snake_case__ )
class __UpperCAmelCase :
"""simple docstring"""
lowercase = 42
lowercase = None
lowercase = None
lowercase = None
lowercase = None
if is_torch_available():
import torch
from torch.utils.data import Dataset
class __UpperCAmelCase ( snake_case__ ):
"""simple docstring"""
lowercase = 42
def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = None , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE = False , ) -> str:
"""simple docstring"""
UpperCamelCase = hans_processors[task]()
UpperCamelCase = os.path.join(
SCREAMING_SNAKE_CASE , "cached_{}_{}_{}_{}".format(
"dev" if evaluate else "train" , tokenizer.__class__.__name__ , str(SCREAMING_SNAKE_CASE ) , SCREAMING_SNAKE_CASE , ) , )
UpperCamelCase = processor.get_labels()
if tokenizer.__class__ in (
RobertaTokenizer,
RobertaTokenizerFast,
XLMRobertaTokenizer,
BartTokenizer,
BartTokenizerFast,
):
# HACK(label indices are swapped in RoBERTa pretrained model)
UpperCamelCase , UpperCamelCase = label_list[2], label_list[1]
UpperCamelCase = label_list
# Make sure only the first process in distributed training processes the dataset,
# and the others will use the cache.
UpperCamelCase = cached_features_file + ".lock"
with FileLock(SCREAMING_SNAKE_CASE ):
if os.path.exists(SCREAMING_SNAKE_CASE ) and not overwrite_cache:
logger.info(f'''Loading features from cached file {cached_features_file}''' )
UpperCamelCase = torch.load(SCREAMING_SNAKE_CASE )
else:
logger.info(f'''Creating features from dataset file at {data_dir}''' )
UpperCamelCase = (
processor.get_dev_examples(SCREAMING_SNAKE_CASE ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE )
)
logger.info("Training examples: %s" , len(SCREAMING_SNAKE_CASE ) )
UpperCamelCase = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
logger.info("Saving features into cached file %s" , SCREAMING_SNAKE_CASE )
torch.save(self.features , SCREAMING_SNAKE_CASE )
def __len__( self ) -> List[str]:
"""simple docstring"""
return len(self.features )
def __getitem__( self , SCREAMING_SNAKE_CASE ) -> InputFeatures:
"""simple docstring"""
return self.features[i]
def __lowerCAmelCase ( self ) -> Optional[Any]:
"""simple docstring"""
return self.label_list
if is_tf_available():
import tensorflow as tf
class __UpperCAmelCase :
"""simple docstring"""
lowercase = 42
def __init__( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE = 128 , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE = False , ) -> Union[str, Any]:
"""simple docstring"""
UpperCamelCase = hans_processors[task]()
UpperCamelCase = processor.get_labels()
if tokenizer.__class__ in (
RobertaTokenizer,
RobertaTokenizerFast,
XLMRobertaTokenizer,
BartTokenizer,
BartTokenizerFast,
):
# HACK(label indices are swapped in RoBERTa pretrained model)
UpperCamelCase , UpperCamelCase = label_list[2], label_list[1]
UpperCamelCase = label_list
UpperCamelCase = processor.get_dev_examples(SCREAMING_SNAKE_CASE ) if evaluate else processor.get_train_examples(SCREAMING_SNAKE_CASE )
UpperCamelCase = hans_convert_examples_to_features(SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE )
def gen():
for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc="convert examples to features" ):
if ex_index % 10000 == 0:
logger.info("Writing example %d of %d" % (ex_index, len(SCREAMING_SNAKE_CASE )) )
yield (
{
"example_id": 0,
"input_ids": ex.input_ids,
"attention_mask": ex.attention_mask,
"token_type_ids": ex.token_type_ids,
},
ex.label,
)
UpperCamelCase = tf.data.Dataset.from_generator(
SCREAMING_SNAKE_CASE , (
{
"example_id": tf.intaa,
"input_ids": tf.intaa,
"attention_mask": tf.intaa,
"token_type_ids": tf.intaa,
},
tf.intaa,
) , (
{
"example_id": tf.TensorShape([] ),
"input_ids": tf.TensorShape([None, None] ),
"attention_mask": tf.TensorShape([None, None] ),
"token_type_ids": tf.TensorShape([None, None] ),
},
tf.TensorShape([] ),
) , )
def __lowerCAmelCase ( self ) -> Dict:
"""simple docstring"""
return self.dataset
def __len__( self ) -> int:
"""simple docstring"""
return len(self.features )
def __getitem__( self , SCREAMING_SNAKE_CASE ) -> InputFeatures:
"""simple docstring"""
return self.features[i]
def __lowerCAmelCase ( self ) -> int:
"""simple docstring"""
return self.label_list
class __UpperCAmelCase ( snake_case__ ):
"""simple docstring"""
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE , "heuristics_train_set.txt" ) ) , "train" )
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE ) -> List[str]:
"""simple docstring"""
return self._create_examples(self._read_tsv(os.path.join(SCREAMING_SNAKE_CASE , "heuristics_evaluation_set.txt" ) ) , "dev" )
def __lowerCAmelCase ( self ) -> Dict:
"""simple docstring"""
return ["contradiction", "entailment", "neutral"]
def __lowerCAmelCase ( self , SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ) -> Optional[Any]:
"""simple docstring"""
UpperCamelCase = []
for i, line in enumerate(SCREAMING_SNAKE_CASE ):
if i == 0:
continue
UpperCamelCase = "%s-%s" % (set_type, line[0])
UpperCamelCase = line[5]
UpperCamelCase = line[6]
UpperCamelCase = line[7][2:] if line[7].startswith("ex" ) else line[7]
UpperCamelCase = line[0]
examples.append(InputExample(guid=SCREAMING_SNAKE_CASE , text_a=SCREAMING_SNAKE_CASE , text_b=SCREAMING_SNAKE_CASE , label=SCREAMING_SNAKE_CASE , pairID=SCREAMING_SNAKE_CASE ) )
return examples
def __magic_name__ ( lowercase_ , lowercase_ , lowercase_ , lowercase_ , ) -> Dict:
'''simple docstring'''
UpperCamelCase = {label: i for i, label in enumerate(lowercase_ )}
UpperCamelCase = []
for ex_index, example in tqdm.tqdm(enumerate(lowercase_ ) , desc="convert examples to features" ):
if ex_index % 10000 == 0:
logger.info("Writing example %d" % (ex_index) )
UpperCamelCase = tokenizer(
example.text_a , example.text_b , add_special_tokens=lowercase_ , max_length=lowercase_ , padding="max_length" , truncation=lowercase_ , return_overflowing_tokens=lowercase_ , )
UpperCamelCase = label_map[example.label] if example.label in label_map else 0
UpperCamelCase = int(example.pairID )
features.append(InputFeatures(**lowercase_ , label=lowercase_ , pairID=lowercase_ ) )
for i, example in enumerate(examples[:5] ):
logger.info("*** Example ***" )
logger.info(f'''guid: {example}''' )
logger.info(f'''features: {features[i]}''' )
return features
__a : int = {
"""hans""": 3,
}
__a : Union[str, Any] = {
"""hans""": HansProcessor,
}
| 606 |
__a : Union[str, Any] = 6_5_5_2_1
def __magic_name__ ( lowercase_ ) -> int:
'''simple docstring'''
UpperCamelCase = 1
UpperCamelCase = 0
for plain_chr in plain_text:
UpperCamelCase = (a + ord(lowercase_ )) % MOD_ADLER
UpperCamelCase = (b + a) % MOD_ADLER
return (b << 16) | a
| 606 | 1 |
from argparse import ArgumentParser
from ..pipelines import Pipeline, PipelineDataFormat, get_supported_tasks, pipeline
from ..utils import logging
from . import BaseTransformersCLICommand
__lowercase : List[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name
def lowercase ( __A : str ) -> Any:
'''simple docstring'''
if not path:
return "pipe"
for ext in PipelineDataFormat.SUPPORTED_FORMATS:
if path.endswith(__A ):
return ext
raise Exception(
f"""Unable to determine file format from file extension {path}. """
f"""Please provide the format through --format {PipelineDataFormat.SUPPORTED_FORMATS}""" )
def lowercase ( __A : str ) -> List[str]:
'''simple docstring'''
snake_case : Optional[int] = pipeline(
task=args.task , model=args.model if args.model else None , config=args.config , tokenizer=args.tokenizer , device=args.device , )
snake_case : Dict = try_infer_format_from_ext(args.input ) if args.format == """infer""" else args.format
snake_case : List[Any] = PipelineDataFormat.from_str(
format=__A , output_path=args.output , input_path=args.input , column=args.column if args.column else nlp.default_input_names , overwrite=args.overwrite , )
return RunCommand(__A , __A )
class _A ( snake_case ):
'''simple docstring'''
def __init__( self ,SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ):
'''simple docstring'''
snake_case : Dict = nlp
snake_case : List[Any] = reader
@staticmethod
def snake_case_ ( SCREAMING_SNAKE_CASE_ ):
'''simple docstring'''
snake_case : Any = parser.add_parser("""run""" ,help="""Run a pipeline through the CLI""" )
run_parser.add_argument("""--task""" ,choices=get_supported_tasks() ,help="""Task to run""" )
run_parser.add_argument("""--input""" ,type=SCREAMING_SNAKE_CASE_ ,help="""Path to the file to use for inference""" )
run_parser.add_argument("""--output""" ,type=SCREAMING_SNAKE_CASE_ ,help="""Path to the file that will be used post to write results.""" )
run_parser.add_argument("""--model""" ,type=SCREAMING_SNAKE_CASE_ ,help="""Name or path to the model to instantiate.""" )
run_parser.add_argument("""--config""" ,type=SCREAMING_SNAKE_CASE_ ,help="""Name or path to the model's config to instantiate.""" )
run_parser.add_argument(
"""--tokenizer""" ,type=SCREAMING_SNAKE_CASE_ ,help="""Name of the tokenizer to use. (default: same as the model name)""" )
run_parser.add_argument(
"""--column""" ,type=SCREAMING_SNAKE_CASE_ ,help="""Name of the column to use as input. (For multi columns input as QA use column1,columns2)""" ,)
run_parser.add_argument(
"""--format""" ,type=SCREAMING_SNAKE_CASE_ ,default="""infer""" ,choices=PipelineDataFormat.SUPPORTED_FORMATS ,help="""Input format to read from""" ,)
run_parser.add_argument(
"""--device""" ,type=SCREAMING_SNAKE_CASE_ ,default=-1 ,help="""Indicate the device to run onto, -1 indicates CPU, >= 0 indicates GPU (default: -1)""" ,)
run_parser.add_argument("""--overwrite""" ,action="""store_true""" ,help="""Allow overwriting the output file.""" )
run_parser.set_defaults(func=SCREAMING_SNAKE_CASE_ )
def snake_case_ ( self ):
'''simple docstring'''
snake_case , snake_case : List[str] = self._nlp, []
for entry in self._reader:
snake_case : List[Any] = nlp(**SCREAMING_SNAKE_CASE_ ) if self._reader.is_multi_columns else nlp(SCREAMING_SNAKE_CASE_ )
if isinstance(SCREAMING_SNAKE_CASE_ ,SCREAMING_SNAKE_CASE_ ):
outputs.append(SCREAMING_SNAKE_CASE_ )
else:
outputs += output
# Saving data
if self._nlp.binary_output:
snake_case : Tuple = self._reader.save_binary(SCREAMING_SNAKE_CASE_ )
logger.warning(F"""Current pipeline requires output to be in binary format, saving at {binary_path}""" )
else:
self._reader.save(SCREAMING_SNAKE_CASE_ )
| 315 |
import argparse
from pathlib import Path
from transformers import AutoConfig, AutoTokenizer, RagConfig, RagSequenceForGeneration, RagTokenForGeneration
def lowercase ( __A : List[str] , __A : str , __A : str , __A : Path , __A : str = None , __A : str = None , __A : str = None , ) -> int:
'''simple docstring'''
if config_name_or_path is None:
snake_case : Tuple = """facebook/rag-token-base""" if model_type == """rag_token""" else """facebook/rag-sequence-base"""
if generator_tokenizer_name_or_path is None:
snake_case : str = generator_name_or_path
if question_encoder_tokenizer_name_or_path is None:
snake_case : List[Any] = question_encoder_name_or_path
snake_case : Optional[Any] = RagTokenForGeneration if model_type == """rag_token""" else RagSequenceForGeneration
# Save model.
snake_case : Optional[Any] = RagConfig.from_pretrained(__A )
snake_case : Optional[Any] = AutoConfig.from_pretrained(__A )
snake_case : Tuple = AutoConfig.from_pretrained(__A )
snake_case : Tuple = gen_config
snake_case : Optional[Any] = question_encoder_config
snake_case : Tuple = model_class.from_pretrained_question_encoder_generator(
__A , __A , config=__A )
rag_model.save_pretrained(__A )
# Sanity check.
model_class.from_pretrained(__A )
# Save tokenizers.
snake_case : Union[str, Any] = AutoTokenizer.from_pretrained(__A )
gen_tokenizer.save_pretrained(dest_dir / """generator_tokenizer/""" )
snake_case : List[Any] = AutoTokenizer.from_pretrained(__A )
question_encoder_tokenizer.save_pretrained(dest_dir / """question_encoder_tokenizer/""" )
if __name__ == "__main__":
__lowercase : Any = argparse.ArgumentParser()
parser.add_argument(
'''--model_type''',
choices=['''rag_sequence''', '''rag_token'''],
required=True,
type=str,
help='''RAG model type: rag_sequence, rag_token''',
)
parser.add_argument('''--dest''', type=str, required=True, help='''Path to the output checkpoint directory.''')
parser.add_argument('''--generator_name_or_path''', type=str, required=True, help='''Generator model identifier''')
parser.add_argument(
'''--question_encoder_name_or_path''', type=str, required=True, help='''Question encoder model identifier'''
)
parser.add_argument(
'''--generator_tokenizer_name_or_path''',
type=str,
help='''Generator tokenizer identifier, if not specified, resolves to ``generator_name_or_path``''',
)
parser.add_argument(
'''--question_encoder_tokenizer_name_or_path''',
type=str,
help='''Question encoder tokenizer identifier, if not specified, resolves to ``question_encoder_name_or_path``''',
)
parser.add_argument(
'''--config_name_or_path''',
type=str,
help=(
'''Identifier of the model config to use, if not provided, resolves to a base config for a given'''
''' ``model_type``'''
),
)
__lowercase : Optional[Any] = parser.parse_args()
__lowercase : Dict = Path(args.dest)
dest_dir.mkdir(exist_ok=True)
consolidate(
args.model_type,
args.generator_name_or_path,
args.question_encoder_name_or_path,
dest_dir,
args.config_name_or_path,
args.generator_tokenizer_name_or_path,
args.question_encoder_tokenizer_name_or_path,
)
| 315 | 1 |
import json
import os
import unittest
from transformers.models.biogpt.tokenization_biogpt import VOCAB_FILES_NAMES, BioGptTokenizer
from transformers.testing_utils import slow
from ...test_tokenization_common import TokenizerTesterMixin
class a__ ( A__ , unittest.TestCase ):
A = BioGptTokenizer
A = False
def __UpperCamelCase ( self : Optional[Any] ):
"""simple docstring"""
super().setUp()
# Adapted from Sennrich et al. 2015 and https://github.com/rsennrich/subword-nmt
SCREAMING_SNAKE_CASE_ : Dict = [
"l",
"o",
"w",
"e",
"r",
"s",
"t",
"i",
"d",
"n",
"w</w>",
"r</w>",
"t</w>",
"lo",
"low",
"er</w>",
"low</w>",
"lowest</w>",
"newer</w>",
"wider</w>",
"<unk>",
]
SCREAMING_SNAKE_CASE_ : Union[str, Any] = dict(zip(_A,range(len(_A ) ) ) )
SCREAMING_SNAKE_CASE_ : int = ["l o 123", "lo w 1456", "e r</w> 1789", ""]
SCREAMING_SNAKE_CASE_ : Union[str, Any] = os.path.join(self.tmpdirname,VOCAB_FILES_NAMES["vocab_file"] )
SCREAMING_SNAKE_CASE_ : Tuple = os.path.join(self.tmpdirname,VOCAB_FILES_NAMES["merges_file"] )
with open(self.vocab_file,"w" ) as fp:
fp.write(json.dumps(_A ) )
with open(self.merges_file,"w" ) as fp:
fp.write("\n".join(_A ) )
def __UpperCamelCase ( self : Dict,_A : Dict ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict = "lower newer"
SCREAMING_SNAKE_CASE_ : Optional[Any] = "lower newer"
return input_text, output_text
def __UpperCamelCase ( self : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Any = BioGptTokenizer(self.vocab_file,self.merges_file )
SCREAMING_SNAKE_CASE_ : int = "lower"
SCREAMING_SNAKE_CASE_ : Union[str, Any] = ["low", "er</w>"]
SCREAMING_SNAKE_CASE_ : Tuple = tokenizer.tokenize(_A )
self.assertListEqual(_A,_A )
SCREAMING_SNAKE_CASE_ : Any = tokens + ["<unk>"]
SCREAMING_SNAKE_CASE_ : Optional[int] = [14, 15, 20]
self.assertListEqual(tokenizer.convert_tokens_to_ids(_A ),_A )
@slow
def __UpperCamelCase ( self : Tuple ):
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : List[Any] = BioGptTokenizer.from_pretrained("microsoft/biogpt" )
SCREAMING_SNAKE_CASE_ : List[Any] = tokenizer.encode("sequence builders",add_special_tokens=_A )
SCREAMING_SNAKE_CASE_ : Optional[Any] = tokenizer.encode("multi-sequence build",add_special_tokens=_A )
SCREAMING_SNAKE_CASE_ : int = tokenizer.build_inputs_with_special_tokens(_A )
SCREAMING_SNAKE_CASE_ : List[str] = tokenizer.build_inputs_with_special_tokens(_A,_A )
self.assertTrue(encoded_sentence == [2] + text )
self.assertTrue(encoded_pair == [2] + text + [2] + text_a )
| 216 | from scipy.stats import pearsonr
import datasets
__lowerCamelCase : Union[str, Any] = '''
Pearson correlation coefficient and p-value for testing non-correlation.
The Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.
The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.
'''
__lowerCamelCase : Optional[int] = '''
Args:
predictions (`list` of `int`): Predicted class labels, as returned by a model.
references (`list` of `int`): Ground truth labels.
return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.
Returns:
pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.
p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.
Examples:
Example 1-A simple example using only predictions and references.
>>> pearsonr_metric = datasets.load_metric("pearsonr")
>>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])
>>> print(round(results[\'pearsonr\'], 2))
-0.74
Example 2-The same as Example 1, but that also returns the `p-value`.
>>> pearsonr_metric = datasets.load_metric("pearsonr")
>>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)
>>> print(sorted(list(results.keys())))
[\'p-value\', \'pearsonr\']
>>> print(round(results[\'pearsonr\'], 2))
-0.74
>>> print(round(results[\'p-value\'], 2))
0.15
'''
__lowerCamelCase : Tuple = '''
@article{2020SciPy-NMeth,
author = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and
Haberland, Matt and Reddy, Tyler and Cournapeau, David and
Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and
Bright, Jonathan and {van der Walt}, St{\'e}fan J. and
Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and
Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and
Kern, Robert and Larson, Eric and Carey, C J and
Polat, Ilhan and Feng, Yu and Moore, Eric W. and
{VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and
Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and
Harris, Charles R. and Archibald, Anne M. and
Ribeiro, Antonio H. and Pedregosa, Fabian and
{van Mulbregt}, Paul and {SciPy 1.0 Contributors}},
title = {{{SciPy} 1.0: Fundamental Algorithms for Scientific
Computing in Python}},
journal = {Nature Methods},
year = {2020},
volume = {17},
pages = {261--272},
adsurl = {https://rdcu.be/b08Wh},
doi = {10.1038/s41592-019-0686-2},
}
'''
@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION )
class a__ ( datasets.Metric ):
def __UpperCamelCase ( self : int ):
"""simple docstring"""
return datasets.MetricInfo(
description=_DESCRIPTION,citation=_CITATION,inputs_description=_KWARGS_DESCRIPTION,features=datasets.Features(
{
"predictions": datasets.Value("float" ),
"references": datasets.Value("float" ),
} ),reference_urls=["https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html"],)
def __UpperCamelCase ( self : int,_A : List[str],_A : Optional[int],_A : int=False ):
"""simple docstring"""
if return_pvalue:
SCREAMING_SNAKE_CASE_ : Any = pearsonr(_A,_A )
return {"pearsonr": results[0], "p-value": results[1]}
else:
return {"pearsonr": float(pearsonr(_A,_A )[0] )}
| 216 | 1 |
from typing import Optional, Tuple, Union
import torch
from einops import rearrange, reduce
from diffusers import DDIMScheduler, DDPMScheduler, DiffusionPipeline, ImagePipelineOutput, UNetaDConditionModel
from diffusers.schedulers.scheduling_ddim import DDIMSchedulerOutput
from diffusers.schedulers.scheduling_ddpm import DDPMSchedulerOutput
lowercase : Any = 8
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] , _lowerCamelCase : List[Any]=BITS) -> List[str]:
'''simple docstring'''
__UpperCamelCase : List[str] = x.device
__UpperCamelCase : List[str] = (x * 255).int().clamp(0 , 255)
__UpperCamelCase : Tuple = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__UpperCAmelCase)
__UpperCamelCase : Union[str, Any] = rearrange(__UpperCAmelCase , "d -> d 1 1")
__UpperCamelCase : str = rearrange(__UpperCAmelCase , "b c h w -> b c 1 h w")
__UpperCamelCase : Dict = ((x & mask) != 0).float()
__UpperCamelCase : Tuple = rearrange(__UpperCAmelCase , "b c d h w -> b (c d) h w")
__UpperCamelCase : List[str] = bits * 2 - 1
return bits
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : List[str] , _lowerCamelCase : Optional[int]=BITS) -> Optional[int]:
'''simple docstring'''
__UpperCamelCase : List[str] = x.device
__UpperCamelCase : List[str] = (x > 0).int()
__UpperCamelCase : int = 2 ** torch.arange(bits - 1 , -1 , -1 , device=__UpperCAmelCase , dtype=torch.intaa)
__UpperCamelCase : List[str] = rearrange(__UpperCAmelCase , "d -> d 1 1")
__UpperCamelCase : int = rearrange(__UpperCAmelCase , "b (c d) h w -> b c d h w" , d=8)
__UpperCamelCase : Optional[int] = reduce(x * mask , "b c d h w -> b c h w" , "sum")
return (dec / 255).clamp(0.0 , 1.0)
def _SCREAMING_SNAKE_CASE ( self : Tuple , _lowerCamelCase : Any , _lowerCamelCase : Tuple , _lowerCamelCase : Any , _lowerCamelCase : List[str] = 0.0 , _lowerCamelCase : Optional[Any] = True , _lowerCamelCase : int=None , _lowerCamelCase : Union[str, Any] = True , ) -> Union[DDIMSchedulerOutput, Tuple]:
'''simple docstring'''
if self.num_inference_steps is None:
raise ValueError(
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler")
# See formulas (12) and (16) of DDIM paper https://arxiv.org/pdf/2010.02502.pdf
# Ideally, read DDIM paper in-detail understanding
# Notation (<variable name> -> <name in paper>
# - pred_noise_t -> e_theta(x_t, t)
# - pred_original_sample -> f_theta(x_t, t) or x_0
# - std_dev_t -> sigma_t
# - eta -> η
# - pred_sample_direction -> "direction pointing to x_t"
# - pred_prev_sample -> "x_t-1"
# 1. get previous step value (=t-1)
__UpperCamelCase : Dict = timestep - self.config.num_train_timesteps // self.num_inference_steps
# 2. compute alphas, betas
__UpperCamelCase : Any = self.alphas_cumprod[timestep]
__UpperCamelCase : int = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
__UpperCamelCase : Optional[int] = 1 - alpha_prod_t
# 3. compute predicted original sample from predicted noise also called
# "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__UpperCamelCase : str = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
# 4. Clip "predicted x_0"
__UpperCamelCase : List[str] = self.bit_scale
if self.config.clip_sample:
__UpperCamelCase : Any = torch.clamp(__UpperCAmelCase , -scale , __UpperCAmelCase)
# 5. compute variance: "sigma_t(η)" -> see formula (16)
# σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
__UpperCamelCase : str = self._get_variance(__UpperCAmelCase , __UpperCAmelCase)
__UpperCamelCase : str = eta * variance ** 0.5
if use_clipped_model_output:
# the model_output is always re-derived from the clipped x_0 in Glide
__UpperCamelCase : Optional[Any] = (sample - alpha_prod_t ** 0.5 * pred_original_sample) / beta_prod_t ** 0.5
# 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__UpperCamelCase : Dict = (1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output
# 7. compute x_t without "random noise" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
__UpperCamelCase : Dict = alpha_prod_t_prev ** 0.5 * pred_original_sample + pred_sample_direction
if eta > 0:
# randn_like does not support generator https://github.com/pytorch/pytorch/issues/27072
__UpperCamelCase : List[str] = model_output.device if torch.is_tensor(__UpperCAmelCase) else "cpu"
__UpperCamelCase : List[str] = torch.randn(model_output.shape , dtype=model_output.dtype , generator=__UpperCAmelCase).to(__UpperCAmelCase)
__UpperCamelCase : Dict = self._get_variance(__UpperCAmelCase , __UpperCAmelCase) ** 0.5 * eta * noise
__UpperCamelCase : int = prev_sample + variance
if not return_dict:
return (prev_sample,)
return DDIMSchedulerOutput(prev_sample=__UpperCAmelCase , pred_original_sample=__UpperCAmelCase)
def _SCREAMING_SNAKE_CASE ( self : Union[str, Any] , _lowerCamelCase : Tuple , _lowerCamelCase : Tuple , _lowerCamelCase : Optional[int] , _lowerCamelCase : Optional[Any]="epsilon" , _lowerCamelCase : List[Any]=None , _lowerCamelCase : Any = True , ) -> Union[DDPMSchedulerOutput, Tuple]:
'''simple docstring'''
__UpperCamelCase : int = timestep
if model_output.shape[1] == sample.shape[1] * 2 and self.variance_type in ["learned", "learned_range"]:
__UpperCamelCase , __UpperCamelCase : Dict = torch.split(__UpperCAmelCase , sample.shape[1] , dim=1)
else:
__UpperCamelCase : Tuple = None
# 1. compute alphas, betas
__UpperCamelCase : Optional[int] = self.alphas_cumprod[t]
__UpperCamelCase : str = self.alphas_cumprod[t - 1] if t > 0 else self.one
__UpperCamelCase : Any = 1 - alpha_prod_t
__UpperCamelCase : int = 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 prediction_type == "epsilon":
__UpperCamelCase : str = (sample - beta_prod_t ** 0.5 * model_output) / alpha_prod_t ** 0.5
elif prediction_type == "sample":
__UpperCamelCase : Tuple = model_output
else:
raise ValueError(F'Unsupported prediction_type {prediction_type}.')
# 3. Clip "predicted x_0"
__UpperCamelCase : Union[str, Any] = self.bit_scale
if self.config.clip_sample:
__UpperCamelCase : Optional[int] = torch.clamp(__UpperCAmelCase , -scale , __UpperCAmelCase)
# 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[Any] = (alpha_prod_t_prev ** 0.5 * self.betas[t]) / beta_prod_t
__UpperCamelCase : int = self.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 : Dict = pred_original_sample_coeff * pred_original_sample + current_sample_coeff * sample
# 6. Add noise
__UpperCamelCase : Dict = 0
if t > 0:
__UpperCamelCase : str = torch.randn(
model_output.size() , dtype=model_output.dtype , layout=model_output.layout , generator=__UpperCAmelCase).to(model_output.device)
__UpperCamelCase : Union[str, Any] = (self._get_variance(__UpperCAmelCase , predicted_variance=__UpperCAmelCase) ** 0.5) * noise
__UpperCamelCase : int = pred_prev_sample + variance
if not return_dict:
return (pred_prev_sample,)
return DDPMSchedulerOutput(prev_sample=__UpperCAmelCase , pred_original_sample=__UpperCAmelCase)
class lowerCamelCase__ ( _snake_case):
'''simple docstring'''
def __init__( self :Optional[Any] , a :UNetaDConditionModel , a :Union[DDIMScheduler, DDPMScheduler] , a :Optional[float] = 1.0 , ) -> Optional[Any]:
super().__init__()
__UpperCamelCase : int = bit_scale
__UpperCamelCase : int = (
ddim_bit_scheduler_step if isinstance(a , a ) else ddpm_bit_scheduler_step
)
self.register_modules(unet=a , scheduler=a )
@torch.no_grad()
def __call__( self :Optional[Any] , a :Optional[int] = 2_5_6 , a :Optional[int] = 2_5_6 , a :Optional[int] = 5_0 , a :Optional[torch.Generator] = None , a :Optional[int] = 1 , a :Optional[str] = "pil" , a :bool = True , **a :List[Any] , ) -> List[Any]:
__UpperCamelCase : Optional[int] = torch.randn(
(batch_size, self.unet.config.in_channels, height, width) , generator=a , )
__UpperCamelCase : Dict = decimal_to_bits(a ) * self.bit_scale
__UpperCamelCase : Optional[Any] = latents.to(self.device )
self.scheduler.set_timesteps(a )
for t in self.progress_bar(self.scheduler.timesteps ):
# predict the noise residual
__UpperCamelCase : str = self.unet(a , a ).sample
# compute the previous noisy sample x_t -> x_t-1
__UpperCamelCase : str = self.scheduler.step(a , a , a ).prev_sample
__UpperCamelCase : Optional[int] = bits_to_decimal(a )
if output_type == "pil":
__UpperCamelCase : Tuple = self.numpy_to_pil(a )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=a ) | 713 |
# 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,
)
lowercase : Any = 'pytorch_model.bin'
lowercase : List[str] = 'pytorch_model.bin.index.json'
lowercase : List[Any] = 'adapter_config.json'
lowercase : str = 'adapter_model.bin'
lowercase : List[str] = 'adapter_model.safetensors'
lowercase : Any = 'tf_model.h5'
lowercase : str = 'tf_model.h5.index.json'
lowercase : Any = 'model.ckpt'
lowercase : Optional[int] = 'flax_model.msgpack'
lowercase : Dict = 'flax_model.msgpack.index.json'
lowercase : Dict = 'model.safetensors'
lowercase : Dict = 'model.safetensors.index.json'
lowercase : Union[str, Any] = 'config.json'
lowercase : Tuple = 'preprocessor_config.json'
lowercase : Tuple = FEATURE_EXTRACTOR_NAME
lowercase : Dict = 'generation_config.json'
lowercase : Dict = 'modelcard.json'
lowercase : Optional[int] = '▁'
lowercase : Any = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility
lowercase : List[Any] = [
[[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too.
lowercase : Tuple = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
lowercase : Any = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]
def _SCREAMING_SNAKE_CASE ( _lowerCamelCase : Union[str, Any]) -> List[str]:
'''simple docstring'''
if version.parse(_lowerCamelCase) < version.parse(_lowerCamelCase):
if "dev" in min_version:
__UpperCamelCase : List[str] = (
"This example requires a source install from HuggingFace Transformers (see "
"`https://huggingface.co/docs/transformers/installation#install-from-source`),"
)
else:
__UpperCamelCase : Optional[Any] = F'This example requires a minimum version of {min_version},'
error_message += F' but the version found is {__version__}.\n'
raise ImportError(
error_message
+ "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other "
"versions of HuggingFace Transformers.") | 94 | 0 |
"""simple docstring"""
from __future__ import annotations
from collections import namedtuple
def _SCREAMING_SNAKE_CASE ( UpperCamelCase : Union[str, Any] , UpperCamelCase : str , UpperCamelCase : Optional[int] ):
A__ = namedtuple("""result""" , """name value""" )
if (voltage, current, power).count(0 ) != 1:
raise ValueError("""Only one argument must be 0""" )
elif power < 0:
raise ValueError(
"""Power cannot be negative in any electrical/electronics system""" )
elif voltage == 0:
return result("""voltage""" , power / current )
elif current == 0:
return result("""current""" , power / voltage )
elif power == 0:
return result("""power""" , float(round(abs(voltage * current ) , 2 ) ) )
else:
raise ValueError("""Exactly one argument must be 0""" )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 574 |
import inspect
import unittest
from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import MobileViTImageProcessor
class a (_lowerCAmelCase ):
"""simple docstring"""
def __snake_case ( self : str ) -> str:
__snake_case : Tuple = self.config_class(**self.inputs_dict )
self.parent.assertTrue(hasattr(lowerCamelCase , "hidden_sizes" ) )
self.parent.assertTrue(hasattr(lowerCamelCase , "neck_hidden_sizes" ) )
self.parent.assertTrue(hasattr(lowerCamelCase , "num_attention_heads" ) )
class a :
"""simple docstring"""
def __init__( self : Optional[int] , lowerCamelCase : List[str] , lowerCamelCase : Tuple=13 , lowerCamelCase : str=32 , lowerCamelCase : Dict=2 , lowerCamelCase : List[str]=3 , lowerCamelCase : Any=640 , lowerCamelCase : Optional[Any]=4 , lowerCamelCase : Tuple="silu" , lowerCamelCase : int=3 , lowerCamelCase : Dict=32 , lowerCamelCase : str=0.1 , lowerCamelCase : Optional[int]=0.1 , lowerCamelCase : Optional[Any]=0.1 , lowerCamelCase : Dict=0.02 , lowerCamelCase : Union[str, Any]=True , lowerCamelCase : Optional[int]=True , lowerCamelCase : Union[str, Any]=10 , lowerCamelCase : int=None , ) -> str:
__snake_case : Optional[Any] = parent
__snake_case : Optional[Any] = batch_size
__snake_case : Any = image_size
__snake_case : List[Any] = patch_size
__snake_case : Any = num_channels
__snake_case : Union[str, Any] = last_hidden_size
__snake_case : Any = num_attention_heads
__snake_case : Any = hidden_act
__snake_case : Tuple = conv_kernel_size
__snake_case : Any = output_stride
__snake_case : Any = hidden_dropout_prob
__snake_case : List[Any] = attention_probs_dropout_prob
__snake_case : Optional[Any] = classifier_dropout_prob
__snake_case : Union[str, Any] = use_labels
__snake_case : Optional[int] = is_training
__snake_case : Dict = num_labels
__snake_case : Any = initializer_range
__snake_case : Optional[int] = scope
def __snake_case ( self : str ) -> Union[str, Any]:
__snake_case : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__snake_case : List[Any] = None
__snake_case : Optional[int] = None
if self.use_labels:
__snake_case : Optional[int] = ids_tensor([self.batch_size] , self.num_labels )
__snake_case : Any = ids_tensor([self.batch_size, self.image_size, self.image_size] , self.num_labels )
__snake_case : Optional[Any] = self.get_config()
return config, pixel_values, labels, pixel_labels
def __snake_case ( self : Any ) -> Union[str, Any]:
return MobileViTConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , num_attention_heads=self.num_attention_heads , hidden_act=self.hidden_act , conv_kernel_size=self.conv_kernel_size , output_stride=self.output_stride , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , classifier_dropout_prob=self.classifier_dropout_prob , initializer_range=self.initializer_range , )
def __snake_case ( self : Any , lowerCamelCase : Tuple , lowerCamelCase : int , lowerCamelCase : Tuple , lowerCamelCase : Optional[int] ) -> Dict:
__snake_case : List[Any] = MobileViTModel(config=lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
__snake_case : List[str] = model(lowerCamelCase )
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 __snake_case ( self : Optional[Any] , lowerCamelCase : List[str] , lowerCamelCase : Dict , lowerCamelCase : Optional[Any] , lowerCamelCase : Tuple ) -> List[str]:
__snake_case : str = self.num_labels
__snake_case : List[Any] = MobileViTForImageClassification(lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
__snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def __snake_case ( self : Dict , lowerCamelCase : Any , lowerCamelCase : Any , lowerCamelCase : Optional[Any] , lowerCamelCase : Dict ) -> Dict:
__snake_case : Union[str, Any] = self.num_labels
__snake_case : Optional[int] = MobileViTForSemanticSegmentation(lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
__snake_case : Tuple = model(lowerCamelCase )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
__snake_case : List[Any] = model(lowerCamelCase , labels=lowerCamelCase )
self.parent.assertEqual(
result.logits.shape , (
self.batch_size,
self.num_labels,
self.image_size // self.output_stride,
self.image_size // self.output_stride,
) , )
def __snake_case ( self : Optional[int] ) -> List[Any]:
__snake_case : Optional[Any] = self.prepare_config_and_inputs()
__snake_case , __snake_case , __snake_case , __snake_case : Union[str, Any] = config_and_inputs
__snake_case : Dict = {"pixel_values": pixel_values}
return config, inputs_dict
@require_torch
class a (_lowerCAmelCase , _lowerCAmelCase , unittest.TestCase ):
"""simple docstring"""
__UpperCAmelCase : str = (
(MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
if is_torch_available()
else ()
)
__UpperCAmelCase : Optional[Any] = (
{
"feature-extraction": MobileViTModel,
"image-classification": MobileViTForImageClassification,
"image-segmentation": MobileViTForSemanticSegmentation,
}
if is_torch_available()
else {}
)
__UpperCAmelCase : List[str] = False
__UpperCAmelCase : int = False
__UpperCAmelCase : Optional[int] = False
__UpperCAmelCase : Optional[int] = False
def __snake_case ( self : Optional[int] ) -> Dict:
__snake_case : Tuple = MobileViTModelTester(self )
__snake_case : Any = MobileViTConfigTester(self , config_class=lowerCamelCase , has_text_modality=lowerCamelCase )
def __snake_case ( self : Optional[int] ) -> Dict:
self.config_tester.run_common_tests()
@unittest.skip(reason="MobileViT does not use inputs_embeds" )
def __snake_case ( self : Dict ) -> Any:
pass
@unittest.skip(reason="MobileViT does not support input and output embeddings" )
def __snake_case ( self : Dict ) -> List[Any]:
pass
@unittest.skip(reason="MobileViT does not output attentions" )
def __snake_case ( self : int ) -> Dict:
pass
def __snake_case ( self : int ) -> Union[str, Any]:
__snake_case , __snake_case : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case : Optional[Any] = model_class(lowerCamelCase )
__snake_case : List[Any] = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case : int = [*signature.parameters.keys()]
__snake_case : List[str] = ["pixel_values"]
self.assertListEqual(arg_names[:1] , lowerCamelCase )
@unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." )
def __snake_case ( self : int ) -> Tuple:
pass
def __snake_case ( self : Any ) -> Tuple:
__snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase )
def __snake_case ( self : Any ) -> str:
def check_hidden_states_output(lowerCamelCase : Union[str, Any] , lowerCamelCase : Dict , lowerCamelCase : Any ):
__snake_case : int = model_class(lowerCamelCase )
model.to(lowerCamelCase )
model.eval()
with torch.no_grad():
__snake_case : int = model(**self._prepare_for_class(lowerCamelCase , lowerCamelCase ) )
__snake_case : Union[str, Any] = outputs.hidden_states
__snake_case : int = 5
self.assertEqual(len(lowerCamelCase ) , lowerCamelCase )
# MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
# with the width and height being successively divided by 2.
__snake_case : List[Any] = 2
for i in range(len(lowerCamelCase ) ):
self.assertListEqual(
list(hidden_states[i].shape[-2:] ) , [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor] , )
divisor *= 2
self.assertEqual(self.model_tester.output_stride , divisor // 2 )
__snake_case , __snake_case : Optional[Any] = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__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"]
__snake_case : List[Any] = True
check_hidden_states_output(lowerCamelCase , lowerCamelCase , lowerCamelCase )
def __snake_case ( self : Any ) -> Any:
__snake_case : Any = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*lowerCamelCase )
def __snake_case ( self : List[str] ) -> List[str]:
__snake_case : List[Any] = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_semantic_segmentation(*lowerCamelCase )
@slow
def __snake_case ( self : List[str] ) -> Any:
for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case : List[str] = MobileViTModel.from_pretrained(lowerCamelCase )
self.assertIsNotNone(lowerCamelCase )
def lowerCAmelCase_ ( ):
__snake_case : Optional[int] = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" )
return image
@require_torch
@require_vision
class a (unittest.TestCase ):
"""simple docstring"""
@cached_property
def __snake_case ( self : str ) -> Dict:
return MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small" ) if is_vision_available() else None
@slow
def __snake_case ( self : Union[str, Any] ) -> List[str]:
__snake_case : Tuple = MobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small" ).to(lowerCamelCase )
__snake_case : Optional[Any] = self.default_image_processor
__snake_case : Union[str, Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase )
# forward pass
with torch.no_grad():
__snake_case : Dict = model(**lowerCamelCase )
# verify the logits
__snake_case : Union[str, Any] = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , lowerCamelCase )
__snake_case : List[Any] = torch.tensor([-1.93_64, -1.23_27, -0.46_53] ).to(lowerCamelCase )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , lowerCamelCase , atol=1E-4 ) )
@slow
def __snake_case ( self : str ) -> Optional[int]:
__snake_case : Optional[int] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
__snake_case : str = model.to(lowerCamelCase )
__snake_case : int = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
__snake_case : Optional[int] = prepare_img()
__snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase )
# forward pass
with torch.no_grad():
__snake_case : List[str] = model(**lowerCamelCase )
__snake_case : Union[str, Any] = outputs.logits
# verify the logits
__snake_case : Tuple = torch.Size((1, 21, 32, 32) )
self.assertEqual(logits.shape , lowerCamelCase )
__snake_case : Union[str, Any] = torch.tensor(
[
[[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
[[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
[[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
] , device=lowerCamelCase , )
self.assertTrue(torch.allclose(logits[0, :3, :3, :3] , lowerCamelCase , atol=1E-4 ) )
@slow
def __snake_case ( self : Union[str, Any] ) -> Optional[int]:
__snake_case : Optional[Any] = MobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
__snake_case : Tuple = model.to(lowerCamelCase )
__snake_case : Dict = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small" )
__snake_case : List[Any] = prepare_img()
__snake_case : List[Any] = image_processor(images=lowerCamelCase , return_tensors="pt" ).to(lowerCamelCase )
# forward pass
with torch.no_grad():
__snake_case : Any = model(**lowerCamelCase )
__snake_case : Dict = outputs.logits.detach().cpu()
__snake_case : Any = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase , target_sizes=[(50, 60)] )
__snake_case : int = torch.Size((50, 60) )
self.assertEqual(segmentation[0].shape , lowerCamelCase )
__snake_case : List[str] = image_processor.post_process_semantic_segmentation(outputs=lowerCamelCase )
__snake_case : Optional[int] = torch.Size((32, 32) )
self.assertEqual(segmentation[0].shape , lowerCamelCase )
| 81 | 0 |
'''simple docstring'''
import argparse
import logging
import os
import time
import timeit
import datasets
import numpy as np
import pycuda.autoinit # noqa: F401
import pycuda.driver as cuda
import tensorrt as trt
import torch
from absl import logging as absl_logging
from accelerate import Accelerator
from datasets import load_dataset, load_metric
from torch.utils.data import DataLoader
from utils_qa import postprocess_qa_predictions
import transformers
from transformers import AutoTokenizer, EvalPrediction, default_data_collator, set_seed
from transformers.trainer_pt_utils import nested_concat, nested_truncate
_SCREAMING_SNAKE_CASE = trt.Logger(trt.Logger.WARNING)
_SCREAMING_SNAKE_CASE = absl_logging.get_absl_logger()
absl_logger.setLevel(logging.WARNING)
_SCREAMING_SNAKE_CASE = logging.getLogger(__name__)
_SCREAMING_SNAKE_CASE = argparse.ArgumentParser()
# Required parameters
parser.add_argument(
"--onnx_model_path",
default=None,
type=str,
required=True,
help="Path to ONNX model: ",
)
parser.add_argument(
"--output_dir",
default=None,
type=str,
required=True,
help="The output directory where the model checkpoints and predictions will be written.",
)
# Other parameters
parser.add_argument(
"--tokenizer_name",
default="",
type=str,
required=True,
help="Pretrained tokenizer name or path if not the same as model_name",
)
parser.add_argument(
"--version_2_with_negative",
action="store_true",
help="If true, the SQuAD examples contain some that do not have an answer.",
)
parser.add_argument(
"--null_score_diff_threshold",
type=float,
default=0.0,
help="If null_score - best_non_null is greater than the threshold predict null.",
)
parser.add_argument(
"--max_seq_length",
default=384,
type=int,
help=(
"The maximum total input sequence length after WordPiece tokenization. Sequences "
"longer than this will be truncated, and sequences shorter than this will be padded."
),
)
parser.add_argument(
"--doc_stride",
default=128,
type=int,
help="When splitting up a long document into chunks, how much stride to take between chunks.",
)
parser.add_argument("--per_device_eval_batch_size", default=8, type=int, help="Batch size per GPU/CPU for evaluation.")
parser.add_argument(
"--n_best_size",
default=20,
type=int,
help="The total number of n-best predictions to generate in the nbest_predictions.json output file.",
)
parser.add_argument(
"--max_answer_length",
default=30,
type=int,
help=(
"The maximum length of an answer that can be generated. This is needed because the start "
"and end predictions are not conditioned on one another."
),
)
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument(
"--dataset_name",
type=str,
default=None,
required=True,
help="The name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--dataset_config_name",
type=str,
default=None,
help="The configuration name of the dataset to use (via the datasets library).",
)
parser.add_argument(
"--preprocessing_num_workers", type=int, default=4, help="A csv or a json file containing the training data."
)
parser.add_argument("--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets")
parser.add_argument(
"--fp16",
action="store_true",
help="Whether to use 16-bit (mixed) precision instead of 32-bit",
)
parser.add_argument(
"--int8",
action="store_true",
help="Whether to use INT8",
)
_SCREAMING_SNAKE_CASE = parser.parse_args()
if args.tokenizer_name:
_SCREAMING_SNAKE_CASE = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=True)
else:
raise ValueError(
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
)
logger.info("Training/evaluation parameters %s", args)
_SCREAMING_SNAKE_CASE = args.per_device_eval_batch_size
_SCREAMING_SNAKE_CASE = (args.eval_batch_size, args.max_seq_length)
# TRT Engine properties
_SCREAMING_SNAKE_CASE = True
_SCREAMING_SNAKE_CASE = "temp_engine/bert-fp32.engine"
if args.fpaa:
_SCREAMING_SNAKE_CASE = "temp_engine/bert-fp16.engine"
if args.inta:
_SCREAMING_SNAKE_CASE = "temp_engine/bert-int8.engine"
# import ONNX file
if not os.path.exists("temp_engine"):
os.makedirs("temp_engine")
_SCREAMING_SNAKE_CASE = 1 << (int)(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH)
with trt.Builder(TRT_LOGGER) as builder, builder.create_network(EXPLICIT_BATCH) as network, trt.OnnxParser(
network, TRT_LOGGER
) as parser:
with open(args.onnx_model_path, "rb") as model:
if not parser.parse(model.read()):
for error in range(parser.num_errors):
print(parser.get_error(error))
# Query input names and shapes from parsed TensorRT network
_SCREAMING_SNAKE_CASE = [network.get_input(i) for i in range(network.num_inputs)]
_SCREAMING_SNAKE_CASE = [_input.name for _input in network_inputs] # ex: ["actual_input1"]
with builder.create_builder_config() as config:
_SCREAMING_SNAKE_CASE = 1 << 50
if STRICT_TYPES:
config.set_flag(trt.BuilderFlag.STRICT_TYPES)
if args.fpaa:
config.set_flag(trt.BuilderFlag.FPaa)
if args.inta:
config.set_flag(trt.BuilderFlag.INTa)
_SCREAMING_SNAKE_CASE = builder.create_optimization_profile()
config.add_optimization_profile(profile)
for i in range(len(input_names)):
profile.set_shape(input_names[i], INPUT_SHAPE, INPUT_SHAPE, INPUT_SHAPE)
_SCREAMING_SNAKE_CASE = builder.build_engine(network, config)
# serialize_engine and store in file (can be directly loaded and deserialized):
with open(engine_name, "wb") as f:
f.write(engine.serialize())
def __lowerCamelCase ( __lowerCAmelCase : List[Any] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Tuple , __lowerCAmelCase : int , __lowerCAmelCase : Dict , __lowerCAmelCase : Optional[Any] , __lowerCAmelCase : int , __lowerCAmelCase : List[str] ) -> Dict:
snake_case = np.asarray(inputs["""input_ids"""] , dtype=np.intaa )
snake_case = np.asarray(inputs["""attention_mask"""] , dtype=np.intaa )
snake_case = np.asarray(inputs["""token_type_ids"""] , dtype=np.intaa )
# Copy inputs
cuda.memcpy_htod_async(d_inputs[0] , input_ids.ravel() , __lowerCAmelCase )
cuda.memcpy_htod_async(d_inputs[1] , attention_mask.ravel() , __lowerCAmelCase )
cuda.memcpy_htod_async(d_inputs[2] , token_type_ids.ravel() , __lowerCAmelCase )
# start time
snake_case = time.time()
# Run inference
context.execute_async(
bindings=[int(__lowerCAmelCase ) for d_inp in d_inputs] + [int(__lowerCAmelCase ), int(__lowerCAmelCase )] , stream_handle=stream.handle )
# Transfer predictions back from GPU
cuda.memcpy_dtoh_async(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
cuda.memcpy_dtoh_async(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
# Synchronize the stream and take time
stream.synchronize()
# end time
snake_case = time.time()
snake_case = end_time - start_time
snake_case = (h_outputa, h_outputa)
# print(outputs)
return outputs, infer_time
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
_SCREAMING_SNAKE_CASE = Accelerator()
# Make one log on every process with the configuration for debugging.
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
# Setup logging, we only want one process per machine to log things on the screen.
# accelerator.is_local_main_process is only True for one process per machine.
logger.setLevel(logging.INFO if accelerator.is_local_main_process else logging.ERROR)
if accelerator.is_local_main_process:
datasets.utils.logging.set_verbosity_warning()
transformers.utils.logging.set_verbosity_info()
else:
datasets.utils.logging.set_verbosity_error()
transformers.utils.logging.set_verbosity_error()
# If passed along, set the training seed now.
if args.seed is not None:
set_seed(args.seed)
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
# (the dataset will be downloaded automatically from the datasets Hub).
#
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
# 'text' is found. You can easily tweak this behavior (see below).
if args.dataset_name is not None:
# Downloading and loading a dataset from the hub.
_SCREAMING_SNAKE_CASE = load_dataset(args.dataset_name, args.dataset_config_name)
else:
raise ValueError("Evaluation requires a dataset name")
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
# https://huggingface.co/docs/datasets/loading_datasets.html.
# Preprocessing the datasets.
# Preprocessing is slighlty different for training and evaluation.
_SCREAMING_SNAKE_CASE = raw_datasets["validation"].column_names
_SCREAMING_SNAKE_CASE = "question" if "question" in column_names else column_names[0]
_SCREAMING_SNAKE_CASE = "context" if "context" in column_names else column_names[1]
_SCREAMING_SNAKE_CASE = "answers" if "answers" in column_names else column_names[2]
# Padding side determines if we do (question|context) or (context|question).
_SCREAMING_SNAKE_CASE = tokenizer.padding_side == "right"
if args.max_seq_length > tokenizer.model_max_length:
logger.warning(
F"""The max_seq_length passed ({args.max_seq_length}) is larger than the maximum length for the"""
F"""model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}."""
)
_SCREAMING_SNAKE_CASE = min(args.max_seq_length, tokenizer.model_max_length)
def __lowerCamelCase ( __lowerCAmelCase : Dict ) -> Any:
# Some of the questions have lots of whitespace on the left, which is not useful and will make the
# truncation of the context fail (the tokenized question will take a lots of space). So we remove that
# left whitespace
snake_case = [q.lstrip() for q in examples[question_column_name]]
# Tokenize our examples with truncation and maybe padding, but keep the overflows using a stride. This results
# in one example possible giving several features when a context is long, each of those features having a
# context that overlaps a bit the context of the previous feature.
snake_case = tokenizer(
examples[question_column_name if pad_on_right else context_column_name] , examples[context_column_name if pad_on_right else question_column_name] , truncation="""only_second""" if pad_on_right else """only_first""" , max_length=__lowerCAmelCase , stride=args.doc_stride , return_overflowing_tokens=__lowerCAmelCase , return_offsets_mapping=__lowerCAmelCase , padding="""max_length""" , )
# Since one example might give us several features if it has a long context, we need a map from a feature to
# its corresponding example. This key gives us just that.
snake_case = tokenized_examples.pop("""overflow_to_sample_mapping""" )
# For evaluation, we will need to convert our predictions to substrings of the context, so we keep the
# corresponding example_id and we will store the offset mappings.
snake_case = []
for i in range(len(tokenized_examples["""input_ids"""] ) ):
# Grab the sequence corresponding to that example (to know what is the context and what is the question).
snake_case = tokenized_examples.sequence_ids(__lowerCAmelCase )
snake_case = 1 if pad_on_right else 0
# One example can give several spans, this is the index of the example containing this span of text.
snake_case = sample_mapping[i]
tokenized_examples["example_id"].append(examples["""id"""][sample_index] )
# Set to None the offset_mapping that are not part of the context so it's easy to determine if a token
# position is part of the context or not.
snake_case = [
(o if sequence_ids[k] == context_index else None)
for k, o in enumerate(tokenized_examples["""offset_mapping"""][i] )
]
return tokenized_examples
_SCREAMING_SNAKE_CASE = raw_datasets["validation"]
# Validation Feature Creation
_SCREAMING_SNAKE_CASE = eval_examples.map(
prepare_validation_features,
batched=True,
num_proc=args.preprocessing_num_workers,
remove_columns=column_names,
load_from_cache_file=not args.overwrite_cache,
desc="Running tokenizer on validation dataset",
)
_SCREAMING_SNAKE_CASE = default_data_collator
_SCREAMING_SNAKE_CASE = eval_dataset.remove_columns(["example_id", "offset_mapping"])
_SCREAMING_SNAKE_CASE = DataLoader(
eval_dataset_for_model, collate_fn=data_collator, batch_size=args.per_device_eval_batch_size
)
def __lowerCamelCase ( __lowerCAmelCase : Optional[int] , __lowerCAmelCase : Dict , __lowerCAmelCase : List[Any] , __lowerCAmelCase : Union[str, Any]="eval" ) -> Any:
# Post-processing: we match the start logits and end logits to answers in the original context.
snake_case = postprocess_qa_predictions(
examples=__lowerCAmelCase , features=__lowerCAmelCase , predictions=__lowerCAmelCase , version_2_with_negative=args.version_2_with_negative , n_best_size=args.n_best_size , max_answer_length=args.max_answer_length , null_score_diff_threshold=args.null_score_diff_threshold , output_dir=args.output_dir , prefix=__lowerCAmelCase , )
# Format the result to the format the metric expects.
if args.version_2_with_negative:
snake_case = [
{"""id""": k, """prediction_text""": v, """no_answer_probability""": 0.0} for k, v in predictions.items()
]
else:
snake_case = [{"""id""": k, """prediction_text""": v} for k, v in predictions.items()]
snake_case = [{"""id""": ex["""id"""], """answers""": ex[answer_column_name]} for ex in examples]
return EvalPrediction(predictions=__lowerCAmelCase , label_ids=__lowerCAmelCase )
_SCREAMING_SNAKE_CASE = load_metric("squad_v2" if args.version_2_with_negative else "squad")
# Evaluation!
logger.info("Loading ONNX model %s for evaluation", args.onnx_model_path)
with open(engine_name, "rb") as f, trt.Runtime(TRT_LOGGER) as runtime, runtime.deserialize_cuda_engine(
f.read()
) as engine, engine.create_execution_context() as context:
# setup for TRT inferrence
for i in range(len(input_names)):
context.set_binding_shape(i, INPUT_SHAPE)
assert context.all_binding_shapes_specified
def __lowerCamelCase ( __lowerCAmelCase : Union[str, Any] ) -> int:
return trt.volume(engine.get_binding_shape(__lowerCAmelCase ) ) * engine.get_binding_dtype(__lowerCAmelCase ).itemsize
# Allocate device memory for inputs and outputs.
_SCREAMING_SNAKE_CASE = [cuda.mem_alloc(binding_nbytes(binding)) for binding in engine if engine.binding_is_input(binding)]
# Allocate output buffer
_SCREAMING_SNAKE_CASE = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.floataa)
_SCREAMING_SNAKE_CASE = cuda.pagelocked_empty(tuple(context.get_binding_shape(4)), dtype=np.floataa)
_SCREAMING_SNAKE_CASE = cuda.mem_alloc(h_outputa.nbytes)
_SCREAMING_SNAKE_CASE = cuda.mem_alloc(h_outputa.nbytes)
# Create a stream in which to copy inputs/outputs and run inference.
_SCREAMING_SNAKE_CASE = cuda.Stream()
# Evaluation
logger.info("***** Running Evaluation *****")
logger.info(F""" Num examples = {len(eval_dataset)}""")
logger.info(F""" Batch size = {args.per_device_eval_batch_size}""")
_SCREAMING_SNAKE_CASE = 0.0
_SCREAMING_SNAKE_CASE = 0
_SCREAMING_SNAKE_CASE = timeit.default_timer()
_SCREAMING_SNAKE_CASE = None
for step, batch in enumerate(eval_dataloader):
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = model_infer(batch, context, d_inputs, h_outputa, h_outputa, d_outputa, d_outputa, stream)
total_time += infer_time
niter += 1
_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE = outputs
_SCREAMING_SNAKE_CASE = torch.tensor(start_logits)
_SCREAMING_SNAKE_CASE = torch.tensor(end_logits)
# necessary to pad predictions and labels for being gathered
_SCREAMING_SNAKE_CASE = accelerator.pad_across_processes(start_logits, dim=1, pad_index=-100)
_SCREAMING_SNAKE_CASE = accelerator.pad_across_processes(end_logits, dim=1, pad_index=-100)
_SCREAMING_SNAKE_CASE = (accelerator.gather(start_logits).cpu().numpy(), accelerator.gather(end_logits).cpu().numpy())
_SCREAMING_SNAKE_CASE = logits if all_preds is None else nested_concat(all_preds, logits, padding_index=-100)
if all_preds is not None:
_SCREAMING_SNAKE_CASE = nested_truncate(all_preds, len(eval_dataset))
_SCREAMING_SNAKE_CASE = timeit.default_timer() - start_time
logger.info(" Evaluation done in total %f secs (%f sec per example)", evalTime, evalTime / len(eval_dataset))
# Inference time from TRT
logger.info("Average Inference Time = {:.3f} ms".format(total_time * 1000 / niter))
logger.info("Total Inference Time = {:.3f} ms".format(total_time * 1000))
logger.info("Total Number of Inference = %d", niter)
_SCREAMING_SNAKE_CASE = post_processing_function(eval_examples, eval_dataset, all_preds)
_SCREAMING_SNAKE_CASE = metric.compute(predictions=prediction.predictions, references=prediction.label_ids)
logger.info(F"""Evaluation metrics: {eval_metric}""")
| 713 |
'''simple docstring'''
import inspect
import os
import re
from transformers.configuration_utils import PretrainedConfig
from transformers.utils import direct_transformers_import
# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/check_config_docstrings.py
_SCREAMING_SNAKE_CASE = "src/transformers"
# This is to make sure the transformers module imported is the one in the repo.
_SCREAMING_SNAKE_CASE = direct_transformers_import(PATH_TO_TRANSFORMERS)
_SCREAMING_SNAKE_CASE = transformers.models.auto.configuration_auto.CONFIG_MAPPING
_SCREAMING_SNAKE_CASE = {
# used to compute the property `self.chunk_length`
"EncodecConfig": ["overlap"],
# used as `self.bert_model = BertModel(config, ...)`
"DPRConfig": True,
# not used in modeling files, but it's an important information
"FSMTConfig": ["langs"],
# used internally in the configuration class file
"GPTNeoConfig": ["attention_types"],
# used internally in the configuration class file
"EsmConfig": ["is_folding_model"],
# used during training (despite we don't have training script for these models yet)
"Mask2FormerConfig": ["ignore_value"],
# `ignore_value` used during training (despite we don't have training script for these models yet)
# `norm` used in conversion script (despite not using in the modeling file)
"OneFormerConfig": ["ignore_value", "norm"],
# used during preprocessing and collation, see `collating_graphormer.py`
"GraphormerConfig": ["spatial_pos_max"],
# used internally in the configuration class file
"T5Config": ["feed_forward_proj"],
# used internally in the configuration class file
# `tokenizer_class` get default value `T5Tokenizer` intentionally
"MT5Config": ["feed_forward_proj", "tokenizer_class"],
"UMT5Config": ["feed_forward_proj", "tokenizer_class"],
# used internally in the configuration class file
"LongT5Config": ["feed_forward_proj"],
# used internally in the configuration class file
"SwitchTransformersConfig": ["feed_forward_proj"],
# having default values other than `1e-5` - we can't fix them without breaking
"BioGptConfig": ["layer_norm_eps"],
# having default values other than `1e-5` - we can't fix them without breaking
"GLPNConfig": ["layer_norm_eps"],
# having default values other than `1e-5` - we can't fix them without breaking
"SegformerConfig": ["layer_norm_eps"],
# having default values other than `1e-5` - we can't fix them without breaking
"CvtConfig": ["layer_norm_eps"],
# having default values other than `1e-5` - we can't fix them without breaking
"PerceiverConfig": ["layer_norm_eps"],
# used internally to calculate the feature size
"InformerConfig": ["num_static_real_features", "num_time_features"],
# used internally to calculate the feature size
"TimeSeriesTransformerConfig": ["num_static_real_features", "num_time_features"],
# used internally to calculate the feature size
"AutoformerConfig": ["num_static_real_features", "num_time_features"],
# used internally to calculate `mlp_dim`
"SamVisionConfig": ["mlp_ratio"],
# For (head) training, but so far not implemented
"ClapAudioConfig": ["num_classes"],
# Not used, but providing useful information to users
"SpeechT5HifiGanConfig": ["sampling_rate"],
}
# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure
SPECIAL_CASES_TO_ALLOW.update(
{
"CLIPSegConfig": True,
"DeformableDetrConfig": True,
"DetaConfig": True,
"DinatConfig": True,
"DonutSwinConfig": True,
"EfficientFormerConfig": True,
"FSMTConfig": True,
"JukeboxConfig": True,
"LayoutLMv2Config": True,
"MaskFormerSwinConfig": True,
"MT5Config": True,
"NatConfig": True,
"OneFormerConfig": True,
"PerceiverConfig": True,
"RagConfig": True,
"SpeechT5Config": True,
"SwinConfig": True,
"Swin2SRConfig": True,
"Swinv2Config": True,
"SwitchTransformersConfig": True,
"TableTransformerConfig": True,
"TapasConfig": True,
"TransfoXLConfig": True,
"UniSpeechConfig": True,
"UniSpeechSatConfig": True,
"WavLMConfig": True,
"WhisperConfig": True,
# TODO: @Arthur (for `alignment_head` and `alignment_layer`)
"JukeboxPriorConfig": True,
# TODO: @Younes (for `is_decoder`)
"Pix2StructTextConfig": True,
}
)
def __lowerCamelCase ( __lowerCAmelCase : Any , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : Union[str, Any] , __lowerCAmelCase : str ) -> List[str]:
snake_case = False
for attribute in attributes:
for modeling_source in source_strings:
# check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)`
if (
F'''config.{attribute}''' in modeling_source
or F'''getattr(config, "{attribute}"''' in modeling_source
or F'''getattr(self.config, "{attribute}"''' in modeling_source
):
snake_case = True
# Deal with multi-line cases
elif (
re.search(
rF'''getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"''' , __lowerCAmelCase , )
is not None
):
snake_case = True
# `SequenceSummary` is called with `SequenceSummary(config)`
elif attribute in [
"summary_type",
"summary_use_proj",
"summary_activation",
"summary_last_dropout",
"summary_proj_to_labels",
"summary_first_dropout",
]:
if "SequenceSummary" in modeling_source:
snake_case = True
if attribute_used:
break
if attribute_used:
break
# common and important attributes, even if they do not always appear in the modeling files
snake_case = [
"""bos_index""",
"""eos_index""",
"""pad_index""",
"""unk_index""",
"""mask_index""",
"""image_size""",
"""use_cache""",
"""out_features""",
"""out_indices""",
]
snake_case = ["""encoder_no_repeat_ngram_size"""]
# Special cases to be allowed
snake_case = True
if not attribute_used:
snake_case = False
for attribute in attributes:
# Allow if the default value in the configuration class is different from the one in `PretrainedConfig`
if attribute in ["is_encoder_decoder"] and default_value is True:
snake_case = True
elif attribute in ["tie_word_embeddings"] and default_value is False:
snake_case = True
# Allow cases without checking the default value in the configuration class
elif attribute in attributes_to_allow + attributes_used_in_generation:
snake_case = True
elif attribute.endswith("""_token_id""" ):
snake_case = True
# configuration class specific cases
if not case_allowed:
snake_case = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] )
snake_case = allowed_cases is True or attribute in allowed_cases
return attribute_used or case_allowed
def __lowerCamelCase ( __lowerCAmelCase : int ) -> Union[str, Any]:
snake_case = dict(inspect.signature(config_class.__init__ ).parameters )
snake_case = [x for x in list(signature.keys() ) if x not in ["""self""", """kwargs"""]]
snake_case = [signature[param].default for param in parameter_names]
# If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long
# as one variant is used, the test should pass
snake_case = {}
if len(config_class.attribute_map ) > 0:
snake_case = {v: k for k, v in config_class.attribute_map.items()}
# Get the path to modeling source files
snake_case = inspect.getsourcefile(__lowerCAmelCase )
snake_case = os.path.dirname(__lowerCAmelCase )
# Let's check against all frameworks: as long as one framework uses an attribute, we are good.
snake_case = [os.path.join(__lowerCAmelCase , __lowerCAmelCase ) for fn in os.listdir(__lowerCAmelCase ) if fn.startswith("""modeling_""" )]
# Get the source code strings
snake_case = []
for path in modeling_paths:
if os.path.isfile(__lowerCAmelCase ):
with open(__lowerCAmelCase ) as fp:
modeling_sources.append(fp.read() )
snake_case = []
for config_param, default_value in zip(__lowerCAmelCase , __lowerCAmelCase ):
# `attributes` here is all the variant names for `config_param`
snake_case = [config_param]
# some configuration classes have non-empty `attribute_map`, and both names could be used in the
# corresponding modeling files. As long as one of them appears, it is fine.
if config_param in reversed_attribute_map:
attributes.append(reversed_attribute_map[config_param] )
if not check_attribute_being_used(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ):
unused_attributes.append(attributes[0] )
return sorted(__lowerCAmelCase )
def __lowerCamelCase ( ) -> Optional[Any]:
snake_case = {}
for _config_class in list(CONFIG_MAPPING.values() ):
# Skip deprecated models
if "models.deprecated" in _config_class.__module__:
continue
# Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.)
snake_case = [
cls
for name, cls in inspect.getmembers(
inspect.getmodule(_config_class ) , lambda __lowerCAmelCase : inspect.isclass(__lowerCAmelCase )
and issubclass(__lowerCAmelCase , __lowerCAmelCase )
and inspect.getmodule(__lowerCAmelCase ) == inspect.getmodule(_config_class ) , )
]
for config_class in config_classes_in_module:
snake_case = check_config_attributes_being_used(__lowerCAmelCase )
if len(__lowerCAmelCase ) > 0:
snake_case = unused_attributes
if len(__lowerCAmelCase ) > 0:
snake_case = """The following configuration classes contain unused attributes in the corresponding modeling files:\n"""
for name, attributes in configs_with_unused_attributes.items():
error += F'''{name}: {attributes}\n'''
raise ValueError(__lowerCAmelCase )
if __name__ == "__main__":
check_config_attributes()
| 517 | 0 |
import os
import zipfile
import pytest
from datasets.utils.extract import (
BzipaExtractor,
Extractor,
GzipExtractor,
LzaExtractor,
SevenZipExtractor,
TarExtractor,
XzExtractor,
ZipExtractor,
ZstdExtractor,
)
from .utils import require_lza, require_pyazr, require_zstandard
@pytest.mark.parametrize(
"compression_format, is_archive" , [
("7z", True),
("bz2", False),
("gzip", False),
("lz4", False),
("tar", True),
("xz", False),
("zip", True),
("zstd", False),
] , )
def lowerCAmelCase_ ( _snake_case : str , _snake_case : str , _snake_case : Optional[int] , _snake_case : List[str] , _snake_case : Optional[Any] , _snake_case : Union[str, Any] , _snake_case : Optional[Any] , _snake_case : Optional[Any] , _snake_case : Optional[int] , _snake_case : Optional[Any] , _snake_case : Union[str, Any] , _snake_case : List[Any] , ) -> Optional[Any]:
'''simple docstring'''
__magic_name__ : int = {
"7z": (seven_zip_file, SevenZipExtractor),
"bz2": (bza_file, BzipaExtractor),
"gzip": (gz_file, GzipExtractor),
"lz4": (lza_file, LzaExtractor),
"tar": (tar_file, TarExtractor),
"xz": (xz_file, XzExtractor),
"zip": (zip_file, ZipExtractor),
"zstd": (zstd_file, ZstdExtractor),
}
__magic_name__ , __magic_name__ : Any = input_paths_and_base_extractors[compression_format]
if input_path is None:
__magic_name__ : Optional[Any] = F'''for \'{compression_format}\' compression_format, '''
if compression_format == "7z":
reason += require_pyazr.kwargs["reason"]
elif compression_format == "lz4":
reason += require_lza.kwargs["reason"]
elif compression_format == "zstd":
reason += require_zstandard.kwargs["reason"]
pytest.skip(_snake_case )
assert base_extractor.is_extractable(_snake_case )
__magic_name__ : str = tmp_path / ("extracted" if is_archive else "extracted.txt")
base_extractor.extract(_snake_case , _snake_case )
if is_archive:
assert output_path.is_dir()
for file_path in output_path.iterdir():
assert file_path.name == text_file.name
__magic_name__ : Optional[int] = file_path.read_text(encoding="utf-8" )
else:
__magic_name__ : Optional[Any] = output_path.read_text(encoding="utf-8" )
__magic_name__ : Union[str, Any] = text_file.read_text(encoding="utf-8" )
assert extracted_file_content == expected_file_content
@pytest.mark.parametrize(
"compression_format, is_archive" , [
("7z", True),
("bz2", False),
("gzip", False),
("lz4", False),
("tar", True),
("xz", False),
("zip", True),
("zstd", False),
] , )
def lowerCAmelCase_ ( _snake_case : Dict , _snake_case : str , _snake_case : Optional[Any] , _snake_case : int , _snake_case : int , _snake_case : Dict , _snake_case : List[Any] , _snake_case : Tuple , _snake_case : int , _snake_case : Any , _snake_case : Tuple , _snake_case : Optional[Any] , ) -> Union[str, Any]:
'''simple docstring'''
__magic_name__ : List[Any] = {
"7z": seven_zip_file,
"bz2": bza_file,
"gzip": gz_file,
"lz4": lza_file,
"tar": tar_file,
"xz": xz_file,
"zip": zip_file,
"zstd": zstd_file,
}
__magic_name__ : List[str] = input_paths[compression_format]
if input_path is None:
__magic_name__ : Optional[Any] = F'''for \'{compression_format}\' compression_format, '''
if compression_format == "7z":
reason += require_pyazr.kwargs["reason"]
elif compression_format == "lz4":
reason += require_lza.kwargs["reason"]
elif compression_format == "zstd":
reason += require_zstandard.kwargs["reason"]
pytest.skip(_snake_case )
__magic_name__ : Dict = Extractor.infer_extractor_format(_snake_case )
assert extractor_format is not None
__magic_name__ : Tuple = tmp_path / ("extracted" if is_archive else "extracted.txt")
Extractor.extract(_snake_case , _snake_case , _snake_case )
if is_archive:
assert output_path.is_dir()
for file_path in output_path.iterdir():
assert file_path.name == text_file.name
__magic_name__ : List[Any] = file_path.read_text(encoding="utf-8" )
else:
__magic_name__ : Optional[int] = output_path.read_text(encoding="utf-8" )
__magic_name__ : Optional[int] = text_file.read_text(encoding="utf-8" )
assert extracted_file_content == expected_file_content
@pytest.fixture
def lowerCAmelCase_ ( _snake_case : int , _snake_case : Union[str, Any] ) -> int:
'''simple docstring'''
import tarfile
__magic_name__ : Tuple = tmp_path / "data_dot_dot"
directory.mkdir()
__magic_name__ : List[str] = directory / "tar_file_with_dot_dot.tar"
with tarfile.TarFile(_snake_case , "w" ) as f:
f.add(_snake_case , arcname=os.path.join(".." , text_file.name ) )
return path
@pytest.fixture
def lowerCAmelCase_ ( _snake_case : Dict ) -> List[str]:
'''simple docstring'''
import tarfile
__magic_name__ : Union[str, Any] = tmp_path / "data_sym_link"
directory.mkdir()
__magic_name__ : str = directory / "tar_file_with_sym_link.tar"
os.symlink(".." , directory / "subdir" , target_is_directory=_snake_case )
with tarfile.TarFile(_snake_case , "w" ) as f:
f.add(str(directory / "subdir" ) , arcname="subdir" ) # str required by os.readlink on Windows and Python < 3.8
return path
@pytest.mark.parametrize(
"insecure_tar_file, error_log" , [("tar_file_with_dot_dot", "illegal path"), ("tar_file_with_sym_link", "Symlink")] , )
def lowerCAmelCase_ ( _snake_case : str , _snake_case : Any , _snake_case : List[Any] , _snake_case : Union[str, Any] , _snake_case : str , _snake_case : int ) -> Dict:
'''simple docstring'''
__magic_name__ : Optional[int] = {
"tar_file_with_dot_dot": tar_file_with_dot_dot,
"tar_file_with_sym_link": tar_file_with_sym_link,
}
__magic_name__ : List[str] = insecure_tar_files[insecure_tar_file]
__magic_name__ : Any = tmp_path / "extracted"
TarExtractor.extract(_snake_case , _snake_case )
assert caplog.text
for record in caplog.records:
assert record.levelname == "ERROR"
assert error_log in record.msg
def lowerCAmelCase_ ( _snake_case : Optional[int] ) -> Any:
'''simple docstring'''
__magic_name__ : Optional[int] = tmpdir / "not_a_zip_file"
# From: https://github.com/python/cpython/pull/5053
__magic_name__ : Dict = (
B"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x01\x00\x00"
B"\x00\x02\x08\x06\x00\x00\x00\x99\x81\xb6'\x00\x00\x00\x15I"
B"DATx\x01\x01\n\x00\xf5\xff\x00PK\x05\x06\x00PK\x06\x06\x07"
B"\xac\x01N\xc6|a\r\x00\x00\x00\x00IEND\xaeB`\x82"
)
with not_a_zip_file.open("wb" ) as f:
f.write(_snake_case )
assert zipfile.is_zipfile(str(_snake_case ) ) # is a false positive for `zipfile`
assert not ZipExtractor.is_extractable(_snake_case ) # but we're right
| 124 |
import os
import tempfile
import unittest
from transformers.models.marian.convert_marian_tatoeba_to_pytorch import DEFAULT_REPO, TatoebaConverter
from transformers.testing_utils import slow
from transformers.utils import cached_property
@unittest.skipUnless(os.path.exists(snake_case ) , 'Tatoeba directory does not exist.' )
class _snake_case ( unittest.TestCase ):
@cached_property
def SCREAMING_SNAKE_CASE ( self ):
__magic_name__ : Any = tempfile.mkdtemp()
return TatoebaConverter(save_dir=_a )
@slow
def SCREAMING_SNAKE_CASE ( self ):
self.resolver.convert_models(["heb-eng"] )
@slow
def SCREAMING_SNAKE_CASE ( self ):
__magic_name__ , __magic_name__ : str = self.resolver.write_model_card("opus-mt-he-en" , dry_run=_a )
assert mmeta["long_pair"] == "heb-eng"
| 124 | 1 |
from typing import List, Optional, Tuple, Union
import torch
from ...models import UNetaDModel
from ...schedulers import KarrasVeScheduler
from ...utils import randn_tensor
from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput
class __magic_name__ ( _a):
_UpperCAmelCase : UNetaDModel
_UpperCAmelCase : KarrasVeScheduler
def __init__( self : Any ,__SCREAMING_SNAKE_CASE : UNetaDModel ,__SCREAMING_SNAKE_CASE : KarrasVeScheduler ):
super().__init__()
self.register_modules(unet=__SCREAMING_SNAKE_CASE ,scheduler=__SCREAMING_SNAKE_CASE )
@torch.no_grad()
def __call__( self : List[Any] ,__SCREAMING_SNAKE_CASE : int = 1 ,__SCREAMING_SNAKE_CASE : int = 5_0 ,__SCREAMING_SNAKE_CASE : Optional[Union[torch.Generator, List[torch.Generator]]] = None ,__SCREAMING_SNAKE_CASE : Optional[str] = "pil" ,__SCREAMING_SNAKE_CASE : bool = True ,**__SCREAMING_SNAKE_CASE : str ,):
UpperCAmelCase = self.unet.config.sample_size
UpperCAmelCase = (batch_size, 3, img_size, img_size)
UpperCAmelCase = self.unet
# sample x_0 ~ N(0, sigma_0^2 * I)
UpperCAmelCase = randn_tensor(__SCREAMING_SNAKE_CASE ,generator=__SCREAMING_SNAKE_CASE ,device=self.device ) * self.scheduler.init_noise_sigma
self.scheduler.set_timesteps(__SCREAMING_SNAKE_CASE )
for t in self.progress_bar(self.scheduler.timesteps ):
# here sigma_t == t_i from the paper
UpperCAmelCase = self.scheduler.schedule[t]
UpperCAmelCase = self.scheduler.schedule[t - 1] if t > 0 else 0
# 1. Select temporarily increased noise level sigma_hat
# 2. Add new noise to move from sample_i to sample_hat
UpperCAmelCase , UpperCAmelCase = self.scheduler.add_noise_to_input(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,generator=__SCREAMING_SNAKE_CASE )
# 3. Predict the noise residual given the noise magnitude `sigma_hat`
# The model inputs and output are adjusted by following eq. (213) in [1].
UpperCAmelCase = (sigma_hat / 2) * model((sample_hat + 1) / 2 ,sigma_hat / 2 ).sample
# 4. Evaluate dx/dt at sigma_hat
# 5. Take Euler step from sigma to sigma_prev
UpperCAmelCase = self.scheduler.step(__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE )
if sigma_prev != 0:
# 6. Apply 2nd order correction
# The model inputs and output are adjusted by following eq. (213) in [1].
UpperCAmelCase = (sigma_prev / 2) * model((step_output.prev_sample + 1) / 2 ,sigma_prev / 2 ).sample
UpperCAmelCase = self.scheduler.step_correct(
__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,__SCREAMING_SNAKE_CASE ,step_output.prev_sample ,step_output["derivative"] ,)
UpperCAmelCase = step_output.prev_sample
UpperCAmelCase = (sample / 2 + 0.5).clamp(0 ,1 )
UpperCAmelCase = sample.cpu().permute(0 ,2 ,3 ,1 ).numpy()
if output_type == "pil":
UpperCAmelCase = self.numpy_to_pil(__SCREAMING_SNAKE_CASE )
if not return_dict:
return (image,)
return ImagePipelineOutput(images=__SCREAMING_SNAKE_CASE )
| 712 |
# Lint as: python3
# pylint: enable=line-too-long
# pylint: disable=g-import-not-at-top,g-bad-import-order,wrong-import-position
__lowerCAmelCase ="2.13.1"
import platform
import pyarrow
from packaging import version
if version.parse(platform.python_version()) < version.parse("3.7"):
raise ImportWarning(
"To use `datasets`, Python>=3.7 is required, and the current version of Python doesn't match this condition."
)
if version.parse(pyarrow.__version__).major < 8:
raise ImportWarning(
"To use `datasets`, the module `pyarrow>=8.0.0` is required, and the current version of `pyarrow` doesn't match this condition.\n"
"If you are running this in a Google Colab, you should probably just restart the runtime to use the right version of `pyarrow`."
)
del platform
del pyarrow
del version
from .arrow_dataset import Dataset
from .arrow_reader import ReadInstruction
from .builder import ArrowBasedBuilder, BeamBasedBuilder, BuilderConfig, DatasetBuilder, GeneratorBasedBuilder
from .combine import concatenate_datasets, interleave_datasets
from .dataset_dict import DatasetDict, IterableDatasetDict
from .download import *
from .features import *
from .fingerprint import disable_caching, enable_caching, is_caching_enabled, set_caching_enabled
from .info import DatasetInfo, MetricInfo
from .inspect import (
get_dataset_config_info,
get_dataset_config_names,
get_dataset_infos,
get_dataset_split_names,
inspect_dataset,
inspect_metric,
list_datasets,
list_metrics,
)
from .iterable_dataset import IterableDataset
from .load import load_dataset, load_dataset_builder, load_from_disk, load_metric
from .metric import Metric
from .splits import (
NamedSplit,
NamedSplitAll,
Split,
SplitBase,
SplitDict,
SplitGenerator,
SplitInfo,
SubSplitInfo,
percent,
)
from .tasks import *
from .utils import *
from .utils import logging
# deprecated modules
from datasets import arrow_dataset as _arrow_dataset # isort:skip
from datasets import utils as _utils # isort:skip
from datasets.utils import download_manager as _deprecated_download_manager # isort:skip
__lowerCAmelCase =concatenate_datasets
__lowerCAmelCase =DownloadConfig
__lowerCAmelCase =DownloadManager
__lowerCAmelCase =DownloadMode
__lowerCAmelCase =DownloadConfig
__lowerCAmelCase =DownloadMode
__lowerCAmelCase =DownloadManager
del _arrow_dataset, _utils, _deprecated_download_manager
| 405 | 0 |
__SCREAMING_SNAKE_CASE = 'Alexander Joslin'
import operator as op
from .stack import Stack
def SCREAMING_SNAKE_CASE__ ( lowerCAmelCase_ : str ) -> int:
"""simple docstring"""
SCREAMING_SNAKE_CASE_ : Dict ={'''*''': op.mul, '''/''': op.truediv, '''+''': op.add, '''-''': op.sub}
SCREAMING_SNAKE_CASE_ : Stack[int] =Stack()
SCREAMING_SNAKE_CASE_ : Stack[str] =Stack()
for i in equation:
if i.isdigit():
# RULE 1
operand_stack.push(int(lowerCAmelCase_ ) )
elif i in operators:
# RULE 2
operator_stack.push(lowerCAmelCase_ )
elif i == ")":
# RULE 4
SCREAMING_SNAKE_CASE_ : List[str] =operator_stack.peek()
operator_stack.pop()
SCREAMING_SNAKE_CASE_ : Dict =operand_stack.peek()
operand_stack.pop()
SCREAMING_SNAKE_CASE_ : Tuple =operand_stack.peek()
operand_stack.pop()
SCREAMING_SNAKE_CASE_ : Union[str, Any] =operators[opr](lowerCAmelCase_ ,lowerCAmelCase_ )
operand_stack.push(lowerCAmelCase_ )
# RULE 5
return operand_stack.peek()
if __name__ == "__main__":
__SCREAMING_SNAKE_CASE = '(5 + ((4 * 2) * (2 + 3)))'
# answer = 45
print(f"""{equation} = {dijkstras_two_stack_algorithm(equation)}""")
| 220 |
'''simple docstring'''
from __future__ import annotations
import random
# Maximum size of the population. Bigger could be faster but is more memory expensive.
UpperCamelCase_ = 200
# Number of elements selected in every generation of evolution. The selection takes
# place from best to worst of that generation and must be smaller than N_POPULATION.
UpperCamelCase_ = 50
# Probability that an element of a generation can mutate, changing one of its genes.
# This will guarantee that all genes will be used during evolution.
UpperCamelCase_ = 0.4
# Just a seed to improve randomness required by the algorithm.
random.seed(random.randint(0, 1000))
def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : str ) -> tuple[str, float]:
lowercase : int =len([g for position, g in enumerate(__magic_name__ ) if g == main_target[position]] )
return (item, float(__magic_name__ ))
def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : str ) -> tuple[str, str]:
lowercase : Any =random.randint(0 , len(__magic_name__ ) - 1 )
lowercase : Tuple =parent_a[:random_slice] + parent_a[random_slice:]
lowercase : List[str] =parent_a[:random_slice] + parent_a[random_slice:]
return (child_a, child_a)
def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : list[str] ) -> str:
lowercase : Union[str, Any] =list(__magic_name__ )
if random.uniform(0 , 1 ) < MUTATION_PROBABILITY:
lowercase : Dict =random.choice(__magic_name__ )
return "".join(__magic_name__ )
def _lowerCAmelCase ( __magic_name__ : tuple[str, float] , __magic_name__ : list[tuple[str, float]] , __magic_name__ : list[str] , ) -> list[str]:
lowercase : Any =[]
# Generate more children proportionally to the fitness score.
lowercase : Dict =int(parent_a[1] * 100 ) + 1
lowercase : List[str] =10 if child_n >= 10 else child_n
for _ in range(__magic_name__ ):
lowercase : List[str] =population_score[random.randint(0 , __magic_name__ )][0]
lowercase , lowercase : Dict =crossover(parent_a[0] , __magic_name__ )
# Append new string to the population list.
pop.append(mutate(__magic_name__ , __magic_name__ ) )
pop.append(mutate(__magic_name__ , __magic_name__ ) )
return pop
def _lowerCAmelCase ( __magic_name__ : str , __magic_name__ : list[str] , __magic_name__ : bool = True ) -> tuple[int, int, str]:
# Verify if N_POPULATION is bigger than N_SELECTED
if N_POPULATION < N_SELECTED:
lowercase : List[str] =f'''{N_POPULATION} must be bigger than {N_SELECTED}'''
raise ValueError(__magic_name__ )
# Verify that the target contains no genes besides the ones inside genes variable.
lowercase : Optional[int] =sorted({c for c in target if c not in genes} )
if not_in_genes_list:
lowercase : Dict =f'''{not_in_genes_list} is not in genes list, evolution cannot converge'''
raise ValueError(__magic_name__ )
# Generate random starting population.
lowercase : int =[]
for _ in range(__magic_name__ ):
population.append(''''''.join([random.choice(__magic_name__ ) for i in range(len(__magic_name__ ) )] ) )
# Just some logs to know what the algorithms is doing.
lowercase , lowercase : Optional[int] =0, 0
# This loop will end when we find a perfect match for our target.
while True:
generation += 1
total_population += len(__magic_name__ )
# Random population created. Now it's time to evaluate.
# Adding a bit of concurrency can make everything faster,
#
# import concurrent.futures
# population_score: list[tuple[str, float]] = []
# with concurrent.futures.ThreadPoolExecutor(
# max_workers=NUM_WORKERS) as executor:
# futures = {executor.submit(evaluate, item) for item in population}
# concurrent.futures.wait(futures)
# population_score = [item.result() for item in futures]
#
# but with a simple algorithm like this, it will probably be slower.
# We just need to call evaluate for every item inside the population.
lowercase : List[str] =[evaluate(__magic_name__ , __magic_name__ ) for item in population]
# Check if there is a matching evolution.
lowercase : int =sorted(__magic_name__ , key=lambda __magic_name__ : x[1] , reverse=__magic_name__ )
if population_score[0][0] == target:
return (generation, total_population, population_score[0][0])
# Print the best result every 10 generation.
# Just to know that the algorithm is working.
if debug and generation % 10 == 0:
print(
f'''\nGeneration: {generation}'''
f'''\nTotal Population:{total_population}'''
f'''\nBest score: {population_score[0][1]}'''
f'''\nBest string: {population_score[0][0]}''' )
# Flush the old population, keeping some of the best evolutions.
# Keeping this avoid regression of evolution.
lowercase : Any =population[: int(N_POPULATION / 3 )]
population.clear()
population.extend(__magic_name__ )
# Normalize population score to be between 0 and 1.
lowercase : Dict =[
(item, score / len(__magic_name__ )) for item, score in population_score
]
# This is selection
for i in range(__magic_name__ ):
population.extend(select(population_score[int(__magic_name__ )] , __magic_name__ , __magic_name__ ) )
# Check if the population has already reached the maximum value and if so,
# break the cycle. If this check is disabled, the algorithm will take
# forever to compute large strings, but will also calculate small strings in
# a far fewer generations.
if len(__magic_name__ ) > N_POPULATION:
break
if __name__ == "__main__":
UpperCamelCase_ = (
"""This is a genetic algorithm to evaluate, combine, evolve, and mutate a string!"""
)
UpperCamelCase_ = list(
""" ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm"""
"""nopqrstuvwxyz.,;!?+-*#@^'èéòà€ù=)(&%$£/\\"""
)
UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ = basic(target_str, genes_list)
print(
f'''\nGeneration: {generation}\nTotal Population: {population}\nTarget: {target}'''
)
| 92 | 0 |
import os
import pytest
import yaml
from datasets.features.features import Features, Value
from datasets.info import DatasetInfo, DatasetInfosDict
@pytest.mark.parametrize(
'''files''' , [
['''full:README.md''', '''dataset_infos.json'''],
['''empty:README.md''', '''dataset_infos.json'''],
['''dataset_infos.json'''],
['''full:README.md'''],
] , )
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = tmp_path_factory.mktemp('''dset_infos_dir''' )
if "full:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''---\ndataset_info:\n dataset_size: 42\n---''' )
if "empty:README.md" in files:
with open(dataset_infos_dir / '''README.md''' , '''w''' ) as f:
f.write('''''' )
# we want to support dataset_infos.json for backward compatibility
if "dataset_infos.json" in files:
with open(dataset_infos_dir / '''dataset_infos.json''' , '''w''' ) as f:
f.write('''{\"default\": {\"dataset_size\": 42}}''' )
A_ = DatasetInfosDict.from_directory(_lowerCamelCase )
assert dataset_infos
assert dataset_infos["default"].dataset_size == 42
@pytest.mark.parametrize(
'''dataset_info''' , [
DatasetInfo(),
DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , ),
] , )
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = str(_lowerCamelCase )
dataset_info.write_to_directory(_lowerCamelCase )
A_ = DatasetInfo.from_directory(_lowerCamelCase )
assert dataset_info == reloaded
assert os.path.exists(os.path.join(_lowerCamelCase , '''dataset_info.json''' ) )
def _lowerCamelCase ( ):
'''simple docstring'''
A_ = DatasetInfo(
description='''foo''' , citation='''bar''' , homepage='''https://foo.bar''' , license='''CC0''' , features=Features({'''a''': Value('''int32''' )} ) , post_processed={} , supervised_keys=() , task_templates=[] , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train''', '''num_examples''': 42}] , download_checksums={} , download_size=1337 , post_processing_size=442 , dataset_size=1234 , size_in_bytes=1337 + 442 + 1234 , )
A_ = dataset_info._to_yaml_dict()
assert sorted(_lowerCamelCase ) == sorted(DatasetInfo._INCLUDED_INFO_IN_YAML )
for key in DatasetInfo._INCLUDED_INFO_IN_YAML:
assert key in dataset_info_yaml_dict
assert isinstance(dataset_info_yaml_dict[key] , (list, dict, int, str) )
A_ = yaml.safe_dump(_lowerCamelCase )
A_ = yaml.safe_load(_lowerCamelCase )
assert dataset_info_yaml_dict == reloaded
def _lowerCamelCase ( ):
'''simple docstring'''
A_ = DatasetInfo()
A_ = dataset_info._to_yaml_dict()
assert dataset_info_yaml_dict == {}
@pytest.mark.parametrize(
'''dataset_infos_dict''' , [
DatasetInfosDict(),
DatasetInfosDict({'''default''': DatasetInfo()} ),
DatasetInfosDict({'''my_config_name''': DatasetInfo()} ),
DatasetInfosDict(
{
'''default''': DatasetInfo(
description='''foo''' , features=Features({'''a''': Value('''int32''' )} ) , builder_name='''builder''' , config_name='''config''' , version='''1.0.0''' , splits=[{'''name''': '''train'''}] , download_size=42 , )
} ),
DatasetInfosDict(
{
'''v1''': DatasetInfo(dataset_size=42 ),
'''v2''': DatasetInfo(dataset_size=1337 ),
} ),
] , )
def _lowerCamelCase ( SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE ):
'''simple docstring'''
A_ = str(_lowerCamelCase )
dataset_infos_dict.write_to_directory(_lowerCamelCase )
A_ = DatasetInfosDict.from_directory(_lowerCamelCase )
# the config_name of the dataset_infos_dict take over the attribute
for config_name, dataset_info in dataset_infos_dict.items():
A_ = config_name
# the yaml representation doesn't include fields like description or citation
# so we just test that we can recover what we can from the yaml
A_ = DatasetInfo._from_yaml_dict(dataset_info._to_yaml_dict() )
assert dataset_infos_dict == reloaded
if dataset_infos_dict:
assert os.path.exists(os.path.join(_lowerCamelCase , '''README.md''' ) )
| 719 |
from __future__ import annotations
import unittest
from transformers import FunnelConfig, is_tf_available
from transformers.testing_utils import require_tf
from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
if is_tf_available():
import tensorflow as tf
from transformers import (
TFFunnelBaseModel,
TFFunnelForMaskedLM,
TFFunnelForMultipleChoice,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForSequenceClassification,
TFFunnelForTokenClassification,
TFFunnelModel,
)
class _lowercase :
def __init__( self : Dict , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : str=1_3 , lowerCamelCase__ : Any=7 , lowerCamelCase__ : Optional[Any]=True , lowerCamelCase__ : Optional[Any]=True , lowerCamelCase__ : List[Any]=True , lowerCamelCase__ : Optional[Any]=True , lowerCamelCase__ : List[str]=9_9 , lowerCamelCase__ : Optional[Any]=[1, 1, 2] , lowerCamelCase__ : Optional[Any]=1 , lowerCamelCase__ : Union[str, Any]=3_2 , lowerCamelCase__ : int=4 , lowerCamelCase__ : Optional[int]=8 , lowerCamelCase__ : Union[str, Any]=3_7 , lowerCamelCase__ : List[Any]="gelu_new" , lowerCamelCase__ : List[Any]=0.1 , lowerCamelCase__ : Union[str, Any]=0.1 , lowerCamelCase__ : Optional[Any]=0.0 , lowerCamelCase__ : List[Any]=5_1_2 , lowerCamelCase__ : Optional[int]=3 , lowerCamelCase__ : List[Any]=0.02 , lowerCamelCase__ : str=3 , lowerCamelCase__ : Union[str, Any]=4 , lowerCamelCase__ : Union[str, Any]=None , lowerCamelCase__ : List[Any]=False , ) -> Union[str, Any]:
"""simple docstring"""
A_ = parent
A_ = batch_size
A_ = seq_length
A_ = is_training
A_ = use_input_mask
A_ = use_token_type_ids
A_ = use_labels
A_ = vocab_size
A_ = block_sizes
A_ = num_decoder_layers
A_ = d_model
A_ = n_head
A_ = d_head
A_ = d_inner
A_ = hidden_act
A_ = hidden_dropout
A_ = attention_dropout
A_ = activation_dropout
A_ = max_position_embeddings
A_ = type_vocab_size
A_ = 2
A_ = num_labels
A_ = num_choices
A_ = scope
A_ = initializer_std
# Used in the tests to check the size of the first attention layer
A_ = n_head
# Used in the tests to check the size of the first hidden state
A_ = self.d_model
# Used in the tests to check the number of output hidden states/attentions
A_ = sum(self.block_sizes ) + (0 if base else self.num_decoder_layers)
# FunnelModel adds two hidden layers: input embeddings and the sum of the upsampled encoder hidden state with
# the last hidden state of the first block (which is the first hidden state of the decoder).
if not base:
A_ = self.num_hidden_layers + 2
def UpperCamelCase ( self : List[Any] ) -> Union[str, Any]:
"""simple docstring"""
A_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size )
A_ = None
if self.use_input_mask:
A_ = random_attention_mask([self.batch_size, self.seq_length] )
A_ = None
if self.use_token_type_ids:
A_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size )
A_ = None
A_ = None
A_ = None
if self.use_labels:
A_ = ids_tensor([self.batch_size] , self.type_sequence_label_size )
A_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels )
A_ = ids_tensor([self.batch_size] , self.num_choices )
A_ = FunnelConfig(
vocab_size=self.vocab_size , block_sizes=self.block_sizes , num_decoder_layers=self.num_decoder_layers , d_model=self.d_model , n_head=self.n_head , d_head=self.d_head , d_inner=self.d_inner , hidden_act=self.hidden_act , hidden_dropout=self.hidden_dropout , attention_dropout=self.attention_dropout , activation_dropout=self.activation_dropout , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_std=self.initializer_std , )
return (
config,
input_ids,
token_type_ids,
input_mask,
sequence_labels,
token_labels,
choice_labels,
)
def UpperCamelCase ( self : Optional[Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : str , lowerCamelCase__ : str , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : int , ) -> List[Any]:
"""simple docstring"""
A_ = TFFunnelModel(config=lowerCamelCase__ )
A_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
A_ = model(lowerCamelCase__ )
A_ = [input_ids, input_mask]
A_ = model(lowerCamelCase__ )
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
A_ = False
A_ = TFFunnelModel(config=lowerCamelCase__ )
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
A_ = False
A_ = TFFunnelModel(config=lowerCamelCase__ )
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.d_model) )
def UpperCamelCase ( self : List[Any] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : str , lowerCamelCase__ : Tuple , lowerCamelCase__ : Any , lowerCamelCase__ : Tuple , lowerCamelCase__ : Tuple , lowerCamelCase__ : Tuple , ) -> Tuple:
"""simple docstring"""
A_ = TFFunnelBaseModel(config=lowerCamelCase__ )
A_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
A_ = model(lowerCamelCase__ )
A_ = [input_ids, input_mask]
A_ = model(lowerCamelCase__ )
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) )
A_ = False
A_ = TFFunnelBaseModel(config=lowerCamelCase__ )
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 3, self.d_model) )
A_ = False
A_ = TFFunnelBaseModel(config=lowerCamelCase__ )
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, 2, self.d_model) )
def UpperCamelCase ( self : Optional[Any] , lowerCamelCase__ : int , lowerCamelCase__ : Dict , lowerCamelCase__ : int , lowerCamelCase__ : Dict , lowerCamelCase__ : List[str] , lowerCamelCase__ : Tuple , lowerCamelCase__ : Optional[int] , ) -> List[str]:
"""simple docstring"""
A_ = TFFunnelForPreTraining(config=lowerCamelCase__ )
A_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length) )
def UpperCamelCase ( self : List[Any] , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : List[str] , lowerCamelCase__ : int , lowerCamelCase__ : int , lowerCamelCase__ : List[str] , lowerCamelCase__ : Dict , ) -> List[str]:
"""simple docstring"""
A_ = TFFunnelForMaskedLM(config=lowerCamelCase__ )
A_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) )
def UpperCamelCase ( self : str , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Dict , lowerCamelCase__ : Dict , lowerCamelCase__ : int , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : str , lowerCamelCase__ : Tuple , ) -> Union[str, Any]:
"""simple docstring"""
A_ = self.num_labels
A_ = TFFunnelForSequenceClassification(config=lowerCamelCase__ )
A_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) )
def UpperCamelCase ( self : List[str] , lowerCamelCase__ : List[str] , lowerCamelCase__ : Tuple , lowerCamelCase__ : int , lowerCamelCase__ : Dict , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : List[Any] , ) -> Optional[Any]:
"""simple docstring"""
A_ = self.num_choices
A_ = TFFunnelForMultipleChoice(config=lowerCamelCase__ )
A_ = tf.tile(tf.expand_dims(lowerCamelCase__ , 1 ) , (1, self.num_choices, 1) )
A_ = tf.tile(tf.expand_dims(lowerCamelCase__ , 1 ) , (1, self.num_choices, 1) )
A_ = tf.tile(tf.expand_dims(lowerCamelCase__ , 1 ) , (1, self.num_choices, 1) )
A_ = {
'''input_ids''': multiple_choice_inputs_ids,
'''attention_mask''': multiple_choice_input_mask,
'''token_type_ids''': multiple_choice_token_type_ids,
}
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) )
def UpperCamelCase ( self : Optional[Any] , lowerCamelCase__ : Dict , lowerCamelCase__ : Dict , lowerCamelCase__ : str , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Optional[Any] , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : Dict , ) -> Union[str, Any]:
"""simple docstring"""
A_ = self.num_labels
A_ = TFFunnelForTokenClassification(config=lowerCamelCase__ )
A_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) )
def UpperCamelCase ( self : Any , lowerCamelCase__ : Any , lowerCamelCase__ : List[str] , lowerCamelCase__ : Optional[int] , lowerCamelCase__ : List[Any] , lowerCamelCase__ : Union[str, Any] , lowerCamelCase__ : Dict , lowerCamelCase__ : str , ) -> str:
"""simple docstring"""
A_ = TFFunnelForQuestionAnswering(config=lowerCamelCase__ )
A_ = {'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
A_ = model(lowerCamelCase__ )
self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) )
self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) )
def UpperCamelCase ( self : Dict ) -> str:
"""simple docstring"""
A_ = self.prepare_config_and_inputs()
(
(
A_
) ,(
A_
) ,(
A_
) ,(
A_
) ,(
A_
) ,(
A_
) ,(
A_
) ,
) = config_and_inputs
A_ = {'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
return config, inputs_dict
@require_tf
class _lowercase ( __lowerCamelCase,__lowerCamelCase,unittest.TestCase ):
_lowercase : Optional[Any] = (
(
TFFunnelModel,
TFFunnelForMaskedLM,
TFFunnelForPreTraining,
TFFunnelForQuestionAnswering,
TFFunnelForTokenClassification,
)
if is_tf_available()
else ()
)
_lowercase : List[Any] = (
{
'feature-extraction': (TFFunnelBaseModel, TFFunnelModel),
'fill-mask': TFFunnelForMaskedLM,
'question-answering': TFFunnelForQuestionAnswering,
'text-classification': TFFunnelForSequenceClassification,
'token-classification': TFFunnelForTokenClassification,
'zero-shot': TFFunnelForSequenceClassification,
}
if is_tf_available()
else {}
)
_lowercase : Dict = False
_lowercase : Optional[int] = False
def UpperCamelCase ( self : Union[str, Any] ) -> List[Any]:
"""simple docstring"""
A_ = TFFunnelModelTester(self )
A_ = ConfigTester(self , config_class=lowerCamelCase__ )
def UpperCamelCase ( self : int ) -> Dict:
"""simple docstring"""
self.config_tester.run_common_tests()
def UpperCamelCase ( self : List[Any] ) -> int:
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*lowerCamelCase__ )
def UpperCamelCase ( self : Any ) -> List[str]:
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_pretraining(*lowerCamelCase__ )
def UpperCamelCase ( self : Dict ) -> Dict:
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase__ )
def UpperCamelCase ( self : Any ) -> Any:
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_token_classification(*lowerCamelCase__ )
def UpperCamelCase ( self : Union[str, Any] ) -> Tuple:
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_question_answering(*lowerCamelCase__ )
@require_tf
class _lowercase ( __lowerCamelCase,unittest.TestCase ):
_lowercase : Any = (
(TFFunnelBaseModel, TFFunnelForMultipleChoice, TFFunnelForSequenceClassification) if is_tf_available() else ()
)
_lowercase : str = False
_lowercase : Any = False
def UpperCamelCase ( self : int ) -> Optional[int]:
"""simple docstring"""
A_ = TFFunnelModelTester(self , base=lowerCamelCase__ )
A_ = ConfigTester(self , config_class=lowerCamelCase__ )
def UpperCamelCase ( self : Union[str, Any] ) -> str:
"""simple docstring"""
self.config_tester.run_common_tests()
def UpperCamelCase ( self : Optional[int] ) -> Union[str, Any]:
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_base_model(*lowerCamelCase__ )
def UpperCamelCase ( self : str ) -> Dict:
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase__ )
def UpperCamelCase ( self : Any ) -> Union[str, Any]:
"""simple docstring"""
A_ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase__ )
| 563 | 0 |
'''simple docstring'''
from __future__ import annotations
UpperCamelCase : Dict = [
[-1, 0], # left
[0, -1], # down
[1, 0], # right
[0, 1], # up
]
def A__ ( __lowerCAmelCase : list[list[int]] , __lowerCAmelCase : list[int] , __lowerCAmelCase : list[int] , __lowerCAmelCase : int , __lowerCAmelCase : list[list[int]] , ):
lowerCamelCase__ = [
[0 for col in range(len(grid[0] ) )] for row in range(len(__lowerCAmelCase ) )
] # the reference grid
lowerCamelCase__ = 1
lowerCamelCase__ = [
[0 for col in range(len(grid[0] ) )] for row in range(len(__lowerCAmelCase ) )
] # the action grid
lowerCamelCase__ = init[0]
lowerCamelCase__ = init[1]
lowerCamelCase__ = 0
lowerCamelCase__ = g + heuristic[x][y] # cost from starting cell to destination cell
lowerCamelCase__ = [[f, g, x, y]]
lowerCamelCase__ = False # flag that is set when search is complete
lowerCamelCase__ = False # flag set if we can't find expand
while not found and not resign:
if len(__lowerCAmelCase ) == 0:
raise ValueError("""Algorithm is unable to find solution""" )
else: # to choose the least costliest action so as to move closer to the goal
cell.sort()
cell.reverse()
lowerCamelCase__ = cell.pop()
lowerCamelCase__ = next_cell[2]
lowerCamelCase__ = next_cell[3]
lowerCamelCase__ = next_cell[1]
if x == goal[0] and y == goal[1]:
lowerCamelCase__ = True
else:
for i in range(len(__lowerCAmelCase ) ): # to try out different valid actions
lowerCamelCase__ = x + DIRECTIONS[i][0]
lowerCamelCase__ = y + DIRECTIONS[i][1]
if xa >= 0 and xa < len(__lowerCAmelCase ) and ya >= 0 and ya < len(grid[0] ):
if closed[xa][ya] == 0 and grid[xa][ya] == 0:
lowerCamelCase__ = g + cost
lowerCamelCase__ = ga + heuristic[xa][ya]
cell.append([fa, ga, xa, ya] )
lowerCamelCase__ = 1
lowerCamelCase__ = i
lowerCamelCase__ = []
lowerCamelCase__ = goal[0]
lowerCamelCase__ = goal[1]
invpath.append([x, y] ) # we get the reverse path from here
while x != init[0] or y != init[1]:
lowerCamelCase__ = x - DIRECTIONS[action[x][y]][0]
lowerCamelCase__ = y - DIRECTIONS[action[x][y]][1]
lowerCamelCase__ = xa
lowerCamelCase__ = ya
invpath.append([x, y] )
lowerCamelCase__ = []
for i in range(len(__lowerCAmelCase ) ):
path.append(invpath[len(__lowerCAmelCase ) - 1 - i] )
return path, action
if __name__ == "__main__":
UpperCamelCase : List[Any] = [
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 1, 0, 0, 0, 0],
[0, 1, 0, 0, 1, 0],
[0, 0, 0, 0, 1, 0],
]
UpperCamelCase : List[Any] = [0, 0]
# all coordinates are given in format [y,x]
UpperCamelCase : int = [len(grid) - 1, len(grid[0]) - 1]
UpperCamelCase : Dict = 1
# the cost map which pushes the path closer to the goal
UpperCamelCase : Tuple = [[0 for row in range(len(grid[0]))] for col in range(len(grid))]
for i in range(len(grid)):
for j in range(len(grid[0])):
UpperCamelCase : str = abs(i - goal[0]) + abs(j - goal[1])
if grid[i][j] == 1:
# added extra penalty in the heuristic map
UpperCamelCase : Any = 99
UpperCamelCase , UpperCamelCase : int = search(grid, init, goal, cost, heuristic)
print('ACTION MAP')
for i in range(len(action)):
print(action[i])
for i in range(len(path)):
print(path[i])
| 50 |
'''simple docstring'''
from typing import List, Union
from ..utils import (
add_end_docstrings,
is_tf_available,
is_torch_available,
is_vision_available,
logging,
requires_backends,
)
from .base import PIPELINE_INIT_ARGS, Pipeline
if is_vision_available():
from PIL import Image
from ..image_utils import load_image
if is_tf_available():
import tensorflow as tf
from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
from ..tf_utils import stable_softmax
if is_torch_available():
from ..models.auto.modeling_auto import MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
lowercase =logging.get_logger(__name__)
@add_end_docstrings(lowerCAmelCase )
class __magic_name__ ( lowerCAmelCase ):
def __init__( self , *snake_case , **snake_case) -> Dict:
'''simple docstring'''
super().__init__(*snake_case , **snake_case)
requires_backends(self , 'vision')
self.check_model_type(
TF_MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING
if self.framework == 'tf'
else MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING)
def lowerCAmelCase ( self , snake_case=None) -> str:
'''simple docstring'''
_UpperCAmelCase : Any ={}
if top_k is not None:
_UpperCAmelCase : Optional[int] =top_k
return {}, {}, postprocess_params
def __call__( self , snake_case , **snake_case) -> List[str]:
'''simple docstring'''
return super().__call__(snake_case , **snake_case)
def lowerCAmelCase ( self , snake_case) -> List[str]:
'''simple docstring'''
_UpperCAmelCase : int =load_image(snake_case)
_UpperCAmelCase : Tuple =self.image_processor(images=snake_case , return_tensors=self.framework)
return model_inputs
def lowerCAmelCase ( self , snake_case) -> Optional[Any]:
'''simple docstring'''
_UpperCAmelCase : List[str] =self.model(**snake_case)
return model_outputs
def lowerCAmelCase ( self , snake_case , snake_case=5) -> Any:
'''simple docstring'''
if top_k > self.model.config.num_labels:
_UpperCAmelCase : Optional[Any] =self.model.config.num_labels
if self.framework == "pt":
_UpperCAmelCase : List[Any] =model_outputs.logits.softmax(-1)[0]
_UpperCAmelCase , _UpperCAmelCase : Optional[Any] =probs.topk(snake_case)
elif self.framework == "tf":
_UpperCAmelCase : int =stable_softmax(model_outputs.logits , axis=-1)[0]
_UpperCAmelCase : List[Any] =tf.math.top_k(snake_case , k=snake_case)
_UpperCAmelCase , _UpperCAmelCase : List[str] =topk.values.numpy(), topk.indices.numpy()
else:
raise ValueError(f"Unsupported framework: {self.framework}")
_UpperCAmelCase : int =scores.tolist()
_UpperCAmelCase : Tuple =ids.tolist()
return [{"score": score, "label": self.model.config.idalabel[_id]} for score, _id in zip(snake_case , snake_case)]
| 446 | 0 |
"""simple docstring"""
import math
import flax.linen as nn
import jax.numpy as jnp
def lowerCAmelCase_ ( lowercase_ : jnp.ndarray , lowercase_ : int , lowercase_ : float = 1 , lowercase_ : float = 1 , lowercase_ : float = 1.0E4 , lowercase_ : bool = False , lowercase_ : float = 1.0 , ):
'''simple docstring'''
assert timesteps.ndim == 1, "Timesteps should be a 1d-array"
assert embedding_dim % 2 == 0, F'''Embedding dimension {embedding_dim} should be even'''
__SCREAMING_SNAKE_CASE : List[Any] = float(embedding_dim // 2 )
__SCREAMING_SNAKE_CASE : Dict = math.log(max_timescale / min_timescale ) / (num_timescales - freq_shift)
__SCREAMING_SNAKE_CASE : Tuple = min_timescale * jnp.exp(jnp.arange(lowercase_ , dtype=jnp.floataa ) * -log_timescale_increment )
__SCREAMING_SNAKE_CASE : Any = jnp.expand_dims(lowercase_ , 1 ) * jnp.expand_dims(lowercase_ , 0 )
# scale embeddings
__SCREAMING_SNAKE_CASE : str = scale * emb
if flip_sin_to_cos:
__SCREAMING_SNAKE_CASE : List[Any] = jnp.concatenate([jnp.cos(lowercase_ ), jnp.sin(lowercase_ )] , axis=1 )
else:
__SCREAMING_SNAKE_CASE : Optional[int] = jnp.concatenate([jnp.sin(lowercase_ ), jnp.cos(lowercase_ )] , axis=1 )
__SCREAMING_SNAKE_CASE : List[str] = jnp.reshape(lowercase_ , [jnp.shape(lowercase_ )[0], embedding_dim] )
return signal
class snake_case ( nn.Module ):
lowerCamelCase__ = 32
lowerCamelCase__ = jnp.floataa
@nn.compact
def __call__( self :Any , _lowerCamelCase :Tuple ):
__SCREAMING_SNAKE_CASE : str = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='''linear_1''' )(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : int = nn.silu(_lowerCamelCase )
__SCREAMING_SNAKE_CASE : List[Any] = nn.Dense(self.time_embed_dim , dtype=self.dtype , name='''linear_2''' )(_lowerCamelCase )
return temb
class snake_case ( nn.Module ):
lowerCamelCase__ = 32
lowerCamelCase__ = False
lowerCamelCase__ = 1
@nn.compact
def __call__( self :Any , _lowerCamelCase :List[str] ):
return get_sinusoidal_embeddings(
_lowerCamelCase , embedding_dim=self.dim , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.freq_shift )
| 401 |
"""simple docstring"""
def lowerCAmelCase_ ( lowercase_ : Union[str, Any] , lowercase_ : List[str] , lowercase_ : Tuple , lowercase_ : int , lowercase_ : int , lowercase_ : Optional[int] ):
'''simple docstring'''
if index == r:
for j in range(lowercase_ ):
print(data[j] , end=''' ''' )
print(''' ''' )
return
# When no more elements are there to put in data[]
if i >= n:
return
# current is included, put next at next location
__SCREAMING_SNAKE_CASE : str = arr[i]
combination_util(lowercase_ , lowercase_ , lowercase_ , index + 1 , lowercase_ , i + 1 )
# current is excluded, replace it with
# next (Note that i+1 is passed, but
# index is not changed)
combination_util(lowercase_ , lowercase_ , lowercase_ , lowercase_ , lowercase_ , i + 1 )
# The main function that prints all combinations
# of size r in arr[] of size n. This function
# mainly uses combinationUtil()
def lowerCAmelCase_ ( lowercase_ : int , lowercase_ : List[Any] , lowercase_ : Optional[Any] ):
'''simple docstring'''
__SCREAMING_SNAKE_CASE : Any = [0] * r
# Print all combination using temporary array 'data[]'
combination_util(lowercase_ , lowercase_ , lowercase_ , 0 , lowercase_ , 0 )
if __name__ == "__main__":
# Driver code to check the function above
_lowerCamelCase = [10, 20, 30, 40, 50]
print_combination(arr, len(arr), 3)
# This code is contributed by Ambuj sahu
| 401 | 1 |
import warnings
from ...utils import logging
from .image_processing_videomae import VideoMAEImageProcessor
_a : int = logging.get_logger(__name__)
class a_ ( A__ ):
def __init__( self : List[str] , *UpperCAmelCase__ : Dict , **UpperCAmelCase__ : str ):
"""simple docstring"""
warnings.warn(
'''The class VideoMAEFeatureExtractor is deprecated and will be removed in version 5 of Transformers.'''
''' Please use VideoMAEImageProcessor instead.''' , a_ , )
super().__init__(*a_ , **a_ )
| 598 |
"""simple docstring"""
import warnings
from typing import List, Optional, Union
from ...image_utils import ImageInput
from ...processing_utils import ProcessorMixin
from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy
from ...utils import TensorType
class __lowerCamelCase ( A__ ):
'''simple docstring'''
a_ : Union[str, Any] = ["""image_processor""", """tokenizer"""]
a_ : Any = """FlavaImageProcessor"""
a_ : Tuple = ("""BertTokenizer""", """BertTokenizerFast""")
def __init__( self : Any , a_ : List[str]=None , a_ : Dict=None , **a_ : Tuple ):
lowerCAmelCase_ : Optional[Any] = None
if "feature_extractor" in kwargs:
warnings.warn(
"The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`"
" instead." , a_ , )
lowerCAmelCase_ : List[Any] = kwargs.pop("feature_extractor" )
lowerCAmelCase_ : List[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__(a_ , a_ )
lowerCAmelCase_ : Optional[int] = self.image_processor
def __call__( self : str , a_ : Optional[ImageInput] = None , a_ : Optional[Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]]] = None , a_ : bool = True , a_ : Union[bool, str, PaddingStrategy] = False , a_ : Union[bool, str, TruncationStrategy] = False , a_ : Optional[int] = None , a_ : int = 0 , a_ : Optional[int] = None , a_ : Optional[bool] = None , a_ : Optional[bool] = None , a_ : Optional[bool] = None , a_ : Optional[bool] = None , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = False , a_ : bool = True , a_ : Optional[Union[str, TensorType]] = None , **a_ : Optional[Any] , ):
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:
lowerCAmelCase_ : Any = self.tokenizer(
text=a_ , add_special_tokens=a_ , padding=a_ , truncation=a_ , max_length=a_ , stride=a_ , pad_to_multiple_of=a_ , return_token_type_ids=a_ , return_attention_mask=a_ , return_overflowing_tokens=a_ , return_special_tokens_mask=a_ , return_offsets_mapping=a_ , return_length=a_ , verbose=a_ , return_tensors=a_ , **a_ , )
if images is not None:
lowerCAmelCase_ : str = self.image_processor(
a_ , return_image_mask=a_ , return_codebook_pixels=a_ , return_tensors=a_ , **a_ , )
if text is not None and images is not None:
encoding.update(a_ )
return encoding
elif text is not None:
return encoding
else:
return BatchEncoding(data=dict(**a_ ) , tensor_type=a_ )
def lowerCamelCase ( self : Optional[int] , *a_ : Optional[Any] , **a_ : Dict ):
return self.tokenizer.batch_decode(*a_ , **a_ )
def lowerCamelCase ( self : Tuple , *a_ : Optional[int] , **a_ : Optional[int] ):
return self.tokenizer.decode(*a_ , **a_ )
@property
def lowerCamelCase ( self : List[str] ):
lowerCAmelCase_ : str = self.tokenizer.model_input_names
lowerCAmelCase_ : List[str] = self.image_processor.model_input_names
return list(dict.fromkeys(tokenizer_input_names + image_processor_input_names ) )
@property
def lowerCamelCase ( self : Optional[Any] ):
warnings.warn(
"`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , a_ , )
return self.image_processor_class
@property
def lowerCamelCase ( self : Union[str, Any] ):
warnings.warn(
"`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , a_ , )
return self.image_processor
| 610 | 0 |
'''simple docstring'''
import json
import os
from typing import Optional, Tuple
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
__magic_name__ : Optional[int] = logging.get_logger(__name__)
__magic_name__ : List[str] = {"""vocab_file""": """vocab.json"""}
__magic_name__ : Union[str, Any] = {
"""vocab_file""": {
"""mgp-str""": """https://huggingface.co/alibaba-damo/mgp-str-base/blob/main/vocab.json""",
}
}
__magic_name__ : Optional[Any] = {"""mgp-str""": 27}
class __SCREAMING_SNAKE_CASE ( _UpperCAmelCase ):
'''simple docstring'''
UpperCAmelCase__ : Tuple = VOCAB_FILES_NAMES
UpperCAmelCase__ : Optional[Any] = PRETRAINED_VOCAB_FILES_MAP
UpperCAmelCase__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
def __init__( self , lowerCamelCase , lowerCamelCase="[GO]" , lowerCamelCase="[GO]" , lowerCamelCase="[s]" , lowerCamelCase="[GO]" , **lowerCamelCase ):
super().__init__(
unk_token=lowercase__ , bos_token=lowercase__ , eos_token=lowercase__ , pad_token=lowercase__ , **lowercase__ , )
with open(lowercase__ , encoding="utf-8" ) as vocab_handle:
_snake_case = json.load(lowercase__ )
_snake_case = {v: k for k, v in self.vocab.items()}
@property
def UpperCamelCase( self ):
return len(self.vocab )
def UpperCamelCase( self ):
return dict(self.vocab , **self.added_tokens_encoder )
def UpperCamelCase( self , lowerCamelCase ):
_snake_case = []
for s in text:
char_tokens.extend(lowercase__ )
return char_tokens
def UpperCamelCase( self , lowerCamelCase ):
return self.vocab.get(lowercase__ , self.vocab.get(self.unk_token ) )
def UpperCamelCase( self , lowerCamelCase ):
return self.decoder.get(lowercase__ )
def UpperCamelCase( self , lowerCamelCase , lowerCamelCase = None ):
if not os.path.isdir(lowercase__ ):
logger.error("Vocabulary path ({}) should be a directory".format(lowercase__ ) )
return
_snake_case = os.path.join(
lowercase__ , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] )
with open(lowercase__ , "w" , encoding="utf-8" ) as f:
f.write(json.dumps(self.vocab , indent=2 , sort_keys=lowercase__ , ensure_ascii=lowercase__ ) + "\n" )
return (vocab_file,)
| 704 |
'''simple docstring'''
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.layers import LSTM, Dense
from tensorflow.keras.models import Sequential
if __name__ == "__main__":
__magic_name__ : Union[str, Any] = pd.read_csv("""sample_data.csv""", header=None)
__magic_name__ : Optional[Any] = df.shape[:1][0]
# If you're using some other dataset input the target column
__magic_name__ : str = df.iloc[:, 1:2]
__magic_name__ : Dict = actual_data.values.reshape(len_data, 1)
__magic_name__ : Tuple = MinMaxScaler().fit_transform(actual_data)
__magic_name__ : Union[str, Any] = 10
__magic_name__ : Optional[int] = 5
__magic_name__ : Any = 20
__magic_name__ : int = len_data - periods * look_back
__magic_name__ : Union[str, Any] = actual_data[:division]
__magic_name__ : int = actual_data[division - look_back :]
__magic_name__ , __magic_name__ : List[str] = [], []
__magic_name__ , __magic_name__ : Tuple = [], []
for i in range(0, len(train_data) - forward_days - look_back + 1):
train_x.append(train_data[i : i + look_back])
train_y.append(train_data[i + look_back : i + look_back + forward_days])
for i in range(0, len(test_data) - forward_days - look_back + 1):
test_x.append(test_data[i : i + look_back])
test_y.append(test_data[i + look_back : i + look_back + forward_days])
__magic_name__ : List[str] = np.array(train_x)
__magic_name__ : List[str] = np.array(test_x)
__magic_name__ : int = np.array([list(i.ravel()) for i in train_y])
__magic_name__ : int = np.array([list(i.ravel()) for i in test_y])
__magic_name__ : Tuple = Sequential()
model.add(LSTM(128, input_shape=(look_back, 1), return_sequences=True))
model.add(LSTM(64, input_shape=(128, 1)))
model.add(Dense(forward_days))
model.compile(loss="""mean_squared_error""", optimizer="""adam""")
__magic_name__ : int = model.fit(
x_train, y_train, epochs=150, verbose=1, shuffle=True, batch_size=4
)
__magic_name__ : int = model.predict(x_test)
| 368 | 0 |
from typing import TYPE_CHECKING
from ...utils import (
OptionalDependencyNotAvailable,
_LazyModule,
is_flax_available,
is_tf_available,
is_tokenizers_available,
is_torch_available,
is_vision_available,
)
SCREAMING_SNAKE_CASE_:List[str] = {
"""configuration_clip""": [
"""CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""",
"""CLIPConfig""",
"""CLIPOnnxConfig""",
"""CLIPTextConfig""",
"""CLIPVisionConfig""",
],
"""processing_clip""": ["""CLIPProcessor"""],
"""tokenization_clip""": ["""CLIPTokenizer"""],
}
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_:int = ["""CLIPTokenizerFast"""]
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_:List[Any] = ["""CLIPFeatureExtractor"""]
SCREAMING_SNAKE_CASE_:Any = ["""CLIPImageProcessor"""]
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_:List[Any] = [
"""CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""CLIPModel""",
"""CLIPPreTrainedModel""",
"""CLIPTextModel""",
"""CLIPTextModelWithProjection""",
"""CLIPVisionModel""",
"""CLIPVisionModelWithProjection""",
]
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_:Any = [
"""TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""TFCLIPModel""",
"""TFCLIPPreTrainedModel""",
"""TFCLIPTextModel""",
"""TFCLIPVisionModel""",
]
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
SCREAMING_SNAKE_CASE_:Tuple = [
"""FlaxCLIPModel""",
"""FlaxCLIPPreTrainedModel""",
"""FlaxCLIPTextModel""",
"""FlaxCLIPTextPreTrainedModel""",
"""FlaxCLIPVisionModel""",
"""FlaxCLIPVisionPreTrainedModel""",
]
if TYPE_CHECKING:
from .configuration_clip import (
CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP,
CLIPConfig,
CLIPOnnxConfig,
CLIPTextConfig,
CLIPVisionConfig,
)
from .processing_clip import CLIPProcessor
from .tokenization_clip import CLIPTokenizer
try:
if not is_tokenizers_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .tokenization_clip_fast import CLIPTokenizerFast
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .feature_extraction_clip import CLIPFeatureExtractor
from .image_processing_clip import CLIPImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_clip import (
CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
CLIPModel,
CLIPPreTrainedModel,
CLIPTextModel,
CLIPTextModelWithProjection,
CLIPVisionModel,
CLIPVisionModelWithProjection,
)
try:
if not is_tf_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_tf_clip import (
TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST,
TFCLIPModel,
TFCLIPPreTrainedModel,
TFCLIPTextModel,
TFCLIPVisionModel,
)
try:
if not is_flax_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_flax_clip import (
FlaxCLIPModel,
FlaxCLIPPreTrainedModel,
FlaxCLIPTextModel,
FlaxCLIPTextPreTrainedModel,
FlaxCLIPVisionModel,
FlaxCLIPVisionPreTrainedModel,
)
else:
import sys
SCREAMING_SNAKE_CASE_:List[Any] = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 662 |
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 BeitConfig, BeitForImageClassification, BeitForMaskedImageModeling, BeitImageProcessor
from transformers.image_utils import PILImageResampling
from transformers.utils import logging
logging.set_verbosity_info()
SCREAMING_SNAKE_CASE_:Tuple = logging.get_logger(__name__)
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase=False , _lowerCAmelCase=False ) -> Any:
"""simple docstring"""
A : Dict = """backbone.""" if is_semantic else """"""
A : Union[str, Any] = []
for i in range(config.num_hidden_layers ):
# encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
rename_keys.append((f'''{prefix}blocks.{i}.norm1.weight''', f'''beit.encoder.layer.{i}.layernorm_before.weight''') )
rename_keys.append((f'''{prefix}blocks.{i}.norm1.bias''', f'''beit.encoder.layer.{i}.layernorm_before.bias''') )
rename_keys.append(
(f'''{prefix}blocks.{i}.attn.proj.weight''', f'''beit.encoder.layer.{i}.attention.output.dense.weight''') )
rename_keys.append(
(f'''{prefix}blocks.{i}.attn.proj.bias''', f'''beit.encoder.layer.{i}.attention.output.dense.bias''') )
rename_keys.append((f'''{prefix}blocks.{i}.norm2.weight''', f'''beit.encoder.layer.{i}.layernorm_after.weight''') )
rename_keys.append((f'''{prefix}blocks.{i}.norm2.bias''', f'''beit.encoder.layer.{i}.layernorm_after.bias''') )
rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc1.weight''', f'''beit.encoder.layer.{i}.intermediate.dense.weight''') )
rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc1.bias''', f'''beit.encoder.layer.{i}.intermediate.dense.bias''') )
rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc2.weight''', f'''beit.encoder.layer.{i}.output.dense.weight''') )
rename_keys.append((f'''{prefix}blocks.{i}.mlp.fc2.bias''', f'''beit.encoder.layer.{i}.output.dense.bias''') )
# projection layer + position embeddings
rename_keys.extend(
[
(f'''{prefix}cls_token''', """beit.embeddings.cls_token"""),
(f'''{prefix}patch_embed.proj.weight''', """beit.embeddings.patch_embeddings.projection.weight"""),
(f'''{prefix}patch_embed.proj.bias''', """beit.embeddings.patch_embeddings.projection.bias"""),
(f'''{prefix}pos_embed''', """beit.embeddings.position_embeddings"""),
] )
if has_lm_head:
# mask token + layernorm
rename_keys.extend(
[
("""mask_token""", """beit.embeddings.mask_token"""),
("""norm.weight""", """layernorm.weight"""),
("""norm.bias""", """layernorm.bias"""),
] )
else:
# layernorm + classification head
rename_keys.extend(
[
("""fc_norm.weight""", """beit.pooler.layernorm.weight"""),
("""fc_norm.bias""", """beit.pooler.layernorm.bias"""),
("""head.weight""", """classifier.weight"""),
("""head.bias""", """classifier.bias"""),
] )
return rename_keys
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False , _lowerCAmelCase=False ) -> Any:
"""simple docstring"""
for i in range(config.num_hidden_layers ):
A : Dict = """backbone.""" if is_semantic else """"""
# queries, keys and values
A : Union[str, Any] = state_dict.pop(f'''{prefix}blocks.{i}.attn.qkv.weight''' )
A : Tuple = state_dict.pop(f'''{prefix}blocks.{i}.attn.q_bias''' )
A : Optional[int] = state_dict.pop(f'''{prefix}blocks.{i}.attn.v_bias''' )
A : int = in_proj_weight[
: config.hidden_size, :
]
A : Any = q_bias
A : Tuple = in_proj_weight[
config.hidden_size : config.hidden_size * 2, :
]
A : Tuple = in_proj_weight[
-config.hidden_size :, :
]
A : Union[str, Any] = v_bias
# gamma_1 and gamma_2
# we call them lambda because otherwise they are renamed when using .from_pretrained
A : str = state_dict.pop(f'''{prefix}blocks.{i}.gamma_1''' )
A : List[Any] = state_dict.pop(f'''{prefix}blocks.{i}.gamma_2''' )
A : Dict = gamma_a
A : Dict = gamma_a
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> Dict:
"""simple docstring"""
A : List[str] = dct.pop(_lowerCAmelCase )
A : Optional[Any] = val
def __UpperCamelCase ( ) -> List[str]:
"""simple docstring"""
A : int = """http://images.cocodataset.org/val2017/000000039769.jpg"""
A : Optional[Any] = Image.open(requests.get(_lowerCAmelCase , stream=_lowerCAmelCase ).raw )
return im
@torch.no_grad()
def __UpperCamelCase ( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase=False ) -> str:
"""simple docstring"""
A : Dict = False if """rvlcdip""" in checkpoint_url else True
A : Union[str, Any] = BeitConfig(use_absolute_position_embeddings=_lowerCAmelCase , use_mask_token=_lowerCAmelCase )
# size of the architecture
if "large" in checkpoint_url or "dit-l" in checkpoint_url:
A : Dict = 1024
A : List[Any] = 4096
A : int = 24
A : int = 16
# labels
if "rvlcdip" in checkpoint_url:
A : List[Any] = 16
A : List[Any] = """huggingface/label-files"""
A : int = """rvlcdip-id2label.json"""
A : Dict = json.load(open(hf_hub_download(_lowerCAmelCase , _lowerCAmelCase , repo_type="""dataset""" ) , """r""" ) )
A : List[str] = {int(_lowerCAmelCase ): v for k, v in idalabel.items()}
A : int = idalabel
A : Union[str, Any] = {v: k for k, v in idalabel.items()}
# load state_dict of original model, remove and rename some keys
A : List[str] = torch.hub.load_state_dict_from_url(_lowerCAmelCase , map_location="""cpu""" )["""model"""]
A : str = create_rename_keys(_lowerCAmelCase , has_lm_head=_lowerCAmelCase )
for src, dest in rename_keys:
rename_key(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase )
read_in_q_k_v(_lowerCAmelCase , _lowerCAmelCase , has_lm_head=_lowerCAmelCase )
# load HuggingFace model
A : Any = BeitForMaskedImageModeling(_lowerCAmelCase ) if has_lm_head else BeitForImageClassification(_lowerCAmelCase )
model.eval()
model.load_state_dict(_lowerCAmelCase )
# Check outputs on an image
A : Any = BeitImageProcessor(
size=config.image_size , resample=PILImageResampling.BILINEAR , do_center_crop=_lowerCAmelCase )
A : int = prepare_img()
A : Tuple = image_processor(images=_lowerCAmelCase , return_tensors="""pt""" )
A : str = encoding["""pixel_values"""]
A : Tuple = model(_lowerCAmelCase )
A : Optional[int] = outputs.logits
# verify logits
A : Tuple = [1, 16] if """rvlcdip""" in checkpoint_url else [1, 196, 8192]
assert logits.shape == torch.Size(_lowerCAmelCase ), "Shape of logits not as expected"
Path(_lowerCAmelCase ).mkdir(exist_ok=_lowerCAmelCase )
print(f'''Saving model to {pytorch_dump_folder_path}''' )
model.save_pretrained(_lowerCAmelCase )
print(f'''Saving image processor to {pytorch_dump_folder_path}''' )
image_processor.save_pretrained(_lowerCAmelCase )
if push_to_hub:
if has_lm_head:
A : Any = """dit-base""" if """base""" in checkpoint_url else """dit-large"""
else:
A : List[Any] = """dit-base-finetuned-rvlcdip""" if """dit-b""" in checkpoint_url else """dit-large-finetuned-rvlcdip"""
image_processor.push_to_hub(
repo_path_or_name=Path(_lowerCAmelCase , _lowerCAmelCase ) , organization="""nielsr""" , commit_message="""Add image processor""" , use_temp_dir=_lowerCAmelCase , )
model.push_to_hub(
repo_path_or_name=Path(_lowerCAmelCase , _lowerCAmelCase ) , organization="""nielsr""" , commit_message="""Add model""" , use_temp_dir=_lowerCAmelCase , )
if __name__ == "__main__":
SCREAMING_SNAKE_CASE_:Optional[int] = argparse.ArgumentParser()
parser.add_argument(
"""--checkpoint_url""",
default="""https://layoutlm.blob.core.windows.net/dit/dit-pts/dit-base-224-p16-500k-62d53a.pth""",
type=str,
help="""URL to the original PyTorch checkpoint (.pth file).""",
)
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""",
)
SCREAMING_SNAKE_CASE_:Optional[Any] = parser.parse_args()
convert_dit_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
| 662 | 1 |
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : list[list[int]] ) -> int:
def update_area_of_max_square(UpperCAmelCase_ : int , UpperCAmelCase_ : int ) -> int:
# BASE CASE
if row >= rows or col >= cols:
return 0
SCREAMING_SNAKE_CASE_ : Any =update_area_of_max_square(UpperCAmelCase_ , col + 1 )
SCREAMING_SNAKE_CASE_ : List[str] =update_area_of_max_square(row + 1 , col + 1 )
SCREAMING_SNAKE_CASE_ : Optional[Any] =update_area_of_max_square(row + 1 , UpperCAmelCase_ )
if mat[row][col]:
SCREAMING_SNAKE_CASE_ : Tuple =1 + min([right, diagonal, down] )
SCREAMING_SNAKE_CASE_ : Optional[int] =max(largest_square_area[0] , UpperCAmelCase_ )
return sub_problem_sol
else:
return 0
SCREAMING_SNAKE_CASE_ : Optional[Any] =[0]
update_area_of_max_square(0 , 0 )
return largest_square_area[0]
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : list[list[int]] ) -> int:
def update_area_of_max_square_using_dp_array(
UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : list[list[int]] ) -> int:
if row >= rows or col >= cols:
return 0
if dp_array[row][col] != -1:
return dp_array[row][col]
SCREAMING_SNAKE_CASE_ : Dict =update_area_of_max_square_using_dp_array(UpperCAmelCase_ , col + 1 , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE_ : Tuple =update_area_of_max_square_using_dp_array(row + 1 , col + 1 , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE_ : Union[str, Any] =update_area_of_max_square_using_dp_array(row + 1 , UpperCAmelCase_ , UpperCAmelCase_ )
if mat[row][col]:
SCREAMING_SNAKE_CASE_ : Union[str, Any] =1 + min([right, diagonal, down] )
SCREAMING_SNAKE_CASE_ : Union[str, Any] =max(largest_square_area[0] , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE_ : Optional[Any] =sub_problem_sol
return sub_problem_sol
else:
return 0
SCREAMING_SNAKE_CASE_ : int =[0]
SCREAMING_SNAKE_CASE_ : Union[str, Any] =[[-1] * cols for _ in range(UpperCAmelCase_ )]
update_area_of_max_square_using_dp_array(0 , 0 , UpperCAmelCase_ )
return largest_square_area[0]
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : list[list[int]] ) -> int:
SCREAMING_SNAKE_CASE_ : Union[str, Any] =[[0] * (cols + 1) for _ in range(rows + 1 )]
SCREAMING_SNAKE_CASE_ : Optional[Any] =0
for row in range(rows - 1 , -1 , -1 ):
for col in range(cols - 1 , -1 , -1 ):
SCREAMING_SNAKE_CASE_ : Tuple =dp_array[row][col + 1]
SCREAMING_SNAKE_CASE_ : Tuple =dp_array[row + 1][col + 1]
SCREAMING_SNAKE_CASE_ : Tuple =dp_array[row + 1][col]
if mat[row][col] == 1:
SCREAMING_SNAKE_CASE_ : Optional[Any] =1 + min(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE_ : List[str] =max(dp_array[row][col] , UpperCAmelCase_ )
else:
SCREAMING_SNAKE_CASE_ : Optional[Any] =0
return largest_square_area
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : int , UpperCAmelCase_ : int , UpperCAmelCase_ : list[list[int]] ) -> int:
SCREAMING_SNAKE_CASE_ : int =[0] * (cols + 1)
SCREAMING_SNAKE_CASE_ : Optional[Any] =[0] * (cols + 1)
SCREAMING_SNAKE_CASE_ : Optional[int] =0
for row in range(rows - 1 , -1 , -1 ):
for col in range(cols - 1 , -1 , -1 ):
SCREAMING_SNAKE_CASE_ : Union[str, Any] =current_row[col + 1]
SCREAMING_SNAKE_CASE_ : int =next_row[col + 1]
SCREAMING_SNAKE_CASE_ : List[Any] =next_row[col]
if mat[row][col] == 1:
SCREAMING_SNAKE_CASE_ : List[Any] =1 + min(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE_ : str =max(current_row[col] , UpperCAmelCase_ )
else:
SCREAMING_SNAKE_CASE_ : List[Any] =0
SCREAMING_SNAKE_CASE_ : List[Any] =current_row
return largest_square_area
if __name__ == "__main__":
import doctest
doctest.testmod()
print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
| 431 |
# tests directory-specific settings - this file is run automatically
# by pytest before any tests are run
import doctest
import sys
import warnings
from os.path import abspath, dirname, join
import _pytest
from transformers.testing_utils import HfDoctestModule, HfDocTestParser
# allow having multiple repository checkouts and not needing to remember to rerun
# 'pip install -e .[dev]' when switching between checkouts and running tests.
_lowercase = abspath(join(dirname(__file__), """src"""))
sys.path.insert(1, git_repo_path)
# silence FutureWarning warnings in tests since often we can't act on them until
# they become normal warnings - i.e. the tests still need to test the current functionality
warnings.simplefilter(action="""ignore""", category=FutureWarning)
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : Union[str, Any] ) -> Optional[int]:
config.addinivalue_line(
'''markers''' , '''is_pt_tf_cross_test: mark test to run only when PT and TF interactions are tested''' )
config.addinivalue_line(
'''markers''' , '''is_pt_flax_cross_test: mark test to run only when PT and FLAX interactions are tested''' )
config.addinivalue_line('''markers''' , '''is_pipeline_test: mark test to run only when pipelines are tested''' )
config.addinivalue_line('''markers''' , '''is_staging_test: mark test to run only in the staging environment''' )
config.addinivalue_line('''markers''' , '''accelerate_tests: mark test that require accelerate''' )
config.addinivalue_line('''markers''' , '''tool_tests: mark the tool tests that are run on their specific schedule''' )
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : List[Any] ) -> List[str]:
from transformers.testing_utils import pytest_addoption_shared
pytest_addoption_shared(UpperCAmelCase_ )
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : Dict ) -> Optional[int]:
from transformers.testing_utils import pytest_terminal_summary_main
SCREAMING_SNAKE_CASE_ : List[Any] =terminalreporter.config.getoption('''--make-reports''' )
if make_reports:
pytest_terminal_summary_main(UpperCAmelCase_ , id=UpperCAmelCase_ )
def SCREAMING_SNAKE_CASE_ ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Optional[int] ) -> int:
# If no tests are collected, pytest exists with code 5, which makes the CI fail.
if exitstatus == 5:
SCREAMING_SNAKE_CASE_ : Union[str, Any] =0
# Doctest custom flag to ignore output.
_lowercase = doctest.register_optionflag("""IGNORE_RESULT""")
_lowercase = doctest.OutputChecker
class lowercase_ ( A ):
def _snake_case ( self , __A , __A , __A ) -> List[Any]:
if IGNORE_RESULT & optionflags:
return True
return OutputChecker.check_output(self , __A , __A , __A )
_lowercase = CustomOutputChecker
_lowercase = HfDoctestModule
_lowercase = HfDocTestParser
| 431 | 1 |
"""simple docstring"""
from math import atan, cos, radians, sin, tan
from .haversine_distance import haversine_distance
a :str = 637_8137.0
a :Optional[Any] = 635_6752.31_4245
a :List[Any] = 6_378_137
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> float:
SCREAMING_SNAKE_CASE__ : Dict = (AXIS_A - AXIS_B) / AXIS_A
# Parametric latitudes
# https://en.wikipedia.org/wiki/Latitude#Parametric_(or_reduced)_latitude
SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) )
SCREAMING_SNAKE_CASE__ : Dict = atan((1 - flattening) * tan(radians(__lowerCAmelCase ) ) )
# Compute central angle between two points
# using haversine theta. sigma = haversine_distance / equatorial radius
SCREAMING_SNAKE_CASE__ : Tuple = haversine_distance(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) / EQUATORIAL_RADIUS
# Intermediate P and Q values
SCREAMING_SNAKE_CASE__ : List[str] = (b_lata + b_lata) / 2
SCREAMING_SNAKE_CASE__ : Dict = (b_lata - b_lata) / 2
# Intermediate X value
# X = (sigma - sin(sigma)) * sin^2Pcos^2Q / cos^2(sigma/2)
SCREAMING_SNAKE_CASE__ : Tuple = (sin(__lowerCAmelCase ) ** 2) * (cos(__lowerCAmelCase ) ** 2)
SCREAMING_SNAKE_CASE__ : str = cos(sigma / 2 ) ** 2
SCREAMING_SNAKE_CASE__ : List[str] = (sigma - sin(__lowerCAmelCase )) * (x_numerator / x_demonimator)
# Intermediate Y value
# Y = (sigma + sin(sigma)) * cos^2Psin^2Q / sin^2(sigma/2)
SCREAMING_SNAKE_CASE__ : int = (cos(__lowerCAmelCase ) ** 2) * (sin(__lowerCAmelCase ) ** 2)
SCREAMING_SNAKE_CASE__ : int = sin(sigma / 2 ) ** 2
SCREAMING_SNAKE_CASE__ : Optional[Any] = (sigma + sin(__lowerCAmelCase )) * (y_numerator / y_denominator)
return EQUATORIAL_RADIUS * (sigma - ((flattening / 2) * (x_value + y_value)))
if __name__ == "__main__":
import doctest
doctest.testmod()
| 680 |
"""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()
a :Any = logging.get_logger(__name__)
# here we list all keys to be renamed (original name on the left, our name on the right)
a :str = []
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 _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> str:
SCREAMING_SNAKE_CASE__ : Tuple = state_dict.pop(__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = val
def _lowercase ( __lowerCAmelCase ) -> Tuple:
SCREAMING_SNAKE_CASE__ : str = OrderedDict()
for key, value in state_dict.items():
if "backbone.0.body" in key:
SCREAMING_SNAKE_CASE__ : List[Any] = key.replace("""backbone.0.body""" , """backbone.conv_encoder.model""" )
SCREAMING_SNAKE_CASE__ : Dict = value
else:
SCREAMING_SNAKE_CASE__ : Tuple = value
return new_state_dict
def _lowercase ( __lowerCAmelCase ) -> int:
SCREAMING_SNAKE_CASE__ : str = """"""
# 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)
SCREAMING_SNAKE_CASE__ : Any = state_dict.pop(F'''{prefix}transformer.encoder.layers.{i}.self_attn.in_proj_weight''' )
SCREAMING_SNAKE_CASE__ : int = 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
SCREAMING_SNAKE_CASE__ : int = in_proj_weight[:256, :]
SCREAMING_SNAKE_CASE__ : Any = in_proj_bias[:256]
SCREAMING_SNAKE_CASE__ : Dict = in_proj_weight[256:512, :]
SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[256:512]
SCREAMING_SNAKE_CASE__ : int = in_proj_weight[-256:, :]
SCREAMING_SNAKE_CASE__ : List[Any] = in_proj_bias[-256:]
# next: transformer decoder (which is a bit more complex because it also includes cross-attention)
for i in range(6 ):
# read in weights + bias of input projection layer of self-attention
SCREAMING_SNAKE_CASE__ : List[str] = state_dict.pop(F'''{prefix}transformer.decoder.layers.{i}.self_attn.in_proj_weight''' )
SCREAMING_SNAKE_CASE__ : Tuple = 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
SCREAMING_SNAKE_CASE__ : Any = in_proj_weight[:256, :]
SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias[:256]
SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight[256:512, :]
SCREAMING_SNAKE_CASE__ : Tuple = in_proj_bias[256:512]
SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_weight[-256:, :]
SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias[-256:]
# read in weights + bias of input projection layer of cross-attention
SCREAMING_SNAKE_CASE__ : Optional[Any] = state_dict.pop(
F'''{prefix}transformer.decoder.layers.{i}.multihead_attn.in_proj_weight''' )
SCREAMING_SNAKE_CASE__ : List[Any] = 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
SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[:256, :]
SCREAMING_SNAKE_CASE__ : List[str] = in_proj_bias_cross_attn[:256]
SCREAMING_SNAKE_CASE__ : Optional[Any] = in_proj_weight_cross_attn[256:512, :]
SCREAMING_SNAKE_CASE__ : Optional[int] = in_proj_bias_cross_attn[256:512]
SCREAMING_SNAKE_CASE__ : int = in_proj_weight_cross_attn[-256:, :]
SCREAMING_SNAKE_CASE__ : Dict = in_proj_bias_cross_attn[-256:]
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase ) -> Optional[int]:
SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ : Optional[int] = image.size
SCREAMING_SNAKE_CASE__ : Optional[Any] = max(__lowerCAmelCase , __lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Dict = 800 if """detection""" in checkpoint_url else 1000
SCREAMING_SNAKE_CASE__ : List[str] = target_max_size / current_max_size
SCREAMING_SNAKE_CASE__ : str = image.resize((int(round(scale * width ) ), int(round(scale * height ) )) )
return resized_image
def _lowercase ( __lowerCAmelCase ) -> Union[str, Any]:
SCREAMING_SNAKE_CASE__ : Optional[int] = F.to_tensor(__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : List[str] = F.normalize(__lowerCAmelCase , mean=[0.485, 0.456, 0.406] , std=[0.229, 0.224, 0.225] )
return image
@torch.no_grad()
def _lowercase ( __lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase ) -> Optional[Any]:
logger.info("""Converting model...""" )
# load original state dict
SCREAMING_SNAKE_CASE__ : str = torch.hub.load_state_dict_from_url(__lowerCAmelCase , map_location="""cpu""" )
# rename keys
for src, dest in rename_keys:
rename_key(__lowerCAmelCase , __lowerCAmelCase , __lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Optional[int] = rename_backbone_keys(__lowerCAmelCase )
# query, key and value matrices need special treatment
read_in_q_k_v(__lowerCAmelCase )
# important: we need to prepend a prefix to each of the base model keys as the head models use different attributes for them
SCREAMING_SNAKE_CASE__ : Optional[int] = """model."""
for key in state_dict.copy().keys():
if not key.startswith("""class_labels_classifier""" ) and not key.startswith("""bbox_predictor""" ):
SCREAMING_SNAKE_CASE__ : Optional[int] = state_dict.pop(__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : List[str] = val
# create HuggingFace model and load state dict
SCREAMING_SNAKE_CASE__ : Tuple = 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:
SCREAMING_SNAKE_CASE__ : Optional[int] = 15
SCREAMING_SNAKE_CASE__ : Any = 2
SCREAMING_SNAKE_CASE__ : str = {0: """table""", 1: """table rotated"""}
SCREAMING_SNAKE_CASE__ : Union[str, Any] = idalabel
SCREAMING_SNAKE_CASE__ : List[str] = {v: k for k, v in idalabel.items()}
else:
SCREAMING_SNAKE_CASE__ : Tuple = 125
SCREAMING_SNAKE_CASE__ : str = 6
SCREAMING_SNAKE_CASE__ : List[Any] = {
0: """table""",
1: """table column""",
2: """table row""",
3: """table column header""",
4: """table projected row header""",
5: """table spanning cell""",
}
SCREAMING_SNAKE_CASE__ : Any = idalabel
SCREAMING_SNAKE_CASE__ : Dict = {v: k for k, v in idalabel.items()}
SCREAMING_SNAKE_CASE__ : Dict = DetrImageProcessor(
format="""coco_detection""" , max_size=800 if """detection""" in checkpoint_url else 1000 )
SCREAMING_SNAKE_CASE__ : Tuple = TableTransformerForObjectDetection(__lowerCAmelCase )
model.load_state_dict(__lowerCAmelCase )
model.eval()
# verify our conversion
SCREAMING_SNAKE_CASE__ : Dict = """example_pdf.png""" if """detection""" in checkpoint_url else """example_table.png"""
SCREAMING_SNAKE_CASE__ : Tuple = hf_hub_download(repo_id="""nielsr/example-pdf""" , repo_type="""dataset""" , filename=__lowerCAmelCase )
SCREAMING_SNAKE_CASE__ : Any = Image.open(__lowerCAmelCase ).convert("""RGB""" )
SCREAMING_SNAKE_CASE__ : Union[str, Any] = normalize(resize(__lowerCAmelCase , __lowerCAmelCase ) ).unsqueeze(0 )
SCREAMING_SNAKE_CASE__ : Dict = model(__lowerCAmelCase )
if "detection" in checkpoint_url:
SCREAMING_SNAKE_CASE__ : List[Any] = (1, 15, 3)
SCREAMING_SNAKE_CASE__ : str = torch.tensor(
[[-6.7_897, -16.9_985, 6.7_937], [-8.0_186, -22.2_192, 6.9_677], [-7.3_117, -21.0_708, 7.4_055]] )
SCREAMING_SNAKE_CASE__ : str = torch.tensor([[0.4_867, 0.1_767, 0.6_732], [0.6_718, 0.4_479, 0.3_830], [0.4_716, 0.1_760, 0.6_364]] )
else:
SCREAMING_SNAKE_CASE__ : Dict = (1, 125, 7)
SCREAMING_SNAKE_CASE__ : Any = torch.tensor(
[[-18.1_430, -8.3_214, 4.8_274], [-18.4_685, -7.1_361, -4.2_667], [-26.3_693, -9.3_429, -4.9_962]] )
SCREAMING_SNAKE_CASE__ : Optional[Any] = torch.tensor([[0.4_983, 0.5_595, 0.9_440], [0.4_916, 0.6_315, 0.5_954], [0.6_108, 0.8_637, 0.1_135]] )
assert outputs.logits.shape == expected_shape
assert torch.allclose(outputs.logits[0, :3, :3] , __lowerCAmelCase , atol=1E-4 )
assert torch.allclose(outputs.pred_boxes[0, :3, :3] , __lowerCAmelCase , 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(__lowerCAmelCase ).mkdir(exist_ok=__lowerCAmelCase )
model.save_pretrained(__lowerCAmelCase )
image_processor.save_pretrained(__lowerCAmelCase )
if push_to_hub:
# Push model to HF hub
logger.info("""Pushing model to the hub...""" )
SCREAMING_SNAKE_CASE__ : List[Any] = (
"""microsoft/table-transformer-detection"""
if """detection""" in checkpoint_url
else """microsoft/table-transformer-structure-recognition"""
)
model.push_to_hub(__lowerCAmelCase )
image_processor.push_to_hub(__lowerCAmelCase )
if __name__ == "__main__":
a :Any = 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."
)
a :int = parser.parse_args()
convert_table_transformer_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path, args.push_to_hub)
| 680 | 1 |
from pathlib import Path
from typing import List
from transformers import is_torch_available, is_vision_available
from transformers.testing_utils import get_tests_dir, is_tool_test
from transformers.tools.agent_types import AGENT_TYPE_MAPPING, AgentAudio, AgentImage, AgentText
if is_torch_available():
import torch
if is_vision_available():
from PIL import Image
snake_case_ = ['text', 'image', 'audio']
def lowerCamelCase__ ( snake_case_ : List[str] ) -> Dict:
__snake_case = []
for input_type in input_types:
if input_type == "text":
inputs.append('''Text input''' )
elif input_type == "image":
inputs.append(
Image.open(Path(get_tests_dir('''fixtures/tests_samples/COCO''' ) ) / '''000000039769.png''' ).resize((512, 512) ) )
elif input_type == "audio":
inputs.append(torch.ones(3000 ) )
elif isinstance(snake_case_ , snake_case_ ):
inputs.append(create_inputs(snake_case_ ) )
else:
raise ValueError(f"""Invalid type requested: {input_type}""" )
return inputs
def lowerCamelCase__ ( snake_case_ : List ) -> int:
__snake_case = []
for output in outputs:
if isinstance(snake_case_ , (str, AgentText) ):
output_types.append('''text''' )
elif isinstance(snake_case_ , (Image.Image, AgentImage) ):
output_types.append('''image''' )
elif isinstance(snake_case_ , (torch.Tensor, AgentAudio) ):
output_types.append('''audio''' )
else:
raise ValueError(f"""Invalid output: {output}""" )
return output_types
@is_tool_test
class SCREAMING_SNAKE_CASE__ :
def a (self : List[str] ):
"""simple docstring"""
self.assertTrue(hasattr(self.tool , '''inputs''' ) )
self.assertTrue(hasattr(self.tool , '''outputs''' ) )
__snake_case = self.tool.inputs
for _input in inputs:
if isinstance(_input , a__ ):
for __input in _input:
self.assertTrue(__input in authorized_types )
else:
self.assertTrue(_input in authorized_types )
__snake_case = self.tool.outputs
for _output in outputs:
self.assertTrue(_output in authorized_types )
def a (self : Union[str, Any] ):
"""simple docstring"""
__snake_case = create_inputs(self.tool.inputs )
__snake_case = self.tool(*a__ )
# There is a single output
if len(self.tool.outputs ) == 1:
__snake_case = [outputs]
self.assertListEqual(output_types(a__ ) , self.tool.outputs )
def a (self : Tuple ):
"""simple docstring"""
self.assertTrue(hasattr(self.tool , '''description''' ) )
self.assertTrue(hasattr(self.tool , '''default_checkpoint''' ) )
self.assertTrue(self.tool.description.startswith('''This is a tool that''' ) )
def a (self : Dict ):
"""simple docstring"""
__snake_case = create_inputs(self.tool.inputs )
__snake_case = self.tool(*a__ )
if not isinstance(a__ , a__ ):
__snake_case = [outputs]
self.assertEqual(len(a__ ) , len(self.tool.outputs ) )
for output, output_type in zip(a__ , self.tool.outputs ):
__snake_case = AGENT_TYPE_MAPPING[output_type]
self.assertTrue(isinstance(a__ , a__ ) )
def a (self : int ):
"""simple docstring"""
__snake_case = create_inputs(self.tool.inputs )
__snake_case = []
for _input, input_type in zip(a__ , self.tool.inputs ):
if isinstance(a__ , a__ ):
_inputs.append([AGENT_TYPE_MAPPING[_input_type](_input ) for _input_type in input_type] )
else:
_inputs.append(AGENT_TYPE_MAPPING[input_type](_input ) )
# Should not raise an error
__snake_case = self.tool(*a__ )
if not isinstance(a__ , a__ ):
__snake_case = [outputs]
self.assertEqual(len(a__ ) , len(self.tool.outputs ) )
| 388 |
import collections
import inspect
import unittest
from transformers import SwinvaConfig
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, _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 SwinvaForImageClassification, SwinvaForMaskedImageModeling, SwinvaModel
from transformers.models.swinva.modeling_swinva import SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST
if is_vision_available():
from PIL import Image
from transformers import AutoImageProcessor
class SCREAMING_SNAKE_CASE__ :
def __init__(self : List[Any] , a__ : Union[str, Any] , a__ : Any=13 , a__ : List[str]=32 , a__ : Union[str, Any]=2 , a__ : int=3 , a__ : Tuple=16 , a__ : Dict=[1, 2, 1] , a__ : Any=[2, 2, 4] , a__ : Optional[int]=2 , a__ : List[Any]=2.0 , a__ : Any=True , a__ : Optional[Any]=0.0 , a__ : Union[str, Any]=0.0 , a__ : Optional[Any]=0.1 , a__ : Any="gelu" , a__ : Optional[int]=False , a__ : Union[str, Any]=True , a__ : List[Any]=0.0_2 , a__ : int=1E-5 , a__ : int=True , a__ : str=None , a__ : Union[str, Any]=True , a__ : Any=10 , a__ : str=8 , ):
"""simple docstring"""
__snake_case = parent
__snake_case = batch_size
__snake_case = image_size
__snake_case = patch_size
__snake_case = num_channels
__snake_case = embed_dim
__snake_case = depths
__snake_case = num_heads
__snake_case = window_size
__snake_case = mlp_ratio
__snake_case = qkv_bias
__snake_case = hidden_dropout_prob
__snake_case = attention_probs_dropout_prob
__snake_case = drop_path_rate
__snake_case = hidden_act
__snake_case = use_absolute_embeddings
__snake_case = patch_norm
__snake_case = layer_norm_eps
__snake_case = initializer_range
__snake_case = is_training
__snake_case = scope
__snake_case = use_labels
__snake_case = type_sequence_label_size
__snake_case = encoder_stride
def a (self : List[Any] ):
"""simple docstring"""
__snake_case = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )
__snake_case = None
if self.use_labels:
__snake_case = ids_tensor([self.batch_size] , self.type_sequence_label_size )
__snake_case = self.get_config()
return config, pixel_values, labels
def a (self : Dict ):
"""simple docstring"""
return SwinvaConfig(
image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , embed_dim=self.embed_dim , depths=self.depths , num_heads=self.num_heads , window_size=self.window_size , mlp_ratio=self.mlp_ratio , qkv_bias=self.qkv_bias , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , drop_path_rate=self.drop_path_rate , hidden_act=self.hidden_act , use_absolute_embeddings=self.use_absolute_embeddings , path_norm=self.patch_norm , layer_norm_eps=self.layer_norm_eps , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , )
def a (self : Union[str, Any] , a__ : List[Any] , a__ : str , a__ : Optional[int] ):
"""simple docstring"""
__snake_case = SwinvaModel(config=a__ )
model.to(a__ )
model.eval()
__snake_case = model(a__ )
__snake_case = ((config.image_size // config.patch_size) ** 2) // (4 ** (len(config.depths ) - 1))
__snake_case = int(config.embed_dim * 2 ** (len(config.depths ) - 1) )
self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, expected_seq_len, expected_dim) )
def a (self : str , a__ : int , a__ : Tuple , a__ : Union[str, Any] ):
"""simple docstring"""
__snake_case = SwinvaForMaskedImageModeling(config=a__ )
model.to(a__ )
model.eval()
__snake_case = model(a__ )
self.parent.assertEqual(
result.logits.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) )
# test greyscale images
__snake_case = 1
__snake_case = SwinvaForMaskedImageModeling(a__ )
model.to(a__ )
model.eval()
__snake_case = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] )
__snake_case = model(a__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, 1, self.image_size, self.image_size) )
def a (self : Any , a__ : int , a__ : Dict , a__ : Tuple ):
"""simple docstring"""
__snake_case = self.type_sequence_label_size
__snake_case = SwinvaForImageClassification(a__ )
model.to(a__ )
model.eval()
__snake_case = model(a__ , labels=a__ )
self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) )
def a (self : Union[str, Any] ):
"""simple docstring"""
__snake_case = self.prepare_config_and_inputs()
__snake_case , __snake_case , __snake_case = config_and_inputs
__snake_case = {'''pixel_values''': pixel_values}
return config, inputs_dict
@require_torch
class SCREAMING_SNAKE_CASE__ ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ):
A_ : Dict = (
(SwinvaModel, SwinvaForImageClassification, SwinvaForMaskedImageModeling) if is_torch_available() else ()
)
A_ : int = (
{'feature-extraction': SwinvaModel, 'image-classification': SwinvaForImageClassification}
if is_torch_available()
else {}
)
A_ : Dict = False
A_ : Dict = False
A_ : Dict = False
A_ : List[Any] = False
def a (self : Optional[int] ):
"""simple docstring"""
__snake_case = SwinvaModelTester(self )
__snake_case = ConfigTester(self , config_class=a__ , embed_dim=37 )
def a (self : Optional[int] ):
"""simple docstring"""
self.config_tester.create_and_test_config_to_json_string()
self.config_tester.create_and_test_config_to_json_file()
self.config_tester.create_and_test_config_from_and_save_pretrained()
self.config_tester.create_and_test_config_with_num_labels()
self.config_tester.check_config_can_be_init_without_params()
self.config_tester.check_config_arguments_init()
def a (self : Any ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_model(*a__ )
@unittest.skip(reason='''Got `CUDA error: misaligned address` with PyTorch 2.0.0.''' )
def a (self : str ):
"""simple docstring"""
pass
@unittest.skip(reason='''Swinv2 does not use inputs_embeds''' )
def a (self : str ):
"""simple docstring"""
pass
def a (self : Any ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = model_class(a__ )
self.assertIsInstance(model.get_input_embeddings() , (nn.Module) )
__snake_case = model.get_output_embeddings()
self.assertTrue(x is None or isinstance(a__ , nn.Linear ) )
def a (self : List[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
__snake_case = model_class(a__ )
__snake_case = inspect.signature(model.forward )
# signature.parameters is an OrderedDict => so arg_names order is deterministic
__snake_case = [*signature.parameters.keys()]
__snake_case = ['''pixel_values''']
self.assertListEqual(arg_names[:1] , a__ )
def a (self : str ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = True
for model_class in self.all_model_classes:
__snake_case = True
__snake_case = False
__snake_case = True
__snake_case = model_class(a__ )
model.to(a__ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a__ , a__ ) )
__snake_case = outputs.attentions
__snake_case = len(self.model_tester.depths )
self.assertEqual(len(a__ ) , a__ )
# check that output_attentions also work using config
del inputs_dict["output_attentions"]
__snake_case = True
__snake_case = config.window_size**2
__snake_case = model_class(a__ )
model.to(a__ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a__ , a__ ) )
__snake_case = outputs.attentions
self.assertEqual(len(a__ ) , a__ )
self.assertListEqual(
list(attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , )
__snake_case = len(a__ )
# Check attention is always last and order is fine
__snake_case = True
__snake_case = True
__snake_case = model_class(a__ )
model.to(a__ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a__ , a__ ) )
if hasattr(self.model_tester , '''num_hidden_states_types''' ):
__snake_case = self.model_tester.num_hidden_states_types
else:
# also another +1 for reshaped_hidden_states
__snake_case = 2
self.assertEqual(out_len + added_hidden_states , len(a__ ) )
__snake_case = outputs.attentions
self.assertEqual(len(a__ ) , a__ )
self.assertListEqual(
list(self_attentions[0].shape[-3:] ) , [self.model_tester.num_heads[0], window_size_squared, window_size_squared] , )
def a (self : Dict , a__ : int , a__ : List[str] , a__ : List[Any] , a__ : Dict ):
"""simple docstring"""
__snake_case = model_class(a__ )
model.to(a__ )
model.eval()
with torch.no_grad():
__snake_case = model(**self._prepare_for_class(a__ , a__ ) )
__snake_case = outputs.hidden_states
__snake_case = getattr(
self.model_tester , '''expected_num_hidden_layers''' , len(self.model_tester.depths ) + 1 )
self.assertEqual(len(a__ ) , a__ )
# Swinv2 has a different seq_length
__snake_case = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
__snake_case = (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] , )
__snake_case = outputs.reshaped_hidden_states
self.assertEqual(len(a__ ) , a__ )
__snake_case , __snake_case , __snake_case , __snake_case = reshaped_hidden_states[0].shape
__snake_case = (
reshaped_hidden_states[0].view(a__ , a__ , height * width ).permute(0 , 2 , 1 )
)
self.assertListEqual(
list(reshaped_hidden_states.shape[-2:] ) , [num_patches, self.model_tester.embed_dim] , )
def a (self : Optional[Any] ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = (
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:
__snake_case = True
self.check_hidden_states_output(a__ , a__ , a__ , a__ )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case = True
self.check_hidden_states_output(a__ , a__ , a__ , a__ )
def a (self : int ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = 3
__snake_case = (
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)
)
__snake_case = (
config.patch_size
if isinstance(config.patch_size , collections.abc.Iterable )
else (config.patch_size, config.patch_size)
)
__snake_case = image_size[0] + patch_size[0] - (image_size[0] % patch_size[0])
__snake_case = image_size[1] + patch_size[1] - (image_size[1] % patch_size[1])
for model_class in self.all_model_classes:
__snake_case = True
self.check_hidden_states_output(a__ , a__ , a__ , (padded_height, padded_width) )
# check that output_hidden_states also work using config
del inputs_dict["output_hidden_states"]
__snake_case = True
self.check_hidden_states_output(a__ , a__ , a__ , (padded_height, padded_width) )
def a (self : Optional[int] ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_masked_image_modeling(*a__ )
def a (self : Dict ):
"""simple docstring"""
__snake_case = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_for_image_classification(*a__ )
@slow
def a (self : List[str] ):
"""simple docstring"""
for model_name in SWINV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
__snake_case = SwinvaModel.from_pretrained(a__ )
self.assertIsNotNone(a__ )
def a (self : Dict ):
"""simple docstring"""
__snake_case , __snake_case = self.model_tester.prepare_config_and_inputs_for_common()
__snake_case = _config_zero_init(a__ )
for model_class in self.all_model_classes:
__snake_case = model_class(config=a__ )
for name, param in model.named_parameters():
if "embeddings" not in name and "logit_scale" 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 SCREAMING_SNAKE_CASE__ ( unittest.TestCase ):
@cached_property
def a (self : Dict ):
"""simple docstring"""
return (
AutoImageProcessor.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' )
if is_vision_available()
else None
)
@slow
def a (self : Dict ):
"""simple docstring"""
__snake_case = SwinvaForImageClassification.from_pretrained('''microsoft/swinv2-tiny-patch4-window8-256''' ).to(
a__ )
__snake_case = self.default_image_processor
__snake_case = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
__snake_case = image_processor(images=a__ , return_tensors='''pt''' ).to(a__ )
# forward pass
with torch.no_grad():
__snake_case = model(**a__ )
# verify the logits
__snake_case = torch.Size((1, 1000) )
self.assertEqual(outputs.logits.shape , a__ )
__snake_case = torch.tensor([-0.3_9_4_7, -0.4_3_0_6, 0.0_0_2_6] ).to(a__ )
self.assertTrue(torch.allclose(outputs.logits[0, :3] , a__ , atol=1E-4 ) )
| 388 | 1 |
'''simple docstring'''
from __future__ import annotations
from collections.abc import Callable
lowercase : Union[str, Any] = list[list[float | int]]
def lowerCAmelCase_ ( snake_case__ , snake_case__ ):
'''simple docstring'''
A : int = len(snake_case__ )
A : Matrix = [[0 for _ in range(size + 1 )] for _ in range(snake_case__ )]
A : int
A : int
A : int
A : int
A : int
A : float
for row in range(snake_case__ ):
for col in range(snake_case__ ):
A : Union[str, Any] = matrix[row][col]
A : List[str] = vector[row][0]
A : Optional[Any] = 0
A : Union[str, Any] = 0
while row < size and col < size:
# pivoting
A : Optional[Any] = max((abs(augmented[rowa][col] ), rowa) for rowa in range(snake_case__ , snake_case__ ) )[
1
]
if augmented[pivot_row][col] == 0:
col += 1
continue
else:
A, A : Any = augmented[pivot_row], augmented[row]
for rowa in range(row + 1 , snake_case__ ):
A : Optional[Any] = augmented[rowa][col] / augmented[row][col]
A : int = 0
for cola in range(col + 1 , size + 1 ):
augmented[rowa][cola] -= augmented[row][cola] * ratio
row += 1
col += 1
# back substitution
for col in range(1 , snake_case__ ):
for row in range(snake_case__ ):
A : List[Any] = augmented[row][col] / augmented[col][col]
for cola in range(snake_case__ , size + 1 ):
augmented[row][cola] -= augmented[col][cola] * ratio
# round to get rid of numbers like 2.000000000000004
return [
[round(augmented[row][size] / augmented[row][row] , 10 )] for row in range(snake_case__ )
]
def lowerCAmelCase_ ( snake_case__ ):
'''simple docstring'''
A : int = len(snake_case__ )
A : Matrix = [[0 for _ in range(snake_case__ )] for _ in range(snake_case__ )]
A : Matrix = [[0] for _ in range(snake_case__ )]
A : Matrix
A : int
A : int
A : int
for x_val, y_val in enumerate(snake_case__ ):
for col in range(snake_case__ ):
A : List[str] = (x_val + 1) ** (size - col - 1)
A : List[str] = y_val
A : Union[str, Any] = solve(snake_case__ , snake_case__ )
def interpolated_func(snake_case__ ) -> int:
return sum(
round(coeffs[x_val][0] ) * (var ** (size - x_val - 1))
for x_val in range(snake_case__ ) )
return interpolated_func
def lowerCAmelCase_ ( snake_case__ ):
'''simple docstring'''
return (
1
- variable
+ variable**2
- variable**3
+ variable**4
- variable**5
+ variable**6
- variable**7
+ variable**8
- variable**9
+ variable**10
)
def lowerCAmelCase_ ( snake_case__ = question_function , snake_case__ = 10 ):
'''simple docstring'''
A : list[int] = [func(snake_case__ ) for x_val in range(1 , order + 1 )]
A : list[Callable[[int], int]] = [
interpolate(data_points[:max_coeff] ) for max_coeff in range(1 , order + 1 )
]
A : int = 0
A : Callable[[int], int]
A : int
for poly in polynomials:
A : Dict = 1
while func(snake_case__ ) == poly(snake_case__ ):
x_val += 1
ret += poly(snake_case__ )
return ret
if __name__ == "__main__":
print(f'''{solution() = }''')
| 634 |
'''simple docstring'''
def lowerCAmelCase_ ( snake_case__ ):
'''simple docstring'''
if len(snake_case__ ) <= 1:
return [tuple(snake_case__ )]
A : int = []
def generate(snake_case__ , snake_case__ ):
if k == 1:
res.append(tuple(arr[:] ) )
return
generate(k - 1 , snake_case__ )
for i in range(k - 1 ):
if k % 2 == 0: # k is even
A, A : Any = arr[k - 1], arr[i]
else: # k is odd
A, A : List[str] = arr[k - 1], arr[0]
generate(k - 1 , snake_case__ )
generate(len(snake_case__ ) , snake_case__ )
return res
if __name__ == "__main__":
lowercase : int = input('Enter numbers separated by a comma:\n').strip()
lowercase : Dict = [int(item) for item in user_input.split(',')]
print(heaps(arr))
| 634 | 1 |
from __future__ import annotations
def _a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ) -> float:
if days_between_payments <= 0:
raise ValueError('days_between_payments must be > 0' )
if daily_interest_rate < 0:
raise ValueError('daily_interest_rate must be >= 0' )
if principal <= 0:
raise ValueError('principal must be > 0' )
return principal * daily_interest_rate * days_between_payments
def _a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float:
if number_of_compounding_periods <= 0:
raise ValueError('number_of_compounding_periods must be > 0' )
if nominal_annual_interest_rate_percentage < 0:
raise ValueError('nominal_annual_interest_rate_percentage must be >= 0' )
if principal <= 0:
raise ValueError('principal must be > 0' )
return principal * (
(1 + nominal_annual_interest_rate_percentage) ** number_of_compounding_periods
- 1
)
def _a ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , ) -> float:
if number_of_years <= 0:
raise ValueError('number_of_years must be > 0' )
if nominal_annual_percentage_rate < 0:
raise ValueError('nominal_annual_percentage_rate must be >= 0' )
if principal <= 0:
raise ValueError('principal must be > 0' )
return compound_interest(
lowerCamelCase__ , nominal_annual_percentage_rate / 3_65 , number_of_years * 3_65 )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 716 |
from __future__ import annotations
import time
UpperCamelCase = list[tuple[int, int]]
UpperCamelCase = [
[0, 0, 0, 0, 0, 0, 0],
[0, 1, 0, 0, 0, 0, 0], # 0 are free path whereas 1's are obstacles
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 1, 0, 0, 0, 0],
[1, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 1, 0, 0],
]
UpperCamelCase = [[-1, 0], [0, -1], [1, 0], [0, 1]] # up, left, down, right
class lowerCamelCase__ :
def __init__(self : Union[str, Any] , _snake_case : int , _snake_case : int , _snake_case : int , _snake_case : int , _snake_case : Node | None ) -> List[str]:
"""simple docstring"""
lowerCamelCase_ : Optional[int] = pos_x
lowerCamelCase_ : int = pos_y
lowerCamelCase_ : Union[str, Any] = (pos_y, pos_x)
lowerCamelCase_ : Optional[int] = goal_x
lowerCamelCase_ : Dict = goal_y
lowerCamelCase_ : str = parent
class lowerCamelCase__ :
def __init__(self : Any , _snake_case : tuple[int, int] , _snake_case : tuple[int, int] ) -> int:
"""simple docstring"""
lowerCamelCase_ : Optional[Any] = Node(start[1] , start[0] , goal[1] , goal[0] , _snake_case )
lowerCamelCase_ : Optional[Any] = Node(goal[1] , goal[0] , goal[1] , goal[0] , _snake_case )
lowerCamelCase_ : List[str] = [self.start]
lowerCamelCase_ : str = False
def UpperCAmelCase_ (self : Tuple ) -> Path | None:
"""simple docstring"""
while self.node_queue:
lowerCamelCase_ : Tuple = self.node_queue.pop(0 )
if current_node.pos == self.target.pos:
lowerCamelCase_ : int = True
return self.retrace_path(_snake_case )
lowerCamelCase_ : Tuple = self.get_successors(_snake_case )
for node in successors:
self.node_queue.append(_snake_case )
if not self.reached:
return [self.start.pos]
return None
def UpperCAmelCase_ (self : List[str] , _snake_case : Node ) -> list[Node]:
"""simple docstring"""
lowerCamelCase_ : Optional[Any] = []
for action in delta:
lowerCamelCase_ : Tuple = parent.pos_x + action[1]
lowerCamelCase_ : Optional[int] = parent.pos_y + action[0]
if not (0 <= pos_x <= len(grid[0] ) - 1 and 0 <= pos_y <= len(_snake_case ) - 1):
continue
if grid[pos_y][pos_x] != 0:
continue
successors.append(
Node(_snake_case , _snake_case , self.target.pos_y , self.target.pos_x , _snake_case ) )
return successors
def UpperCAmelCase_ (self : List[Any] , _snake_case : Node | None ) -> Path:
"""simple docstring"""
lowerCamelCase_ : List[Any] = node
lowerCamelCase_ : Any = []
while current_node is not None:
path.append((current_node.pos_y, current_node.pos_x) )
lowerCamelCase_ : Optional[Any] = current_node.parent
path.reverse()
return path
class lowerCamelCase__ :
def __init__(self : Optional[int] , _snake_case : Tuple , _snake_case : Union[str, Any] ) -> List[str]:
"""simple docstring"""
lowerCamelCase_ : Optional[Any] = BreadthFirstSearch(_snake_case , _snake_case )
lowerCamelCase_ : Optional[Any] = BreadthFirstSearch(_snake_case , _snake_case )
lowerCamelCase_ : int = False
def UpperCAmelCase_ (self : Dict ) -> Path | None:
"""simple docstring"""
while self.fwd_bfs.node_queue or self.bwd_bfs.node_queue:
lowerCamelCase_ : Union[str, Any] = self.fwd_bfs.node_queue.pop(0 )
lowerCamelCase_ : Optional[int] = self.bwd_bfs.node_queue.pop(0 )
if current_bwd_node.pos == current_fwd_node.pos:
lowerCamelCase_ : List[Any] = True
return self.retrace_bidirectional_path(
_snake_case , _snake_case )
lowerCamelCase_ : List[str] = current_bwd_node
lowerCamelCase_ : Dict = current_fwd_node
lowerCamelCase_ : str = {
self.fwd_bfs: self.fwd_bfs.get_successors(_snake_case ),
self.bwd_bfs: self.bwd_bfs.get_successors(_snake_case ),
}
for bfs in [self.fwd_bfs, self.bwd_bfs]:
for node in successors[bfs]:
bfs.node_queue.append(_snake_case )
if not self.reached:
return [self.fwd_bfs.start.pos]
return None
def UpperCAmelCase_ (self : str , _snake_case : Node , _snake_case : Node ) -> Path:
"""simple docstring"""
lowerCamelCase_ : int = self.fwd_bfs.retrace_path(_snake_case )
lowerCamelCase_ : List[str] = self.bwd_bfs.retrace_path(_snake_case )
bwd_path.pop()
bwd_path.reverse()
lowerCamelCase_ : Tuple = fwd_path + bwd_path
return path
if __name__ == "__main__":
# all coordinates are given in format [y,x]
import doctest
doctest.testmod()
UpperCamelCase = (0, 0)
UpperCamelCase = (len(grid) - 1, len(grid[0]) - 1)
for elem in grid:
print(elem)
UpperCamelCase = time.time()
UpperCamelCase = BreadthFirstSearch(init, goal)
UpperCamelCase = bfs.search()
UpperCamelCase = time.time() - start_bfs_time
print('''Unidirectional BFS computation time : ''', bfs_time)
UpperCamelCase = time.time()
UpperCamelCase = BidirectionalBreadthFirstSearch(init, goal)
UpperCamelCase = bd_bfs.search()
UpperCamelCase = time.time() - start_bd_bfs_time
print('''Bidirectional BFS computation time : ''', bd_bfs_time)
| 144 | 0 |
import gc
import random
import tempfile
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
from diffusers import (
AutoencoderKL,
DDIMInverseScheduler,
DDIMScheduler,
DPMSolverMultistepInverseScheduler,
DPMSolverMultistepScheduler,
StableDiffusionDiffEditPipeline,
UNetaDConditionModel,
)
from diffusers.utils import load_image, slow
from diffusers.utils.testing_utils import enable_full_determinism, floats_tensor, require_torch_gpu, torch_device
from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin
enable_full_determinism()
class lowercase_ ( UpperCamelCase_ , UpperCamelCase_ , unittest.TestCase ):
"""simple docstring"""
UpperCAmelCase_ : List[Any] = StableDiffusionDiffEditPipeline
UpperCAmelCase_ : Dict = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""height""", """width""", """image"""} | {"""image_latents"""}
UpperCAmelCase_ : List[str] = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS - {"""image"""} | {"""image_latents"""}
UpperCAmelCase_ : Tuple = frozenset(
[] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess
UpperCAmelCase_ : List[str] = frozenset([] )
def SCREAMING_SNAKE_CASE_ ( self ) ->Any:
torch.manual_seed(0 )
lowerCAmelCase = UNetaDConditionModel(
block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('''DownBlock2D''', '''CrossAttnDownBlock2D''') , up_block_types=('''CrossAttnUpBlock2D''', '''UpBlock2D''') , cross_attention_dim=32 , attention_head_dim=(2, 4) , use_linear_projection=_lowerCamelCase , )
lowerCAmelCase = DDIMScheduler(
beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_one=_lowerCamelCase , )
lowerCAmelCase = DDIMInverseScheduler(
beta_start=0.0_0_0_8_5 , beta_end=0.0_1_2 , beta_schedule='''scaled_linear''' , clip_sample=_lowerCamelCase , set_alpha_to_zero=_lowerCamelCase , )
torch.manual_seed(0 )
lowerCAmelCase = AutoencoderKL(
block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D'''] , up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D'''] , latent_channels=4 , sample_size=128 , )
torch.manual_seed(0 )
lowerCAmelCase = CLIPTextConfig(
bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , hidden_act='''gelu''' , projection_dim=512 , )
lowerCAmelCase = CLIPTextModel(_lowerCamelCase )
lowerCAmelCase = CLIPTokenizer.from_pretrained('''hf-internal-testing/tiny-random-clip''' )
lowerCAmelCase = {
'''unet''': unet,
'''scheduler''': scheduler,
'''inverse_scheduler''': inverse_scheduler,
'''vae''': vae,
'''text_encoder''': text_encoder,
'''tokenizer''': tokenizer,
'''safety_checker''': None,
'''feature_extractor''': None,
}
return components
def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ) ->Dict:
lowerCAmelCase = floats_tensor((1, 16, 16) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase )
lowerCAmelCase = floats_tensor((1, 2, 4, 16, 16) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase )
if str(_lowerCamelCase ).startswith('''mps''' ):
lowerCAmelCase = torch.manual_seed(_lowerCamelCase )
else:
lowerCAmelCase = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase )
lowerCAmelCase = {
'''prompt''': '''a dog and a newt''',
'''mask_image''': mask,
'''image_latents''': latents,
'''generator''': generator,
'''num_inference_steps''': 2,
'''inpaint_strength''': 1.0,
'''guidance_scale''': 6.0,
'''output_type''': '''numpy''',
}
return inputs
def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ) ->Optional[int]:
lowerCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase )
lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0]
lowerCAmelCase = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('''RGB''' )
if str(_lowerCamelCase ).startswith('''mps''' ):
lowerCAmelCase = torch.manual_seed(_lowerCamelCase )
else:
lowerCAmelCase = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase )
lowerCAmelCase = {
'''image''': image,
'''source_prompt''': '''a cat and a frog''',
'''target_prompt''': '''a dog and a newt''',
'''generator''': generator,
'''num_inference_steps''': 2,
'''num_maps_per_mask''': 2,
'''mask_encode_strength''': 1.0,
'''guidance_scale''': 6.0,
'''output_type''': '''numpy''',
}
return inputs
def SCREAMING_SNAKE_CASE_ ( self , __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE=0 ) ->Any:
lowerCAmelCase = floats_tensor((1, 3, 32, 32) , rng=random.Random(_lowerCamelCase ) ).to(_lowerCamelCase )
lowerCAmelCase = image.cpu().permute(0 , 2 , 3 , 1 )[0]
lowerCAmelCase = Image.fromarray(np.uinta(_lowerCamelCase ) ).convert('''RGB''' )
if str(_lowerCamelCase ).startswith('''mps''' ):
lowerCAmelCase = torch.manual_seed(_lowerCamelCase )
else:
lowerCAmelCase = torch.Generator(device=_lowerCamelCase ).manual_seed(_lowerCamelCase )
lowerCAmelCase = {
'''image''': image,
'''prompt''': '''a cat and a frog''',
'''generator''': generator,
'''num_inference_steps''': 2,
'''inpaint_strength''': 1.0,
'''guidance_scale''': 6.0,
'''decode_latents''': True,
'''output_type''': '''numpy''',
}
return inputs
def SCREAMING_SNAKE_CASE_ ( self ) ->Tuple:
if not hasattr(self.pipeline_class , '''_optional_components''' ):
return
lowerCAmelCase = self.get_dummy_components()
lowerCAmelCase = self.pipeline_class(**_lowerCamelCase )
pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
# set all optional components to None and update pipeline config accordingly
for optional_component in pipe._optional_components:
setattr(_lowerCamelCase , _lowerCamelCase , _lowerCamelCase )
pipe.register_modules(**{optional_component: None for optional_component in pipe._optional_components} )
lowerCAmelCase = self.get_dummy_inputs(_lowerCamelCase )
lowerCAmelCase = pipe(**_lowerCamelCase )[0]
with tempfile.TemporaryDirectory() as tmpdir:
pipe.save_pretrained(_lowerCamelCase )
lowerCAmelCase = self.pipeline_class.from_pretrained(_lowerCamelCase )
pipe_loaded.to(_lowerCamelCase )
pipe_loaded.set_progress_bar_config(disable=_lowerCamelCase )
for optional_component in pipe._optional_components:
self.assertTrue(
getattr(_lowerCamelCase , _lowerCamelCase ) is None , F"`{optional_component}` did not stay set to None after loading." , )
lowerCAmelCase = self.get_dummy_inputs(_lowerCamelCase )
lowerCAmelCase = pipe_loaded(**_lowerCamelCase )[0]
lowerCAmelCase = np.abs(output - output_loaded ).max()
self.assertLess(_lowerCamelCase , 1e-4 )
def SCREAMING_SNAKE_CASE_ ( self ) ->str:
lowerCAmelCase = '''cpu'''
lowerCAmelCase = self.get_dummy_components()
lowerCAmelCase = self.pipeline_class(**_lowerCamelCase )
pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
lowerCAmelCase = self.get_dummy_mask_inputs(_lowerCamelCase )
lowerCAmelCase = pipe.generate_mask(**_lowerCamelCase )
lowerCAmelCase = mask[0, -3:, -3:]
self.assertEqual(mask.shape , (1, 16, 16) )
lowerCAmelCase = np.array([0] * 9 )
lowerCAmelCase = np.abs(mask_slice.flatten() - expected_slice ).max()
self.assertLessEqual(_lowerCamelCase , 1e-3 )
self.assertEqual(mask[0, -3, -4] , 0 )
def SCREAMING_SNAKE_CASE_ ( self ) ->Optional[int]:
lowerCAmelCase = '''cpu'''
lowerCAmelCase = self.get_dummy_components()
lowerCAmelCase = self.pipeline_class(**_lowerCamelCase )
pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
lowerCAmelCase = self.get_dummy_inversion_inputs(_lowerCamelCase )
lowerCAmelCase = pipe.invert(**_lowerCamelCase ).images
lowerCAmelCase = image[0, -1, -3:, -3:]
self.assertEqual(image.shape , (2, 32, 32, 3) )
lowerCAmelCase = np.array(
[0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9] , )
lowerCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(_lowerCamelCase , 1e-3 )
def SCREAMING_SNAKE_CASE_ ( self ) ->Any:
super().test_inference_batch_single_identical(expected_max_diff=5e-3 )
def SCREAMING_SNAKE_CASE_ ( self ) ->Union[str, Any]:
lowerCAmelCase = '''cpu'''
lowerCAmelCase = self.get_dummy_components()
lowerCAmelCase = {'''beta_start''': 0.0_0_0_8_5, '''beta_end''': 0.0_1_2, '''beta_schedule''': '''scaled_linear'''}
lowerCAmelCase = DPMSolverMultistepScheduler(**_lowerCamelCase )
lowerCAmelCase = DPMSolverMultistepInverseScheduler(**_lowerCamelCase )
lowerCAmelCase = self.pipeline_class(**_lowerCamelCase )
pipe.to(_lowerCamelCase )
pipe.set_progress_bar_config(disable=_lowerCamelCase )
lowerCAmelCase = self.get_dummy_inversion_inputs(_lowerCamelCase )
lowerCAmelCase = pipe.invert(**_lowerCamelCase ).images
lowerCAmelCase = image[0, -1, -3:, -3:]
self.assertEqual(image.shape , (2, 32, 32, 3) )
lowerCAmelCase = np.array(
[0.5_1_5_0, 0.5_1_3_4, 0.5_0_4_3, 0.5_3_7_6, 0.4_6_9_4, 0.5_1_0_5_0, 0.5_0_1_5, 0.4_4_0_7, 0.4_7_9_9] , )
lowerCAmelCase = np.abs(image_slice.flatten() - expected_slice ).max()
self.assertLessEqual(_lowerCamelCase , 1e-3 )
@require_torch_gpu
@slow
class lowercase_ ( unittest.TestCase ):
"""simple docstring"""
def SCREAMING_SNAKE_CASE_ ( self ) ->str:
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
@classmethod
def SCREAMING_SNAKE_CASE_ ( cls ) ->int:
lowerCAmelCase = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/diffedit/fruit.png''' )
lowerCAmelCase = raw_image.convert('''RGB''' ).resize((768, 768) )
lowerCAmelCase = raw_image
def SCREAMING_SNAKE_CASE_ ( self ) ->Any:
lowerCAmelCase = torch.manual_seed(0 )
lowerCAmelCase = StableDiffusionDiffEditPipeline.from_pretrained(
'''stabilityai/stable-diffusion-2-1''' , safety_checker=_lowerCamelCase , torch_dtype=torch.floataa )
lowerCAmelCase = DDIMScheduler.from_config(pipe.scheduler.config )
lowerCAmelCase = DDIMInverseScheduler.from_config(pipe.scheduler.config )
pipe.enable_model_cpu_offload()
pipe.set_progress_bar_config(disable=_lowerCamelCase )
lowerCAmelCase = '''a bowl of fruit'''
lowerCAmelCase = '''a bowl of pears'''
lowerCAmelCase = pipe.generate_mask(
image=self.raw_image , source_prompt=_lowerCamelCase , target_prompt=_lowerCamelCase , generator=_lowerCamelCase , )
lowerCAmelCase = pipe.invert(
prompt=_lowerCamelCase , image=self.raw_image , inpaint_strength=0.7 , generator=_lowerCamelCase ).latents
lowerCAmelCase = pipe(
prompt=_lowerCamelCase , mask_image=_lowerCamelCase , image_latents=_lowerCamelCase , generator=_lowerCamelCase , negative_prompt=_lowerCamelCase , inpaint_strength=0.7 , output_type='''numpy''' , ).images[0]
lowerCAmelCase = (
np.array(
load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/diffedit/pears.png''' ).resize((768, 768) ) )
/ 255
)
assert np.abs((expected_image - image).max() ) < 5e-1
def SCREAMING_SNAKE_CASE_ ( self ) ->str:
lowerCAmelCase = torch.manual_seed(0 )
lowerCAmelCase = StableDiffusionDiffEditPipeline.from_pretrained(
'''stabilityai/stable-diffusion-2-1''' , safety_checker=_lowerCamelCase , torch_dtype=torch.floataa )
lowerCAmelCase = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config )
lowerCAmelCase = DPMSolverMultistepInverseScheduler.from_config(pipe.scheduler.config )
pipe.enable_model_cpu_offload()
pipe.set_progress_bar_config(disable=_lowerCamelCase )
lowerCAmelCase = '''a bowl of fruit'''
lowerCAmelCase = '''a bowl of pears'''
lowerCAmelCase = pipe.generate_mask(
image=self.raw_image , source_prompt=_lowerCamelCase , target_prompt=_lowerCamelCase , generator=_lowerCamelCase , )
lowerCAmelCase = pipe.invert(
prompt=_lowerCamelCase , image=self.raw_image , inpaint_strength=0.7 , generator=_lowerCamelCase , num_inference_steps=25 , ).latents
lowerCAmelCase = pipe(
prompt=_lowerCamelCase , mask_image=_lowerCamelCase , image_latents=_lowerCamelCase , generator=_lowerCamelCase , negative_prompt=_lowerCamelCase , inpaint_strength=0.7 , num_inference_steps=25 , output_type='''numpy''' , ).images[0]
lowerCAmelCase = (
np.array(
load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main'''
'''/diffedit/pears.png''' ).resize((768, 768) ) )
/ 255
)
assert np.abs((expected_image - image).max() ) < 5e-1
| 312 |
'''simple docstring'''
_lowerCAmelCase = "\n# Transformers installation\n! pip install transformers datasets\n# To install from source instead of the last release, comment the command above and uncomment the following one.\n# ! pip install git+https://github.com/huggingface/transformers.git\n"
_lowerCAmelCase = [{"type": "code", "content": INSTALL_CONTENT}]
_lowerCAmelCase = {
"{processor_class}": "FakeProcessorClass",
"{model_class}": "FakeModelClass",
"{object_class}": "FakeObjectClass",
}
| 161 | 0 |
"""simple docstring"""
from __future__ import annotations
def _snake_case ( snake_case__ : list[int] ):
return len(set(_UpperCamelCase ) ) == len(_UpperCamelCase )
if __name__ == "__main__":
import doctest
doctest.testmod() | 720 |
"""simple docstring"""
import os
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple
import sentencepiece as spm
from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging
_lowercase = logging.get_logger(__name__)
_lowercase = {'''vocab_file''': '''spm_char.model'''}
_lowercase = {
'''vocab_file''': {
'''microsoft/speecht5_asr''': '''https://huggingface.co/microsoft/speecht5_asr/resolve/main/spm_char.model''',
'''microsoft/speecht5_tts''': '''https://huggingface.co/microsoft/speecht5_tts/resolve/main/spm_char.model''',
'''microsoft/speecht5_vc''': '''https://huggingface.co/microsoft/speecht5_vc/resolve/main/spm_char.model''',
}
}
_lowercase = {
'''microsoft/speecht5_asr''': 10_24,
'''microsoft/speecht5_tts''': 10_24,
'''microsoft/speecht5_vc''': 10_24,
}
class lowerCAmelCase_ ( _lowercase ):
'''simple docstring'''
_lowerCamelCase: Optional[Any] = VOCAB_FILES_NAMES
_lowerCamelCase: List[Any] = PRETRAINED_VOCAB_FILES_MAP
_lowerCamelCase: str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
_lowerCamelCase: Tuple = ['''input_ids''', '''attention_mask''']
def __init__( self : List[str] ,A_ : int ,A_ : List[str]="<s>" ,A_ : Optional[Any]="</s>" ,A_ : Optional[Any]="<unk>" ,A_ : str="<pad>" ,A_ : Optional[Dict[str, Any]] = None ,**A_ : List[str] ,) -> None:
A = {} if sp_model_kwargs is None else sp_model_kwargs
super().__init__(
bos_token=A_ ,eos_token=A_ ,unk_token=A_ ,pad_token=A_ ,sp_model_kwargs=self.sp_model_kwargs ,**A_ ,)
A = vocab_file
A = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(A_ )
@property
def _SCREAMING_SNAKE_CASE ( self : Any ) -> str:
return self.sp_model.get_piece_size()
def _SCREAMING_SNAKE_CASE ( self : Optional[int] ) -> Optional[Any]:
A = {self.convert_ids_to_tokens(A_ ): i for i in range(self.vocab_size )}
vocab.update(self.added_tokens_encoder )
return vocab
def __getstate__( self : str ) -> Any:
A = self.__dict__.copy()
A = None
return state
def __setstate__( self : Optional[int] ,A_ : str ) -> Tuple:
A = d
# for backward compatibility
if not hasattr(self ,'sp_model_kwargs' ):
A = {}
A = spm.SentencePieceProcessor(**self.sp_model_kwargs )
self.sp_model.Load(self.vocab_file )
def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ) -> List[str]:
return self.sp_model.encode(A_ ,out_type=A_ )
def _SCREAMING_SNAKE_CASE ( self : List[str] ,A_ : Union[str, Any] ) -> Union[str, Any]:
return self.sp_model.piece_to_id(A_ )
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : Dict ) -> List[Any]:
A = self.sp_model.IdToPiece(A_ )
return token
def _SCREAMING_SNAKE_CASE ( self : Tuple ,A_ : Optional[Any] ) -> List[str]:
A = []
A = ''
for token in tokens:
# make sure that special tokens are not decoded using sentencepiece model
if token in self.all_special_tokens:
out_string += self.sp_model.decode(A_ ) + token
A = []
else:
current_sub_tokens.append(A_ )
out_string += self.sp_model.decode(A_ )
return out_string.strip()
def _SCREAMING_SNAKE_CASE ( self : Dict ,A_ : Dict ,A_ : Optional[int]=None ) -> List[int]:
if token_ids_a is None:
return token_ids_a + [self.eos_token_id]
# We don't expect to process pairs, but leave the pair logic for API consistency
return token_ids_a + token_ids_a + [self.eos_token_id]
def _SCREAMING_SNAKE_CASE ( self : Optional[Any] ,A_ : List[int] ,A_ : Optional[List[int]] = None ,A_ : bool = False ) -> List[int]:
if already_has_special_tokens:
return super().get_special_tokens_mask(
token_ids_a=A_ ,token_ids_a=A_ ,already_has_special_tokens=A_ )
A = [1]
if token_ids_a is None:
return ([0] * len(A_ )) + suffix_ones
return ([0] * len(A_ )) + ([0] * len(A_ )) + suffix_ones
def _SCREAMING_SNAKE_CASE ( self : str ,A_ : str ,A_ : Optional[str] = None ) -> Tuple[str]:
if not os.path.isdir(A_ ):
logger.error(F'Vocabulary path ({save_directory}) should be a directory' )
return
A = os.path.join(
A_ ,(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] )
if os.path.abspath(self.vocab_file ) != os.path.abspath(A_ ) and os.path.isfile(self.vocab_file ):
copyfile(self.vocab_file ,A_ )
elif not os.path.isfile(self.vocab_file ):
with open(A_ ,'wb' ) as fi:
A = self.sp_model.serialized_model_proto()
fi.write(A_ )
return (out_vocab_file,) | 22 | 0 |
import gc
import unittest
from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline
from diffusers.utils import is_flax_available, load_image, slow
from diffusers.utils.testing_utils import require_flax
if is_flax_available():
import jax
import jax.numpy as jnp
from flax.jax_utils import replicate
from flax.training.common_utils import shard
@slow
@require_flax
class lowerCamelCase_ ( unittest.TestCase ):
def A ( self ):
"""simple docstring"""
# clean up the VRAM after each test
super().tearDown()
gc.collect()
def A ( self ):
"""simple docstring"""
__magic_name__ , __magic_name__ :Any = FlaxControlNetModel.from_pretrained(
'''lllyasviel/sd-controlnet-canny''' , from_pt=__SCREAMING_SNAKE_CASE , dtype=jnp.bfloataa )
__magic_name__ , __magic_name__ :List[Any] = FlaxStableDiffusionControlNetPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , controlnet=__SCREAMING_SNAKE_CASE , from_pt=__SCREAMING_SNAKE_CASE , dtype=jnp.bfloataa )
__magic_name__ :List[str] = controlnet_params
__magic_name__ :Tuple = '''bird'''
__magic_name__ :List[Any] = jax.device_count()
__magic_name__ :Union[str, Any] = pipe.prepare_text_inputs([prompts] * num_samples )
__magic_name__ :Optional[Any] = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png''' )
__magic_name__ :Union[str, Any] = pipe.prepare_image_inputs([canny_image] * num_samples )
__magic_name__ :Optional[Any] = jax.random.PRNGKey(0 )
__magic_name__ :Any = jax.random.split(__SCREAMING_SNAKE_CASE , jax.device_count() )
__magic_name__ :int = replicate(__SCREAMING_SNAKE_CASE )
__magic_name__ :List[str] = shard(__SCREAMING_SNAKE_CASE )
__magic_name__ :str = shard(__SCREAMING_SNAKE_CASE )
__magic_name__ :Tuple = pipe(
prompt_ids=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , params=__SCREAMING_SNAKE_CASE , prng_seed=__SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , jit=__SCREAMING_SNAKE_CASE , ).images
assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3)
__magic_name__ :List[Any] = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
__magic_name__ :Dict = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
__magic_name__ :Tuple = jnp.asarray(jax.device_get(image_slice.flatten() ) )
__magic_name__ :Optional[Any] = jnp.array(
[0.167969, 0.116699, 0.081543, 0.154297, 0.132812, 0.108887, 0.169922, 0.169922, 0.205078] )
print(F'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
def A ( self ):
"""simple docstring"""
__magic_name__ , __magic_name__ :Dict = FlaxControlNetModel.from_pretrained(
'''lllyasviel/sd-controlnet-openpose''' , from_pt=__SCREAMING_SNAKE_CASE , dtype=jnp.bfloataa )
__magic_name__ , __magic_name__ :List[Any] = FlaxStableDiffusionControlNetPipeline.from_pretrained(
'''runwayml/stable-diffusion-v1-5''' , controlnet=__SCREAMING_SNAKE_CASE , from_pt=__SCREAMING_SNAKE_CASE , dtype=jnp.bfloataa )
__magic_name__ :Tuple = controlnet_params
__magic_name__ :List[Any] = '''Chef in the kitchen'''
__magic_name__ :Union[str, Any] = jax.device_count()
__magic_name__ :str = pipe.prepare_text_inputs([prompts] * num_samples )
__magic_name__ :Optional[Any] = load_image(
'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png''' )
__magic_name__ :Optional[int] = pipe.prepare_image_inputs([pose_image] * num_samples )
__magic_name__ :List[Any] = jax.random.PRNGKey(0 )
__magic_name__ :str = jax.random.split(__SCREAMING_SNAKE_CASE , jax.device_count() )
__magic_name__ :List[str] = replicate(__SCREAMING_SNAKE_CASE )
__magic_name__ :int = shard(__SCREAMING_SNAKE_CASE )
__magic_name__ :Optional[Any] = shard(__SCREAMING_SNAKE_CASE )
__magic_name__ :Any = pipe(
prompt_ids=__SCREAMING_SNAKE_CASE , image=__SCREAMING_SNAKE_CASE , params=__SCREAMING_SNAKE_CASE , prng_seed=__SCREAMING_SNAKE_CASE , num_inference_steps=5_0 , jit=__SCREAMING_SNAKE_CASE , ).images
assert images.shape == (jax.device_count(), 1, 7_6_8, 5_1_2, 3)
__magic_name__ :Dict = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:] )
__magic_name__ :Optional[int] = images[0, 2_5_3:2_5_6, 2_5_3:2_5_6, -1]
__magic_name__ :Dict = jnp.asarray(jax.device_get(image_slice.flatten() ) )
__magic_name__ :Union[str, Any] = jnp.array(
[[0.271484, 0.261719, 0.275391, 0.277344, 0.279297, 0.291016, 0.294922, 0.302734, 0.302734]] )
print(F'''output_slice: {output_slice}''' )
assert jnp.abs(output_slice - expected_slice ).max() < 1E-2
| 0 |
"""simple docstring"""
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional
import datasets
import evaluate
import numpy as np
from datasets import load_dataset
import transformers
from transformers import (
AutoConfig,
AutoModelForSequenceClassification,
AutoTokenizer,
DataCollatorWithPadding,
EvalPrediction,
HfArgumentParser,
Trainer,
TrainingArguments,
default_data_collator,
set_seed,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version('''4.31.0''')
require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/text-classification/requirements.txt''')
_SCREAMING_SNAKE_CASE : str = logging.getLogger(__name__)
@dataclass
class a :
SCREAMING_SNAKE_CASE : Optional[int] = field(
default=1_2_8 , metadata={
"""help""": (
"""The maximum total input sequence length after tokenization. Sequences longer """
"""than this will be truncated, sequences shorter will be padded."""
)
} , )
SCREAMING_SNAKE_CASE : bool = field(
default=__snake_case , metadata={"""help""": """Overwrite the cached preprocessed datasets or not."""} )
SCREAMING_SNAKE_CASE : bool = field(
default=__snake_case , metadata={
"""help""": (
"""Whether to pad all samples to `max_seq_length`. """
"""If False, will pad the samples dynamically when batching to the maximum length in the batch."""
)
} , )
SCREAMING_SNAKE_CASE : Optional[int] = field(
default=__snake_case , metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of training examples to this """
"""value if set."""
)
} , )
SCREAMING_SNAKE_CASE : Optional[int] = field(
default=__snake_case , metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of evaluation examples to this """
"""value if set."""
)
} , )
SCREAMING_SNAKE_CASE : Optional[int] = field(
default=__snake_case , metadata={
"""help""": (
"""For debugging purposes or quicker training, truncate the number of prediction examples to this """
"""value if set."""
)
} , )
@dataclass
class a :
SCREAMING_SNAKE_CASE : str = field(
default=__snake_case , metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} )
SCREAMING_SNAKE_CASE : str = field(
default=__snake_case , metadata={"""help""": """Evaluation language. Also train language if `train_language` is set to None."""} )
SCREAMING_SNAKE_CASE : Optional[str] = field(
default=__snake_case , metadata={"""help""": """Train language if it is different from the evaluation language."""} )
SCREAMING_SNAKE_CASE : Optional[str] = field(
default=__snake_case , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} )
SCREAMING_SNAKE_CASE : Optional[str] = field(
default=__snake_case , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} )
SCREAMING_SNAKE_CASE : Optional[str] = field(
default=__snake_case , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , )
SCREAMING_SNAKE_CASE : Optional[bool] = field(
default=__snake_case , metadata={"""help""": """arg to indicate if tokenizer should do lower case in AutoTokenizer.from_pretrained()"""} , )
SCREAMING_SNAKE_CASE : bool = field(
default=__snake_case , metadata={"""help""": """Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."""} , )
SCREAMING_SNAKE_CASE : str = field(
default="""main""" , metadata={"""help""": """The specific model version to use (can be a branch name, tag name or commit id)."""} , )
SCREAMING_SNAKE_CASE : bool = field(
default=__snake_case , metadata={
"""help""": (
"""Will use the token generated when running `huggingface-cli login` (necessary to use this script """
"""with private models)."""
)
} , )
SCREAMING_SNAKE_CASE : bool = field(
default=__snake_case , metadata={"""help""": """Will enable to load a pretrained model whose head dimensions are different."""} , )
def lowerCamelCase__ ( ) -> Any:
# See all possible arguments in src/transformers/training_args.py
# or by passing the --help flag to this script.
# We now keep distinct sets of args, for a cleaner separation of concerns.
lowerCamelCase_ = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) )
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = parser.parse_args_into_dataclasses()
# Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
# information sent is the one passed as arguments along with your Python/PyTorch versions.
send_example_telemetry('run_xnli' , _lowerCamelCase )
# Setup logging
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , handlers=[logging.StreamHandler(sys.stdout )] , )
if training_args.should_log:
# The default of training_args.log_level is passive, so we set log level at info here to have that default.
transformers.utils.logging.set_verbosity_info()
lowerCamelCase_ = training_args.get_process_log_level()
logger.setLevel(_lowerCamelCase )
datasets.utils.logging.set_verbosity(_lowerCamelCase )
transformers.utils.logging.set_verbosity(_lowerCamelCase )
transformers.utils.logging.enable_default_handler()
transformers.utils.logging.enable_explicit_format()
# Log on each process the small summary:
logger.warning(
F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
+ F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' )
logger.info(F'''Training/evaluation parameters {training_args}''' )
# Detecting last checkpoint.
lowerCamelCase_ = None
if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir:
lowerCamelCase_ = get_last_checkpoint(training_args.output_dir )
if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0:
raise ValueError(
F'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
'Use --overwrite_output_dir to overcome.' )
elif last_checkpoint is not None:
logger.info(
F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.' )
# Set seed before initializing model.
set_seed(training_args.seed )
# In distributed training, the load_dataset function guarantees that only one local process can concurrently
# download the dataset.
# Downloading and loading xnli dataset from the hub.
if training_args.do_train:
if model_args.train_language is None:
lowerCamelCase_ = load_dataset(
'xnli' , model_args.language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
else:
lowerCamelCase_ = load_dataset(
'xnli' , model_args.train_language , split='train' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
lowerCamelCase_ = train_dataset.features['label'].names
if training_args.do_eval:
lowerCamelCase_ = load_dataset(
'xnli' , model_args.language , split='validation' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
lowerCamelCase_ = eval_dataset.features['label'].names
if training_args.do_predict:
lowerCamelCase_ = load_dataset(
'xnli' , model_args.language , split='test' , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , )
lowerCamelCase_ = predict_dataset.features['label'].names
# Labels
lowerCamelCase_ = len(_lowerCamelCase )
# Load pretrained model and tokenizer
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
# download model & vocab.
lowerCamelCase_ = AutoConfig.from_pretrained(
model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_lowerCamelCase , idalabel={str(_lowerCamelCase ): label for i, label in enumerate(_lowerCamelCase )} , labelaid={label: i for i, label in enumerate(_lowerCamelCase )} , finetuning_task='xnli' , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
lowerCamelCase_ = AutoTokenizer.from_pretrained(
model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , do_lower_case=model_args.do_lower_case , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast_tokenizer , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , )
lowerCamelCase_ = AutoModelForSequenceClassification.from_pretrained(
model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_lowerCamelCase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ignore_mismatched_sizes=model_args.ignore_mismatched_sizes , )
# Preprocessing the datasets
# Padding strategy
if data_args.pad_to_max_length:
lowerCamelCase_ = 'max_length'
else:
# We will pad later, dynamically at batch creation, to the max sequence length in each batch
lowerCamelCase_ = False
def preprocess_function(_lowerCamelCase : Any ):
# Tokenize the texts
return tokenizer(
examples['premise'] , examples['hypothesis'] , padding=_lowerCamelCase , max_length=data_args.max_seq_length , truncation=_lowerCamelCase , )
if training_args.do_train:
if data_args.max_train_samples is not None:
lowerCamelCase_ = min(len(_lowerCamelCase ) , data_args.max_train_samples )
lowerCamelCase_ = train_dataset.select(range(_lowerCamelCase ) )
with training_args.main_process_first(desc='train dataset map pre-processing' ):
lowerCamelCase_ = train_dataset.map(
_lowerCamelCase , batched=_lowerCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on train dataset' , )
# Log a few random samples from the training set:
for index in random.sample(range(len(_lowerCamelCase ) ) , 3 ):
logger.info(F'''Sample {index} of the training set: {train_dataset[index]}.''' )
if training_args.do_eval:
if data_args.max_eval_samples is not None:
lowerCamelCase_ = min(len(_lowerCamelCase ) , data_args.max_eval_samples )
lowerCamelCase_ = eval_dataset.select(range(_lowerCamelCase ) )
with training_args.main_process_first(desc='validation dataset map pre-processing' ):
lowerCamelCase_ = eval_dataset.map(
_lowerCamelCase , batched=_lowerCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on validation dataset' , )
if training_args.do_predict:
if data_args.max_predict_samples is not None:
lowerCamelCase_ = min(len(_lowerCamelCase ) , data_args.max_predict_samples )
lowerCamelCase_ = predict_dataset.select(range(_lowerCamelCase ) )
with training_args.main_process_first(desc='prediction dataset map pre-processing' ):
lowerCamelCase_ = predict_dataset.map(
_lowerCamelCase , batched=_lowerCamelCase , load_from_cache_file=not data_args.overwrite_cache , desc='Running tokenizer on prediction dataset' , )
# Get the metric function
lowerCamelCase_ = evaluate.load('xnli' )
# You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
# predictions and label_ids field) and has to return a dictionary string to float.
def compute_metrics(_lowerCamelCase : EvalPrediction ):
lowerCamelCase_ = p.predictions[0] if isinstance(p.predictions , _lowerCamelCase ) else p.predictions
lowerCamelCase_ = np.argmax(_lowerCamelCase , axis=1 )
return metric.compute(predictions=_lowerCamelCase , references=p.label_ids )
# Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding.
if data_args.pad_to_max_length:
lowerCamelCase_ = default_data_collator
elif training_args.fpaa:
lowerCamelCase_ = DataCollatorWithPadding(_lowerCamelCase , pad_to_multiple_of=8 )
else:
lowerCamelCase_ = None
# Initialize our Trainer
lowerCamelCase_ = Trainer(
model=_lowerCamelCase , args=_lowerCamelCase , train_dataset=train_dataset if training_args.do_train else None , eval_dataset=eval_dataset if training_args.do_eval else None , compute_metrics=_lowerCamelCase , tokenizer=_lowerCamelCase , data_collator=_lowerCamelCase , )
# Training
if training_args.do_train:
lowerCamelCase_ = None
if training_args.resume_from_checkpoint is not None:
lowerCamelCase_ = training_args.resume_from_checkpoint
elif last_checkpoint is not None:
lowerCamelCase_ = last_checkpoint
lowerCamelCase_ = trainer.train(resume_from_checkpoint=_lowerCamelCase )
lowerCamelCase_ = train_result.metrics
lowerCamelCase_ = (
data_args.max_train_samples if data_args.max_train_samples is not None else len(_lowerCamelCase )
)
lowerCamelCase_ = min(_lowerCamelCase , len(_lowerCamelCase ) )
trainer.save_model() # Saves the tokenizer too for easy upload
trainer.log_metrics('train' , _lowerCamelCase )
trainer.save_metrics('train' , _lowerCamelCase )
trainer.save_state()
# Evaluation
if training_args.do_eval:
logger.info('*** Evaluate ***' )
lowerCamelCase_ = trainer.evaluate(eval_dataset=_lowerCamelCase )
lowerCamelCase_ = data_args.max_eval_samples if data_args.max_eval_samples is not None else len(_lowerCamelCase )
lowerCamelCase_ = min(_lowerCamelCase , len(_lowerCamelCase ) )
trainer.log_metrics('eval' , _lowerCamelCase )
trainer.save_metrics('eval' , _lowerCamelCase )
# Prediction
if training_args.do_predict:
logger.info('*** Predict ***' )
lowerCamelCase_ , lowerCamelCase_ , lowerCamelCase_ = trainer.predict(_lowerCamelCase , metric_key_prefix='predict' )
lowerCamelCase_ = (
data_args.max_predict_samples if data_args.max_predict_samples is not None else len(_lowerCamelCase )
)
lowerCamelCase_ = min(_lowerCamelCase , len(_lowerCamelCase ) )
trainer.log_metrics('predict' , _lowerCamelCase )
trainer.save_metrics('predict' , _lowerCamelCase )
lowerCamelCase_ = np.argmax(_lowerCamelCase , axis=1 )
lowerCamelCase_ = os.path.join(training_args.output_dir , 'predictions.txt' )
if trainer.is_world_process_zero():
with open(_lowerCamelCase , 'w' ) as writer:
writer.write('index\tprediction\n' )
for index, item in enumerate(_lowerCamelCase ):
lowerCamelCase_ = label_list[item]
writer.write(F'''{index}\t{item}\n''' )
if __name__ == "__main__":
main()
| 549 | 0 |
import copy
from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import CONFIG_MAPPING
__lowerCAmelCase = logging.get_logger(__name__)
class __a ( __UpperCamelCase ):
__lowercase : Union[str, Any] = 'upernet'
def __init__( self , lowerCAmelCase__=None , lowerCAmelCase__=512 , lowerCAmelCase__=0.0_2 , lowerCAmelCase__=[1, 2, 3, 6] , lowerCAmelCase__=True , lowerCAmelCase__=0.4 , lowerCAmelCase__=384 , lowerCAmelCase__=256 , lowerCAmelCase__=1 , lowerCAmelCase__=False , lowerCAmelCase__=255 , **lowerCAmelCase__ , ) -> Optional[Any]:
'''simple docstring'''
super().__init__(**lowerCAmelCase__ )
if backbone_config is None:
logger.info('`backbone_config` is `None`. Initializing the config with the default `ResNet` backbone.' )
lowercase__: str = CONFIG_MAPPING['resnet'](out_features=['stage1', 'stage2', 'stage3', 'stage4'] )
elif isinstance(lowerCAmelCase__ , lowerCAmelCase__ ):
lowercase__: str = backbone_config.get('model_type' )
lowercase__: Union[str, Any] = CONFIG_MAPPING[backbone_model_type]
lowercase__: Dict = config_class.from_dict(lowerCAmelCase__ )
lowercase__: List[Any] = backbone_config
lowercase__: Union[str, Any] = hidden_size
lowercase__: Tuple = initializer_range
lowercase__: Optional[int] = pool_scales
lowercase__: Union[str, Any] = use_auxiliary_head
lowercase__: Any = auxiliary_loss_weight
lowercase__: Tuple = auxiliary_in_channels
lowercase__: Optional[Any] = auxiliary_channels
lowercase__: List[Any] = auxiliary_num_convs
lowercase__: List[str] = auxiliary_concat_input
lowercase__: Any = loss_ignore_index
def SCREAMING_SNAKE_CASE__ ( self ) -> Tuple:
'''simple docstring'''
lowercase__: Tuple = copy.deepcopy(self.__dict__ )
lowercase__: List[Any] = self.backbone_config.to_dict()
lowercase__: str = self.__class__.model_type
return output
| 707 |
from __future__ import annotations
import unittest
from transformers import is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
if is_tf_available():
import numpy as np
import tensorflow as tf
from transformers import TFXLMRobertaModel
@require_tf
@require_sentencepiece
@require_tokenizers
class __a ( unittest.TestCase ):
@slow
def SCREAMING_SNAKE_CASE__ ( self ) -> Optional[Any]:
'''simple docstring'''
lowercase__: int = TFXLMRobertaModel.from_pretrained('jplu/tf-xlm-roberta-base' )
lowercase__: Any = {
'input_ids': tf.convert_to_tensor([[0, 2_646, 10_269, 83, 99_942, 2]] , dtype=tf.intaa ), # "My dog is cute"
'attention_mask': tf.convert_to_tensor([[1, 1, 1, 1, 1, 1]] , dtype=tf.intaa ),
}
lowercase__: Tuple = model(lowerCAmelCase__ )['last_hidden_state']
lowercase__: Optional[int] = tf.TensorShape((1, 6, 768) )
self.assertEqual(output.shape , lowerCAmelCase__ )
# compare the actual values for a slice.
lowercase__: Tuple = tf.convert_to_tensor(
[
[
[0.0_6_8_1_7_6_2, 0.1_0_8_9_4_4_5_1, 0.0_6_7_7_2_5_0_4],
[-0.0_6_4_2_3_6_6_8, 0.0_2_3_6_6_6_1_5, 0.0_4_3_2_9_3_4_4],
[-0.0_6_0_5_7_2_9_5, 0.0_9_9_7_4_1_3_5, -0.0_0_0_7_0_5_8_4],
]
] , dtype=tf.floataa , )
self.assertTrue(np.allclose(output[:, :3, :3].numpy() , expected_slice.numpy() , atol=1E-4 ) )
| 335 | 0 |
'''simple docstring'''
def a_ ( __UpperCAmelCase , __UpperCAmelCase , __UpperCAmelCase ) -> list:
"""simple docstring"""
snake_case: List[Any] =len(__UpperCAmelCase )
snake_case: Union[str, Any] =[[0] * n for i in range(__UpperCAmelCase )]
for i in range(__UpperCAmelCase ):
snake_case: int =y_points[i]
for i in range(2 , __UpperCAmelCase ):
for j in range(__UpperCAmelCase , __UpperCAmelCase ):
snake_case: Optional[Any] =(
(xa - x_points[j - i + 1]) * q[j][i - 1]
- (xa - x_points[j]) * q[j - 1][i - 1]
) / (x_points[j] - x_points[j - i + 1])
return [q[n - 1][n - 1], q]
if __name__ == "__main__":
import doctest
doctest.testmod()
| 350 |
import gc
import random
import unittest
import numpy as np
import torch
from PIL import Image
from transformers import XLMRobertaTokenizerFast
from diffusers import DDIMScheduler, KandinskyInpaintPipeline, KandinskyPriorPipeline, UNetaDConditionModel, VQModel
from diffusers.pipelines.kandinsky.text_encoder import MCLIPConfig, MultilingualCLIP
from diffusers.utils import floats_tensor, load_image, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
enable_full_determinism()
class __A ( A_ , unittest.TestCase ):
UpperCamelCase :Optional[int] = KandinskyInpaintPipeline
UpperCamelCase :Optional[Any] = ['''prompt''', '''image_embeds''', '''negative_image_embeds''', '''image''', '''mask_image''']
UpperCamelCase :Union[str, Any] = [
'''prompt''',
'''negative_prompt''',
'''image_embeds''',
'''negative_image_embeds''',
'''image''',
'''mask_image''',
]
UpperCamelCase :int = [
'''generator''',
'''height''',
'''width''',
'''latents''',
'''guidance_scale''',
'''negative_prompt''',
'''num_inference_steps''',
'''return_dict''',
'''guidance_scale''',
'''num_images_per_prompt''',
'''output_type''',
'''return_dict''',
]
UpperCamelCase :str = False
@property
def _snake_case (self ):
return 32
@property
def _snake_case (self ):
return 32
@property
def _snake_case (self ):
return self.time_input_dim
@property
def _snake_case (self ):
return self.time_input_dim * 4
@property
def _snake_case (self ):
return 100
@property
def _snake_case (self ):
lowerCamelCase__ : List[Any] = XLMRobertaTokenizerFast.from_pretrained("""YiYiXu/tiny-random-mclip-base""" )
return tokenizer
@property
def _snake_case (self ):
torch.manual_seed(0 )
lowerCamelCase__ : int = MCLIPConfig(
numDims=self.cross_attention_dim , transformerDimensions=self.text_embedder_hidden_size , hidden_size=self.text_embedder_hidden_size , intermediate_size=37 , num_attention_heads=4 , num_hidden_layers=5 , vocab_size=1005 , )
lowerCamelCase__ : int = MultilingualCLIP(__magic_name__ )
lowerCamelCase__ : Optional[int] = text_encoder.eval()
return text_encoder
@property
def _snake_case (self ):
torch.manual_seed(0 )
lowerCamelCase__ : str = {
"""in_channels""": 9,
# Out channels is double in channels because predicts mean and variance
"""out_channels""": 8,
"""addition_embed_type""": """text_image""",
"""down_block_types""": ("""ResnetDownsampleBlock2D""", """SimpleCrossAttnDownBlock2D"""),
"""up_block_types""": ("""SimpleCrossAttnUpBlock2D""", """ResnetUpsampleBlock2D"""),
"""mid_block_type""": """UNetMidBlock2DSimpleCrossAttn""",
"""block_out_channels""": (self.block_out_channels_a, self.block_out_channels_a * 2),
"""layers_per_block""": 1,
"""encoder_hid_dim""": self.text_embedder_hidden_size,
"""encoder_hid_dim_type""": """text_image_proj""",
"""cross_attention_dim""": self.cross_attention_dim,
"""attention_head_dim""": 4,
"""resnet_time_scale_shift""": """scale_shift""",
"""class_embed_type""": None,
}
lowerCamelCase__ : int = UNetaDConditionModel(**__magic_name__ )
return model
@property
def _snake_case (self ):
return {
"block_out_channels": [32, 64],
"down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"],
"in_channels": 3,
"latent_channels": 4,
"layers_per_block": 1,
"norm_num_groups": 8,
"norm_type": "spatial",
"num_vq_embeddings": 12,
"out_channels": 3,
"up_block_types": [
"AttnUpDecoderBlock2D",
"UpDecoderBlock2D",
],
"vq_embed_dim": 4,
}
@property
def _snake_case (self ):
torch.manual_seed(0 )
lowerCamelCase__ : Tuple = VQModel(**self.dummy_movq_kwargs )
return model
def _snake_case (self ):
lowerCamelCase__ : int = self.dummy_text_encoder
lowerCamelCase__ : List[str] = self.dummy_tokenizer
lowerCamelCase__ : Dict = self.dummy_unet
lowerCamelCase__ : str = self.dummy_movq
lowerCamelCase__ : Dict = DDIMScheduler(
num_train_timesteps=1000 , beta_schedule="""linear""" , beta_start=0.0_00_85 , beta_end=0.0_12 , clip_sample=__magic_name__ , set_alpha_to_one=__magic_name__ , steps_offset=1 , prediction_type="""epsilon""" , thresholding=__magic_name__ , )
lowerCamelCase__ : List[str] = {
"""text_encoder""": text_encoder,
"""tokenizer""": tokenizer,
"""unet""": unet,
"""scheduler""": scheduler,
"""movq""": movq,
}
return components
def _snake_case (self , __magic_name__ , __magic_name__=0 ):
lowerCamelCase__ : List[Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ )
lowerCamelCase__ : List[Any] = floats_tensor((1, self.cross_attention_dim) , rng=random.Random(seed + 1 ) ).to(__magic_name__ )
# create init_image
lowerCamelCase__ : List[Any] = floats_tensor((1, 3, 64, 64) , rng=random.Random(__magic_name__ ) ).to(__magic_name__ )
lowerCamelCase__ : Optional[int] = image.cpu().permute(0 , 2 , 3 , 1 )[0]
lowerCamelCase__ : List[Any] = Image.fromarray(np.uinta(__magic_name__ ) ).convert("""RGB""" ).resize((256, 256) )
# create mask
lowerCamelCase__ : Optional[Any] = np.ones((64, 64) , dtype=np.floataa )
lowerCamelCase__ : Dict = 0
if str(__magic_name__ ).startswith("""mps""" ):
lowerCamelCase__ : Any = torch.manual_seed(__magic_name__ )
else:
lowerCamelCase__ : List[str] = torch.Generator(device=__magic_name__ ).manual_seed(__magic_name__ )
lowerCamelCase__ : List[str] = {
"""prompt""": """horse""",
"""image""": init_image,
"""mask_image""": mask,
"""image_embeds""": image_embeds,
"""negative_image_embeds""": negative_image_embeds,
"""generator""": generator,
"""height""": 64,
"""width""": 64,
"""num_inference_steps""": 2,
"""guidance_scale""": 4.0,
"""output_type""": """np""",
}
return inputs
def _snake_case (self ):
lowerCamelCase__ : str = """cpu"""
lowerCamelCase__ : List[str] = self.get_dummy_components()
lowerCamelCase__ : Optional[Any] = self.pipeline_class(**__magic_name__ )
lowerCamelCase__ : List[str] = pipe.to(__magic_name__ )
pipe.set_progress_bar_config(disable=__magic_name__ )
lowerCamelCase__ : Union[str, Any] = pipe(**self.get_dummy_inputs(__magic_name__ ) )
lowerCamelCase__ : Dict = output.images
lowerCamelCase__ : List[str] = pipe(
**self.get_dummy_inputs(__magic_name__ ) , return_dict=__magic_name__ , )[0]
lowerCamelCase__ : Optional[Any] = image[0, -3:, -3:, -1]
lowerCamelCase__ : Optional[int] = image_from_tuple[0, -3:, -3:, -1]
print(f"image.shape {image.shape}" )
assert image.shape == (1, 64, 64, 3)
lowerCamelCase__ : Dict = np.array(
[0.8_32_69_19, 0.73_79_04_67, 0.20_91_85_81, 0.9_30_96_12, 0.5_51_17_91, 0.43_71_33_28, 0.5_51_33_21, 0.49_92_29_34, 0.59_49_77_86] )
assert (
np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
), f" expected_slice {expected_slice}, but got {image_slice.flatten()}"
assert (
np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2
), f" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}"
def _snake_case (self ):
super().test_inference_batch_single_identical(expected_max_diff=3E-3 )
@slow
@require_torch_gpu
class __A ( unittest.TestCase ):
def _snake_case (self ):
# clean up the VRAM after each test
super().tearDown()
gc.collect()
torch.cuda.empty_cache()
def _snake_case (self ):
lowerCamelCase__ : Optional[int] = load_numpy(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
"""/kandinsky/kandinsky_inpaint_cat_with_hat_fp16.npy""" )
lowerCamelCase__ : Optional[Any] = load_image(
"""https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/kandinsky/cat.png""" )
lowerCamelCase__ : Dict = np.ones((768, 768) , dtype=np.floataa )
lowerCamelCase__ : Tuple = 0
lowerCamelCase__ : Optional[Any] = """a hat"""
lowerCamelCase__ : str = KandinskyPriorPipeline.from_pretrained(
"""kandinsky-community/kandinsky-2-1-prior""" , torch_dtype=torch.floataa )
pipe_prior.to(__magic_name__ )
lowerCamelCase__ : Union[str, Any] = KandinskyInpaintPipeline.from_pretrained(
"""kandinsky-community/kandinsky-2-1-inpaint""" , torch_dtype=torch.floataa )
lowerCamelCase__ : Optional[int] = pipeline.to(__magic_name__ )
pipeline.set_progress_bar_config(disable=__magic_name__ )
lowerCamelCase__ : Dict = torch.Generator(device="""cpu""" ).manual_seed(0 )
lowerCamelCase__ ,lowerCamelCase__ : str = pipe_prior(
__magic_name__ , generator=__magic_name__ , num_inference_steps=5 , negative_prompt="""""" , ).to_tuple()
lowerCamelCase__ : List[str] = pipeline(
__magic_name__ , image=__magic_name__ , mask_image=__magic_name__ , image_embeds=__magic_name__ , negative_image_embeds=__magic_name__ , generator=__magic_name__ , num_inference_steps=100 , height=768 , width=768 , output_type="""np""" , )
lowerCamelCase__ : int = output.images[0]
assert image.shape == (768, 768, 3)
assert_mean_pixel_difference(__magic_name__ , __magic_name__ )
| 157 | 0 |
"""simple docstring"""
from __future__ import annotations
from typing import Any
class _lowercase :
'''simple docstring'''
def __init__( self , __UpperCamelCase , __UpperCamelCase , __UpperCamelCase = 0 )-> None:
UpperCAmelCase__ : Dict = row, column
UpperCAmelCase__ : Union[str, Any] = [[default_value for c in range(__UpperCamelCase )] for r in range(__UpperCamelCase )]
def __str__( self )-> str:
UpperCAmelCase__ : List[Any] = F"Matrix consist of {self.row} rows and {self.column} columns\n"
# Make string identifier
UpperCAmelCase__ : Union[str, Any] = 0
for row_vector in self.array:
for obj in row_vector:
UpperCAmelCase__ : int = max(__UpperCamelCase , len(str(__UpperCamelCase ) ) )
UpperCAmelCase__ : Optional[Any] = F"%{max_element_length}s"
# Make string and return
def single_line(__UpperCamelCase ) -> str:
nonlocal string_format_identifier
UpperCAmelCase__ : Union[str, Any] = "["
line += ", ".join(string_format_identifier % (obj,) for obj in row_vector )
line += "]"
return line
s += "\n".join(single_line(__UpperCamelCase ) for row_vector in self.array )
return s
def __repr__( self )-> str:
return str(self )
def lowerCAmelCase__ ( self , __UpperCamelCase )-> bool:
if not (isinstance(__UpperCamelCase , (list, tuple) ) and len(__UpperCamelCase ) == 2):
return False
elif not (0 <= loc[0] < self.row and 0 <= loc[1] < self.column):
return False
else:
return True
def __getitem__( self , __UpperCamelCase )-> Any:
assert self.validate_indicies(__UpperCamelCase )
return self.array[loc[0]][loc[1]]
def __setitem__( self , __UpperCamelCase , __UpperCamelCase )-> None:
assert self.validate_indicies(__UpperCamelCase )
UpperCAmelCase__ : Dict = value
def __add__( self , __UpperCamelCase )-> Matrix:
assert isinstance(__UpperCamelCase , __UpperCamelCase )
assert self.row == another.row and self.column == another.column
# Add
UpperCAmelCase__ : Union[str, Any] = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
UpperCAmelCase__ : Union[str, Any] = self[r, c] + another[r, c]
return result
def __neg__( self )-> Matrix:
UpperCAmelCase__ : Union[str, Any] = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
UpperCAmelCase__ : List[Any] = -self[r, c]
return result
def __sub__( self , __UpperCamelCase )-> Matrix:
return self + (-another)
def __mul__( self , __UpperCamelCase )-> Matrix:
if isinstance(__UpperCamelCase , (int, float) ): # Scalar multiplication
UpperCAmelCase__ : Any = Matrix(self.row , self.column )
for r in range(self.row ):
for c in range(self.column ):
UpperCAmelCase__ : Optional[int] = self[r, c] * another
return result
elif isinstance(__UpperCamelCase , __UpperCamelCase ): # Matrix multiplication
assert self.column == another.row
UpperCAmelCase__ : int = Matrix(self.row , another.column )
for r in range(self.row ):
for c in range(another.column ):
for i in range(self.column ):
result[r, c] += self[r, i] * another[i, c]
return result
else:
UpperCAmelCase__ : List[str] = F"Unsupported type given for another ({type(__UpperCamelCase )})"
raise TypeError(__UpperCamelCase )
def lowerCAmelCase__ ( self )-> Matrix:
UpperCAmelCase__ : Dict = Matrix(self.column , self.row )
for r in range(self.row ):
for c in range(self.column ):
UpperCAmelCase__ : List[str] = self[r, c]
return result
def lowerCAmelCase__ ( self , __UpperCamelCase , __UpperCamelCase )-> Any:
assert isinstance(__UpperCamelCase , __UpperCamelCase ) and isinstance(__UpperCamelCase , __UpperCamelCase )
assert self.row == self.column == u.row == v.row # u, v should be column vector
assert u.column == v.column == 1 # u, v should be column vector
# Calculate
UpperCAmelCase__ : List[str] = v.transpose()
UpperCAmelCase__ : Dict = (v_t * self * u)[0, 0] + 1
if numerator_factor == 0:
return None # It's not invertable
return self - ((self * u) * (v_t * self) * (1.0 / numerator_factor))
# Testing
if __name__ == "__main__":
def a__ ( ):
'''simple docstring'''
UpperCAmelCase__ : Optional[int] = Matrix(3 , 3 , 0 )
for i in range(3 ):
UpperCAmelCase__ : List[str] = 1
print(F"a^(-1) is {ainv}" )
# u, v
UpperCAmelCase__ : str = Matrix(3 , 1 , 0 )
UpperCAmelCase__ : Union[str, Any] = 1, 2, -3
UpperCAmelCase__ : int = Matrix(3 , 1 , 0 )
UpperCAmelCase__ : List[Any] = 4, -2, 5
print(F"u is {u}" )
print(F"v is {v}" )
print(F"uv^T is {u * v.transpose()}" )
# Sherman Morrison
print(F"(a + uv^T)^(-1) is {ainv.sherman_morrison(lowerCAmelCase , lowerCAmelCase )}" )
def a__ ( ):
'''simple docstring'''
import doctest
doctest.testmod()
testa()
| 715 |
"""simple docstring"""
import unicodedata
from dataclasses import dataclass
from typing import Optional, Union
import numpy as np
from transformers.data.data_collator import DataCollatorMixin
from transformers.file_utils import PaddingStrategy
from transformers.tokenization_utils_base import PreTrainedTokenizerBase
def a__ ( lowerCAmelCase : str , lowerCAmelCase : Optional[Any] , lowerCAmelCase : Dict , lowerCAmelCase : List[Any] ):
'''simple docstring'''
if isinstance(lowerCAmelCase , lowerCAmelCase ):
UpperCAmelCase__ : Optional[int] = np.full((len(lowerCAmelCase ), sequence_length, 2) , lowerCAmelCase )
else:
UpperCAmelCase__ : Optional[Any] = np.full((len(lowerCAmelCase ), sequence_length) , lowerCAmelCase )
for i, tensor in enumerate(lowerCAmelCase ):
if padding_side == "right":
if isinstance(lowerCAmelCase , lowerCAmelCase ):
UpperCAmelCase__ : Dict = tensor[:sequence_length]
else:
UpperCAmelCase__ : Tuple = tensor[:sequence_length]
else:
if isinstance(lowerCAmelCase , lowerCAmelCase ):
UpperCAmelCase__ : Optional[Any] = tensor[:sequence_length]
else:
UpperCAmelCase__ : int = tensor[:sequence_length]
return out_tensor.tolist()
def a__ ( lowerCAmelCase : Optional[int] ):
'''simple docstring'''
UpperCAmelCase__ : Tuple = ord(lowerCAmelCase )
if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126):
return True
UpperCAmelCase__ : Optional[Any] = unicodedata.category(lowerCAmelCase )
if cat.startswith("P" ):
return True
return False
@dataclass
class _lowercase ( lowerCAmelCase_ ):
'''simple docstring'''
_A = 42
_A = True
_A = None
_A = None
_A = -100
_A = "pt"
def lowerCAmelCase__ ( self , __UpperCamelCase )-> List[str]:
import torch
UpperCAmelCase__ : Optional[Any] = "label" if "label" in features[0].keys() else "labels"
UpperCAmelCase__ : Dict = [feature[label_name] for feature in features] if label_name in features[0].keys() else None
UpperCAmelCase__ : str = self.tokenizer.pad(
__UpperCamelCase , padding=self.padding , max_length=self.max_length , pad_to_multiple_of=self.pad_to_multiple_of , return_tensors="pt" if labels is None else None , )
if labels is None:
return batch
UpperCAmelCase__ : Optional[Any] = torch.tensor(batch["entity_ids"] ).shape[1]
UpperCAmelCase__ : int = self.tokenizer.padding_side
if padding_side == "right":
UpperCAmelCase__ : int = [
list(__UpperCamelCase ) + [self.label_pad_token_id] * (sequence_length - len(__UpperCamelCase )) for label in labels
]
else:
UpperCAmelCase__ : List[Any] = [
[self.label_pad_token_id] * (sequence_length - len(__UpperCamelCase )) + list(__UpperCamelCase ) for label in labels
]
UpperCAmelCase__ : Optional[Any] = [feature["ner_tags"] for feature in features]
UpperCAmelCase__ : int = padding_tensor(__UpperCamelCase , -1 , __UpperCamelCase , __UpperCamelCase )
UpperCAmelCase__ : List[Any] = [feature["original_entity_spans"] for feature in features]
UpperCAmelCase__ : int = padding_tensor(__UpperCamelCase , (-1, -1) , __UpperCamelCase , __UpperCamelCase )
UpperCAmelCase__ : Optional[int] = {k: torch.tensor(__UpperCamelCase , dtype=torch.intaa ) for k, v in batch.items()}
return batch
| 660 | 0 |
"""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.whisper import WhisperForConditionalGeneration, WhisperProcessor
from .base import PipelineTool
class a__ ( a_ ):
__lowerCAmelCase = """openai/whisper-base"""
__lowerCAmelCase = (
"""This is a tool that transcribes an audio into text. It takes an input named `audio` and returns the """
"""transcribed text."""
)
__lowerCAmelCase = """transcriber"""
__lowerCAmelCase = WhisperProcessor
__lowerCAmelCase = WhisperForConditionalGeneration
__lowerCAmelCase = ["""audio"""]
__lowerCAmelCase = ["""text"""]
def __magic_name__ ( self , _a ):
return self.pre_processor(_a , return_tensors="pt" ).input_features
def __magic_name__ ( self , _a ):
return self.model.generate(inputs=_a )
def __magic_name__ ( self , _a ):
return self.pre_processor.batch_decode(_a , skip_special_tokens=_a )[0]
| 361 |
"""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
_A : Optional[int] = {
"""configuration_mgp_str""": ["""MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP""", """MgpstrConfig"""],
"""processing_mgp_str""": ["""MgpstrProcessor"""],
"""tokenization_mgp_str""": ["""MgpstrTokenizer"""],
}
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_A : Any = [
"""MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST""",
"""MgpstrModel""",
"""MgpstrPreTrainedModel""",
"""MgpstrForSceneTextRecognition""",
]
if TYPE_CHECKING:
from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig
from .processing_mgp_str import MgpstrProcessor
from .tokenization_mgp_str import MgpstrTokenizer
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_mgp_str import (
MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST,
MgpstrForSceneTextRecognition,
MgpstrModel,
MgpstrPreTrainedModel,
)
else:
import sys
_A : Tuple = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
| 361 | 1 |
"""simple docstring"""
from ..utils import DummyObject, requires_backends
class lowerCamelCase__ ( metaclass=snake_case ):
SCREAMING_SNAKE_CASE = ['''torch''', '''transformers''', '''onnx''']
def __init__( self ,*A ,**A ):
requires_backends(self ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
class lowerCamelCase__ ( metaclass=snake_case ):
SCREAMING_SNAKE_CASE = ['''torch''', '''transformers''', '''onnx''']
def __init__( self ,*A ,**A ):
requires_backends(self ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
class lowerCamelCase__ ( metaclass=snake_case ):
SCREAMING_SNAKE_CASE = ['''torch''', '''transformers''', '''onnx''']
def __init__( self ,*A ,**A ):
requires_backends(self ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
class lowerCamelCase__ ( metaclass=snake_case ):
SCREAMING_SNAKE_CASE = ['''torch''', '''transformers''', '''onnx''']
def __init__( self ,*A ,**A ):
requires_backends(self ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
class lowerCamelCase__ ( metaclass=snake_case ):
SCREAMING_SNAKE_CASE = ['''torch''', '''transformers''', '''onnx''']
def __init__( self ,*A ,**A ):
requires_backends(self ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
class lowerCamelCase__ ( metaclass=snake_case ):
SCREAMING_SNAKE_CASE = ['''torch''', '''transformers''', '''onnx''']
def __init__( self ,*A ,**A ):
requires_backends(self ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
@classmethod
def _UpperCamelCase ( cls ,*A ,**A ):
requires_backends(cls ,["""torch""", """transformers""", """onnx"""] )
| 74 |
"""simple docstring"""
import unittest
from transformers.utils.backbone_utils import (
BackboneMixin,
get_aligned_output_features_output_indices,
verify_out_features_out_indices,
)
class lowerCamelCase__ ( unittest.TestCase ):
def _UpperCamelCase ( self ):
UpperCAmelCase = ["""a""", """b""", """c"""]
# Defaults to last layer if both are None
UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices(A ,A ,A )
self.assertEqual(A ,["""c"""] )
self.assertEqual(A ,[2] )
# Out indices set to match out features
UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices(["""a""", """c"""] ,A ,A )
self.assertEqual(A ,["""a""", """c"""] )
self.assertEqual(A ,[0, 2] )
# Out features set to match out indices
UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices(A ,[0, 2] ,A )
self.assertEqual(A ,["""a""", """c"""] )
self.assertEqual(A ,[0, 2] )
# Out features selected from negative indices
UpperCAmelCase , UpperCAmelCase = get_aligned_output_features_output_indices(A ,[-3, -1] ,A )
self.assertEqual(A ,["""a""", """c"""] )
self.assertEqual(A ,[-3, -1] )
def _UpperCamelCase ( self ):
# Stage names must be set
with self.assertRaises(A ):
verify_out_features_out_indices(["""a""", """b"""] ,(0, 1) ,A )
# Out features must be a list
with self.assertRaises(A ):
verify_out_features_out_indices(("""a""", """b""") ,(0, 1) ,["""a""", """b"""] )
# Out features must be a subset of stage names
with self.assertRaises(A ):
verify_out_features_out_indices(["""a""", """b"""] ,(0, 1) ,["""a"""] )
# Out indices must be a list or tuple
with self.assertRaises(A ):
verify_out_features_out_indices(A ,0 ,["""a""", """b"""] )
# Out indices must be a subset of stage names
with self.assertRaises(A ):
verify_out_features_out_indices(A ,(0, 1) ,["""a"""] )
# Out features and out indices must be the same length
with self.assertRaises(A ):
verify_out_features_out_indices(["""a""", """b"""] ,(0,) ,["""a""", """b""", """c"""] )
# Out features should match out indices
with self.assertRaises(A ):
verify_out_features_out_indices(["""a""", """b"""] ,(0, 2) ,["""a""", """b""", """c"""] )
# Out features and out indices should be in order
with self.assertRaises(A ):
verify_out_features_out_indices(["""b""", """a"""] ,(0, 1) ,["""a""", """b"""] )
# Check passes with valid inputs
verify_out_features_out_indices(["""a""", """b""", """d"""] ,(0, 1, -1) ,["""a""", """b""", """c""", """d"""] )
def _UpperCamelCase ( self ):
UpperCAmelCase = BackboneMixin()
UpperCAmelCase = ["""a""", """b""", """c"""]
UpperCAmelCase = ["""a""", """c"""]
UpperCAmelCase = [0, 2]
# Check that the output features and indices are set correctly
self.assertEqual(backbone.out_features ,["""a""", """c"""] )
self.assertEqual(backbone.out_indices ,[0, 2] )
# Check out features and indices are updated correctly
UpperCAmelCase = ["""a""", """b"""]
self.assertEqual(backbone.out_features ,["""a""", """b"""] )
self.assertEqual(backbone.out_indices ,[0, 1] )
UpperCAmelCase = [-3, -1]
self.assertEqual(backbone.out_features ,["""a""", """c"""] )
self.assertEqual(backbone.out_indices ,[-3, -1] )
| 74 | 1 |
__snake_case :str ={
0: '0',
1: '1',
2: '2',
3: '3',
4: '4',
5: '5',
6: '6',
7: '7',
8: '8',
9: '9',
10: 'a',
11: 'b',
12: 'c',
13: 'd',
14: 'e',
15: 'f',
}
def lowerCamelCase_ ( lowerCAmelCase__ : float ) -> str:
'''simple docstring'''
assert type(lowerCAmelCase__ ) in (int, float) and decimal == int(lowerCAmelCase__ )
A = int(lowerCAmelCase__ )
A = ''
A = False
if decimal < 0:
A = True
decimal *= -1
while decimal > 0:
A , A = divmod(lowerCAmelCase__ , 16 )
A = values[remainder] + hexadecimal
A = '0x' + hexadecimal
if negative:
A = '-' + hexadecimal
return hexadecimal
if __name__ == "__main__":
import doctest
doctest.testmod() | 106 |
import unittest
from diffusers.pipelines.pipeline_utils import is_safetensors_compatible
class lowerCAmelCase__ ( unittest.TestCase ):
def __UpperCamelCase ( self : List[str] ) -> Any:
A = [
'safety_checker/pytorch_model.bin',
'safety_checker/model.safetensors',
'vae/diffusion_pytorch_model.bin',
'vae/diffusion_pytorch_model.safetensors',
'text_encoder/pytorch_model.bin',
'text_encoder/model.safetensors',
'unet/diffusion_pytorch_model.bin',
'unet/diffusion_pytorch_model.safetensors',
]
self.assertTrue(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : str ) -> List[Any]:
A = [
'unet/diffusion_pytorch_model.bin',
'unet/diffusion_pytorch_model.safetensors',
]
self.assertTrue(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : Any ) -> Tuple:
A = [
'safety_checker/pytorch_model.bin',
'safety_checker/model.safetensors',
'vae/diffusion_pytorch_model.bin',
'vae/diffusion_pytorch_model.safetensors',
'text_encoder/pytorch_model.bin',
'text_encoder/model.safetensors',
'unet/diffusion_pytorch_model.bin',
# Removed: 'unet/diffusion_pytorch_model.safetensors',
]
self.assertFalse(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : Dict ) -> Any:
A = [
'text_encoder/pytorch_model.bin',
'text_encoder/model.safetensors',
]
self.assertTrue(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : Optional[int] ) -> List[str]:
A = [
'safety_checker/pytorch_model.bin',
'safety_checker/model.safetensors',
'vae/diffusion_pytorch_model.bin',
'vae/diffusion_pytorch_model.safetensors',
'text_encoder/pytorch_model.bin',
# Removed: 'text_encoder/model.safetensors',
'unet/diffusion_pytorch_model.bin',
'unet/diffusion_pytorch_model.safetensors',
]
self.assertFalse(is_safetensors_compatible(__UpperCamelCase ) )
def __UpperCamelCase ( self : List[str] ) -> List[str]:
A = [
'safety_checker/pytorch_model.fp16.bin',
'safety_checker/model.fp16.safetensors',
'vae/diffusion_pytorch_model.fp16.bin',
'vae/diffusion_pytorch_model.fp16.safetensors',
'text_encoder/pytorch_model.fp16.bin',
'text_encoder/model.fp16.safetensors',
'unet/diffusion_pytorch_model.fp16.bin',
'unet/diffusion_pytorch_model.fp16.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : Optional[Any] ) -> Optional[Any]:
A = [
'unet/diffusion_pytorch_model.fp16.bin',
'unet/diffusion_pytorch_model.fp16.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : int ) -> Optional[int]:
# pass variant but use the non-variant filenames
A = [
'unet/diffusion_pytorch_model.bin',
'unet/diffusion_pytorch_model.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : Any ) -> List[str]:
A = [
'safety_checker/pytorch_model.fp16.bin',
'safety_checker/model.fp16.safetensors',
'vae/diffusion_pytorch_model.fp16.bin',
'vae/diffusion_pytorch_model.fp16.safetensors',
'text_encoder/pytorch_model.fp16.bin',
'text_encoder/model.fp16.safetensors',
'unet/diffusion_pytorch_model.fp16.bin',
# Removed: 'unet/diffusion_pytorch_model.fp16.safetensors',
]
A = 'fp16'
self.assertFalse(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : Optional[Any] ) -> Optional[int]:
A = [
'text_encoder/pytorch_model.fp16.bin',
'text_encoder/model.fp16.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : List[str] ) -> int:
# pass variant but use the non-variant filenames
A = [
'text_encoder/pytorch_model.bin',
'text_encoder/model.safetensors',
]
A = 'fp16'
self.assertTrue(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) )
def __UpperCamelCase ( self : List[str] ) -> Optional[Any]:
A = [
'safety_checker/pytorch_model.fp16.bin',
'safety_checker/model.fp16.safetensors',
'vae/diffusion_pytorch_model.fp16.bin',
'vae/diffusion_pytorch_model.fp16.safetensors',
'text_encoder/pytorch_model.fp16.bin',
# 'text_encoder/model.fp16.safetensors',
'unet/diffusion_pytorch_model.fp16.bin',
'unet/diffusion_pytorch_model.fp16.safetensors',
]
A = 'fp16'
self.assertFalse(is_safetensors_compatible(__UpperCamelCase , variant=__UpperCamelCase ) ) | 106 | 1 |
'''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 (
center_crop,
get_resize_output_image_size,
normalize,
rescale,
resize,
to_channel_dimension_format,
)
from ...image_utils import (
IMAGENET_STANDARD_MEAN,
IMAGENET_STANDARD_STD,
ChannelDimension,
ImageInput,
PILImageResampling,
make_list_of_images,
to_numpy_array,
valid_images,
)
from ...utils import TensorType, logging
UpperCamelCase__ : Any = logging.get_logger(__name__)
class _a (_lowerCamelCase):
"""simple docstring"""
SCREAMING_SNAKE_CASE = ['pixel_values']
def __init__( self , A__ = True , A__ = None , A__ = PILImageResampling.BILINEAR , A__ = True , A__ = None , A__ = True , A__ = 1 / 2_55 , A__ = True , A__ = None , A__ = None , **A__ , ) -> None:
super().__init__(**A__ )
_SCREAMING_SNAKE_CASE = size if size is not None else {"""shortest_edge""": 2_56}
_SCREAMING_SNAKE_CASE = get_size_dict(A__ , default_to_square=A__ )
_SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else {"""height""": 2_24, """width""": 2_24}
_SCREAMING_SNAKE_CASE = get_size_dict(A__ )
_SCREAMING_SNAKE_CASE = do_resize
_SCREAMING_SNAKE_CASE = size
_SCREAMING_SNAKE_CASE = resample
_SCREAMING_SNAKE_CASE = do_center_crop
_SCREAMING_SNAKE_CASE = crop_size
_SCREAMING_SNAKE_CASE = do_rescale
_SCREAMING_SNAKE_CASE = rescale_factor
_SCREAMING_SNAKE_CASE = do_normalize
_SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else IMAGENET_STANDARD_MEAN
_SCREAMING_SNAKE_CASE = image_std if image_std is not None else IMAGENET_STANDARD_STD
def UpperCamelCase ( self , A__ , A__ , A__ = PILImageResampling.BICUBIC , A__ = None , **A__ , ) -> np.ndarray:
_SCREAMING_SNAKE_CASE = get_size_dict(A__ , default_to_square=A__ )
if "shortest_edge" not in size:
raise ValueError(F"The `size` parameter must contain the key `shortest_edge`. Got {size.keys()}" )
_SCREAMING_SNAKE_CASE = get_resize_output_image_size(A__ , size=size["""shortest_edge"""] , default_to_square=A__ )
return resize(A__ , size=A__ , resample=A__ , data_format=A__ , **A__ )
def UpperCamelCase ( self , A__ , A__ , A__ = None , **A__ , ) -> np.ndarray:
_SCREAMING_SNAKE_CASE = get_size_dict(A__ )
return center_crop(A__ , size=(size["""height"""], size["""width"""]) , data_format=A__ , **A__ )
def UpperCamelCase ( self , A__ , A__ , A__ = None , **A__ ) -> np.ndarray:
return rescale(A__ , scale=A__ , data_format=A__ , **A__ )
def UpperCamelCase ( self , A__ , A__ , A__ , A__ = None , **A__ , ) -> np.ndarray:
return normalize(A__ , mean=A__ , std=A__ , data_format=A__ , **A__ )
def UpperCamelCase ( self , A__ , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = None , A__ = ChannelDimension.FIRST , **A__ , ) -> Tuple:
_SCREAMING_SNAKE_CASE = do_resize if do_resize is not None else self.do_resize
_SCREAMING_SNAKE_CASE = size if size is not None else self.size
_SCREAMING_SNAKE_CASE = get_size_dict(A__ , default_to_square=A__ )
_SCREAMING_SNAKE_CASE = resample if resample is not None else self.resample
_SCREAMING_SNAKE_CASE = do_center_crop if do_center_crop is not None else self.do_center_crop
_SCREAMING_SNAKE_CASE = crop_size if crop_size is not None else self.crop_size
_SCREAMING_SNAKE_CASE = get_size_dict(A__ )
_SCREAMING_SNAKE_CASE = do_rescale if do_rescale is not None else self.do_rescale
_SCREAMING_SNAKE_CASE = rescale_factor if rescale_factor is not None else self.rescale_factor
_SCREAMING_SNAKE_CASE = do_normalize if do_normalize is not None else self.do_normalize
_SCREAMING_SNAKE_CASE = image_mean if image_mean is not None else self.image_mean
_SCREAMING_SNAKE_CASE = image_std if image_std is not None else self.image_std
_SCREAMING_SNAKE_CASE = make_list_of_images(A__ )
if not valid_images(A__ ):
raise ValueError(
"""Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, """
"""torch.Tensor, tf.Tensor or jax.ndarray.""" )
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.""" )
# All transformations expect numpy arrays.
_SCREAMING_SNAKE_CASE = [to_numpy_array(A__ ) for image in images]
if do_resize:
_SCREAMING_SNAKE_CASE = [self.resize(image=A__ , size=A__ , resample=A__ ) for image in images]
if do_center_crop:
_SCREAMING_SNAKE_CASE = [self.center_crop(image=A__ , size=A__ ) for image in images]
if do_rescale:
_SCREAMING_SNAKE_CASE = [self.rescale(image=A__ , scale=A__ ) for image in images]
if do_normalize:
_SCREAMING_SNAKE_CASE = [self.normalize(image=A__ , mean=A__ , std=A__ ) for image in images]
_SCREAMING_SNAKE_CASE = [to_channel_dimension_format(A__ , A__ ) for image in images]
_SCREAMING_SNAKE_CASE = {"""pixel_values""": images}
return BatchFeature(data=A__ , tensor_type=A__ )
| 0 |
'''simple docstring'''
import pytest
import requests
from datasets.utils.file_utils import http_head
from .utils import OfflineSimulationMode, RequestWouldHangIndefinitelyError, offline
@pytest.mark.integration
def lowerCAmelCase_ ( ) -> List[Any]:
"""simple docstring"""
with offline(OfflineSimulationMode.CONNECTION_TIMES_OUT ):
with pytest.raises(SCREAMING_SNAKE_CASE_ ):
requests.request("""GET""" , """https://huggingface.co""" )
with pytest.raises(requests.exceptions.ConnectTimeout ):
requests.request("""GET""" , """https://huggingface.co""" , timeout=1.0 )
@pytest.mark.integration
def lowerCAmelCase_ ( ) -> int:
"""simple docstring"""
with offline(OfflineSimulationMode.CONNECTION_FAILS ):
with pytest.raises(requests.exceptions.ConnectionError ):
requests.request("""GET""" , """https://huggingface.co""" )
def lowerCAmelCase_ ( ) -> Optional[Any]:
"""simple docstring"""
with offline(OfflineSimulationMode.HF_DATASETS_OFFLINE_SET_TO_1 ):
with pytest.raises(SCREAMING_SNAKE_CASE_ ):
http_head("""https://huggingface.co""" )
| 0 | 1 |
import os
import re
import shutil
import sys
import tempfile
import unittest
import black
_lowerCAmelCase : Union[str, Any] = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))
sys.path.append(os.path.join(git_repo_path, 'utils'))
import check_copies # noqa: E402
# This is the reference code that will be used in the tests.
# If DDPMSchedulerOutput is changed in scheduling_ddpm.py, this code needs to be manually updated.
_lowerCAmelCase : Optional[Any] = ' \"""\n Output class for the scheduler\'s step function output.\n\n Args:\n prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the\n denoising loop.\n pred_original_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):\n The predicted denoised sample (x_{0}) based on the model output from the current timestep.\n `pred_original_sample` can be used to preview progress or for guidance.\n \"""\n\n prev_sample: torch.FloatTensor\n pred_original_sample: Optional[torch.FloatTensor] = None\n'
class lowerCAmelCase ( unittest.TestCase ):
'''simple docstring'''
def lowerCamelCase__ ( self : Any ) -> Optional[Any]:
'''simple docstring'''
lowerCamelCase = tempfile.mkdtemp()
os.makedirs(os.path.join(self.diffusers_dir , 'schedulers/' ) )
lowerCamelCase = self.diffusers_dir
shutil.copy(
os.path.join(SCREAMING_SNAKE_CASE_ , 'src/diffusers/schedulers/scheduling_ddpm.py' ) , os.path.join(self.diffusers_dir , 'schedulers/scheduling_ddpm.py' ) , )
def lowerCamelCase__ ( self : List[str] ) -> List[str]:
'''simple docstring'''
lowerCamelCase = 'src/diffusers'
shutil.rmtree(self.diffusers_dir )
def lowerCamelCase__ ( self : Optional[Any] , __snake_case : Optional[int] , __snake_case : List[str] , __snake_case : str , __snake_case : str=None ) -> Optional[int]:
'''simple docstring'''
lowerCamelCase = comment + F'''\nclass {class_name}(nn.Module):\n''' + class_code
if overwrite_result is not None:
lowerCamelCase = comment + F'''\nclass {class_name}(nn.Module):\n''' + overwrite_result
lowerCamelCase = black.Mode(target_versions={black.TargetVersion.PYaa} , line_length=119 )
lowerCamelCase = black.format_str(SCREAMING_SNAKE_CASE_ , mode=SCREAMING_SNAKE_CASE_ )
lowerCamelCase = os.path.join(self.diffusers_dir , 'new_code.py' )
with open(SCREAMING_SNAKE_CASE_ , 'w' , newline='\n' ) as f:
f.write(SCREAMING_SNAKE_CASE_ )
if overwrite_result is None:
self.assertTrue(len(check_copies.is_copy_consistent(SCREAMING_SNAKE_CASE_ ) ) == 0 )
else:
check_copies.is_copy_consistent(f.name , overwrite=SCREAMING_SNAKE_CASE_ )
with open(SCREAMING_SNAKE_CASE_ , 'r' ) as f:
self.assertTrue(f.read() , SCREAMING_SNAKE_CASE_ )
def lowerCamelCase__ ( self : Union[str, Any] ) -> str:
'''simple docstring'''
lowerCamelCase = check_copies.find_code_in_diffusers('schedulers.scheduling_ddpm.DDPMSchedulerOutput' )
self.assertEqual(SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ )
def lowerCamelCase__ ( self : Optional[Any] ) -> Union[str, Any]:
'''simple docstring'''
self.check_copy_consistency(
'# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput' , 'DDPMSchedulerOutput' , REFERENCE_CODE + '\n' , )
# With no empty line at the end
self.check_copy_consistency(
'# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput' , 'DDPMSchedulerOutput' , SCREAMING_SNAKE_CASE_ , )
# Copy consistency with rename
self.check_copy_consistency(
'# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test' , 'TestSchedulerOutput' , re.sub('DDPM' , 'Test' , SCREAMING_SNAKE_CASE_ ) , )
# Copy consistency with a really long name
lowerCamelCase = 'TestClassWithAReallyLongNameBecauseSomePeopleLikeThatForSomeReason'
self.check_copy_consistency(
F'''# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->{long_class_name}''' , F'''{long_class_name}SchedulerOutput''' , re.sub('Bert' , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ ) , )
# Copy consistency with overwrite
self.check_copy_consistency(
'# Copied from diffusers.schedulers.scheduling_ddpm.DDPMSchedulerOutput with DDPM->Test' , 'TestSchedulerOutput' , SCREAMING_SNAKE_CASE_ , overwrite_result=re.sub('DDPM' , 'Test' , SCREAMING_SNAKE_CASE_ ) , )
| 246 |
import platform
from argparse import ArgumentParser
import huggingface_hub
from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand
def UpperCamelCase ( snake_case__ : Dict ) -> Optional[int]:
return EnvironmentCommand()
class lowerCAmelCase_ ( a__ ):
@staticmethod
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> Tuple:
UpperCamelCase : List[Any] = parser.add_parser('env' )
download_parser.set_defaults(func=SCREAMING_SNAKE_CASE_ )
def snake_case_ ( self ) -> Optional[Any]:
UpperCamelCase : Any = huggingface_hub.__version__
UpperCamelCase : int = 'not installed'
UpperCamelCase : Union[str, Any] = 'NA'
if is_torch_available():
import torch
UpperCamelCase : Any = torch.__version__
UpperCamelCase : str = torch.cuda.is_available()
UpperCamelCase : Dict = 'not installed'
if is_transformers_available():
import transformers
UpperCamelCase : str = transformers.__version__
UpperCamelCase : Optional[Any] = 'not installed'
if is_accelerate_available():
import accelerate
UpperCamelCase : Dict = accelerate.__version__
UpperCamelCase : List[str] = 'not installed'
if is_xformers_available():
import xformers
UpperCamelCase : List[str] = xformers.__version__
UpperCamelCase : Dict = {
'`diffusers` version': version,
'Platform': platform.platform(),
'Python version': platform.python_version(),
'PyTorch version (GPU?)': F"""{pt_version} ({pt_cuda_available})""",
'Huggingface_hub version': hub_version,
'Transformers version': transformers_version,
'Accelerate version': accelerate_version,
'xFormers version': xformers_version,
'Using GPU in script?': '<fill in>',
'Using distributed or parallel set-up in script?': '<fill in>',
}
print('\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n' )
print(self.format_dict(SCREAMING_SNAKE_CASE_ ) )
return info
@staticmethod
def snake_case_ ( SCREAMING_SNAKE_CASE_ ) -> Tuple:
return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n"
| 40 | 0 |
from argparse import ArgumentParser, Namespace
from ..utils import logging
from . import BaseTransformersCLICommand
def _lowerCAmelCase ( A__ ):
return ConvertCommand(
args.model_type , args.tf_checkpoint , args.pytorch_dump_output , args.config , args.finetuning_task_name )
a__ : List[Any] = "\ntransformers can only be used from the commandline to convert TensorFlow models in PyTorch, In that case, it requires\nTensorFlow to be installed. Please see https://www.tensorflow.org/install/ for installation instructions.\n"
class UpperCAmelCase__( __lowerCAmelCase ):
'''simple docstring'''
@staticmethod
def UpperCAmelCase ( lowerCAmelCase : ArgumentParser) -> Optional[int]:
"""simple docstring"""
lowercase__ = parser.add_parser(
'convert' , help='CLI tool to run convert model from original author checkpoints to Transformers PyTorch checkpoints.' , )
train_parser.add_argument('--model_type' , type=lowerCamelCase__ , required=lowerCamelCase__ , help='Model\'s type.')
train_parser.add_argument(
'--tf_checkpoint' , type=lowerCamelCase__ , required=lowerCamelCase__ , help='TensorFlow checkpoint path or folder.')
train_parser.add_argument(
'--pytorch_dump_output' , type=lowerCamelCase__ , required=lowerCamelCase__ , help='Path to the PyTorch saved model output.')
train_parser.add_argument('--config' , type=lowerCamelCase__ , default='' , help='Configuration file path or folder.')
train_parser.add_argument(
'--finetuning_task_name' , type=lowerCamelCase__ , default=lowerCamelCase__ , help='Optional fine-tuning task name if the TF model was a finetuned model.' , )
train_parser.set_defaults(func=lowerCamelCase__)
def __init__( self : Optional[Any] , lowerCAmelCase : str , lowerCAmelCase : str , lowerCAmelCase : str , lowerCAmelCase : str , lowerCAmelCase : str , *lowerCAmelCase : Optional[int] , ) -> List[Any]:
"""simple docstring"""
lowercase__ = logging.get_logger('transformers-cli/converting')
self._logger.info(f'''Loading model {model_type}''')
lowercase__ = model_type
lowercase__ = tf_checkpoint
lowercase__ = pytorch_dump_output
lowercase__ = config
lowercase__ = finetuning_task_name
def UpperCAmelCase ( self : Optional[Any]) -> Optional[Any]:
"""simple docstring"""
if self._model_type == "albert":
try:
from ..models.albert.convert_albert_original_tf_checkpoint_to_pytorch import (
convert_tf_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__)
convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output)
elif self._model_type == "bert":
try:
from ..models.bert.convert_bert_original_tf_checkpoint_to_pytorch import (
convert_tf_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__)
convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output)
elif self._model_type == "funnel":
try:
from ..models.funnel.convert_funnel_original_tf_checkpoint_to_pytorch import (
convert_tf_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__)
convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output)
elif self._model_type == "t5":
try:
from ..models.ta.convert_ta_original_tf_checkpoint_to_pytorch import convert_tf_checkpoint_to_pytorch
except ImportError:
raise ImportError(lowerCamelCase__)
convert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output)
elif self._model_type == "gpt":
from ..models.openai.convert_openai_original_tf_checkpoint_to_pytorch import (
convert_openai_checkpoint_to_pytorch,
)
convert_openai_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output)
elif self._model_type == "transfo_xl":
try:
from ..models.transfo_xl.convert_transfo_xl_original_tf_checkpoint_to_pytorch import (
convert_transfo_xl_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__)
if "ckpt" in self._tf_checkpoint.lower():
lowercase__ = self._tf_checkpoint
lowercase__ = ''''''
else:
lowercase__ = self._tf_checkpoint
lowercase__ = ''''''
convert_transfo_xl_checkpoint_to_pytorch(
lowerCamelCase__ , self._config , self._pytorch_dump_output , lowerCamelCase__)
elif self._model_type == "gpt2":
try:
from ..models.gpta.convert_gpta_original_tf_checkpoint_to_pytorch import (
convert_gpta_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__)
convert_gpta_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output)
elif self._model_type == "xlnet":
try:
from ..models.xlnet.convert_xlnet_original_tf_checkpoint_to_pytorch import (
convert_xlnet_checkpoint_to_pytorch,
)
except ImportError:
raise ImportError(lowerCamelCase__)
convert_xlnet_checkpoint_to_pytorch(
self._tf_checkpoint , self._config , self._pytorch_dump_output , self._finetuning_task_name)
elif self._model_type == "xlm":
from ..models.xlm.convert_xlm_original_pytorch_checkpoint_to_pytorch import (
convert_xlm_checkpoint_to_pytorch,
)
convert_xlm_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output)
elif self._model_type == "lxmert":
from ..models.lxmert.convert_lxmert_original_tf_checkpoint_to_pytorch import (
convert_lxmert_checkpoint_to_pytorch,
)
convert_lxmert_checkpoint_to_pytorch(self._tf_checkpoint , self._pytorch_dump_output)
elif self._model_type == "rembert":
from ..models.rembert.convert_rembert_tf_checkpoint_to_pytorch import (
convert_rembert_tf_checkpoint_to_pytorch,
)
convert_rembert_tf_checkpoint_to_pytorch(self._tf_checkpoint , self._config , self._pytorch_dump_output)
else:
raise ValueError(
'--model_type should be selected in the list [bert, gpt, gpt2, t5, transfo_xl, xlnet, xlm, lxmert]')
| 718 |
import json
from typing import List, Optional, Tuple
from tokenizers import pre_tokenizers, processors
from ...tokenization_utils_base import AddedToken, BatchEncoding
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_bart import BartTokenizer
a__ : List[Any] = logging.get_logger(__name__)
a__ : Optional[int] = {"vocab_file": "vocab.json", "merges_file": "merges.txt", "tokenizer_file": "tokenizer.json"}
# See all BART models at https://huggingface.co/models?filter=bart
a__ : List[Any] = {
"vocab_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/vocab.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/vocab.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/vocab.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/vocab.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/vocab.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/vocab.json",
},
"merges_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/merges.txt",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/merges.txt",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/merges.txt",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/merges.txt",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/merges.txt",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/merges.txt",
},
"tokenizer_file": {
"facebook/bart-base": "https://huggingface.co/facebook/bart-base/resolve/main/tokenizer.json",
"facebook/bart-large": "https://huggingface.co/facebook/bart-large/resolve/main/tokenizer.json",
"facebook/bart-large-mnli": "https://huggingface.co/facebook/bart-large-mnli/resolve/main/tokenizer.json",
"facebook/bart-large-cnn": "https://huggingface.co/facebook/bart-large-cnn/resolve/main/tokenizer.json",
"facebook/bart-large-xsum": "https://huggingface.co/facebook/bart-large-xsum/resolve/main/tokenizer.json",
"yjernite/bart_eli5": "https://huggingface.co/yjernite/bart_eli5/resolve/main/tokenizer.json",
},
}
a__ : int = {
"facebook/bart-base": 10_24,
"facebook/bart-large": 10_24,
"facebook/bart-large-mnli": 10_24,
"facebook/bart-large-cnn": 10_24,
"facebook/bart-large-xsum": 10_24,
"yjernite/bart_eli5": 10_24,
}
class UpperCAmelCase__( lowerCamelCase ):
'''simple docstring'''
A : Optional[Any] = VOCAB_FILES_NAMES
A : Dict = PRETRAINED_VOCAB_FILES_MAP
A : str = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
A : int = ["input_ids", "attention_mask"]
A : Any = BartTokenizer
def __init__( self : List[Any] , lowerCAmelCase : Any=None , lowerCAmelCase : Optional[int]=None , lowerCAmelCase : List[Any]=None , lowerCAmelCase : str="replace" , lowerCAmelCase : str="<s>" , lowerCAmelCase : int="</s>" , lowerCAmelCase : Optional[int]="</s>" , lowerCAmelCase : Union[str, Any]="<s>" , lowerCAmelCase : str="<unk>" , lowerCAmelCase : int="<pad>" , lowerCAmelCase : int="<mask>" , lowerCAmelCase : Dict=False , lowerCAmelCase : List[Any]=True , **lowerCAmelCase : Optional[Any] , ) -> Optional[Any]:
"""simple docstring"""
super().__init__(
lowerCAmelCase , lowerCAmelCase , tokenizer_file=lowerCAmelCase , errors=lowerCAmelCase , bos_token=lowerCAmelCase , eos_token=lowerCAmelCase , sep_token=lowerCAmelCase , cls_token=lowerCAmelCase , unk_token=lowerCAmelCase , pad_token=lowerCAmelCase , mask_token=lowerCAmelCase , add_prefix_space=lowerCAmelCase , trim_offsets=lowerCAmelCase , **lowerCAmelCase , )
lowercase__ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__())
if pre_tok_state.get('add_prefix_space' , lowerCAmelCase) != add_prefix_space:
lowercase__ = getattr(lowerCAmelCase , pre_tok_state.pop('type'))
lowercase__ = add_prefix_space
lowercase__ = pre_tok_class(**lowerCAmelCase)
lowercase__ = add_prefix_space
# the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__`
lowercase__ = 'post_processor'
lowercase__ = getattr(self.backend_tokenizer , lowerCAmelCase , lowerCAmelCase)
if tokenizer_component_instance:
lowercase__ = json.loads(tokenizer_component_instance.__getstate__())
# The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class`
if "sep" in state:
lowercase__ = tuple(state['sep'])
if "cls" in state:
lowercase__ = tuple(state['cls'])
lowercase__ = False
if state.get('add_prefix_space' , lowerCAmelCase) != add_prefix_space:
lowercase__ = add_prefix_space
lowercase__ = True
if state.get('trim_offsets' , lowerCAmelCase) != trim_offsets:
lowercase__ = trim_offsets
lowercase__ = True
if changes_to_apply:
lowercase__ = getattr(lowerCAmelCase , state.pop('type'))
lowercase__ = component_class(**lowerCAmelCase)
setattr(self.backend_tokenizer , lowerCAmelCase , lowerCAmelCase)
@property
def UpperCAmelCase ( self : Union[str, Any]) -> str:
"""simple docstring"""
if self._mask_token is None:
if self.verbose:
logger.error('Using mask_token, but it is not set yet.')
return None
return str(self._mask_token)
@mask_token.setter
def UpperCAmelCase ( self : Tuple , lowerCAmelCase : int) -> Optional[int]:
"""simple docstring"""
lowercase__ = AddedToken(lowerCAmelCase , lstrip=lowerCAmelCase , rstrip=lowerCAmelCase) if isinstance(lowerCAmelCase , lowerCAmelCase) else value
lowercase__ = value
def UpperCAmelCase ( self : List[str] , *lowerCAmelCase : Tuple , **lowerCAmelCase : Optional[int]) -> BatchEncoding:
"""simple docstring"""
lowercase__ = kwargs.get('is_split_into_words' , lowerCAmelCase)
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
'to use it with pretokenized inputs.')
return super()._batch_encode_plus(*lowerCAmelCase , **lowerCAmelCase)
def UpperCAmelCase ( self : str , *lowerCAmelCase : Tuple , **lowerCAmelCase : str) -> BatchEncoding:
"""simple docstring"""
lowercase__ = kwargs.get('is_split_into_words' , lowerCAmelCase)
if is_split_into_words and not self.add_prefix_space:
raise ValueError(
f'''You need to instantiate {self.__class__.__name__} with add_prefix_space=True '''
'to use it with pretokenized inputs.')
return super()._encode_plus(*lowerCAmelCase , **lowerCAmelCase)
def UpperCAmelCase ( self : Dict , lowerCAmelCase : str , lowerCAmelCase : Optional[str] = None) -> Tuple[str]:
"""simple docstring"""
lowercase__ = self._tokenizer.model.save(lowerCAmelCase , name=lowerCAmelCase)
return tuple(lowerCAmelCase)
def UpperCAmelCase ( self : Any , lowerCAmelCase : str , lowerCAmelCase : Optional[int]=None) -> Tuple:
"""simple docstring"""
lowercase__ = [self.bos_token_id] + token_ids_a + [self.eos_token_id]
if token_ids_a is None:
return output
return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]
def UpperCAmelCase ( self : Union[str, Any] , lowerCAmelCase : List[int] , lowerCAmelCase : Optional[List[int]] = None) -> List[int]:
"""simple docstring"""
lowercase__ = [self.sep_token_id]
lowercase__ = [self.cls_token_id]
if token_ids_a is None:
return len(cls + token_ids_a + sep) * [0]
return len(cls + token_ids_a + sep + sep + token_ids_a + sep) * [0]
| 642 | 0 |
from typing import TYPE_CHECKING
from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available, is_vision_available
_SCREAMING_SNAKE_CASE : Dict = {
'configuration_pix2struct': [
'PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP',
'Pix2StructConfig',
'Pix2StructTextConfig',
'Pix2StructVisionConfig',
],
'processing_pix2struct': ['Pix2StructProcessor'],
}
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE : Optional[int] = ['Pix2StructImageProcessor']
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
_SCREAMING_SNAKE_CASE : List[str] = [
'PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST',
'Pix2StructPreTrainedModel',
'Pix2StructForConditionalGeneration',
'Pix2StructVisionModel',
'Pix2StructTextModel',
]
if TYPE_CHECKING:
from .configuration_pixastruct import (
PIX2STRUCT_PRETRAINED_CONFIG_ARCHIVE_MAP,
PixaStructConfig,
PixaStructTextConfig,
PixaStructVisionConfig,
)
from .processing_pixastruct import PixaStructProcessor
try:
if not is_vision_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .image_processing_pixastruct import PixaStructImageProcessor
try:
if not is_torch_available():
raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
pass
else:
from .modeling_pixastruct import (
PIX2STRUCT_PRETRAINED_MODEL_ARCHIVE_LIST,
PixaStructForConditionalGeneration,
PixaStructPreTrainedModel,
PixaStructTextModel,
PixaStructVisionModel,
)
else:
import sys
_SCREAMING_SNAKE_CASE : Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
| 226 |
def A_ ( lowercase_ , lowercase_ , lowercase_ ) -> float:
return round(float(moles / volume ) * nfactor )
def A_ ( lowercase_ , lowercase_ , lowercase_ ) -> float:
return round(float((moles * 0.08_21 * temperature) / (volume) ) )
def A_ ( lowercase_ , lowercase_ , lowercase_ ) -> float:
return round(float((moles * 0.08_21 * temperature) / (pressure) ) )
def A_ ( lowercase_ , lowercase_ , lowercase_ ) -> float:
return round(float((pressure * volume) / (0.08_21 * moles) ) )
if __name__ == "__main__":
import doctest
doctest.testmod()
| 326 | 0 |
"""simple docstring"""
import platform
from argparse import ArgumentParser
import huggingface_hub
from .. import __version__ as version
from ..utils import is_accelerate_available, is_torch_available, is_transformers_available, is_xformers_available
from . import BaseDiffusersCLICommand
def a__ ( __lowercase ) -> Union[str, Any]:
return EnvironmentCommand()
class snake_case ( _UpperCamelCase):
@staticmethod
def a_ ( a__ : ArgumentParser ) -> Union[str, Any]:
'''simple docstring'''
_A = parser.add_parser("env" )
download_parser.set_defaults(func=a__ )
def a_ ( self : List[Any] ) -> Any:
'''simple docstring'''
_A = huggingface_hub.__version__
_A = "not installed"
_A = "NA"
if is_torch_available():
import torch
_A = torch.__version__
_A = torch.cuda.is_available()
_A = "not installed"
if is_transformers_available():
import transformers
_A = transformers.__version__
_A = "not installed"
if is_accelerate_available():
import accelerate
_A = accelerate.__version__
_A = "not installed"
if is_xformers_available():
import xformers
_A = xformers.__version__
_A = {
"`diffusers` version": version,
"Platform": platform.platform(),
"Python version": platform.python_version(),
"PyTorch version (GPU?)": F"""{pt_version} ({pt_cuda_available})""",
"Huggingface_hub version": hub_version,
"Transformers version": transformers_version,
"Accelerate version": accelerate_version,
"xFormers version": xformers_version,
"Using GPU in script?": "<fill in>",
"Using distributed or parallel set-up in script?": "<fill in>",
}
print("\nCopy-and-paste the text below in your GitHub issue and FILL OUT the two last points.\n" )
print(self.format_dict(a__ ) )
return info
@staticmethod
def a_ ( a__ : Optional[Any] ) -> List[str]:
'''simple docstring'''
return "\n".join([F"""- {prop}: {val}""" for prop, val in d.items()] ) + "\n" | 621 |
"""simple docstring"""
def a__ ( __lowercase , __lowercase ) -> int:
while a != 0:
_A , _A = b % a, a
return b
def a__ ( __lowercase , __lowercase ) -> int:
if gcd(__lowercase , __lowercase ) != 1:
_A = f"""mod inverse of {a!r} and {m!r} does not exist"""
raise ValueError(__lowercase )
_A , _A , _A = 1, 0, a
_A , _A , _A = 0, 1, m
while va != 0:
_A = ua // va
_A , _A , _A , _A , _A , _A = (ua - q * va), (ua - q * va), (ua - q * va), va, va, va
return ua % m | 621 | 1 |
from __future__ import annotations
import copy
import tempfile
import unittest
from transformers import CONFIG_MAPPING, AutoConfig, BertConfig, GPTaConfig, TaConfig, TapasConfig, is_tf_available
from transformers.testing_utils import (
DUMMY_UNKNOWN_IDENTIFIER,
SMALL_MODEL_IDENTIFIER,
RequestCounter,
require_tensorflow_probability,
require_tf,
slow,
)
from ..bert.test_modeling_bert import BertModelTester
if is_tf_available():
from transformers import (
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSeqaSeqLM,
TFAutoModelForSequenceClassification,
TFAutoModelForTableQuestionAnswering,
TFAutoModelForTokenClassification,
TFAutoModelWithLMHead,
TFBertForMaskedLM,
TFBertForPreTraining,
TFBertForQuestionAnswering,
TFBertForSequenceClassification,
TFBertModel,
TFFunnelBaseModel,
TFFunnelModel,
TFGPTaLMHeadModel,
TFRobertaForMaskedLM,
TFTaForConditionalGeneration,
TFTapasForQuestionAnswering,
)
from transformers.models.auto.modeling_tf_auto import (
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_MASKED_LM_MAPPING,
TF_MODEL_FOR_PRETRAINING_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
TF_MODEL_MAPPING,
)
from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST
from transformers.models.tapas.modeling_tf_tapas import TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST
class SCREAMING_SNAKE_CASE ( lowerCAmelCase ):
'''simple docstring'''
UpperCamelCase_ : Optional[int] = '''new-model'''
if is_tf_available():
class SCREAMING_SNAKE_CASE ( lowerCAmelCase ):
'''simple docstring'''
UpperCamelCase_ : Union[str, Any] = NewModelConfig
@require_tf
class SCREAMING_SNAKE_CASE ( unittest.TestCase ):
'''simple docstring'''
@slow
def _A ( self : List[str] ):
SCREAMING_SNAKE_CASE : Dict = "bert-base-cased"
SCREAMING_SNAKE_CASE : Optional[Any] = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : str = TFAutoModel.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
@slow
def _A ( self : Any ):
SCREAMING_SNAKE_CASE : Dict = "bert-base-cased"
SCREAMING_SNAKE_CASE : List[Any] = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForPreTraining.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
@slow
def _A ( self : List[Any] ):
for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE : Any = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : Dict = TFAutoModelForCausalLM.from_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForCausalLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
@slow
def _A ( self : Any ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
@slow
def _A ( self : Union[str, Any] ):
for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE : Dict = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : str = TFAutoModelForMaskedLM.from_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForMaskedLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
@slow
def _A ( self : Tuple ):
for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
SCREAMING_SNAKE_CASE : Tuple = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForSeqaSeqLM.from_pretrained(UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
@slow
def _A ( self : List[Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
SCREAMING_SNAKE_CASE : str = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : int = TFAutoModelForSequenceClassification.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
@slow
def _A ( self : Union[str, Any] ):
# for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
for model_name in ["bert-base-uncased"]:
SCREAMING_SNAKE_CASE : Union[str, Any] = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : Tuple = TFAutoModelForQuestionAnswering.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
@slow
@require_tensorflow_probability
def _A ( self : Optional[int] ):
for model_name in TF_TAPAS_PRETRAINED_MODEL_ARCHIVE_LIST[5:6]:
SCREAMING_SNAKE_CASE : int = AutoConfig.from_pretrained(UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : List[str] = TFAutoModelForTableQuestionAnswering.from_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE , SCREAMING_SNAKE_CASE : Dict = TFAutoModelForTableQuestionAnswering.from_pretrained(
UpperCAmelCase_ , output_loading_info=UpperCAmelCase_ )
self.assertIsNotNone(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
def _A ( self : Any ):
SCREAMING_SNAKE_CASE : List[str] = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
self.assertEqual(model.num_parameters() , 1_4410 )
self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase_ ) , 1_4410 )
def _A ( self : Optional[Any] ):
SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModelWithLMHead.from_pretrained(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
self.assertEqual(model.num_parameters() , 1_4410 )
self.assertEqual(model.num_parameters(only_trainable=UpperCAmelCase_ ) , 1_4410 )
def _A ( self : Optional[Any] ):
# For the auto model mapping, FunnelConfig has two models: FunnelModel and FunnelBaseModel
SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained("sgugger/funnel-random-tiny" )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : Dict = copy.deepcopy(model.config )
SCREAMING_SNAKE_CASE : str = ["FunnelBaseModel"]
SCREAMING_SNAKE_CASE : List[Any] = TFAutoModel.from_config(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : List[str] = TFAutoModel.from_pretrained(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
def _A ( self : Optional[int] ):
try:
AutoConfig.register("new-model" , UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : int = [
TFAutoModel,
TFAutoModelForCausalLM,
TFAutoModelForMaskedLM,
TFAutoModelForPreTraining,
TFAutoModelForQuestionAnswering,
TFAutoModelForSequenceClassification,
TFAutoModelForTokenClassification,
]
for auto_class in auto_classes:
with self.subTest(auto_class.__name__ ):
# Wrong config class will raise an error
with self.assertRaises(UpperCAmelCase_ ):
auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ )
auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ )
# Trying to register something existing in the Transformers library will raise an error
with self.assertRaises(UpperCAmelCase_ ):
auto_class.register(UpperCAmelCase_ , UpperCAmelCase_ )
# Now that the config is registered, it can be used as any other config with the auto-API
SCREAMING_SNAKE_CASE : Optional[int] = BertModelTester(self ).get_config()
SCREAMING_SNAKE_CASE : Any = NewModelConfig(**tiny_config.to_dict() )
SCREAMING_SNAKE_CASE : Dict = auto_class.from_config(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
with tempfile.TemporaryDirectory() as tmp_dir:
model.save_pretrained(UpperCAmelCase_ )
SCREAMING_SNAKE_CASE : Tuple = auto_class.from_pretrained(UpperCAmelCase_ )
self.assertIsInstance(UpperCAmelCase_ , UpperCAmelCase_ )
finally:
if "new-model" in CONFIG_MAPPING._extra_content:
del CONFIG_MAPPING._extra_content["new-model"]
for mapping in (
TF_MODEL_MAPPING,
TF_MODEL_FOR_PRETRAINING_MAPPING,
TF_MODEL_FOR_QUESTION_ANSWERING_MAPPING,
TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING,
TF_MODEL_FOR_CAUSAL_LM_MAPPING,
TF_MODEL_FOR_MASKED_LM_MAPPING,
):
if NewModelConfig in mapping._extra_content:
del mapping._extra_content[NewModelConfig]
def _A ( self : Any ):
with self.assertRaisesRegex(
UpperCAmelCase_ , "bert-base is not a local folder and is not a valid model identifier" ):
SCREAMING_SNAKE_CASE : Dict = TFAutoModel.from_pretrained("bert-base" )
def _A ( self : Optional[int] ):
with self.assertRaisesRegex(
UpperCAmelCase_ , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ):
SCREAMING_SNAKE_CASE : int = TFAutoModel.from_pretrained(UpperCAmelCase_ , revision="aaaaaa" )
def _A ( self : str ):
with self.assertRaisesRegex(
UpperCAmelCase_ , "hf-internal-testing/config-no-model does not appear to have a file named pytorch_model.bin" , ):
SCREAMING_SNAKE_CASE : Optional[int] = TFAutoModel.from_pretrained("hf-internal-testing/config-no-model" )
def _A ( self : Dict ):
with self.assertRaisesRegex(UpperCAmelCase_ , "Use `from_pt=True` to load this model" ):
SCREAMING_SNAKE_CASE : str = TFAutoModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only" )
def _A ( self : Optional[int] ):
# Make sure we have cached the model.
SCREAMING_SNAKE_CASE : str = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" )
with RequestCounter() as counter:
SCREAMING_SNAKE_CASE : Dict = TFAutoModel.from_pretrained("hf-internal-testing/tiny-random-bert" )
self.assertEqual(counter.get_request_count , 0 )
self.assertEqual(counter.head_request_count , 1 )
self.assertEqual(counter.other_request_count , 0 )
# With a sharded checkpoint
SCREAMING_SNAKE_CASE : Tuple = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" )
with RequestCounter() as counter:
SCREAMING_SNAKE_CASE : Optional[Any] = TFAutoModel.from_pretrained("ArthurZ/tiny-random-bert-sharded" )
self.assertEqual(counter.get_request_count , 0 )
self.assertEqual(counter.head_request_count , 1 )
self.assertEqual(counter.other_request_count , 0 )
| 62 |
import os
from argparse import ArgumentParser
from typing import List
import torch.utils.data
from datasets import Dataset, IterableDataset
from datasets.distributed import split_dataset_by_node
UpperCAmelCase__ : List[Any] = 4
UpperCAmelCase__ : Optional[Any] = 3
class __lowercase ( lowerCamelCase__ ):
pass
def A ( snake_case__ : List[str] ) -> str:
'''simple docstring'''
for shard in shards:
for i in range(snake_case__ ):
yield {"i": i, "shard": shard}
def A ( ) -> List[str]:
'''simple docstring'''
__snake_case = int(os.environ['RANK'] )
__snake_case = int(os.environ['WORLD_SIZE'] )
__snake_case = ArgumentParser()
parser.add_argument('--streaming' , type=snake_case__ )
parser.add_argument('--local_rank' , type=snake_case__ )
parser.add_argument('--num_workers' , type=snake_case__ , default=0 )
__snake_case = parser.parse_args()
__snake_case = args.streaming
__snake_case = args.num_workers
__snake_case = {'shards': [f"shard_{shard_idx}" for shard_idx in range(snake_case__ )]}
__snake_case = IterableDataset.from_generator(snake_case__ , gen_kwargs=snake_case__ )
if not streaming:
__snake_case = Dataset.from_list(list(snake_case__ ) )
__snake_case = split_dataset_by_node(snake_case__ , rank=snake_case__ , world_size=snake_case__ )
__snake_case = torch.utils.data.DataLoader(snake_case__ , num_workers=snake_case__ )
__snake_case = NUM_SHARDS * NUM_ITEMS_PER_SHARD
__snake_case = full_size // world_size
expected_local_size += int(rank < (full_size % world_size) )
__snake_case = sum(1 for _ in dataloader )
if local_size != expected_local_size:
raise FailedTestError(f"local_size {local_size} != expected_local_size {expected_local_size}" )
if __name__ == "__main__":
main()
| 313 | 0 |
'''simple docstring'''
from __future__ import annotations
import math
import random
from collections.abc import Collection
from typing import overload
class UpperCamelCase_ :
'''simple docstring'''
def __init__( self : str , UpperCAmelCase__ : str = None) ->int:
'''simple docstring'''
if components is None:
A__ = []
A__ = list(lowercase__)
def __len__( self : Optional[int]) ->Any:
'''simple docstring'''
return len(self.__components)
def __str__( self : str) ->List[str]:
'''simple docstring'''
return "(" + ",".join(map(lowercase__ , self.__components)) + ")"
def __add__( self : List[str] , UpperCAmelCase__ : Union[str, Any]) ->List[str]:
'''simple docstring'''
A__ = len(self)
if size == len(lowercase__):
A__ = [self.__components[i] + other.component(lowercase__) for i in range(lowercase__)]
return Vector(lowercase__)
else:
raise Exception('''must have the same size''')
def __sub__( self : List[str] , UpperCAmelCase__ : Dict) ->Tuple:
'''simple docstring'''
A__ = len(self)
if size == len(lowercase__):
A__ = [self.__components[i] - other.component(lowercase__) for i in range(lowercase__)]
return Vector(lowercase__)
else: # error case
raise Exception('''must have the same size''')
@overload
def __mul__( self : int , UpperCAmelCase__ : List[Any]) ->Tuple:
'''simple docstring'''
...
@overload
def __mul__( self : Any , UpperCAmelCase__ : List[Any]) ->Optional[int]:
'''simple docstring'''
...
def __mul__( self : Optional[Any] , UpperCAmelCase__ : str) ->str:
'''simple docstring'''
if isinstance(lowercase__ , (float, int)):
A__ = [c * other for c in self.__components]
return Vector(lowercase__)
elif isinstance(lowercase__ , lowercase__) and len(self) == len(lowercase__):
A__ = len(self)
A__ = [self.__components[i] * other.component(lowercase__) for i in range(lowercase__)]
return sum(lowercase__)
else: # error case
raise Exception('''invalid operand!''')
def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Any:
'''simple docstring'''
return Vector(self.__components)
def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : Tuple) ->Any:
'''simple docstring'''
if isinstance(lowercase__ , lowercase__) and -len(self.__components) <= i < len(self.__components):
return self.__components[i]
else:
raise Exception('''index out of range''')
def SCREAMING_SNAKE_CASE ( self : str , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : Union[str, Any]) ->Dict:
'''simple docstring'''
assert -len(self.__components) <= pos < len(self.__components)
A__ = value
def SCREAMING_SNAKE_CASE ( self : List[Any]) ->int:
'''simple docstring'''
if len(self.__components) == 0:
raise Exception('''Vector is empty''')
A__ = [c**2 for c in self.__components]
return math.sqrt(sum(lowercase__))
def SCREAMING_SNAKE_CASE ( self : List[str] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[str] = False) ->Optional[int]:
'''simple docstring'''
A__ = self * other
A__ = self.euclidean_length() * other.euclidean_length()
if deg:
return math.degrees(math.acos(num / den))
else:
return math.acos(num / den)
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> List[Any]:
"""simple docstring"""
assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
return Vector([0] * dimension )
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ ) -> Optional[Any]:
"""simple docstring"""
assert isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) and (isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ))
A__ = [0] * dimension
A__ = 1
return Vector(SCREAMING_SNAKE_CASE__ )
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Dict:
"""simple docstring"""
assert (
isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
and isinstance(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
and (isinstance(SCREAMING_SNAKE_CASE__ , (int, float) ))
)
return x * scalar + y
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ ) -> Union[str, Any]:
"""simple docstring"""
random.seed(SCREAMING_SNAKE_CASE__ )
A__ = [random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )]
return Vector(SCREAMING_SNAKE_CASE__ )
class UpperCamelCase_ :
'''simple docstring'''
def __init__( self : Union[str, Any] , UpperCAmelCase__ : int , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Optional[Any]) ->Optional[int]:
'''simple docstring'''
A__ = matrix
A__ = w
A__ = h
def __str__( self : Optional[int]) ->List[str]:
'''simple docstring'''
A__ = """"""
for i in range(self.__height):
ans += "|"
for j in range(self.__width):
if j < self.__width - 1:
ans += str(self.__matrix[i][j]) + ","
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
def __add__( self : List[str] , UpperCAmelCase__ : Optional[int]) ->Optional[Any]:
'''simple docstring'''
if self.__width == other.width() and self.__height == other.height():
A__ = []
for i in range(self.__height):
A__ = [
self.__matrix[i][j] + other.component(lowercase__ , lowercase__)
for j in range(self.__width)
]
matrix.append(lowercase__)
return Matrix(lowercase__ , self.__width , self.__height)
else:
raise Exception('''matrix must have the same dimension!''')
def __sub__( self : Optional[Any] , UpperCAmelCase__ : str) ->List[str]:
'''simple docstring'''
if self.__width == other.width() and self.__height == other.height():
A__ = []
for i in range(self.__height):
A__ = [
self.__matrix[i][j] - other.component(lowercase__ , lowercase__)
for j in range(self.__width)
]
matrix.append(lowercase__)
return Matrix(lowercase__ , self.__width , self.__height)
else:
raise Exception('''matrices must have the same dimension!''')
@overload
def __mul__( self : Optional[int] , UpperCAmelCase__ : Tuple) ->Union[str, Any]:
'''simple docstring'''
...
@overload
def __mul__( self : Any , UpperCAmelCase__ : Tuple) ->List[Any]:
'''simple docstring'''
...
def __mul__( self : Dict , UpperCAmelCase__ : List[str]) ->List[Any]:
'''simple docstring'''
if isinstance(lowercase__ , lowercase__): # matrix-vector
if len(lowercase__) == self.__width:
A__ = zero_vector(self.__height)
for i in range(self.__height):
A__ = [
self.__matrix[i][j] * other.component(lowercase__)
for j in range(self.__width)
]
ans.change_component(lowercase__ , sum(lowercase__))
return ans
else:
raise Exception(
'''vector must have the same size as the '''
'''number of columns of the matrix!''')
elif isinstance(lowercase__ , (int, float)): # matrix-scalar
A__ = [
[self.__matrix[i][j] * other for j in range(self.__width)]
for i in range(self.__height)
]
return Matrix(lowercase__ , self.__width , self.__height)
return None
def SCREAMING_SNAKE_CASE ( self : int) ->Optional[Any]:
'''simple docstring'''
return self.__height
def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[int]:
'''simple docstring'''
return self.__width
def SCREAMING_SNAKE_CASE ( self : str , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : List[Any]) ->Any:
'''simple docstring'''
if 0 <= x < self.__height and 0 <= y < self.__width:
return self.__matrix[x][y]
else:
raise Exception('''change_component: indices out of bounds''')
def SCREAMING_SNAKE_CASE ( self : Optional[int] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str , UpperCAmelCase__ : List[Any]) ->Optional[Any]:
'''simple docstring'''
if 0 <= x < self.__height and 0 <= y < self.__width:
A__ = value
else:
raise Exception('''change_component: indices out of bounds''')
def SCREAMING_SNAKE_CASE ( self : Dict , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : str) ->Union[str, Any]:
'''simple docstring'''
if self.__height != self.__width:
raise Exception('''Matrix is not square''')
A__ = self.__matrix[:x] + self.__matrix[x + 1 :]
for i in range(len(lowercase__)):
A__ = minor[i][:y] + minor[i][y + 1 :]
return Matrix(lowercase__ , self.__width - 1 , self.__height - 1).determinant()
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : List[Any] , UpperCAmelCase__ : Any) ->Tuple:
'''simple docstring'''
if self.__height != self.__width:
raise Exception('''Matrix is not square''')
if 0 <= x < self.__height and 0 <= y < self.__width:
return (-1) ** (x + y) * self.minor(lowercase__ , lowercase__)
else:
raise Exception('''Indices out of bounds''')
def SCREAMING_SNAKE_CASE ( self : Any) ->Tuple:
'''simple docstring'''
if self.__height != self.__width:
raise Exception('''Matrix is not square''')
if self.__height < 1:
raise Exception('''Matrix has no element''')
elif self.__height == 1:
return self.__matrix[0][0]
elif self.__height == 2:
return (
self.__matrix[0][0] * self.__matrix[1][1]
- self.__matrix[0][1] * self.__matrix[1][0]
)
else:
A__ = [
self.__matrix[0][y] * self.cofactor(0 , lowercase__) for y in range(self.__width)
]
return sum(lowercase__)
def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Any:
"""simple docstring"""
A__ = [[0] * n for _ in range(SCREAMING_SNAKE_CASE__ )]
return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
def SCREAMING_SNAKE_CASE ( lowercase_ , lowercase_ , lowercase_ , lowercase_ ) -> List[Any]:
"""simple docstring"""
random.seed(SCREAMING_SNAKE_CASE__ )
A__ = [
[random.randint(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ ) for _ in range(SCREAMING_SNAKE_CASE__ )] for _ in range(SCREAMING_SNAKE_CASE__ )
]
return Matrix(SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ , SCREAMING_SNAKE_CASE__ )
| 704 |
import inspect
import unittest
import numpy as np
from tests.test_modeling_common import floats_tensor
from transformers import DetrConfig, MaskFormerConfig, SwinConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin
if is_torch_available():
import torch
from transformers import MaskFormerForInstanceSegmentation, MaskFormerModel
if is_vision_available():
from transformers import MaskFormerImageProcessor
if is_vision_available():
from PIL import Image
class UpperCamelCase_ :
'''simple docstring'''
def __init__( self : Tuple , UpperCAmelCase__ : Dict , UpperCAmelCase__ : Any=2 , UpperCAmelCase__ : List[str]=True , UpperCAmelCase__ : Any=False , UpperCAmelCase__ : Union[str, Any]=10 , UpperCAmelCase__ : Any=3 , UpperCAmelCase__ : Optional[int]=32 * 4 , UpperCAmelCase__ : int=32 * 6 , UpperCAmelCase__ : List[str]=4 , UpperCAmelCase__ : Dict=32 , ) ->Optional[int]:
'''simple docstring'''
A__ = parent
A__ = batch_size
A__ = is_training
A__ = use_auxiliary_loss
A__ = num_queries
A__ = num_channels
A__ = min_size
A__ = max_size
A__ = num_labels
A__ = mask_feature_size
def SCREAMING_SNAKE_CASE ( self : Dict) ->int:
'''simple docstring'''
A__ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]).to(
UpperCAmelCase__)
A__ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=UpperCAmelCase__)
A__ = (
torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=UpperCAmelCase__) > 0.5
).float()
A__ = (torch.rand((self.batch_size, self.num_labels) , device=UpperCAmelCase__) > 0.5).long()
A__ = self.get_config()
return config, pixel_values, pixel_mask, mask_labels, class_labels
def SCREAMING_SNAKE_CASE ( self : str) ->List[Any]:
'''simple docstring'''
return MaskFormerConfig.from_backbone_and_decoder_configs(
backbone_config=SwinConfig(
depths=[1, 1, 1, 1] , ) , decoder_config=DetrConfig(
decoder_ffn_dim=128 , num_queries=self.num_queries , decoder_attention_heads=2 , d_model=self.mask_feature_size , ) , mask_feature_size=self.mask_feature_size , fpn_feature_size=self.mask_feature_size , num_channels=self.num_channels , num_labels=self.num_labels , )
def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->List[Any]:
'''simple docstring'''
A__ , A__ , A__ , A__ , A__ = self.prepare_config_and_inputs()
A__ = {'''pixel_values''': pixel_values, '''pixel_mask''': pixel_mask}
return config, inputs_dict
def SCREAMING_SNAKE_CASE ( self : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[Any]) ->int:
'''simple docstring'''
A__ = output.encoder_hidden_states
A__ = output.pixel_decoder_hidden_states
A__ = output.transformer_decoder_hidden_states
self.parent.assertTrue(len(UpperCAmelCase__) , len(config.backbone_config.depths))
self.parent.assertTrue(len(UpperCAmelCase__) , len(config.backbone_config.depths))
self.parent.assertTrue(len(UpperCAmelCase__) , config.decoder_config.decoder_layers)
def SCREAMING_SNAKE_CASE ( self : Optional[Any] , UpperCAmelCase__ : Optional[Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Union[str, Any] , UpperCAmelCase__ : Optional[Any]=False) ->Optional[int]:
'''simple docstring'''
with torch.no_grad():
A__ = MaskFormerModel(config=UpperCAmelCase__)
model.to(UpperCAmelCase__)
model.eval()
A__ = model(pixel_values=UpperCAmelCase__ , pixel_mask=UpperCAmelCase__)
A__ = model(UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__)
# the correct shape of output.transformer_decoder_hidden_states ensure the correcteness of the
# encoder and pixel decoder
self.parent.assertEqual(
output.transformer_decoder_last_hidden_state.shape , (self.batch_size, self.num_queries, self.mask_feature_size) , )
# let's ensure the other two hidden state exists
self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None)
self.parent.assertTrue(output.encoder_last_hidden_state is not None)
if output_hidden_states:
self.check_output_hidden_state(UpperCAmelCase__ , UpperCAmelCase__)
def SCREAMING_SNAKE_CASE ( self : str , UpperCAmelCase__ : Tuple , UpperCAmelCase__ : Optional[int] , UpperCAmelCase__ : List[str] , UpperCAmelCase__ : int , UpperCAmelCase__ : int) ->List[Any]:
'''simple docstring'''
A__ = MaskFormerForInstanceSegmentation(config=UpperCAmelCase__)
model.to(UpperCAmelCase__)
model.eval()
def comm_check_on_output(UpperCAmelCase__ : str):
# let's still check that all the required stuff is there
self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None)
self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None)
self.parent.assertTrue(result.encoder_last_hidden_state is not None)
# okay, now we need to check the logits shape
# due to the encoder compression, masks have a //4 spatial size
self.parent.assertEqual(
result.masks_queries_logits.shape , (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) , )
# + 1 for null class
self.parent.assertEqual(
result.class_queries_logits.shape , (self.batch_size, self.num_queries, self.num_labels + 1))
with torch.no_grad():
A__ = model(pixel_values=UpperCAmelCase__ , pixel_mask=UpperCAmelCase__)
A__ = model(UpperCAmelCase__)
comm_check_on_output(UpperCAmelCase__)
A__ = model(
pixel_values=UpperCAmelCase__ , pixel_mask=UpperCAmelCase__ , mask_labels=UpperCAmelCase__ , class_labels=UpperCAmelCase__)
comm_check_on_output(UpperCAmelCase__)
self.parent.assertTrue(result.loss is not None)
self.parent.assertEqual(result.loss.shape , torch.Size([1]))
@require_torch
class UpperCamelCase_ ( UpperCAmelCase__ , UpperCAmelCase__ , unittest.TestCase ):
'''simple docstring'''
UpperCAmelCase__ = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else ()
UpperCAmelCase__ = (
{'''feature-extraction''': MaskFormerModel, '''image-segmentation''': MaskFormerForInstanceSegmentation}
if is_torch_available()
else {}
)
UpperCAmelCase__ = False
UpperCAmelCase__ = False
UpperCAmelCase__ = False
UpperCAmelCase__ = False
def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
A__ = MaskFormerModelTester(self)
A__ = ConfigTester(self , config_class=UpperCAmelCase__ , has_text_modality=UpperCAmelCase__)
def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Tuple:
'''simple docstring'''
self.config_tester.run_common_tests()
def SCREAMING_SNAKE_CASE ( self : Dict) ->List[str]:
'''simple docstring'''
A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(UpperCAmelCase__ , **UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__)
def SCREAMING_SNAKE_CASE ( self : str) ->Any:
'''simple docstring'''
A__ = self.model_tester.prepare_config_and_inputs()
self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*UpperCAmelCase__)
@unittest.skip(reason='''MaskFormer does not use inputs_embeds''')
def SCREAMING_SNAKE_CASE ( self : Dict) ->Tuple:
'''simple docstring'''
pass
@unittest.skip(reason='''MaskFormer does not have a get_input_embeddings method''')
def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Union[str, Any]:
'''simple docstring'''
pass
@unittest.skip(reason='''MaskFormer is not a generative model''')
def SCREAMING_SNAKE_CASE ( self : str) ->Union[str, Any]:
'''simple docstring'''
pass
@unittest.skip(reason='''MaskFormer does not use token embeddings''')
def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Union[str, Any]:
'''simple docstring'''
pass
@require_torch_multi_gpu
@unittest.skip(
reason='''MaskFormer has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`''')
def SCREAMING_SNAKE_CASE ( self : Optional[int]) ->Optional[int]:
'''simple docstring'''
pass
@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
def SCREAMING_SNAKE_CASE ( self : Tuple) ->Dict:
'''simple docstring'''
pass
def SCREAMING_SNAKE_CASE ( self : Dict) ->Dict:
'''simple docstring'''
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__)
@slow
def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[Any]:
'''simple docstring'''
for model_name in ["facebook/maskformer-swin-small-coco"]:
A__ = MaskFormerModel.from_pretrained(UpperCAmelCase__)
self.assertIsNotNone(UpperCAmelCase__)
def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
A__ = (self.model_tester.min_size,) * 2
A__ = {
'''pixel_values''': torch.randn((2, 3, *size) , device=UpperCAmelCase__),
'''mask_labels''': torch.randn((2, 10, *size) , device=UpperCAmelCase__),
'''class_labels''': torch.zeros(2 , 10 , device=UpperCAmelCase__).long(),
}
A__ = MaskFormerForInstanceSegmentation(MaskFormerConfig()).to(UpperCAmelCase__)
A__ = model(**UpperCAmelCase__)
self.assertTrue(outputs.loss is not None)
def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Union[str, Any]:
'''simple docstring'''
A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common()
self.model_tester.create_and_check_maskformer_model(UpperCAmelCase__ , **UpperCAmelCase__ , output_hidden_states=UpperCAmelCase__)
def SCREAMING_SNAKE_CASE ( self : str) ->Union[str, Any]:
'''simple docstring'''
A__ , A__ = self.model_tester.prepare_config_and_inputs_for_common()
for model_class in self.all_model_classes:
A__ = model_class(UpperCAmelCase__).to(UpperCAmelCase__)
A__ = model(**UpperCAmelCase__ , output_attentions=UpperCAmelCase__)
self.assertTrue(outputs.attentions is not None)
def SCREAMING_SNAKE_CASE ( self : List[Any]) ->Union[str, Any]:
'''simple docstring'''
if not self.model_tester.is_training:
return
# only MaskFormerForInstanceSegmentation has the loss
A__ = self.all_model_classes[1]
A__ , A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs()
A__ = model_class(UpperCAmelCase__)
model.to(UpperCAmelCase__)
model.train()
A__ = model(UpperCAmelCase__ , mask_labels=UpperCAmelCase__ , class_labels=UpperCAmelCase__).loss
loss.backward()
def SCREAMING_SNAKE_CASE ( self : int) ->str:
'''simple docstring'''
A__ = self.all_model_classes[1]
A__ , A__ , A__ , A__ , A__ = self.model_tester.prepare_config_and_inputs()
A__ = True
A__ = True
A__ = model_class(UpperCAmelCase__)
model.to(UpperCAmelCase__)
model.train()
A__ = model(UpperCAmelCase__ , mask_labels=UpperCAmelCase__ , class_labels=UpperCAmelCase__)
A__ = outputs.encoder_hidden_states[0]
encoder_hidden_states.retain_grad()
A__ = outputs.pixel_decoder_hidden_states[0]
pixel_decoder_hidden_states.retain_grad()
# we requires_grad=True in inputs_embeds (line 2152), the original implementation don't
A__ = outputs.transformer_decoder_hidden_states[0]
transformer_decoder_hidden_states.retain_grad()
A__ = outputs.attentions[0]
attentions.retain_grad()
outputs.loss.backward(retain_graph=UpperCAmelCase__)
self.assertIsNotNone(encoder_hidden_states.grad)
self.assertIsNotNone(pixel_decoder_hidden_states.grad)
self.assertIsNotNone(transformer_decoder_hidden_states.grad)
self.assertIsNotNone(attentions.grad)
_lowerCamelCase : Tuple = 1E-4
def SCREAMING_SNAKE_CASE ( ) -> int:
"""simple docstring"""
A__ = Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
return image
@require_vision
@slow
class UpperCamelCase_ ( unittest.TestCase ):
'''simple docstring'''
@cached_property
def SCREAMING_SNAKE_CASE ( self : Tuple) ->List[str]:
'''simple docstring'''
return (
MaskFormerImageProcessor.from_pretrained('''facebook/maskformer-swin-small-coco''')
if is_vision_available()
else None
)
def SCREAMING_SNAKE_CASE ( self : Union[str, Any]) ->Optional[int]:
'''simple docstring'''
A__ = MaskFormerModel.from_pretrained('''facebook/maskformer-swin-small-coco''').to(UpperCAmelCase__)
A__ = self.default_image_processor
A__ = prepare_img()
A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').to(UpperCAmelCase__)
A__ = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
# check size
self.assertEqual(UpperCAmelCase__ , (1, 3, 800, 1_088))
with torch.no_grad():
A__ = model(**UpperCAmelCase__)
A__ = torch.tensor(
[[-0.0482, 0.9228, 0.4951], [-0.2547, 0.8017, 0.8527], [-0.0069, 0.3385, -0.0089]]).to(UpperCAmelCase__)
self.assertTrue(
torch.allclose(
outputs.encoder_last_hidden_state[0, 0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__))
A__ = torch.tensor(
[[-0.8422, -0.8434, -0.9718], [-1.0144, -0.5565, -0.4195], [-1.0038, -0.4484, -0.1961]]).to(UpperCAmelCase__)
self.assertTrue(
torch.allclose(
outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__))
A__ = torch.tensor(
[[0.2852, -0.0159, 0.9735], [0.6254, 0.1858, 0.8529], [-0.0680, -0.4116, 1.8413]]).to(UpperCAmelCase__)
self.assertTrue(
torch.allclose(
outputs.transformer_decoder_last_hidden_state[0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__))
def SCREAMING_SNAKE_CASE ( self : Any) ->Optional[Any]:
'''simple docstring'''
A__ = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''')
.to(UpperCAmelCase__)
.eval()
)
A__ = self.default_image_processor
A__ = prepare_img()
A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').to(UpperCAmelCase__)
A__ = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
# check size
self.assertEqual(UpperCAmelCase__ , (1, 3, 800, 1_088))
with torch.no_grad():
A__ = model(**UpperCAmelCase__)
# masks_queries_logits
A__ = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
A__ = [
[-1.3737124, -1.7724937, -1.9364233],
[-1.5977281, -1.9867939, -2.1523695],
[-1.5795398, -1.9269832, -2.093942],
]
A__ = torch.tensor(UpperCAmelCase__).to(UpperCAmelCase__)
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__))
# class_queries_logits
A__ = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1))
A__ = torch.tensor(
[
[1.65_12e00, -5.25_72e00, -3.35_19e00],
[3.61_69e-02, -5.90_25e00, -2.93_13e00],
[1.07_66e-04, -7.76_30e00, -5.12_63e00],
]).to(UpperCAmelCase__)
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__))
def SCREAMING_SNAKE_CASE ( self : str) ->Optional[Any]:
'''simple docstring'''
A__ = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-resnet101-coco-stuff''')
.to(UpperCAmelCase__)
.eval()
)
A__ = self.default_image_processor
A__ = prepare_img()
A__ = image_processor(UpperCAmelCase__ , return_tensors='''pt''').to(UpperCAmelCase__)
A__ = inputs['''pixel_values'''].shape
# check size is divisible by 32
self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0)
# check size
self.assertEqual(UpperCAmelCase__ , (1, 3, 800, 1_088))
with torch.no_grad():
A__ = model(**UpperCAmelCase__)
# masks_queries_logits
A__ = outputs.masks_queries_logits
self.assertEqual(
masks_queries_logits.shape , (1, model.config.decoder_config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4) , )
A__ = [[-0.9046, -2.6366, -4.6062], [-3.4179, -5.7890, -8.8057], [-4.9179, -7.6560, -10.7711]]
A__ = torch.tensor(UpperCAmelCase__).to(UpperCAmelCase__)
self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__))
# class_queries_logits
A__ = outputs.class_queries_logits
self.assertEqual(
class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1))
A__ = torch.tensor(
[[4.7188, -3.2585, -2.8857], [6.6871, -2.9181, -1.2487], [7.2449, -2.2764, -2.1874]]).to(UpperCAmelCase__)
self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , UpperCAmelCase__ , atol=UpperCAmelCase__))
def SCREAMING_SNAKE_CASE ( self : Dict) ->Dict:
'''simple docstring'''
A__ = (
MaskFormerForInstanceSegmentation.from_pretrained('''facebook/maskformer-swin-small-coco''')
.to(UpperCAmelCase__)
.eval()
)
A__ = self.default_image_processor
A__ = image_processor(
[np.zeros((3, 800, 1_333)), np.zeros((3, 800, 1_333))] , segmentation_maps=[np.zeros((384, 384)).astype(np.floataa), np.zeros((384, 384)).astype(np.floataa)] , return_tensors='''pt''' , )
A__ = inputs['''pixel_values'''].to(UpperCAmelCase__)
A__ = [el.to(UpperCAmelCase__) for el in inputs['''mask_labels''']]
A__ = [el.to(UpperCAmelCase__) for el in inputs['''class_labels''']]
with torch.no_grad():
A__ = model(**UpperCAmelCase__)
self.assertTrue(outputs.loss is not None)
| 177 | 0 |
'''simple docstring'''
import os
from pathlib import Path
import numpy as np
import pytest
from pack_dataset import pack_data_dir
from parameterized import parameterized
from save_len_file import save_len_file
from torch.utils.data import DataLoader
from transformers import AutoTokenizer
from transformers.models.mbart.modeling_mbart import shift_tokens_right
from transformers.testing_utils import TestCasePlus, slow
from utils import FAIRSEQ_AVAILABLE, DistributedSortishSampler, LegacySeqaSeqDataset, SeqaSeqDataset
_lowerCamelCase : str = "bert-base-cased"
_lowerCamelCase : List[str] = "google/pegasus-xsum"
_lowerCamelCase : List[str] = [" Sam ate lunch today.", "Sams lunch ingredients."]
_lowerCamelCase : str = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"]
_lowerCamelCase : Union[str, Any] = "patrickvonplaten/t5-tiny-random"
_lowerCamelCase : Union[str, Any] = "sshleifer/bart-tiny-random"
_lowerCamelCase : str = "sshleifer/tiny-mbart"
_lowerCamelCase : Union[str, Any] = "sshleifer/tiny-marian-en-de"
def __lowerCamelCase ( A__ , A__ ) -> Any:
"""simple docstring"""
UpperCamelCase = '\n'.join(snake_case__ )
Path(snake_case__ ).open('w' ).writelines(snake_case__ )
def __lowerCamelCase ( A__ ) -> List[str]:
"""simple docstring"""
for split in ["train", "val", "test"]:
_dump_articles(os.path.join(snake_case__ , F"""{split}.source""" ) , snake_case__ )
_dump_articles(os.path.join(snake_case__ , F"""{split}.target""" ) , snake_case__ )
return tmp_dir
class SCREAMING_SNAKE_CASE ( _a ):
"""simple docstring"""
@parameterized.expand(
[
MBART_TINY,
MARIAN_TINY,
T5_TINY,
BART_TINY,
PEGASUS_XSUM,
] , )
@slow
def A ( self : int , UpperCamelCase__ : Dict ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained(a_ )
UpperCamelCase = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() )
UpperCamelCase = max(len(tokenizer.encode(a_ ) ) for a in ARTICLES )
UpperCamelCase = max(len(tokenizer.encode(a_ ) ) for a in SUMMARIES )
UpperCamelCase = 4
UpperCamelCase = 8
assert max_len_target > max_src_len # Will be truncated
assert max_len_source > max_src_len # Will be truncated
UpperCamelCase , UpperCamelCase = 'ro_RO', 'de_DE' # ignored for all but mbart, but never causes error.
UpperCamelCase = SeqaSeqDataset(
a_ , data_dir=a_ , type_path='train' , max_source_length=a_ , max_target_length=a_ , src_lang=a_ , tgt_lang=a_ , )
UpperCamelCase = DataLoader(a_ , batch_size=2 , collate_fn=train_dataset.collate_fn )
for batch in dataloader:
assert isinstance(a_ , a_ )
assert batch["attention_mask"].shape == batch["input_ids"].shape
# show that articles were trimmed.
assert batch["input_ids"].shape[1] == max_src_len
# show that targets are the same len
assert batch["labels"].shape[1] == max_tgt_len
if tok_name != MBART_TINY:
continue
# check language codes in correct place
UpperCamelCase = shift_tokens_right(batch['labels'] , tokenizer.pad_token_id )
assert batch["decoder_input_ids"][0, 0].item() == tokenizer.lang_code_to_id[tgt_lang]
assert batch["decoder_input_ids"][0, -1].item() == tokenizer.eos_token_id
assert batch["input_ids"][0, -2].item() == tokenizer.eos_token_id
assert batch["input_ids"][0, -1].item() == tokenizer.lang_code_to_id[src_lang]
break # No need to test every batch
@parameterized.expand([BART_TINY, BERT_BASE_CASED] )
def A ( self : Union[str, Any] , UpperCamelCase__ : int ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained(a_ )
UpperCamelCase = make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() )
UpperCamelCase = max(len(tokenizer.encode(a_ ) ) for a in ARTICLES )
UpperCamelCase = max(len(tokenizer.encode(a_ ) ) for a in SUMMARIES )
UpperCamelCase = 4
UpperCamelCase = LegacySeqaSeqDataset(
a_ , data_dir=a_ , type_path='train' , max_source_length=2_0 , max_target_length=a_ , )
UpperCamelCase = DataLoader(a_ , batch_size=2 , collate_fn=train_dataset.collate_fn )
for batch in dataloader:
assert batch["attention_mask"].shape == batch["input_ids"].shape
# show that articles were trimmed.
assert batch["input_ids"].shape[1] == max_len_source
assert 2_0 >= batch["input_ids"].shape[1] # trimmed significantly
# show that targets were truncated
assert batch["labels"].shape[1] == trunc_target # Truncated
assert max_len_target > trunc_target # Truncated
break # No need to test every batch
def A ( self : str ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained('facebook/mbart-large-cc25' )
UpperCamelCase = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) )
UpperCamelCase = tmp_dir.joinpath('train.source' ).open().readlines()
UpperCamelCase = Path(make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) )
pack_data_dir(a_ , a_ , 1_2_8 , a_ )
UpperCamelCase = {x.name for x in tmp_dir.iterdir()}
UpperCamelCase = {x.name for x in save_dir.iterdir()}
UpperCamelCase = save_dir.joinpath('train.source' ).open().readlines()
# orig: [' Sam ate lunch today.\n', 'Sams lunch ingredients.']
# desired_packed: [' Sam ate lunch today.\n Sams lunch ingredients.']
assert len(a_ ) < len(a_ )
assert len(a_ ) == 1
assert len(packed_examples[0] ) == sum(len(a_ ) for x in orig_examples )
assert orig_paths == new_paths
@pytest.mark.skipif(not FAIRSEQ_AVAILABLE , reason='This test requires fairseq' )
def A ( self : Optional[Any] ):
"""simple docstring"""
if not FAIRSEQ_AVAILABLE:
return
UpperCamelCase , UpperCamelCase , UpperCamelCase = self._get_dataset(max_len=6_4 )
UpperCamelCase = 6_4
UpperCamelCase = ds.make_dynamic_sampler(a_ , required_batch_size_multiple=a_ )
UpperCamelCase = [len(a_ ) for x in batch_sampler]
assert len(set(a_ ) ) > 1 # it's not dynamic batch size if every batch is the same length
assert sum(a_ ) == len(a_ ) # no dropped or added examples
UpperCamelCase = DataLoader(a_ , batch_sampler=a_ , collate_fn=ds.collate_fn , num_workers=2 )
UpperCamelCase = []
UpperCamelCase = []
for batch in data_loader:
UpperCamelCase = batch['input_ids'].shape
UpperCamelCase = src_shape[0]
assert bs % required_batch_size_multiple == 0 or bs < required_batch_size_multiple
UpperCamelCase = np.product(batch['input_ids'].shape )
num_src_per_batch.append(a_ )
if num_src_tokens > (max_tokens * 1.1):
failures.append(a_ )
assert num_src_per_batch[0] == max(a_ )
if failures:
raise AssertionError(f"""too many tokens in {len(a_ )} batches""" )
def A ( self : Tuple ):
"""simple docstring"""
UpperCamelCase , UpperCamelCase , UpperCamelCase = self._get_dataset(max_len=5_1_2 )
UpperCamelCase = 2
UpperCamelCase = ds.make_sortish_sampler(a_ , shuffle=a_ )
UpperCamelCase = DataLoader(a_ , batch_size=a_ , collate_fn=ds.collate_fn , num_workers=2 )
UpperCamelCase = DataLoader(a_ , batch_size=a_ , collate_fn=ds.collate_fn , num_workers=2 , sampler=a_ )
UpperCamelCase = tokenizer.pad_token_id
def count_pad_tokens(UpperCamelCase__ : Any , UpperCamelCase__ : int="input_ids" ):
return [batch[k].eq(a_ ).sum().item() for batch in data_loader]
assert sum(count_pad_tokens(a_ , k='labels' ) ) < sum(count_pad_tokens(a_ , k='labels' ) )
assert sum(count_pad_tokens(a_ ) ) < sum(count_pad_tokens(a_ ) )
assert len(a_ ) == len(a_ )
def A ( self : int , UpperCamelCase__ : Optional[Any]=1_0_0_0 , UpperCamelCase__ : List[str]=1_2_8 ):
"""simple docstring"""
if os.getenv('USE_REAL_DATA' , a_ ):
UpperCamelCase = 'examples/seq2seq/wmt_en_ro'
UpperCamelCase = max_len * 2 * 6_4
if not Path(a_ ).joinpath('train.len' ).exists():
save_len_file(a_ , a_ )
else:
UpperCamelCase = 'examples/seq2seq/test_data/wmt_en_ro'
UpperCamelCase = max_len * 4
save_len_file(a_ , a_ )
UpperCamelCase = AutoTokenizer.from_pretrained(a_ )
UpperCamelCase = SeqaSeqDataset(
a_ , data_dir=a_ , type_path='train' , max_source_length=a_ , max_target_length=a_ , n_obs=a_ , )
return ds, max_tokens, tokenizer
def A ( self : int ):
"""simple docstring"""
UpperCamelCase , UpperCamelCase , UpperCamelCase = self._get_dataset()
UpperCamelCase = set(DistributedSortishSampler(a_ , 2_5_6 , num_replicas=2 , rank=0 , add_extra_examples=a_ ) )
UpperCamelCase = set(DistributedSortishSampler(a_ , 2_5_6 , num_replicas=2 , rank=1 , add_extra_examples=a_ ) )
assert idsa.intersection(a_ ) == set()
@parameterized.expand(
[
MBART_TINY,
MARIAN_TINY,
T5_TINY,
BART_TINY,
PEGASUS_XSUM,
] , )
def A ( self : Optional[Any] , UpperCamelCase__ : Dict ):
"""simple docstring"""
UpperCamelCase = AutoTokenizer.from_pretrained(a_ , use_fast=a_ )
if tok_name == MBART_TINY:
UpperCamelCase = SeqaSeqDataset(
a_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='train' , max_source_length=4 , max_target_length=8 , src_lang='EN' , tgt_lang='FR' , )
UpperCamelCase = train_dataset.dataset_kwargs
assert "src_lang" in kwargs and "tgt_lang" in kwargs
else:
UpperCamelCase = SeqaSeqDataset(
a_ , data_dir=make_test_data_dir(tmp_dir=self.get_auto_remove_tmp_dir() ) , type_path='train' , max_source_length=4 , max_target_length=8 , )
UpperCamelCase = train_dataset.dataset_kwargs
assert "add_prefix_space" not in kwargs if tok_name != BART_TINY else "add_prefix_space" in kwargs
assert len(a_ ) == 1 if tok_name == BART_TINY else len(a_ ) == 0
| 430 |
from typing import Optional, Union
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithPoolingAndNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_mobilenet_va import MobileNetVaConfig
_lowerCAmelCase : str = logging.get_logger(__name__)
# General docstring
_lowerCAmelCase : Optional[int] = "MobileNetV1Config"
# Base docstring
_lowerCAmelCase : Tuple = "google/mobilenet_v1_1.0_224"
_lowerCAmelCase : Optional[int] = [1, 1_0_2_4, 7, 7]
# Image classification docstring
_lowerCAmelCase : Tuple = "google/mobilenet_v1_1.0_224"
_lowerCAmelCase : List[Any] = "tabby, tabby cat"
_lowerCAmelCase : Tuple = [
"google/mobilenet_v1_1.0_224",
"google/mobilenet_v1_0.75_192",
# See all MobileNetV1 models at https://huggingface.co/models?filter=mobilenet_v1
]
def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__=None ) -> Union[str, Any]:
"""simple docstring"""
lowerCAmelCase__ = {}
if isinstance(snake_case__ , snake_case__ ):
lowerCAmelCase__ = model.mobilenet_va
else:
lowerCAmelCase__ = model
lowerCAmelCase__ = 'MobilenetV1/Conv2d_0/'
lowerCAmelCase__ = backbone.conv_stem.convolution.weight
lowerCAmelCase__ = backbone.conv_stem.normalization.bias
lowerCAmelCase__ = backbone.conv_stem.normalization.weight
lowerCAmelCase__ = backbone.conv_stem.normalization.running_mean
lowerCAmelCase__ = backbone.conv_stem.normalization.running_var
for i in range(13 ):
lowerCAmelCase__ = i + 1
lowerCAmelCase__ = i * 2
lowerCAmelCase__ = backbone.layer[pt_index]
lowerCAmelCase__ = f'MobilenetV1/Conv2d_{tf_index}_depthwise/'
lowerCAmelCase__ = pointer.convolution.weight
lowerCAmelCase__ = pointer.normalization.bias
lowerCAmelCase__ = pointer.normalization.weight
lowerCAmelCase__ = pointer.normalization.running_mean
lowerCAmelCase__ = pointer.normalization.running_var
lowerCAmelCase__ = backbone.layer[pt_index + 1]
lowerCAmelCase__ = f'MobilenetV1/Conv2d_{tf_index}_pointwise/'
lowerCAmelCase__ = pointer.convolution.weight
lowerCAmelCase__ = pointer.normalization.bias
lowerCAmelCase__ = pointer.normalization.weight
lowerCAmelCase__ = pointer.normalization.running_mean
lowerCAmelCase__ = pointer.normalization.running_var
if isinstance(snake_case__ , snake_case__ ):
lowerCAmelCase__ = 'MobilenetV1/Logits/Conv2d_1c_1x1/'
lowerCAmelCase__ = model.classifier.weight
lowerCAmelCase__ = model.classifier.bias
return tf_to_pt_map
def UpperCAmelCase_ ( snake_case__ , snake_case__ , snake_case__ ) -> List[str]:
"""simple docstring"""
try:
import numpy as np
import tensorflow as tf
except ImportError:
logger.error(
'Loading a TensorFlow models in PyTorch, requires TensorFlow to be installed. Please see '
'https://www.tensorflow.org/install/ for installation instructions.' )
raise
# Load weights from TF model
lowerCAmelCase__ = tf.train.list_variables(snake_case__ )
lowerCAmelCase__ = {}
for name, shape in init_vars:
logger.info(f'Loading TF weight {name} with shape {shape}' )
lowerCAmelCase__ = tf.train.load_variable(snake_case__ , snake_case__ )
lowerCAmelCase__ = array
# Build TF to PyTorch weights loading map
lowerCAmelCase__ = _build_tf_to_pytorch_map(snake_case__ , snake_case__ , snake_case__ )
for name, pointer in tf_to_pt_map.items():
logger.info(f'Importing {name}' )
if name not in tf_weights:
logger.info(f'{name} not in tf pre-trained weights, skipping' )
continue
lowerCAmelCase__ = tf_weights[name]
if "depthwise_weights" in name:
logger.info('Transposing depthwise' )
lowerCAmelCase__ = np.transpose(snake_case__ , (2, 3, 0, 1) )
elif "weights" in name:
logger.info('Transposing' )
if len(pointer.shape ) == 2: # copying into linear layer
lowerCAmelCase__ = array.squeeze().transpose()
else:
lowerCAmelCase__ = np.transpose(snake_case__ , (3, 2, 0, 1) )
if pointer.shape != array.shape:
raise ValueError(f'Pointer shape {pointer.shape} and array shape {array.shape} mismatched' )
logger.info(f'Initialize PyTorch weight {name} {array.shape}' )
lowerCAmelCase__ = torch.from_numpy(snake_case__ )
tf_weights.pop(snake_case__ , snake_case__ )
tf_weights.pop(name + '/RMSProp' , snake_case__ )
tf_weights.pop(name + '/RMSProp_1' , snake_case__ )
tf_weights.pop(name + '/ExponentialMovingAverage' , snake_case__ )
logger.info(f'Weights not copied to PyTorch model: {", ".join(tf_weights.keys() )}' )
return model
def UpperCAmelCase_ ( snake_case__ , snake_case__ ) -> torch.Tensor:
"""simple docstring"""
lowerCAmelCase__ , lowerCAmelCase__ = features.shape[-2:]
lowerCAmelCase__ , lowerCAmelCase__ = conv_layer.stride
lowerCAmelCase__ , lowerCAmelCase__ = conv_layer.kernel_size
if in_height % stride_height == 0:
lowerCAmelCase__ = max(kernel_height - stride_height , 0 )
else:
lowerCAmelCase__ = max(kernel_height - (in_height % stride_height) , 0 )
if in_width % stride_width == 0:
lowerCAmelCase__ = max(kernel_width - stride_width , 0 )
else:
lowerCAmelCase__ = max(kernel_width - (in_width % stride_width) , 0 )
lowerCAmelCase__ = pad_along_width // 2
lowerCAmelCase__ = pad_along_width - pad_left
lowerCAmelCase__ = pad_along_height // 2
lowerCAmelCase__ = pad_along_height - pad_top
lowerCAmelCase__ = (pad_left, pad_right, pad_top, pad_bottom)
return nn.functional.pad(snake_case__ , snake_case__ , 'constant' , 0.0 )
class __snake_case ( nn.Module ):
def __init__( self ,a_ ,a_ ,a_ ,a_ ,a_ = 1 ,a_ = 1 ,a_ = False ,a_ = True ,a_ = True ,):
"""simple docstring"""
super().__init__()
lowerCAmelCase__ = config
if in_channels % groups != 0:
raise ValueError(f'Input channels ({in_channels}) are not divisible by {groups} groups.' )
if out_channels % groups != 0:
raise ValueError(f'Output channels ({out_channels}) are not divisible by {groups} groups.' )
lowerCAmelCase__ = 0 if config.tf_padding else int((kernel_size - 1) / 2 )
lowerCAmelCase__ = nn.Convad(
in_channels=a_ ,out_channels=a_ ,kernel_size=a_ ,stride=a_ ,padding=a_ ,groups=a_ ,bias=a_ ,padding_mode='zeros' ,)
if use_normalization:
lowerCAmelCase__ = nn.BatchNormad(
num_features=a_ ,eps=config.layer_norm_eps ,momentum=0.9997 ,affine=a_ ,track_running_stats=a_ ,)
else:
lowerCAmelCase__ = None
if use_activation:
if isinstance(a_ ,a_ ):
lowerCAmelCase__ = ACTaFN[use_activation]
elif isinstance(config.hidden_act ,a_ ):
lowerCAmelCase__ = ACTaFN[config.hidden_act]
else:
lowerCAmelCase__ = config.hidden_act
else:
lowerCAmelCase__ = None
def SCREAMING_SNAKE_CASE_ ( self ,a_ ):
"""simple docstring"""
if self.config.tf_padding:
lowerCAmelCase__ = apply_tf_padding(a_ ,self.convolution )
lowerCAmelCase__ = self.convolution(a_ )
if self.normalization is not None:
lowerCAmelCase__ = self.normalization(a_ )
if self.activation is not None:
lowerCAmelCase__ = self.activation(a_ )
return features
class __snake_case ( SCREAMING_SNAKE_CASE ):
SCREAMING_SNAKE_CASE__ = MobileNetVaConfig
SCREAMING_SNAKE_CASE__ = load_tf_weights_in_mobilenet_va
SCREAMING_SNAKE_CASE__ = 'mobilenet_v1'
SCREAMING_SNAKE_CASE__ = 'pixel_values'
SCREAMING_SNAKE_CASE__ = False
def SCREAMING_SNAKE_CASE_ ( self ,a_ ):
"""simple docstring"""
if isinstance(a_ ,(nn.Linear, nn.Convad) ):
module.weight.data.normal_(mean=0.0 ,std=self.config.initializer_range )
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(a_ ,nn.BatchNormad ):
module.bias.data.zero_()
module.weight.data.fill_(1.0 )
_lowerCAmelCase : Tuple = R"\n This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n behavior.\n\n Parameters:\n config ([`MobileNetV1Config`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n"
_lowerCAmelCase : Dict = R"\n Args:\n pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`MobileNetV1ImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n"
@add_start_docstrings(
'The bare MobileNetV1 model outputting raw hidden-states without any specific head on top.' , SCREAMING_SNAKE_CASE , )
class __snake_case ( SCREAMING_SNAKE_CASE ):
def __init__( self ,a_ ,a_ = True ):
"""simple docstring"""
super().__init__(a_ )
lowerCAmelCase__ = config
lowerCAmelCase__ = 32
lowerCAmelCase__ = max(int(depth * config.depth_multiplier ) ,config.min_depth )
lowerCAmelCase__ = MobileNetVaConvLayer(
a_ ,in_channels=config.num_channels ,out_channels=a_ ,kernel_size=3 ,stride=2 ,)
lowerCAmelCase__ = [1, 2, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1]
lowerCAmelCase__ = nn.ModuleList()
for i in range(13 ):
lowerCAmelCase__ = out_channels
if strides[i] == 2 or i == 0:
depth *= 2
lowerCAmelCase__ = max(int(depth * config.depth_multiplier ) ,config.min_depth )
self.layer.append(
MobileNetVaConvLayer(
a_ ,in_channels=a_ ,out_channels=a_ ,kernel_size=3 ,stride=strides[i] ,groups=a_ ,) )
self.layer.append(
MobileNetVaConvLayer(
a_ ,in_channels=a_ ,out_channels=a_ ,kernel_size=1 ,) )
lowerCAmelCase__ = nn.AdaptiveAvgPoolad((1, 1) ) if add_pooling_layer else None
# Initialize weights and apply final processing
self.post_init()
def SCREAMING_SNAKE_CASE_ ( self ,a_ ):
"""simple docstring"""
raise NotImplementedError
@add_start_docstrings_to_model_forward(a_ )
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC ,output_type=a_ ,config_class=_CONFIG_FOR_DOC ,modality='vision' ,expected_output=_EXPECTED_OUTPUT_SHAPE ,)
def SCREAMING_SNAKE_CASE_ ( self ,a_ = None ,a_ = None ,a_ = None ,):
"""simple docstring"""
lowerCAmelCase__ = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict
if pixel_values is None:
raise ValueError('You have to specify pixel_values' )
lowerCAmelCase__ = self.conv_stem(a_ )
lowerCAmelCase__ = () if output_hidden_states else None
for i, layer_module in enumerate(self.layer ):
lowerCAmelCase__ = layer_module(a_ )
if output_hidden_states:
lowerCAmelCase__ = all_hidden_states + (hidden_states,)
lowerCAmelCase__ = hidden_states
if self.pooler is not None:
lowerCAmelCase__ = torch.flatten(self.pooler(a_ ) ,start_dim=1 )
else:
lowerCAmelCase__ = None
if not return_dict:
return tuple(v for v in [last_hidden_state, pooled_output, all_hidden_states] if v is not None )
return BaseModelOutputWithPoolingAndNoAttention(
last_hidden_state=a_ ,pooler_output=a_ ,hidden_states=a_ ,)
@add_start_docstrings(
'\n MobileNetV1 model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n ' , SCREAMING_SNAKE_CASE , )
class __snake_case ( SCREAMING_SNAKE_CASE ):
def __init__( self ,a_ ):
"""simple docstring"""
super().__init__(a_ )
lowerCAmelCase__ = config.num_labels
lowerCAmelCase__ = MobileNetVaModel(a_ )
lowerCAmelCase__ = self.mobilenet_va.layer[-1].convolution.out_channels
# Classifier head
lowerCAmelCase__ = nn.Dropout(config.classifier_dropout_prob ,inplace=a_ )
lowerCAmelCase__ = nn.Linear(a_ ,config.num_labels ) if config.num_labels > 0 else nn.Identity()
# Initialize weights and apply final processing
self.post_init()
@add_start_docstrings_to_model_forward(a_ )
@add_code_sample_docstrings(
checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=a_ ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,)
def SCREAMING_SNAKE_CASE_ ( self ,a_ = None ,a_ = None ,a_ = None ,a_ = None ,):
"""simple docstring"""
lowerCAmelCase__ = return_dict if return_dict is not None else self.config.use_return_dict
lowerCAmelCase__ = self.mobilenet_va(a_ ,output_hidden_states=a_ ,return_dict=a_ )
lowerCAmelCase__ = outputs.pooler_output if return_dict else outputs[1]
lowerCAmelCase__ = self.classifier(self.dropout(a_ ) )
lowerCAmelCase__ = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
lowerCAmelCase__ = 'regression'
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
lowerCAmelCase__ = 'single_label_classification'
else:
lowerCAmelCase__ = 'multi_label_classification'
if self.config.problem_type == "regression":
lowerCAmelCase__ = MSELoss()
if self.num_labels == 1:
lowerCAmelCase__ = loss_fct(logits.squeeze() ,labels.squeeze() )
else:
lowerCAmelCase__ = loss_fct(a_ ,a_ )
elif self.config.problem_type == "single_label_classification":
lowerCAmelCase__ = CrossEntropyLoss()
lowerCAmelCase__ = loss_fct(logits.view(-1 ,self.num_labels ) ,labels.view(-1 ) )
elif self.config.problem_type == "multi_label_classification":
lowerCAmelCase__ = BCEWithLogitsLoss()
lowerCAmelCase__ = loss_fct(a_ ,a_ )
if not return_dict:
lowerCAmelCase__ = (logits,) + outputs[2:]
return ((loss,) + output) if loss is not None else output
return ImageClassifierOutputWithNoAttention(
loss=a_ ,logits=a_ ,hidden_states=outputs.hidden_states ,)
| 193 | 0 |
# limitations under the License.
# NOTE: This file is deprecated and will be removed in a future version.
# It only exists so that temporarely `from diffusers.pipelines import DiffusionPipeline` works
from .pipelines import DiffusionPipeline, ImagePipelineOutput # noqa: F401
from .utils import deprecate
deprecate(
"pipelines_utils",
"0.22.0",
"Importing `DiffusionPipeline` or `ImagePipelineOutput` from diffusers.pipeline_utils is deprecated. Please import from diffusers.pipelines.pipeline_utils instead.",
standard_warn=False,
stacklevel=3,
)
| 620 |
from dataclasses import dataclass
from typing import Optional, Tuple, Union
import torch
import torch.nn as nn
from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer
@dataclass
class __snake_case ( lowerCAmelCase__ ):
__lowerCAmelCase : torch.FloatTensor
class __snake_case ( lowerCAmelCase__ , lowerCAmelCase__ ):
@register_to_config
def __init__( self , _A = 3 , _A = 3 , _A = ("DownEncoderBlock2D",) , _A = ("UpDecoderBlock2D",) , _A = (64,) , _A = 1 , _A = "silu" , _A = 3 , _A = 32 , _A = 256 , _A = 32 , _A = None , _A = 0.1_8_2_1_5 , _A = "group" , ):
super().__init__()
# pass init params to Encoder
SCREAMING_SNAKE_CASE_ = Encoder(
in_channels=_A , out_channels=_A , down_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , double_z=_A , )
SCREAMING_SNAKE_CASE_ = vq_embed_dim if vq_embed_dim is not None else latent_channels
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
SCREAMING_SNAKE_CASE_ = VectorQuantizer(_A , _A , beta=0.2_5 , remap=_A , sane_index_shape=_A)
SCREAMING_SNAKE_CASE_ = nn.Convad(_A , _A , 1)
# pass init params to Decoder
SCREAMING_SNAKE_CASE_ = Decoder(
in_channels=_A , out_channels=_A , up_block_types=_A , block_out_channels=_A , layers_per_block=_A , act_fn=_A , norm_num_groups=_A , norm_type=_A , )
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = self.encoder(_A)
SCREAMING_SNAKE_CASE_ = self.quant_conv(_A)
if not return_dict:
return (h,)
return VQEncoderOutput(latents=_A)
@apply_forward_hook
def lowerCAmelCase__ ( self , _A , _A = False , _A = True):
# also go through quantization layer
if not force_not_quantize:
SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_ = self.quantize(_A)
else:
SCREAMING_SNAKE_CASE_ = h
SCREAMING_SNAKE_CASE_ = self.post_quant_conv(_A)
SCREAMING_SNAKE_CASE_ = self.decoder(_A , quant if self.config.norm_type == 'spatial' else None)
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
def lowerCAmelCase__ ( self , _A , _A = True):
SCREAMING_SNAKE_CASE_ = sample
SCREAMING_SNAKE_CASE_ = self.encode(_A).latents
SCREAMING_SNAKE_CASE_ = self.decode(_A).sample
if not return_dict:
return (dec,)
return DecoderOutput(sample=_A)
| 620 | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.