code
stringlengths
82
54.1k
code_codestyle
int64
0
699
style_context
stringlengths
111
35.6k
style_context_codestyle
int64
0
699
label
int64
0
1
'''simple docstring''' import os import zipfile import requests from get_ci_error_statistics import download_artifact, get_artifacts_links def lowerCAmelCase_ ( snake_case_ : Union[str, Any] , snake_case_ : Optional[int]=7 ) -> Any: '''simple docstring''' UpperCAmelCase_ = None if token is not None: UpperCAmelCase_ = {"Accept": "application/vnd.github+json", "Authorization": f"""Bearer {token}"""} # The id of a workflow (not of a workflow run) UpperCAmelCase_ = "636036" UpperCAmelCase_ = f"""https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs""" # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results url += f"""?branch=main&event=schedule&exclude_pull_requests=true&per_page={num_runs}""" UpperCAmelCase_ = requests.get(snake_case_ , headers=snake_case_ ).json() return result["workflow_runs"] def lowerCAmelCase_ ( snake_case_ : Any ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = get_daily_ci_runs(snake_case_ ) UpperCAmelCase_ = None for workflow_run in workflow_runs: if workflow_run["status"] == "completed": UpperCAmelCase_ = workflow_run["id"] break return workflow_run_id def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = get_last_daily_ci_runs(snake_case_ ) if workflow_run_id is not None: UpperCAmelCase_ = get_artifacts_links(worflow_run_id=snake_case_ , token=snake_case_ ) for artifact_name in artifact_names: if artifact_name in artifacts_links: UpperCAmelCase_ = artifacts_links[artifact_name] download_artifact( artifact_name=snake_case_ , artifact_url=snake_case_ , output_dir=snake_case_ , token=snake_case_ ) def lowerCAmelCase_ ( snake_case_ : Dict , snake_case_ : Tuple , snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' get_last_daily_ci_artifacts(snake_case_ , snake_case_ , snake_case_ ) UpperCAmelCase_ = {} for artifact_name in artifact_names: UpperCAmelCase_ = os.path.join(snake_case_ , f"""{artifact_name}.zip""" ) if os.path.isfile(snake_case_ ): UpperCAmelCase_ = {} with zipfile.ZipFile(snake_case_ ) as z: for filename in z.namelist(): if not os.path.isdir(snake_case_ ): # read the file with z.open(snake_case_ ) as f: UpperCAmelCase_ = f.read().decode("UTF-8" ) return results
78
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
1
'''simple docstring''' import numpy as np from sklearn.datasets import fetch_california_housing from sklearn.metrics import mean_absolute_error, mean_squared_error from sklearn.model_selection import train_test_split from xgboost import XGBRegressor def lowerCAmelCase_ ( snake_case_ : dict ) -> tuple: '''simple docstring''' return (data["data"], data["target"]) def lowerCAmelCase_ ( snake_case_ : np.ndarray , snake_case_ : np.ndarray , snake_case_ : np.ndarray ) -> np.ndarray: '''simple docstring''' UpperCAmelCase_ = XGBRegressor(verbosity=0 , random_state=42 ) xgb.fit(snake_case_ , snake_case_ ) # Predict target for test data UpperCAmelCase_ = xgb.predict(snake_case_ ) UpperCAmelCase_ = predictions.reshape(len(snake_case_ ) , 1 ) return predictions def lowerCAmelCase_ ( ) -> None: '''simple docstring''' UpperCAmelCase_ = fetch_california_housing() UpperCAmelCase_ , UpperCAmelCase_ = data_handling(snake_case_ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = train_test_split( snake_case_ , snake_case_ , test_size=0.25 , random_state=1 ) UpperCAmelCase_ = xgboost(snake_case_ , snake_case_ , snake_case_ ) # Error printing print(f"""Mean Absolute Error : {mean_absolute_error(snake_case_ , snake_case_ )}""" ) print(f"""Mean Square Error : {mean_squared_error(snake_case_ , snake_case_ )}""" ) if __name__ == "__main__": import doctest doctest.testmod(verbose=True) main()
78
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any]=0.999 , snake_case_ : Tuple="cosine" , ) -> Optional[Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase_ = [] for i in range(snake_case_ ): UpperCAmelCase_ = i / num_diffusion_timesteps UpperCAmelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case_ ) / alpha_bar_fn(snake_case_ ) , snake_case_ ) ) return torch.tensor(snake_case_ , dtype=torch.floataa ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : Tuple = [e.name for e in KarrasDiffusionSchedulers] a__ : Optional[Any] = 2 @register_to_config def __init__(self : Union[str, Any] , __a : int = 1000 , __a : float = 0.0_00_85 , __a : float = 0.0_12 , __a : str = "linear" , __a : Optional[Union[np.ndarray, List[float]]] = None , __a : str = "epsilon" , __a : Optional[bool] = False , __a : Optional[bool] = False , __a : float = 1.0 , __a : str = "linspace" , __a : int = 0 , ): if trained_betas is not None: UpperCAmelCase_ = torch.tensor(__a , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase_ = torch.linspace(__a , __a , __a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="cosine" ) elif beta_schedule == "exp": UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) UpperCAmelCase_ = 1.0 - self.betas UpperCAmelCase_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__a , __a , __a ) UpperCAmelCase_ = use_karras_sigmas def _lowercase (self : Optional[Any] , __a : Union[str, Any] , __a : Tuple=None ): if schedule_timesteps is None: UpperCAmelCase_ = self.timesteps UpperCAmelCase_ = (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: UpperCAmelCase_ = 1 if len(__a ) > 1 else 0 else: UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep UpperCAmelCase_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self : List[Any] ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self : Optional[Any] , __a : torch.FloatTensor , __a : Union[float, torch.FloatTensor] , ): UpperCAmelCase_ = self.index_for_timestep(__a ) UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self : Any , __a : int , __a : Union[str, torch.device] = None , __a : Optional[int] = None , ): UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = 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": UpperCAmelCase_ = np.linspace(0 , num_train_timesteps - 1 , __a , dtype=__a )[::-1].copy() elif self.config.timestep_spacing == "leading": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(0 , __a ) * step_ratio).round()[::-1].copy().astype(__a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(__a , 0 , -step_ratio )).round().copy().astype(__a ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) UpperCAmelCase_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) UpperCAmelCase_ = np.log(__a ) UpperCAmelCase_ = np.interp(__a , np.arange(0 , len(__a ) ) , __a ) if self.config.use_karras_sigmas: UpperCAmelCase_ = self._convert_to_karras(in_sigmas=__a , num_inference_steps=self.num_inference_steps ) UpperCAmelCase_ = np.array([self._sigma_to_t(__a , __a ) for sigma in sigmas] ) UpperCAmelCase_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a ) UpperCAmelCase_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) UpperCAmelCase_ = torch.from_numpy(__a ) UpperCAmelCase_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__a ).startswith("mps" ): # mps does not support float64 UpperCAmelCase_ = timesteps.to(__a , dtype=torch.floataa ) else: UpperCAmelCase_ = timesteps.to(device=__a ) # empty dt and derivative UpperCAmelCase_ = None UpperCAmelCase_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter UpperCAmelCase_ = defaultdict(__a ) def _lowercase (self : int , __a : Optional[Any] , __a : List[str] ): # get log sigma UpperCAmelCase_ = np.log(__a ) # get distribution UpperCAmelCase_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range UpperCAmelCase_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) UpperCAmelCase_ = low_idx + 1 UpperCAmelCase_ = log_sigmas[low_idx] UpperCAmelCase_ = log_sigmas[high_idx] # interpolate sigmas UpperCAmelCase_ = (low - log_sigma) / (low - high) UpperCAmelCase_ = np.clip(__a , 0 , 1 ) # transform interpolation to time range UpperCAmelCase_ = (1 - w) * low_idx + w * high_idx UpperCAmelCase_ = t.reshape(sigma.shape ) return t def _lowercase (self : Dict , __a : torch.FloatTensor , __a : Optional[int] ): UpperCAmelCase_ = in_sigmas[-1].item() UpperCAmelCase_ = in_sigmas[0].item() UpperCAmelCase_ = 7.0 # 7.0 is the value used in the paper UpperCAmelCase_ = np.linspace(0 , 1 , __a ) UpperCAmelCase_ = sigma_min ** (1 / rho) UpperCAmelCase_ = sigma_max ** (1 / rho) UpperCAmelCase_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self : List[str] ): return self.dt is None def _lowercase (self : List[Any] , __a : Union[torch.FloatTensor, np.ndarray] , __a : Union[float, torch.FloatTensor] , __a : Union[torch.FloatTensor, np.ndarray] , __a : bool = True , ): UpperCAmelCase_ = self.index_for_timestep(__a ) # advance index counter by 1 UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method UpperCAmelCase_ = self.sigmas[step_index - 1] UpperCAmelCase_ = 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 UpperCAmelCase_ = 0 UpperCAmelCase_ = 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": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": UpperCAmelCase_ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: UpperCAmelCase_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order UpperCAmelCase_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep UpperCAmelCase_ = sigma_next - sigma_hat # store for 2nd order step UpperCAmelCase_ = derivative UpperCAmelCase_ = dt UpperCAmelCase_ = sample else: # 2. 2nd order / Heun's method UpperCAmelCase_ = (sample - pred_original_sample) / sigma_next UpperCAmelCase_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample UpperCAmelCase_ = self.dt UpperCAmelCase_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a ) def _lowercase (self : Any , __a : torch.FloatTensor , __a : torch.FloatTensor , __a : torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples UpperCAmelCase_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__a ): # mps does not support float64 UpperCAmelCase_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) UpperCAmelCase_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: UpperCAmelCase_ = self.timesteps.to(original_samples.device ) UpperCAmelCase_ = timesteps.to(original_samples.device ) UpperCAmelCase_ = [self.index_for_timestep(__a , __a ) for t in timesteps] UpperCAmelCase_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): UpperCAmelCase_ = sigma.unsqueeze(-1 ) UpperCAmelCase_ = original_samples + noise * sigma return noisy_samples def __len__(self : str ): return self.config.num_train_timesteps
78
1
'''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 MobileViTImageProcessor class __A ( unittest.TestCase ): def __init__(self : Tuple , __a : List[str] , __a : Optional[Any]=7 , __a : Union[str, Any]=3 , __a : Union[str, Any]=18 , __a : List[Any]=30 , __a : List[str]=400 , __a : Optional[int]=True , __a : List[str]=None , __a : Any=True , __a : Any=None , __a : Any=True , ): UpperCAmelCase_ = size if size is not None else {"shortest_edge": 20} UpperCAmelCase_ = crop_size if crop_size is not None else {"height": 18, "width": 18} UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = num_channels UpperCAmelCase_ = image_size UpperCAmelCase_ = min_resolution UpperCAmelCase_ = max_resolution UpperCAmelCase_ = do_resize UpperCAmelCase_ = size UpperCAmelCase_ = do_center_crop UpperCAmelCase_ = crop_size UpperCAmelCase_ = do_flip_channel_order def _lowercase (self : Dict ): return { "do_resize": self.do_resize, "size": self.size, "do_center_crop": self.do_center_crop, "crop_size": self.crop_size, "do_flip_channel_order": self.do_flip_channel_order, } @require_torch @require_vision class __A ( UpperCamelCase__ , unittest.TestCase ): a__ : Tuple = MobileViTImageProcessor if is_vision_available() else None def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = MobileViTImageProcessingTester(self ) @property def _lowercase (self : Any ): return self.image_processor_tester.prepare_image_processor_dict() def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__a , "do_resize" ) ) self.assertTrue(hasattr(__a , "size" ) ) self.assertTrue(hasattr(__a , "do_center_crop" ) ) self.assertTrue(hasattr(__a , "center_crop" ) ) self.assertTrue(hasattr(__a , "do_flip_channel_order" ) ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {"shortest_edge": 20} ) self.assertEqual(image_processor.crop_size , {"height": 18, "width": 18} ) UpperCAmelCase_ = self.image_processing_class.from_dict(self.image_processor_dict , size=42 , crop_size=84 ) self.assertEqual(image_processor.size , {"shortest_edge": 42} ) self.assertEqual(image_processor.crop_size , {"height": 84, "width": 84} ) def _lowercase (self : Tuple ): pass def _lowercase (self : int ): # Initialize image_processing UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PIL images UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a ) for image in image_inputs: self.assertIsInstance(__a , Image.Image ) # Test not batched input UpperCAmelCase_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched UpperCAmelCase_ = image_processing(__a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def _lowercase (self : Any ): # Initialize image_processing UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , numpify=__a ) for image in image_inputs: self.assertIsInstance(__a , np.ndarray ) # Test not batched input UpperCAmelCase_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched UpperCAmelCase_ = image_processing(__a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) def _lowercase (self : Tuple ): # Initialize image_processing UpperCAmelCase_ = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors UpperCAmelCase_ = prepare_image_inputs(self.image_processor_tester , equal_resolution=__a , torchify=__a ) for image in image_inputs: self.assertIsInstance(__a , torch.Tensor ) # Test not batched input UpperCAmelCase_ = image_processing(image_inputs[0] , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( 1, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , ) # Test batched UpperCAmelCase_ = image_processing(__a , return_tensors="pt" ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, self.image_processor_tester.crop_size["height"], self.image_processor_tester.crop_size["width"], ) , )
78
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( UpperCamelCase__ ): a__ : List[str] = """Salesforce/blip-image-captioning-base""" a__ : Optional[Any] = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : str = """image_captioner""" a__ : List[str] = AutoModelForVisionaSeq a__ : int = ["""image"""] a__ : Optional[Any] = ["""text"""] def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*__a , **__a ) def _lowercase (self : Union[str, Any] , __a : "Image" ): return self.pre_processor(images=__a , return_tensors="pt" ) def _lowercase (self : List[str] , __a : Dict ): return self.model.generate(**__a ) def _lowercase (self : int , __a : Optional[Any] ): return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
78
1
'''simple docstring''' import 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_mvp import MvpTokenizer SCREAMING_SNAKE_CASE_: List[str] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Optional[int] ={'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all MVP models at https://huggingface.co/models?filter=mvp SCREAMING_SNAKE_CASE_: Any ={ 'vocab_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json', }, 'added_tokens.json': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json', }, 'merges_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt', }, 'tokenizer_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json', }, } SCREAMING_SNAKE_CASE_: int ={ 'RUCAIBox/mvp': 10_24, } class __A ( UpperCamelCase__ ): a__ : Optional[int] = VOCAB_FILES_NAMES a__ : str = PRETRAINED_VOCAB_FILES_MAP a__ : int = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Any = ["""input_ids""", """attention_mask"""] a__ : List[Any] = MvpTokenizer def __init__(self : Dict , __a : List[Any]=None , __a : List[Any]=None , __a : Optional[int]=None , __a : Any="replace" , __a : Optional[Any]="<s>" , __a : List[str]="</s>" , __a : int="</s>" , __a : Optional[int]="<s>" , __a : str="<unk>" , __a : str="<pad>" , __a : List[Any]="<mask>" , __a : Tuple=False , __a : str=True , **__a : Optional[int] , ): super().__init__( __a , __a , tokenizer_file=__a , errors=__a , bos_token=__a , eos_token=__a , sep_token=__a , cls_token=__a , unk_token=__a , pad_token=__a , mask_token=__a , add_prefix_space=__a , trim_offsets=__a , **__a , ) UpperCAmelCase_ = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get("add_prefix_space" , __a ) != add_prefix_space: UpperCAmelCase_ = getattr(__a , pre_tok_state.pop("type" ) ) UpperCAmelCase_ = add_prefix_space UpperCAmelCase_ = pre_tok_class(**__a ) UpperCAmelCase_ = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` UpperCAmelCase_ = "post_processor" UpperCAmelCase_ = getattr(self.backend_tokenizer , __a , __a ) if tokenizer_component_instance: UpperCAmelCase_ = 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: UpperCAmelCase_ = tuple(state["sep"] ) if "cls" in state: UpperCAmelCase_ = tuple(state["cls"] ) UpperCAmelCase_ = False if state.get("add_prefix_space" , __a ) != add_prefix_space: UpperCAmelCase_ = add_prefix_space UpperCAmelCase_ = True if state.get("trim_offsets" , __a ) != trim_offsets: UpperCAmelCase_ = trim_offsets UpperCAmelCase_ = True if changes_to_apply: UpperCAmelCase_ = getattr(__a , state.pop("type" ) ) UpperCAmelCase_ = component_class(**__a ) setattr(self.backend_tokenizer , __a , __a ) @property def _lowercase (self : List[str] ): 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 _lowercase (self : str , __a : str ): UpperCAmelCase_ = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else value UpperCAmelCase_ = value def _lowercase (self : str , *__a : Dict , **__a : Optional[Any] ): UpperCAmelCase_ = kwargs.get("is_split_into_words" , __a ) 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(*__a , **__a ) def _lowercase (self : Optional[int] , *__a : Optional[int] , **__a : int ): UpperCAmelCase_ = kwargs.get("is_split_into_words" , __a ) 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(*__a , **__a ) def _lowercase (self : List[str] , __a : str , __a : Optional[str] = None ): UpperCAmelCase_ = self._tokenizer.model.save(__a , name=__a ) return tuple(__a ) def _lowercase (self : Tuple , __a : Any , __a : List[str]=None ): UpperCAmelCase_ = [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 _lowercase (self : Tuple , __a : List[int] , __a : Optional[List[int]] = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [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]
78
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
1
'''simple docstring''' from random import shuffle import tensorflow as tf from numpy import array def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Dict ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = int(snake_case_ ) assert noofclusters < len(snake_case_ ) # Find out the dimensionality UpperCAmelCase_ = len(vectors[0] ) # Will help select random centroids from among the available vectors UpperCAmelCase_ = list(range(len(snake_case_ ) ) ) shuffle(snake_case_ ) # GRAPH OF COMPUTATION # We initialize a new graph and set it as the default during each run # of this algorithm. This ensures that as this function is called # multiple times, the default graph doesn't keep getting crowded with # unused ops and Variables from previous function calls. UpperCAmelCase_ = tf.Graph() with graph.as_default(): # SESSION OF COMPUTATION UpperCAmelCase_ = tf.Session() ##CONSTRUCTING THE ELEMENTS OF COMPUTATION ##First lets ensure we have a Variable vector for each centroid, ##initialized to one of the vectors from the available data points UpperCAmelCase_ = [ tf.Variable(vectors[vector_indices[i]] ) for i in range(snake_case_ ) ] ##These nodes will assign the centroid Variables the appropriate ##values UpperCAmelCase_ = tf.placeholder("float64" , [dim] ) UpperCAmelCase_ = [] for centroid in centroids: cent_assigns.append(tf.assign(snake_case_ , snake_case_ ) ) ##Variables for cluster assignments of individual vectors(initialized ##to 0 at first) UpperCAmelCase_ = [tf.Variable(0 ) for i in range(len(snake_case_ ) )] ##These nodes will assign an assignment Variable the appropriate ##value UpperCAmelCase_ = tf.placeholder("int32" ) UpperCAmelCase_ = [] for assignment in assignments: cluster_assigns.append(tf.assign(snake_case_ , snake_case_ ) ) ##Now lets construct the node that will compute the mean # The placeholder for the input UpperCAmelCase_ = tf.placeholder("float" , [None, dim] ) # The Node/op takes the input and computes a mean along the 0th # dimension, i.e. the list of input vectors UpperCAmelCase_ = tf.reduce_mean(snake_case_ , 0 ) ##Node for computing Euclidean distances # Placeholders for input UpperCAmelCase_ = tf.placeholder("float" , [dim] ) UpperCAmelCase_ = tf.placeholder("float" , [dim] ) UpperCAmelCase_ = tf.sqrt(tf.reduce_sum(tf.pow(tf.sub(snake_case_ , snake_case_ ) , 2 ) ) ) ##This node will figure out which cluster to assign a vector to, ##based on Euclidean distances of the vector from the centroids. # Placeholder for input UpperCAmelCase_ = tf.placeholder("float" , [noofclusters] ) UpperCAmelCase_ = tf.argmin(snake_case_ , 0 ) ##INITIALIZING STATE VARIABLES ##This will help initialization of all Variables defined with respect ##to the graph. The Variable-initializer should be defined after ##all the Variables have been constructed, so that each of them ##will be included in the initialization. UpperCAmelCase_ = tf.initialize_all_variables() # Initialize all variables sess.run(snake_case_ ) ##CLUSTERING ITERATIONS # Now perform the Expectation-Maximization steps of K-Means clustering # iterations. To keep things simple, we will only do a set number of # iterations, instead of using a Stopping Criterion. UpperCAmelCase_ = 1_00 for _ in range(snake_case_ ): ##EXPECTATION STEP ##Based on the centroid locations till last iteration, compute ##the _expected_ centroid assignments. # Iterate over each vector for vector_n in range(len(snake_case_ ) ): UpperCAmelCase_ = vectors[vector_n] # Compute Euclidean distance between this vector and each # centroid. Remember that this list cannot be named #'centroid_distances', since that is the input to the # cluster assignment node. UpperCAmelCase_ = [ sess.run(snake_case_ , feed_dict={va: vect, va: sess.run(snake_case_ )} ) for centroid in centroids ] # Now use the cluster assignment node, with the distances # as the input UpperCAmelCase_ = sess.run( snake_case_ , feed_dict={centroid_distances: distances} ) # Now assign the value to the appropriate state variable sess.run( cluster_assigns[vector_n] , feed_dict={assignment_value: assignment} ) ##MAXIMIZATION STEP # Based on the expected state computed from the Expectation Step, # compute the locations of the centroids so as to maximize the # overall objective of minimizing within-cluster Sum-of-Squares for cluster_n in range(snake_case_ ): # Collect all the vectors assigned to this cluster UpperCAmelCase_ = [ vectors[i] for i in range(len(snake_case_ ) ) if sess.run(assignments[i] ) == cluster_n ] # Compute new centroid location UpperCAmelCase_ = sess.run( snake_case_ , feed_dict={mean_input: array(snake_case_ )} ) # Assign value to appropriate variable sess.run( cent_assigns[cluster_n] , feed_dict={centroid_value: new_location} ) # Return centroids and assignments UpperCAmelCase_ = sess.run(snake_case_ ) UpperCAmelCase_ = sess.run(snake_case_ ) return centroids, assignments
78
'''simple docstring''' import copy import re class __A : a__ : Optional[int] = """hp""" a__ : Optional[Any] = {} a__ : List[Any] = None @classmethod def _lowercase (cls : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = prefix UpperCAmelCase_ = defaults cls.build_naming_info() @staticmethod def _lowercase (__a : List[Any] , __a : List[str] ): if len(__a ) == 0: return "" UpperCAmelCase_ = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__a ) + 1 ): UpperCAmelCase_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__a : Union[str, Any] ): UpperCAmelCase_ = "" while integer != 0: UpperCAmelCase_ = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase_ = 0 while True: UpperCAmelCase_ = word + "#" + int_to_alphabetic(__a ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase_ = sword break UpperCAmelCase_ = short_word UpperCAmelCase_ = word return short_word @staticmethod def _lowercase (__a : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = param_name.split("_" ) UpperCAmelCase_ = [TrialShortNamer.shortname_for_word(__a , __a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase_ = ["", "_"] for separator in separators: UpperCAmelCase_ = separator.join(__a ) if shortname not in info["reverse_short_param"]: UpperCAmelCase_ = shortname UpperCAmelCase_ = param_name return shortname return param_name @staticmethod def _lowercase (__a : int , __a : Union[str, Any] ): UpperCAmelCase_ = TrialShortNamer.shortname_for_key(__a , __a ) UpperCAmelCase_ = short_name UpperCAmelCase_ = param_name @classmethod def _lowercase (cls : Any ): if cls.NAMING_INFO is not None: return UpperCAmelCase_ = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } UpperCAmelCase_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__a , __a ) UpperCAmelCase_ = info @classmethod def _lowercase (cls : int , __a : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase_ = cls.NAMING_INFO["short_param"][k] if isinstance(__a , __a ): UpperCAmelCase_ = 1 if v else 0 UpperCAmelCase_ = "" if isinstance(__a , (int, float) ) else "-" UpperCAmelCase_ = f"""{key}{sep}{v}""" name.append(__a ) return "_".join(__a ) @classmethod def _lowercase (cls : Dict , __a : Dict ): UpperCAmelCase_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase_ = [] else: UpperCAmelCase_ = repr.split("_" ) UpperCAmelCase_ = {} for value in values: if "-" in value: UpperCAmelCase_ , UpperCAmelCase_ = value.split("-" ) else: UpperCAmelCase_ = re.sub("[0-9.]" , "" , __a ) UpperCAmelCase_ = float(re.sub("[^0-9.]" , "" , __a ) ) UpperCAmelCase_ = cls.NAMING_INFO["reverse_short_param"][p_k] UpperCAmelCase_ = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase_ = cls.DEFAULTS[k] return parameters
78
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={'vocab_file': 'sentencepiece.model'} SCREAMING_SNAKE_CASE_: List[Any] ={ 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, } SCREAMING_SNAKE_CASE_: Tuple ={ 'google/rembert': 2_56, } class __A ( UpperCamelCase__ ): a__ : Any = VOCAB_FILES_NAMES a__ : Tuple = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES def __init__(self : Union[str, Any] , __a : Tuple , __a : Union[str, Any]=False , __a : Union[str, Any]=True , __a : Optional[Any]=True , __a : str="[CLS]" , __a : Optional[Any]="[SEP]" , __a : List[str]="[UNK]" , __a : Optional[int]="[SEP]" , __a : List[Any]="[PAD]" , __a : int="[CLS]" , __a : Dict="[MASK]" , **__a : Optional[int] , ): super().__init__( do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , **__a , ) UpperCAmelCase_ = do_lower_case UpperCAmelCase_ = remove_space UpperCAmelCase_ = keep_accents UpperCAmelCase_ = vocab_file UpperCAmelCase_ = spm.SentencePieceProcessor() self.sp_model.Load(__a ) @property def _lowercase (self : Any ): return len(self.sp_model ) def _lowercase (self : List[Any] ): UpperCAmelCase_ = {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 : Dict ): UpperCAmelCase_ = self.__dict__.copy() UpperCAmelCase_ = None return state def __setstate__(self : str , __a : Optional[Any] ): UpperCAmelCase_ = d UpperCAmelCase_ = spm.SentencePieceProcessor() self.sp_model.Load(self.vocab_file ) def _lowercase (self : Dict , __a : Union[str, Any] , __a : int=False ): UpperCAmelCase_ = self.sp_model.EncodeAsPieces(__a ) return pieces def _lowercase (self : str , __a : Optional[int] ): return self.sp_model.PieceToId(__a ) def _lowercase (self : int , __a : Optional[int] ): return self.sp_model.IdToPiece(__a ) def _lowercase (self : Dict , __a : Union[str, Any] ): UpperCAmelCase_ = self.sp_model.decode_pieces(__a ) return out_string def _lowercase (self : int , __a : List[int] , __a : Optional[List[int]] = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _lowercase (self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None , __a : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] return [1] + ([0] * len(__a )) + [1] def _lowercase (self : Optional[int] , __a : List[int] , __a : Optional[List[int]] = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [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 _lowercase (self : Tuple , __a : str , __a : Optional[str] = None ): if not os.path.isdir(__a ): logger.error("Vocabulary path ({}) should be a directory".format(__a ) ) return UpperCAmelCase_ = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ): copyfile(self.vocab_file , __a ) return (out_vocab_file,)
78
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ = do_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
1
'''simple docstring''' from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : CLIPSegForImageSegmentation , __a : CLIPSegProcessor , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = 1 UpperCAmelCase_ = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = True UpperCAmelCase_ = FrozenDict(__a ) if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _lowercase (self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _lowercase (self : int ): self.enable_attention_slicing(__a ) def _lowercase (self : Optional[Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : Optional[int] ): if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_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() def __call__(self : Dict , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, PIL.Image.Image] , __a : str , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): UpperCAmelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) UpperCAmelCase_ = self.segmentation_model(**__a ) UpperCAmelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCAmelCase_ = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCAmelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
78
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
1
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case_ : list[int | float] , snake_case_ : int , snake_case_ : int ) -> int | float: '''simple docstring''' if len(snake_case_ ) == 0: raise ValueError("find_max() arg is an empty sequence" ) if ( left >= len(snake_case_ ) or left < -len(snake_case_ ) or right >= len(snake_case_ ) or right < -len(snake_case_ ) ): raise IndexError("list index out of range" ) if left == right: return nums[left] UpperCAmelCase_ = (left + right) >> 1 # the middle UpperCAmelCase_ = find_max(snake_case_ , snake_case_ , snake_case_ ) # find max in range[left, mid] UpperCAmelCase_ = find_max(snake_case_ , mid + 1 , snake_case_ ) # find max in range[mid + 1, right] return left_max if left_max >= right_max else right_max if __name__ == "__main__": import doctest doctest.testmod(verbose=True)
78
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' import inspect import unittest from math import floor from transformers import CvtConfig from transformers.file_utils import cached_property, is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import CvtForImageClassification, CvtModel from transformers.models.cvt.modeling_cvt import CVT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import AutoImageProcessor class __A ( UpperCamelCase__ ): def _lowercase (self : Dict ): UpperCAmelCase_ = self.config_class(**self.inputs_dict ) self.parent.assertTrue(hasattr(__a , "embed_dim" ) ) self.parent.assertTrue(hasattr(__a , "num_heads" ) ) class __A : def __init__(self : List[Any] , __a : Union[str, Any] , __a : Optional[int]=13 , __a : Optional[int]=64 , __a : List[Any]=3 , __a : Tuple=[16, 48, 96] , __a : Optional[Any]=[1, 3, 6] , __a : Union[str, Any]=[1, 2, 10] , __a : int=[7, 3, 3] , __a : List[str]=[4, 2, 2] , __a : Any=[2, 1, 1] , __a : Optional[Any]=[2, 2, 2] , __a : int=[False, False, True] , __a : Tuple=[0.0, 0.0, 0.0] , __a : Optional[int]=0.02 , __a : List[Any]=1E-12 , __a : Union[str, Any]=True , __a : Optional[Any]=True , __a : Any=2 , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = image_size UpperCAmelCase_ = patch_sizes UpperCAmelCase_ = patch_stride UpperCAmelCase_ = patch_padding UpperCAmelCase_ = is_training UpperCAmelCase_ = use_labels UpperCAmelCase_ = num_labels UpperCAmelCase_ = num_channels UpperCAmelCase_ = embed_dim UpperCAmelCase_ = num_heads UpperCAmelCase_ = stride_kv UpperCAmelCase_ = depth UpperCAmelCase_ = cls_token UpperCAmelCase_ = attention_drop_rate UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps def _lowercase (self : str ): UpperCAmelCase_ = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) UpperCAmelCase_ = None if self.use_labels: UpperCAmelCase_ = ids_tensor([self.batch_size] , self.num_labels ) UpperCAmelCase_ = self.get_config() return config, pixel_values, labels def _lowercase (self : List[Any] ): return CvtConfig( image_size=self.image_size , num_labels=self.num_labels , num_channels=self.num_channels , embed_dim=self.embed_dim , num_heads=self.num_heads , patch_sizes=self.patch_sizes , patch_padding=self.patch_padding , patch_stride=self.patch_stride , stride_kv=self.stride_kv , depth=self.depth , cls_token=self.cls_token , attention_drop_rate=self.attention_drop_rate , initializer_range=self.initializer_range , ) def _lowercase (self : List[Any] , __a : Optional[Any] , __a : Tuple , __a : Dict ): UpperCAmelCase_ = CvtModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a ) UpperCAmelCase_ = (self.image_size, self.image_size) UpperCAmelCase_ , UpperCAmelCase_ = image_size[0], image_size[1] for i in range(len(self.depth ) ): UpperCAmelCase_ = floor(((height + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) UpperCAmelCase_ = floor(((width + 2 * self.patch_padding[i] - self.patch_sizes[i]) / self.patch_stride[i]) + 1 ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.embed_dim[-1], height, width) ) def _lowercase (self : Union[str, Any] , __a : str , __a : Union[str, Any] , __a : Union[str, Any] ): UpperCAmelCase_ = self.num_labels UpperCAmelCase_ = CvtForImageClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase (self : Any ): UpperCAmelCase_ = self.prepare_config_and_inputs() UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = config_and_inputs UpperCAmelCase_ = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : Dict = (CvtModel, CvtForImageClassification) if is_torch_available() else () a__ : str = ( {"""feature-extraction""": CvtModel, """image-classification""": CvtForImageClassification} if is_torch_available() else {} ) a__ : Tuple = False a__ : Tuple = False a__ : Optional[Any] = False a__ : str = False a__ : List[str] = False def _lowercase (self : Optional[int] ): UpperCAmelCase_ = CvtModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__a , has_text_modality=__a , hidden_size=37 ) def _lowercase (self : Any ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def _lowercase (self : Union[str, Any] ): return @unittest.skip(reason="Cvt does not output attentions" ) def _lowercase (self : List[str] ): pass @unittest.skip(reason="Cvt does not use inputs_embeds" ) def _lowercase (self : Dict ): pass @unittest.skip(reason="Cvt does not support input and output embeddings" ) def _lowercase (self : List[Any] ): pass def _lowercase (self : List[Any] ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__a ) UpperCAmelCase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) def _lowercase (self : Dict ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def _lowercase (self : Optional[int] ): def check_hidden_states_output(__a : Any , __a : Union[str, Any] , __a : Tuple ): UpperCAmelCase_ = model_class(__a ) model.to(__a ) model.eval() with torch.no_grad(): UpperCAmelCase_ = model(**self._prepare_for_class(__a , __a ) ) UpperCAmelCase_ = outputs.hidden_states UpperCAmelCase_ = len(self.model_tester.depth ) self.assertEqual(len(__a ) , __a ) # verify the first hidden states (first block) self.assertListEqual( list(hidden_states[0].shape[-3:] ) , [ self.model_tester.embed_dim[0], self.model_tester.image_size // 4, self.model_tester.image_size // 4, ] , ) UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = True check_hidden_states_output(__a , __a , __a ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] UpperCAmelCase_ = True check_hidden_states_output(__a , __a , __a ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__a ) @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _lowercase (self : Optional[Any] ): pass @slow def _lowercase (self : Optional[int] ): for model_name in CVT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ = CvtModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def lowerCAmelCase_ ( ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class __A ( unittest.TestCase ): @cached_property def _lowercase (self : Tuple ): return AutoImageProcessor.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) @slow def _lowercase (self : List[Any] ): UpperCAmelCase_ = CvtForImageClassification.from_pretrained(CVT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(__a ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(images=__a , return_tensors="pt" ).to(__a ) # forward pass with torch.no_grad(): UpperCAmelCase_ = model(**__a ) # verify the logits UpperCAmelCase_ = torch.Size((1, 1000) ) self.assertEqual(outputs.logits.shape , __a ) UpperCAmelCase_ = torch.tensor([0.92_85, 0.90_15, -0.31_50] ).to(__a ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __a , atol=1E-4 ) )
78
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
1
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional from ... import PreTrainedTokenizer, TensorType, is_torch_available from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfigWithPast from ...utils import logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Tuple ={ 'EleutherAI/gpt-neo-1.3B': 'https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json', # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo } class __A ( UpperCamelCase__ ): a__ : str = """gpt_neo""" a__ : Union[str, Any] = ["""past_key_values"""] a__ : List[str] = {"""num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__(self : str , __a : List[Any]=50257 , __a : Tuple=2048 , __a : Optional[Any]=2048 , __a : Dict=24 , __a : List[Any]=[[["global", "local"], 12]] , __a : List[Any]=16 , __a : Optional[int]=None , __a : Tuple=256 , __a : Optional[Any]="gelu_new" , __a : List[str]=0.0 , __a : int=0.0 , __a : Any=0.0 , __a : List[Any]=0.1 , __a : Optional[int]=1E-5 , __a : List[Any]=0.02 , __a : str=True , __a : int=50256 , __a : int=50256 , **__a : Dict , ): UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_layers UpperCAmelCase_ = num_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = window_size UpperCAmelCase_ = activation_function UpperCAmelCase_ = resid_dropout UpperCAmelCase_ = embed_dropout UpperCAmelCase_ = attention_dropout UpperCAmelCase_ = classifier_dropout UpperCAmelCase_ = layer_norm_epsilon UpperCAmelCase_ = initializer_range UpperCAmelCase_ = use_cache UpperCAmelCase_ = bos_token_id UpperCAmelCase_ = eos_token_id UpperCAmelCase_ = attention_types UpperCAmelCase_ = self.expand_attention_types_params(__a ) if len(self.attention_layers ) != self.num_layers: raise ValueError( "Configuration for convolutional module is incorrect. " "It is required that `len(config.attention_layers)` == `config.num_layers` " f"""but is `len(config.attention_layers) = {len(self.attention_layers )}`, """ f"""`config.num_layers = {self.num_layers}`. """ "`config.attention_layers` is prepared using `config.attention_types`. " "Please verify the value of `config.attention_types` argument." ) super().__init__(bos_token_id=__a , eos_token_id=__a , **__a ) @staticmethod def _lowercase (__a : int ): UpperCAmelCase_ = [] for item in attention_types: for _ in range(item[1] ): attentions.extend(item[0] ) return attentions def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str , snake_case_ : Union[str, Any] , snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' import torch UpperCAmelCase_ = input.size() UpperCAmelCase_ = len(snake_case_ ) UpperCAmelCase_ = shape[dimension] UpperCAmelCase_ = torch.arange(0 , snake_case_ , snake_case_ ) UpperCAmelCase_ = torch.div(sizedim - size , snake_case_ , rounding_mode="floor" ) + 1 UpperCAmelCase_ = torch.arange(snake_case_ ) + low_indices[:min_length][:, None] UpperCAmelCase_ = [slice(snake_case_ )] * rank UpperCAmelCase_ = indices UpperCAmelCase_ = input[s] UpperCAmelCase_ = list(range(0 , rank + 1 ) ) perm.append(perm.pop(dimension + 1 ) ) return sliced.permute(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : str ) -> str: '''simple docstring''' import torch UpperCAmelCase_ = torch.arange(1 , snake_case_ ) UpperCAmelCase_ = torch.remainder(snake_case_ , snake_case_ ) UpperCAmelCase_ = remainders == 0 UpperCAmelCase_ = candidates[divisor_indices] UpperCAmelCase_ = torch.max(snake_case_ ) return largest_divisor, torch.div(snake_case_ , snake_case_ , rounding_mode="floor" ) class __A ( UpperCamelCase__ ): @property def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = OrderedDict({"input_ids": {0: "batch", 1: "sequence"}} ) if self.use_past: self.fill_with_past_key_values_(__a , direction="inputs" ) UpperCAmelCase_ = {0: "batch", 1: "past_sequence + sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return common_inputs @property def _lowercase (self : Tuple ): return self._config.num_heads def _lowercase (self : int , __a : PreTrainedTokenizer , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , ): UpperCAmelCase_ = super(__a , self ).generate_dummy_inputs( __a , batch_size=__a , seq_length=__a , is_pair=__a , framework=__a ) # We need to order the input in the way they appears in the forward() UpperCAmelCase_ = OrderedDict({"input_ids": common_inputs["input_ids"]} ) # Need to add the past_keys if self.use_past: if not is_torch_available(): raise ValueError("Cannot generate dummy past_keys inputs without PyTorch installed." ) else: import torch UpperCAmelCase_ , UpperCAmelCase_ = common_inputs["input_ids"].shape # Not using the same length for past_key_values UpperCAmelCase_ = seqlen + 2 UpperCAmelCase_ = ( batch, self.num_attention_heads, past_key_values_length, self._config.hidden_size // self.num_attention_heads, ) UpperCAmelCase_ = [ (torch.zeros(__a ), torch.zeros(__a )) for _ in range(self.num_layers ) ] UpperCAmelCase_ = common_inputs["attention_mask"] if self.use_past: UpperCAmelCase_ = ordered_inputs["attention_mask"].dtype UpperCAmelCase_ = torch.cat( [ordered_inputs["attention_mask"], torch.ones(__a , __a , dtype=__a )] , dim=1 ) return ordered_inputs @property def _lowercase (self : Dict ): return 13
78
'''simple docstring''' import requests def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None: '''simple docstring''' UpperCAmelCase_ = {"Content-Type": "application/json"} UpperCAmelCase_ = requests.post(snake_case_ , json={"text": message_body} , headers=snake_case_ ) if response.status_code != 2_00: UpperCAmelCase_ = ( "Request to slack returned an error " f"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(snake_case_ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
78
1
'''simple docstring''' import unittest import numpy as np import torch from diffusers import KarrasVePipeline, KarrasVeScheduler, UNetaDModel from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device enable_full_determinism() class __A ( unittest.TestCase ): @property def _lowercase (self : Dict ): torch.manual_seed(0 ) UpperCAmelCase_ = UNetaDModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=3 , out_channels=3 , down_block_types=("DownBlock2D", "AttnDownBlock2D") , up_block_types=("AttnUpBlock2D", "UpBlock2D") , ) return model def _lowercase (self : Any ): UpperCAmelCase_ = self.dummy_uncond_unet UpperCAmelCase_ = KarrasVeScheduler() UpperCAmelCase_ = KarrasVePipeline(unet=__a , scheduler=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = torch.manual_seed(0 ) UpperCAmelCase_ = pipe(num_inference_steps=2 , generator=__a , output_type="numpy" ).images UpperCAmelCase_ = torch.manual_seed(0 ) UpperCAmelCase_ = pipe(num_inference_steps=2 , generator=__a , output_type="numpy" , return_dict=__a )[0] UpperCAmelCase_ = image[0, -3:, -3:, -1] UpperCAmelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) UpperCAmelCase_ = np.array([0.0, 1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 @slow @require_torch class __A ( unittest.TestCase ): def _lowercase (self : int ): UpperCAmelCase_ = "google/ncsnpp-celebahq-256" UpperCAmelCase_ = UNetaDModel.from_pretrained(__a ) UpperCAmelCase_ = KarrasVeScheduler() UpperCAmelCase_ = KarrasVePipeline(unet=__a , scheduler=__a ) pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = torch.manual_seed(0 ) UpperCAmelCase_ = pipe(num_inference_steps=20 , generator=__a , output_type="numpy" ).images UpperCAmelCase_ = image[0, -3:, -3:, -1] assert image.shape == (1, 256, 256, 3) UpperCAmelCase_ = np.array([0.5_78, 0.58_11, 0.59_24, 0.58_09, 0.5_87, 0.58_86, 0.58_61, 0.58_02, 0.5_86] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2
78
'''simple docstring''' from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : CLIPSegForImageSegmentation , __a : CLIPSegProcessor , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = 1 UpperCAmelCase_ = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = True UpperCAmelCase_ = FrozenDict(__a ) if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _lowercase (self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _lowercase (self : int ): self.enable_attention_slicing(__a ) def _lowercase (self : Optional[Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : Optional[int] ): if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_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() def __call__(self : Dict , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, PIL.Image.Image] , __a : str , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): UpperCAmelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) UpperCAmelCase_ = self.segmentation_model(**__a ) UpperCAmelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCAmelCase_ = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCAmelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
78
1
'''simple docstring''' import unittest from transformers import SPIECE_UNDERLINE, ReformerTokenizer, ReformerTokenizerFast 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_: List[str] =get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class __A ( UpperCamelCase__ , unittest.TestCase ): a__ : str = ReformerTokenizer a__ : Optional[Any] = ReformerTokenizerFast a__ : Any = True a__ : Union[str, Any] = False a__ : int = True def _lowercase (self : List[str] ): super().setUp() UpperCAmelCase_ = ReformerTokenizer(__a , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase (self : int ): UpperCAmelCase_ = "<s>" UpperCAmelCase_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "<unk>" ) self.assertEqual(vocab_keys[1] , "<s>" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__a ) , 1000 ) def _lowercase (self : str ): self.assertEqual(self.get_tokenizer().vocab_size , 1000 ) def _lowercase (self : Dict ): if not self.test_rust_tokenizer: return UpperCAmelCase_ = self.get_tokenizer() UpperCAmelCase_ = self.get_rust_tokenizer() UpperCAmelCase_ = "I was born in 92000, and this is falsé." UpperCAmelCase_ = tokenizer.tokenize(__a ) UpperCAmelCase_ = rust_tokenizer.tokenize(__a ) self.assertListEqual(__a , __a ) UpperCAmelCase_ = tokenizer.encode(__a , add_special_tokens=__a ) UpperCAmelCase_ = rust_tokenizer.encode(__a , add_special_tokens=__a ) self.assertListEqual(__a , __a ) UpperCAmelCase_ = self.get_rust_tokenizer() UpperCAmelCase_ = tokenizer.encode(__a ) UpperCAmelCase_ = rust_tokenizer.encode(__a ) self.assertListEqual(__a , __a ) def _lowercase (self : Union[str, Any] , __a : List[str]=15 ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f"""{tokenizer.__class__.__name__} ({pretrained_name})""" ): UpperCAmelCase_ = self.rust_tokenizer_class.from_pretrained(__a , **__a ) # Simple input UpperCAmelCase_ = "This is a simple input" UpperCAmelCase_ = ["This is a simple input 1", "This is a simple input 2"] UpperCAmelCase_ = ("This is a simple input", "This is a pair") UpperCAmelCase_ = [ ("This is a simple input 1", "This is a simple input 2"), ("This is a simple pair 1", "This is a simple pair 2"), ] # Simple input tests self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding="max_length" ) # Simple input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding="max_length" ) # Simple input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding="max_length" , ) # Pair input self.assertRaises(__a , tokenizer_r.encode , __a , max_length=__a , padding="max_length" ) # Pair input self.assertRaises(__a , tokenizer_r.encode_plus , __a , max_length=__a , padding="max_length" ) # Pair input self.assertRaises( __a , tokenizer_r.batch_encode_plus , __a , max_length=__a , padding="max_length" , ) def _lowercase (self : Optional[Any] ): pass def _lowercase (self : Optional[int] ): UpperCAmelCase_ = ReformerTokenizer(__a , keep_accents=__a ) UpperCAmelCase_ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [285, 46, 10, 170, 382] , ) UpperCAmelCase_ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) UpperCAmelCase_ = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [8, 21, 84, 55, 24, 19, 7, 0, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [ 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 _lowercase (self : Optional[int] ): return ReformerTokenizer.from_pretrained("google/reformer-crime-and-punishment" ) @slow def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = "Hello World!" UpperCAmelCase_ = [126, 32, 262, 152, 38, 72, 287] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @slow def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = ( "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" ) UpperCAmelCase_ = [ 108, 265, 24, 111, 4, 258, 156, 35, 28, 275, 3, 259, 297, 260, 84, 4, 35, 110, 44, 8, 259, 91, 268, 21, 11, 209, 274, 109, 266, 277, 117, 86, 93, 315, 258, 278, 258, 277, 258, 0, 258, 288, 258, 319, 258, 0, 258, 0, 258, 0, 258, 0, 258, 287, 258, 315, 258, 289, 258, 278, 99, 269, 266, 262, 8, 259, 241, 4, 217, 230, 268, 266, 55, 168, 106, 75, 193, 266, 223, 27, 49, 26, 282, 25, 264, 299, 19, 26, 0, 258, 277, 117, 86, 93, 176, 183, 270, 11, 262, 42, 61, 265, ] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @require_torch @slow def _lowercase (self : Tuple ): import torch from transformers import ReformerConfig, ReformerModel # Build sequence UpperCAmelCase_ = list(self.big_tokenizer.get_vocab().keys() )[:10] UpperCAmelCase_ = " ".join(__a ) UpperCAmelCase_ = self.big_tokenizer.encode_plus(__a , return_tensors="pt" ) UpperCAmelCase_ = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors="pt" ) UpperCAmelCase_ = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) UpperCAmelCase_ = encoded_sequence["input_ids"].shape UpperCAmelCase_ = ReformerModel(__a ) # Reformer has config.vocab_size == tokenizer.vocab_size == len(tokenizer) - 1 = 320; len(tokenizer) is 321 (including a pad token with id 320) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__a ) model(**__a ) @slow def _lowercase (self : Dict ): # fmt: off UpperCAmelCase_ = {"input_ids": [[108, 265, 24, 111, 4, 258, 156, 7, 51, 279, 58, 7, 76, 25, 69, 278], [140, 243, 264, 134, 17, 267, 77, 263, 22, 262, 297, 258, 304, 177, 279, 266, 14, 89, 13, 35, 261, 299, 272, 137, 275, 278]], "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]]} # noqa: E501 # fmt: on # This tokenizer does not know some characters like ")". # That is the reason why we use very simple texts here. # Also see https://github.com/huggingface/transformers/pull/11737#issuecomment-850769064 UpperCAmelCase_ = [ "This is a very simple sentence.", "The quick brown fox jumps over the lazy dog.", ] self.tokenizer_integration_test_util( expected_encoding=__a , model_name="google/reformer-crime-and-punishment" , revision="0e6c3decb8211d49bf881013425dc8b0448b3f5a" , padding=__a , sequences=__a , )
78
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' if number < 0: raise ValueError("number must not be negative" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' import sys from collections import defaultdict class __A : def __init__(self : str ): UpperCAmelCase_ = [] def _lowercase (self : Tuple , __a : Tuple ): return self.node_position[vertex] def _lowercase (self : Any , __a : List[Any] , __a : Optional[Any] ): UpperCAmelCase_ = pos def _lowercase (self : Dict , __a : Union[str, Any] , __a : str , __a : str , __a : Dict ): if start > size // 2 - 1: return else: if 2 * start + 2 >= size: UpperCAmelCase_ = 2 * start + 1 else: if heap[2 * start + 1] < heap[2 * start + 2]: UpperCAmelCase_ = 2 * start + 1 else: UpperCAmelCase_ = 2 * start + 2 if heap[smallest_child] < heap[start]: UpperCAmelCase_ , UpperCAmelCase_ = heap[smallest_child], positions[smallest_child] UpperCAmelCase_ , UpperCAmelCase_ = ( heap[start], positions[start], ) UpperCAmelCase_ , UpperCAmelCase_ = temp, tempa UpperCAmelCase_ = self.get_position(positions[smallest_child] ) self.set_position( positions[smallest_child] , self.get_position(positions[start] ) ) self.set_position(positions[start] , __a ) self.top_to_bottom(__a , __a , __a , __a ) def _lowercase (self : int , __a : Dict , __a : Tuple , __a : str , __a : int ): UpperCAmelCase_ = position[index] while index != 0: UpperCAmelCase_ = int((index - 2) / 2 ) if index % 2 == 0 else int((index - 1) / 2 ) if val < heap[parent]: UpperCAmelCase_ = heap[parent] UpperCAmelCase_ = position[parent] self.set_position(position[parent] , __a ) else: UpperCAmelCase_ = val UpperCAmelCase_ = temp self.set_position(__a , __a ) break UpperCAmelCase_ = parent else: UpperCAmelCase_ = val UpperCAmelCase_ = temp self.set_position(__a , 0 ) def _lowercase (self : Any , __a : Optional[Any] , __a : Any ): UpperCAmelCase_ = len(__a ) // 2 - 1 for i in range(__a , -1 , -1 ): self.top_to_bottom(__a , __a , len(__a ) , __a ) def _lowercase (self : Union[str, Any] , __a : Optional[Any] , __a : Union[str, Any] ): UpperCAmelCase_ = positions[0] UpperCAmelCase_ = sys.maxsize self.top_to_bottom(__a , 0 , len(__a ) , __a ) return temp def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = Heap() UpperCAmelCase_ = [0] * len(snake_case_ ) UpperCAmelCase_ = [-1] * len(snake_case_ ) # Neighboring Tree Vertex of selected vertex # Minimum Distance of explored vertex with neighboring vertex of partial tree # formed in graph UpperCAmelCase_ = [] # Heap of Distance of vertices from their neighboring vertex UpperCAmelCase_ = [] for vertex in range(len(snake_case_ ) ): distance_tv.append(sys.maxsize ) positions.append(snake_case_ ) heap.node_position.append(snake_case_ ) UpperCAmelCase_ = [] UpperCAmelCase_ = 1 UpperCAmelCase_ = sys.maxsize for neighbor, distance in adjacency_list[0]: UpperCAmelCase_ = 0 UpperCAmelCase_ = distance heap.heapify(snake_case_ , snake_case_ ) for _ in range(1 , len(snake_case_ ) ): UpperCAmelCase_ = heap.delete_minimum(snake_case_ , snake_case_ ) if visited[vertex] == 0: tree_edges.append((nbr_tv[vertex], vertex) ) UpperCAmelCase_ = 1 for neighbor, distance in adjacency_list[vertex]: if ( visited[neighbor] == 0 and distance < distance_tv[heap.get_position(snake_case_ )] ): UpperCAmelCase_ = distance heap.bottom_to_top( snake_case_ , heap.get_position(snake_case_ ) , snake_case_ , snake_case_ ) UpperCAmelCase_ = vertex return tree_edges if __name__ == "__main__": # pragma: no cover # < --------- Prims Algorithm --------- > SCREAMING_SNAKE_CASE_: List[str] =int(input('Enter number of edges: ').strip()) SCREAMING_SNAKE_CASE_: Tuple =defaultdict(list) for _ in range(edges_number): SCREAMING_SNAKE_CASE_: str =[int(x) for x in input().strip().split()] adjacency_list[edge[0]].append([edge[1], edge[2]]) adjacency_list[edge[1]].append([edge[0], edge[2]]) print(prisms_algorithm(adjacency_list))
78
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __A : a__ : int a__ : TreeNode | None = None a__ : TreeNode | None = None SCREAMING_SNAKE_CASE_: Union[str, Any] =namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase_ ( snake_case_ : TreeNode | None ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case_ ) != count_coins(snake_case_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(snake_case_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.left ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.right ) UpperCAmelCase_ = 1 - left_distrib_excess UpperCAmelCase_ = 1 - right_distrib_excess UpperCAmelCase_ = ( left_distrib_moves + right_distrib_moves + abs(snake_case_ ) + abs(snake_case_ ) ) UpperCAmelCase_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case_ , snake_case_ ) return get_distrib(snake_case_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' from .constants import ( MODEL_NAME, OPTIMIZER_NAME, RNG_STATE_NAME, SAFE_WEIGHTS_INDEX_NAME, SAFE_WEIGHTS_NAME, SCALER_NAME, SCHEDULER_NAME, TORCH_LAUNCH_PARAMS, WEIGHTS_INDEX_NAME, WEIGHTS_NAME, ) from .dataclasses import ( BnbQuantizationConfig, ComputeEnvironment, CustomDtype, DeepSpeedPlugin, DistributedDataParallelKwargs, DistributedType, DynamoBackend, FPaRecipeKwargs, FullyShardedDataParallelPlugin, GradientAccumulationPlugin, GradScalerKwargs, InitProcessGroupKwargs, KwargsHandler, LoggerType, MegatronLMPlugin, PrecisionType, ProjectConfiguration, RNGType, SageMakerDistributedType, TensorInformation, TorchDynamoPlugin, ) from .environment import get_int_from_env, parse_choice_from_env, parse_flag_from_env from .imports import ( get_ccl_version, is_abit_bnb_available, is_abit_bnb_available, is_aim_available, is_bfaa_available, is_bnb_available, is_botoa_available, is_ccl_available, is_comet_ml_available, is_datasets_available, is_deepspeed_available, is_fpa_available, is_ipex_available, is_megatron_lm_available, is_mlflow_available, is_mps_available, is_npu_available, is_rich_available, is_safetensors_available, is_sagemaker_available, is_tensorboard_available, is_tpu_available, is_transformers_available, is_wandb_available, is_xpu_available, ) from .modeling import ( check_device_map, check_tied_parameters_in_config, check_tied_parameters_on_same_device, compute_module_sizes, convert_file_size_to_int, dtype_byte_size, find_tied_parameters, get_balanced_memory, get_max_layer_size, get_max_memory, get_mixed_precision_context_manager, id_tensor_storage, infer_auto_device_map, load_checkpoint_in_model, load_offloaded_weights, load_state_dict, named_module_tensors, retie_parameters, set_module_tensor_to_device, shard_checkpoint, ) from .offload import ( OffloadedWeightsLoader, PrefixedDataset, extract_submodules_state_dict, load_offloaded_weight, offload_state_dict, offload_weight, save_offload_index, ) from .operations import ( broadcast, broadcast_object_list, concatenate, convert_outputs_to_fpaa, convert_to_fpaa, find_batch_size, find_device, gather, gather_object, get_data_structure, honor_type, initialize_tensors, is_namedtuple, is_tensor_information, is_torch_tensor, listify, pad_across_processes, recursively_apply, reduce, send_to_device, slice_tensors, ) from .versions import compare_versions, is_torch_version if is_deepspeed_available(): from .deepspeed import ( DeepSpeedEngineWrapper, DeepSpeedOptimizerWrapper, DeepSpeedSchedulerWrapper, DummyOptim, DummyScheduler, HfDeepSpeedConfig, ) from .bnb import has_abit_bnb_layers, load_and_quantize_model from .fsdp_utils import load_fsdp_model, load_fsdp_optimizer, save_fsdp_model, save_fsdp_optimizer from .launch import ( PrepareForLaunch, _filter_args, prepare_deepspeed_cmd_env, prepare_multi_gpu_env, prepare_sagemager_args_inputs, prepare_simple_launcher_cmd_env, prepare_tpu, ) from .megatron_lm import ( AbstractTrainStep, BertTrainStep, GPTTrainStep, MegatronEngine, MegatronLMDummyDataLoader, MegatronLMDummyScheduler, MegatronLMOptimizerWrapper, MegatronLMSchedulerWrapper, TaTrainStep, avg_losses_across_data_parallel_group, gather_across_data_parallel_groups, ) from .megatron_lm import initialize as megatron_lm_initialize from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader from .megatron_lm import prepare_model as megatron_lm_prepare_model from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler from .memory import find_executable_batch_size, release_memory from .other import ( extract_model_from_parallel, get_pretty_name, is_port_in_use, merge_dicts, patch_environment, save, wait_for_everyone, write_basic_config, ) from .random import set_seed, synchronize_rng_state, synchronize_rng_states from .torch_xla import install_xla from .tqdm import tqdm from .transformer_engine import convert_model, has_transformer_engine_layers
78
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE_: int =logging.getLogger() def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCAmelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> str: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = os.path.join(snake_case_ , "all_results.json" ) if os.path.exists(snake_case_ ): with open(snake_case_ , "r" ) as f: UpperCAmelCase_ = json.load(snake_case_ ) else: raise ValueError(f"""can't find {path}""" ) return results def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = torch.cuda.is_available() and torch_device == "cuda" return is_using_cuda and is_apex_available() SCREAMING_SNAKE_CASE_: Any =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __A ( UpperCamelCase__ ): @classmethod def _lowercase (cls : Any ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = os.path.join(cls.tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) UpperCAmelCase_ = ["accelerate", "launch", "--config_file", cls.configPath] @classmethod def _lowercase (cls : int ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "glue_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "clm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "mlm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCAmelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertLess(result["train_loss"] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "ner_no_trainer" ) ) ) @unittest.skip(reason="Fix me @muellerzr" ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : int ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["eval_f1"] , 28 ) self.assertGreaterEqual(result["eval_exact"] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "qa_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : str ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , "swag_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_rouge1"] , 10 ) self.assertGreaterEqual(result["eval_rouge2"] , 2 ) self.assertGreaterEqual(result["eval_rougeL"] , 7 ) self.assertGreaterEqual(result["eval_rougeLsum"] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "summarization_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : List[str] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_bleu"] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "translation_no_trainer" ) ) ) @slow def _lowercase (self : Dict ): UpperCAmelCase_ = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_overall_accuracy"] , 0.10 ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Any ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result["eval_accuracy"] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , "step_1" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "image_classification_no_trainer" ) ) )
78
1
'''simple docstring''' import contextlib import importlib import io import unittest import transformers # Try to import everything from transformers to ensure every object can be loaded. from transformers import * # noqa F406 from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_flax, require_tf, require_torch from transformers.utils import ContextManagers, find_labels, is_flax_available, is_tf_available, is_torch_available if is_torch_available(): from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification if is_tf_available(): from transformers import TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification if is_flax_available(): from transformers import FlaxBertForPreTraining, FlaxBertForQuestionAnswering, FlaxBertForSequenceClassification SCREAMING_SNAKE_CASE_: Any =DUMMY_UNKNOWN_IDENTIFIER # An actual model hosted on huggingface.co SCREAMING_SNAKE_CASE_: Dict ='main' # Default branch name SCREAMING_SNAKE_CASE_: Optional[int] ='f2c752cfc5c0ab6f4bdec59acea69eefbee381c2' # One particular commit (not the top of `main`) SCREAMING_SNAKE_CASE_: Optional[Any] ='aaaaaaa' # This commit does not exist, so we should 404. SCREAMING_SNAKE_CASE_: List[str] ='d9e9f15bc825e4b2c9249e9578f884bbcb5e3684' # Sha-1 of config.json on the top of `main`, for checking purposes SCREAMING_SNAKE_CASE_: Dict ='4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3' @contextlib.contextmanager def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' print("Welcome!" ) yield print("Bye!" ) @contextlib.contextmanager def lowerCAmelCase_ ( ) -> Tuple: '''simple docstring''' print("Bonjour!" ) yield print("Au revoir!" ) class __A ( unittest.TestCase ): def _lowercase (self : Tuple ): # If the spec is missing, importlib would not be able to import the module dynamically. assert transformers.__spec__ is not None assert importlib.util.find_spec("transformers" ) is not None class __A ( unittest.TestCase ): @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _lowercase (self : str , __a : List[Any] ): with ContextManagers([] ): print("Transformers are awesome!" ) # The print statement adds a new line at the end of the output self.assertEqual(mock_stdout.getvalue() , "Transformers are awesome!\n" ) @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _lowercase (self : Optional[Any] , __a : List[Any] ): with ContextManagers([context_en()] ): print("Transformers are awesome!" ) # The output should be wrapped with an English welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Welcome!\nTransformers are awesome!\nBye!\n" ) @unittest.mock.patch("sys.stdout" , new_callable=io.StringIO ) def _lowercase (self : Dict , __a : Union[str, Any] ): with ContextManagers([context_fr(), context_en()] ): print("Transformers are awesome!" ) # The output should be wrapped with an English and French welcome and goodbye self.assertEqual(mock_stdout.getvalue() , "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n" ) @require_torch def _lowercase (self : int ): self.assertEqual(find_labels(__a ) , ["labels"] ) self.assertEqual(find_labels(__a ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(__a ) , ["start_positions", "end_positions"] ) class __A ( UpperCamelCase__ ): pass self.assertEqual(find_labels(__a ) , ["labels"] ) @require_tf def _lowercase (self : Tuple ): self.assertEqual(find_labels(__a ) , ["labels"] ) self.assertEqual(find_labels(__a ) , ["labels", "next_sentence_label"] ) self.assertEqual(find_labels(__a ) , ["start_positions", "end_positions"] ) class __A ( UpperCamelCase__ ): pass self.assertEqual(find_labels(__a ) , ["labels"] ) @require_flax def _lowercase (self : Tuple ): # Flax models don't have labels self.assertEqual(find_labels(__a ) , [] ) self.assertEqual(find_labels(__a ) , [] ) self.assertEqual(find_labels(__a ) , [] ) class __A ( UpperCamelCase__ ): pass self.assertEqual(find_labels(__a ) , [] )
78
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP SCREAMING_SNAKE_CASE_: Any =False try: SCREAMING_SNAKE_CASE_: Optional[Any] =_is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class __A : def __init__(self : int , __a : str = None , __a : list = [] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = choices UpperCAmelCase_ = prompt if sys.platform == "win32": UpperCAmelCase_ = "*" else: UpperCAmelCase_ = "➔ " def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a ) else: forceWrite(self.choices[index] , __a ) def _lowercase (self : Any , __a : int ): if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def _lowercase (self : Optional[Any] , __a : Direction , __a : int = 1 ): UpperCAmelCase_ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a ) move_cursor(__a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def _lowercase (self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def _lowercase (self : Any ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def _lowercase (self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def _lowercase (self : str ): move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a )] for number in range(10 )] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = int(chr(self.current_selection ) ) UpperCAmelCase_ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __a ) else: return else: return def _lowercase (self : Optional[Any] , __a : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase_ = default_choice for i in range(len(self.choices ) ): self.print_choice(__a ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase_ = int(builtins.input() ) except ValueError: UpperCAmelCase_ = default_choice else: UpperCAmelCase_ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__a , "\n" ) return choice
78
1
'''simple docstring''' # Copyright 2021 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os from accelerate.utils import ComputeEnvironment from .cluster import get_cluster_input from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 from .sagemaker import get_sagemaker_input SCREAMING_SNAKE_CASE_: int ='Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine' def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = _ask_options( "In which compute environment are you running?" , ["This machine", "AWS (Amazon SageMaker)"] , _convert_compute_environment , ) if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: UpperCAmelCase_ = get_sagemaker_input() else: UpperCAmelCase_ = get_cluster_input() return config def lowerCAmelCase_ ( snake_case_ : Union[str, Any]=None ) -> Optional[int]: '''simple docstring''' if subparsers is not None: UpperCAmelCase_ = subparsers.add_parser("config" , description=snake_case_ ) else: UpperCAmelCase_ = argparse.ArgumentParser("Accelerate config command" , description=snake_case_ ) parser.add_argument( "--config_file" , default=snake_case_ , help=( "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " "with 'huggingface'." ) , ) if subparsers is not None: parser.set_defaults(func=snake_case_ ) return parser def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> Dict: '''simple docstring''' UpperCAmelCase_ = get_user_input() if args.config_file is not None: UpperCAmelCase_ = args.config_file else: if not os.path.isdir(snake_case_ ): os.makedirs(snake_case_ ) UpperCAmelCase_ = default_yaml_config_file if config_file.endswith(".json" ): config.to_json_file(snake_case_ ) else: config.to_yaml_file(snake_case_ ) print(f"""accelerate configuration saved at {config_file}""" ) def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' UpperCAmelCase_ = config_command_parser() UpperCAmelCase_ = parser.parse_args() config_command(snake_case_ ) if __name__ == "__main__": main()
78
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_: Optional[int] ={'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['BeitFeatureExtractor'] SCREAMING_SNAKE_CASE_: int =['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: int =[ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
1
'''simple docstring''' import json import os from pathlib import Path from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple, Union import sentencepiece from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE_: Any =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Tuple ='▁' SCREAMING_SNAKE_CASE_: List[Any] ={ 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', 'tokenizer_config_file': 'tokenizer_config.json', } SCREAMING_SNAKE_CASE_: Any ={ 'vocab_file': { 'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json', 'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json', }, 'spm_file': { 'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model', 'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model', }, 'tokenizer_config_file': { 'facebook/m2m100_418M': 'https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json', 'facebook/m2m100_1.2B': 'https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json', }, } SCREAMING_SNAKE_CASE_: int ={ 'facebook/m2m100_418M': 10_24, } # fmt: off SCREAMING_SNAKE_CASE_: Union[str, Any] ={ 'm2m100': ['af', 'am', 'ar', 'ast', 'az', 'ba', 'be', 'bg', 'bn', 'br', 'bs', 'ca', 'ceb', 'cs', 'cy', 'da', 'de', 'el', 'en', 'es', 'et', 'fa', 'ff', 'fi', 'fr', 'fy', 'ga', 'gd', 'gl', 'gu', 'ha', 'he', 'hi', 'hr', 'ht', 'hu', 'hy', 'id', 'ig', 'ilo', 'is', 'it', 'ja', 'jv', 'ka', 'kk', 'km', 'kn', 'ko', 'lb', 'lg', 'ln', 'lo', 'lt', 'lv', 'mg', 'mk', 'ml', 'mn', 'mr', 'ms', 'my', 'ne', 'nl', 'no', 'ns', 'oc', 'or', 'pa', 'pl', 'ps', 'pt', 'ro', 'ru', 'sd', 'si', 'sk', 'sl', 'so', 'sq', 'sr', 'ss', 'su', 'sv', 'sw', 'ta', 'th', 'tl', 'tn', 'tr', 'uk', 'ur', 'uz', 'vi', 'wo', 'xh', 'yi', 'yo', 'zh', 'zu'], 'wmt21': ['en', 'ha', 'is', 'ja', 'cs', 'ru', 'zh', 'de'] } class __A ( UpperCamelCase__ ): a__ : Any = VOCAB_FILES_NAMES a__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : str = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[Any] = ["""input_ids""", """attention_mask"""] a__ : List[int] = [] a__ : List[int] = [] def __init__(self : List[str] , __a : List[str] , __a : Any , __a : Optional[int]=None , __a : Optional[int]=None , __a : Dict="<s>" , __a : Optional[Any]="</s>" , __a : List[str]="</s>" , __a : Union[str, Any]="<pad>" , __a : str="<unk>" , __a : str="m2m100" , __a : Optional[Dict[str, Any]] = None , __a : int=8 , **__a : int , ): UpperCAmelCase_ = {} if sp_model_kwargs is None else sp_model_kwargs UpperCAmelCase_ = language_codes UpperCAmelCase_ = FAIRSEQ_LANGUAGE_CODES[language_codes] UpperCAmelCase_ = {lang_code: f"""__{lang_code}__""" for lang_code in fairseq_language_code} UpperCAmelCase_ = kwargs.get("additional_special_tokens" , [] ) kwargs["additional_special_tokens"] += [ self.get_lang_token(__a ) for lang_code in fairseq_language_code if self.get_lang_token(__a ) not in kwargs["additional_special_tokens"] ] super().__init__( src_lang=__a , tgt_lang=__a , bos_token=__a , eos_token=__a , sep_token=__a , unk_token=__a , pad_token=__a , language_codes=__a , sp_model_kwargs=self.sp_model_kwargs , num_madeup_words=__a , **__a , ) UpperCAmelCase_ = vocab_file UpperCAmelCase_ = load_json(__a ) UpperCAmelCase_ = {v: k for k, v in self.encoder.items()} UpperCAmelCase_ = spm_file UpperCAmelCase_ = load_spm(__a , self.sp_model_kwargs ) UpperCAmelCase_ = len(self.encoder ) UpperCAmelCase_ = { self.get_lang_token(__a ): self.encoder_size + i for i, lang_code in enumerate(__a ) } UpperCAmelCase_ = {lang_code: self.encoder_size + i for i, lang_code in enumerate(__a )} UpperCAmelCase_ = {v: k for k, v in self.lang_token_to_id.items()} UpperCAmelCase_ = src_lang if src_lang is not None else "en" UpperCAmelCase_ = tgt_lang UpperCAmelCase_ = self.get_lang_id(self._src_lang ) self.set_src_lang_special_tokens(self._src_lang ) UpperCAmelCase_ = num_madeup_words @property def _lowercase (self : List[str] ): return len(self.encoder ) + len(self.lang_token_to_id ) @property def _lowercase (self : str ): return self._src_lang @src_lang.setter def _lowercase (self : Optional[int] , __a : str ): UpperCAmelCase_ = new_src_lang self.set_src_lang_special_tokens(self._src_lang ) def _lowercase (self : List[Any] , __a : str ): return self.sp_model.encode(__a , out_type=__a ) def _lowercase (self : str , __a : str ): if token in self.lang_token_to_id: return self.lang_token_to_id[token] return self.encoder.get(__a , self.encoder[self.unk_token] ) def _lowercase (self : Union[str, Any] , __a : int ): if index in self.id_to_lang_token: return self.id_to_lang_token[index] return self.decoder.get(__a , self.unk_token ) def _lowercase (self : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = [] UpperCAmelCase_ = "" 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 UpperCAmelCase_ = [] else: current_sub_tokens.append(__a ) out_string += self.sp_model.decode(__a ) return out_string.strip() def _lowercase (self : List[str] , __a : List[int] , __a : Optional[List[int]] = None , __a : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) UpperCAmelCase_ = [1] * len(self.prefix_tokens ) UpperCAmelCase_ = [1] * len(self.suffix_tokens ) if token_ids_a is None: return prefix_ones + ([0] * len(__a )) + suffix_ones return prefix_ones + ([0] * len(__a )) + ([0] * len(__a )) + suffix_ones def _lowercase (self : List[Any] , __a : List[int] , __a : Optional[List[int]] = None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + self.suffix_tokens # We don't expect to process pairs, but leave the pair logic for API consistency return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens def _lowercase (self : List[Any] ): UpperCAmelCase_ = {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 : Tuple ): UpperCAmelCase_ = self.__dict__.copy() UpperCAmelCase_ = None return state def __setstate__(self : Tuple , __a : Dict ): UpperCAmelCase_ = d # for backward compatibility if not hasattr(self , "sp_model_kwargs" ): UpperCAmelCase_ = {} UpperCAmelCase_ = load_spm(self.spm_file , self.sp_model_kwargs ) def _lowercase (self : Tuple , __a : str , __a : Optional[str] = None ): UpperCAmelCase_ = Path(__a ) if not save_dir.is_dir(): raise OSError(f"""{save_directory} should be a directory""" ) UpperCAmelCase_ = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) UpperCAmelCase_ = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["spm_file"] ) save_json(self.encoder , __a ) if os.path.abspath(self.spm_file ) != os.path.abspath(__a ) and os.path.isfile(self.spm_file ): copyfile(self.spm_file , __a ) elif not os.path.isfile(self.spm_file ): with open(__a , "wb" ) as fi: UpperCAmelCase_ = self.sp_model.serialized_model_proto() fi.write(__a ) return (str(__a ), str(__a )) def _lowercase (self : int , __a : List[str] , __a : str = "en" , __a : Optional[List[str]] = None , __a : str = "ro" , **__a : Optional[Any] , ): UpperCAmelCase_ = src_lang UpperCAmelCase_ = tgt_lang self.set_src_lang_special_tokens(self.src_lang ) return super().prepare_seqaseq_batch(__a , __a , **__a ) def _lowercase (self : str , __a : List[Any] , __a : Optional[str] , __a : Optional[str] , **__a : Tuple ): if src_lang is None or tgt_lang is None: raise ValueError("Translation requires a `src_lang` and a `tgt_lang` for this model" ) UpperCAmelCase_ = src_lang UpperCAmelCase_ = self(__a , add_special_tokens=__a , **__a ) UpperCAmelCase_ = self.get_lang_id(__a ) UpperCAmelCase_ = tgt_lang_id return inputs def _lowercase (self : int ): self.set_src_lang_special_tokens(self.src_lang ) def _lowercase (self : Tuple ): self.set_tgt_lang_special_tokens(self.tgt_lang ) def _lowercase (self : int , __a : str ): UpperCAmelCase_ = self.get_lang_token(__a ) UpperCAmelCase_ = self.lang_token_to_id[lang_token] UpperCAmelCase_ = [self.cur_lang_id] UpperCAmelCase_ = [self.eos_token_id] def _lowercase (self : Optional[Any] , __a : str ): UpperCAmelCase_ = self.get_lang_token(__a ) UpperCAmelCase_ = self.lang_token_to_id[lang_token] UpperCAmelCase_ = [self.cur_lang_id] UpperCAmelCase_ = [self.eos_token_id] def _lowercase (self : List[Any] , __a : str ): return self.lang_code_to_token[lang] def _lowercase (self : str , __a : str ): UpperCAmelCase_ = self.get_lang_token(__a ) return self.lang_token_to_id[lang_token] def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Dict[str, Any] ) -> sentencepiece.SentencePieceProcessor: '''simple docstring''' UpperCAmelCase_ = sentencepiece.SentencePieceProcessor(**snake_case_ ) spm.Load(str(snake_case_ ) ) return spm def lowerCAmelCase_ ( snake_case_ : str ) -> Union[Dict, List]: '''simple docstring''' with open(snake_case_ , "r" ) as f: return json.load(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : str ) -> None: '''simple docstring''' with open(snake_case_ , "w" ) as f: json.dump(snake_case_ , snake_case_ , indent=2 )
78
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed SCREAMING_SNAKE_CASE_: Any ={ 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCAmelCase_ ( snake_case_ : Any ) -> str: '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCAmelCase_ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False elif args.student_type == "gpt2": UpperCAmelCase_ = False def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=snake_case_ , required=snake_case_ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=snake_case_ , required=snake_case_ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=snake_case_ , choices=["distilbert", "roberta", "gpt2"] , required=snake_case_ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=snake_case_ , required=snake_case_ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=snake_case_ , type=snake_case_ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=snake_case_ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=snake_case_ , required=snake_case_ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=snake_case_ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=snake_case_ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=snake_case_ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=snake_case_ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=snake_case_ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=snake_case_ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=snake_case_ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=snake_case_ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=snake_case_ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=snake_case_ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=snake_case_ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=snake_case_ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=snake_case_ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=snake_case_ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=snake_case_ , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=snake_case_ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=snake_case_ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5E-4 , type=snake_case_ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1E-6 , type=snake_case_ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=snake_case_ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=snake_case_ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=snake_case_ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=snake_case_ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=snake_case_ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=snake_case_ , default=56 , help="Random seed" ) parser.add_argument("--log_interval" , type=snake_case_ , default=5_00 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=snake_case_ , default=40_00 , help="Checkpoint interval." ) UpperCAmelCase_ = parser.parse_args() sanity_checks(snake_case_ ) # ARGS # init_gpu_params(snake_case_ ) set_seed(snake_case_ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(f"""Param: {args}""" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(snake_case_ ) , snake_case_ , indent=4 ) git_log(args.dump_path ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.student_type] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCAmelCase_ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCAmelCase_ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCAmelCase_ = tokenizer.all_special_tokens.index(snake_case_ ) UpperCAmelCase_ = tokenizer.all_special_ids[idx] logger.info(f"""Special tokens {special_tok_ids}""" ) UpperCAmelCase_ = special_tok_ids UpperCAmelCase_ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"""Loading data from {args.data_file}""" ) with open(args.data_file , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) if args.mlm: logger.info(f"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) UpperCAmelCase_ = np.maximum(snake_case_ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCAmelCase_ = 0.0 # do not predict special tokens UpperCAmelCase_ = torch.from_numpy(snake_case_ ) else: UpperCAmelCase_ = None UpperCAmelCase_ = LmSeqsDataset(params=snake_case_ , data=snake_case_ ) logger.info("Data loader created." ) # STUDENT # logger.info(f"""Loading student config from {args.student_config}""" ) UpperCAmelCase_ = student_config_class.from_pretrained(args.student_config ) UpperCAmelCase_ = True if args.student_pretrained_weights is not None: logger.info(f"""Loading pretrained weights from {args.student_pretrained_weights}""" ) UpperCAmelCase_ = student_model_class.from_pretrained(args.student_pretrained_weights , config=snake_case_ ) else: UpperCAmelCase_ = student_model_class(snake_case_ ) if args.n_gpu > 0: student.to(f"""cuda:{args.local_rank}""" ) logger.info("Student loaded." ) # TEACHER # UpperCAmelCase_ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=snake_case_ ) if args.n_gpu > 0: teacher.to(f"""cuda:{args.local_rank}""" ) logger.info(f"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(snake_case_ , snake_case_ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(snake_case_ , snake_case_ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCAmelCase_ = Distiller( params=snake_case_ , dataset=snake_case_ , token_probs=snake_case_ , student=snake_case_ , teacher=snake_case_ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
78
1
'''simple docstring''' import os import unittest from transformers import BatchEncoding from transformers.models.bert.tokenization_bert import ( BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.models.prophetnet.tokenization_prophetnet import VOCAB_FILES_NAMES, ProphetNetTokenizer from transformers.testing_utils import require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin class __A ( UpperCamelCase__ , unittest.TestCase ): a__ : Any = ProphetNetTokenizer a__ : List[str] = False def _lowercase (self : List[Any] ): super().setUp() UpperCAmelCase_ = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] UpperCAmelCase_ = os.path.join(self.tmpdirname , VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file , "w" , encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) def _lowercase (self : int , __a : Dict ): UpperCAmelCase_ = "UNwant\u00E9d,running" UpperCAmelCase_ = "unwanted, running" return input_text, output_text def _lowercase (self : str ): UpperCAmelCase_ = self.tokenizer_class(self.vocab_file ) UpperCAmelCase_ = tokenizer.tokenize("UNwant\u00E9d,running" ) self.assertListEqual(__a , ["un", "##want", "##ed", ",", "runn", "##ing"] ) self.assertListEqual(tokenizer.convert_tokens_to_ids(__a ) , [9, 6, 7, 12, 10, 11] ) def _lowercase (self : List[str] ): UpperCAmelCase_ = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) , ["ah", "\u535A", "\u63A8", "zz"] ) def _lowercase (self : Any ): UpperCAmelCase_ = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["hello", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _lowercase (self : int ): UpperCAmelCase_ = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hällo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["h\u00E9llo"] ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["hallo", "!", "how", "are", "you", "?"] ) self.assertListEqual(tokenizer.tokenize("H\u00E9llo" ) , ["hello"] ) def _lowercase (self : int ): UpperCAmelCase_ = BasicTokenizer(do_lower_case=__a ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) , ["HeLLo", "!", "how", "Are", "yoU", "?"] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HäLLo", "!", "how", "Are", "yoU", "?"] ) def _lowercase (self : List[str] ): UpperCAmelCase_ = BasicTokenizer(do_lower_case=__a , strip_accents=__a ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) , ["HaLLo", "!", "how", "Are", "yoU", "?"] ) def _lowercase (self : Tuple ): UpperCAmelCase_ = BasicTokenizer(do_lower_case=__a , never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) , ["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def _lowercase (self : int ): UpperCAmelCase_ = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] UpperCAmelCase_ = {} for i, token in enumerate(__a ): UpperCAmelCase_ = i UpperCAmelCase_ = WordpieceTokenizer(vocab=__a , unk_token="[UNK]" ) self.assertListEqual(tokenizer.tokenize("" ) , [] ) self.assertListEqual(tokenizer.tokenize("unwanted running" ) , ["un", "##want", "##ed", "runn", "##ing"] ) self.assertListEqual(tokenizer.tokenize("unwantedX running" ) , ["[UNK]", "runn", "##ing"] ) @require_torch def _lowercase (self : str ): UpperCAmelCase_ = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased" ) UpperCAmelCase_ = ["A long paragraph for summarization.", "Another paragraph for summarization."] UpperCAmelCase_ = [1037, 2146, 20423, 2005, 7680, 7849, 3989, 1012, 102] UpperCAmelCase_ = tokenizer(__a , padding=__a , return_tensors="pt" ) self.assertIsInstance(__a , __a ) UpperCAmelCase_ = list(batch.input_ids.numpy()[0] ) self.assertListEqual(__a , __a ) self.assertEqual((2, 9) , batch.input_ids.shape ) self.assertEqual((2, 9) , batch.attention_mask.shape ) def _lowercase (self : Any ): self.assertTrue(_is_whitespace(" " ) ) self.assertTrue(_is_whitespace("\t" ) ) self.assertTrue(_is_whitespace("\r" ) ) self.assertTrue(_is_whitespace("\n" ) ) self.assertTrue(_is_whitespace("\u00A0" ) ) self.assertFalse(_is_whitespace("A" ) ) self.assertFalse(_is_whitespace("-" ) ) def _lowercase (self : Optional[Any] ): self.assertTrue(_is_control("\u0005" ) ) self.assertFalse(_is_control("A" ) ) self.assertFalse(_is_control(" " ) ) self.assertFalse(_is_control("\t" ) ) self.assertFalse(_is_control("\r" ) ) def _lowercase (self : Optional[Any] ): self.assertTrue(_is_punctuation("-" ) ) self.assertTrue(_is_punctuation("$" ) ) self.assertTrue(_is_punctuation("`" ) ) self.assertTrue(_is_punctuation("." ) ) self.assertFalse(_is_punctuation("A" ) ) self.assertFalse(_is_punctuation(" " ) ) @slow def _lowercase (self : int ): UpperCAmelCase_ = self.tokenizer_class.from_pretrained("microsoft/prophetnet-large-uncased" ) UpperCAmelCase_ = tokenizer.encode("sequence builders" , add_special_tokens=__a ) UpperCAmelCase_ = tokenizer.encode("multi-sequence build" , add_special_tokens=__a ) UpperCAmelCase_ = tokenizer.build_inputs_with_special_tokens(__a ) UpperCAmelCase_ = tokenizer.build_inputs_with_special_tokens(__a , __a ) assert encoded_sentence == text + [102] assert encoded_pair == text + [102] + text_a + [102]
78
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : int = AutoencoderKL a__ : Optional[Any] = """sample""" a__ : Union[str, Any] = 1e-2 @property def _lowercase (self : Optional[int] ): UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = (32, 32) UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(__a ) return {"sample": image} @property def _lowercase (self : Any ): return (3, 32, 32) @property def _lowercase (self : Dict ): return (3, 32, 32) def _lowercase (self : int ): UpperCAmelCase_ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def _lowercase (self : int ): pass def _lowercase (self : int ): pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase (self : List[Any] ): # enable deterministic behavior for gradient checkpointing UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**__a ) model.to(__a ) assert not model.is_gradient_checkpointing and model.training UpperCAmelCase_ = model(**__a ).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() UpperCAmelCase_ = torch.randn_like(__a ) UpperCAmelCase_ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCAmelCase_ = self.model_class(**__a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCAmelCase_ = model_a(**__a ).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() UpperCAmelCase_ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) UpperCAmelCase_ = dict(model.named_parameters() ) UpperCAmelCase_ = 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 _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__a ) self.assertIsNotNone(__a ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__a ) UpperCAmelCase_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) UpperCAmelCase_ = model.to(__a ) model.eval() if torch_device == "mps": UpperCAmelCase_ = torch.manual_seed(0 ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCAmelCase_ = image.to(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , sample_posterior=__a , generator=__a ).sample UpperCAmelCase_ = 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": UpperCAmelCase_ = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": UpperCAmelCase_ = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: UpperCAmelCase_ = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__a , __a , rtol=1E-2 ) ) @slow class __A ( unittest.TestCase ): def _lowercase (self : Dict , __a : Dict , __a : int ): return f"""gaussian_noise_s={seed}_shape={"_".join([str(__a ) for s in shape] )}.npy""" def _lowercase (self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] , __a : Optional[Any]=0 , __a : str=(4, 3, 512, 512) , __a : List[str]=False ): UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a ) ) ).to(__a ).to(__a ) return image def _lowercase (self : List[Any] , __a : Union[str, Any]="CompVis/stable-diffusion-v1-4" , __a : List[Any]=False ): UpperCAmelCase_ = "fp16" if fpaa else None UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = AutoencoderKL.from_pretrained( __a , subfolder="vae" , torch_dtype=__a , revision=__a , ) model.to(__a ).eval() return model def _lowercase (self : List[Any] , __a : List[Any]=0 ): if torch_device == "mps": return torch.manual_seed(__a ) return torch.Generator(device=__a ).manual_seed(__a ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Dict , __a : Optional[int] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , fpaa=__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : int , __a : int , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , 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 _lowercase (self : List[str] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , 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 _lowercase (self : Union[str, Any] , __a : Dict ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase (self : Tuple , __a : List[Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model.encode(__a ).latent_dist UpperCAmelCase_ = dist.sample(generator=__a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCAmelCase_ = sample[0, -1, -3:, -3:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) UpperCAmelCase_ = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(__a , __a , atol=__a )
78
1
'''simple docstring''' from PIL import Image def lowerCAmelCase_ ( snake_case_ : Image ) -> Image: '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ = image.size UpperCAmelCase_ = 0 UpperCAmelCase_ = image.load() for i in range(snake_case_ ): for j in range(snake_case_ ): UpperCAmelCase_ = pixels[j, i] mean += pixel mean //= width * height for j in range(snake_case_ ): for i in range(snake_case_ ): UpperCAmelCase_ = 2_55 if pixels[i, j] > mean else 0 return image if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =mean_threshold(Image.open('path_to_image').convert('L')) image.save('output_image_path')
78
'''simple docstring''' import logging from transformers import PretrainedConfig SCREAMING_SNAKE_CASE_: Any =logging.getLogger(__name__) SCREAMING_SNAKE_CASE_: Any ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : List[Any] = """bertabs""" def __init__(self : Any , __a : int=30522 , __a : Tuple=512 , __a : Tuple=6 , __a : Dict=512 , __a : int=8 , __a : List[Any]=512 , __a : List[str]=0.2 , __a : List[Any]=6 , __a : int=768 , __a : Any=8 , __a : Dict=2048 , __a : Tuple=0.2 , **__a : Optional[int] , ): super().__init__(**__a ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_pos UpperCAmelCase_ = enc_layers UpperCAmelCase_ = enc_hidden_size UpperCAmelCase_ = enc_heads UpperCAmelCase_ = enc_ff_size UpperCAmelCase_ = enc_dropout UpperCAmelCase_ = dec_layers UpperCAmelCase_ = dec_hidden_size UpperCAmelCase_ = dec_heads UpperCAmelCase_ = dec_ff_size UpperCAmelCase_ = dec_dropout
78
1
'''simple docstring''' import numpy as np class __A : def __init__(self : Union[str, Any] ): UpperCAmelCase_ = (0, 0) UpperCAmelCase_ = None UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 def __eq__(self : List[str] , __a : List[Any] ): return self.position == cell.position def _lowercase (self : List[str] ): print(self.position ) class __A : def __init__(self : Optional[int] , __a : Tuple=(5, 5) ): UpperCAmelCase_ = np.zeros(__a ) UpperCAmelCase_ = world_size[0] UpperCAmelCase_ = world_size[1] def _lowercase (self : str ): print(self.w ) def _lowercase (self : Any , __a : List[Any] ): UpperCAmelCase_ = [ (-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1), ] UpperCAmelCase_ = cell.position[0] UpperCAmelCase_ = cell.position[1] UpperCAmelCase_ = [] for n in neughbour_cord: UpperCAmelCase_ = current_x + n[0] UpperCAmelCase_ = current_y + n[1] if 0 <= x < self.world_x_limit and 0 <= y < self.world_y_limit: UpperCAmelCase_ = Cell() UpperCAmelCase_ = (x, y) UpperCAmelCase_ = cell neighbours.append(__a ) return neighbours def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : str , snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = [] UpperCAmelCase_ = [] _open.append(snake_case_ ) while _open: UpperCAmelCase_ = np.argmin([n.f for n in _open] ) UpperCAmelCase_ = _open[min_f] _closed.append(_open.pop(snake_case_ ) ) if current == goal: break for n in world.get_neigbours(snake_case_ ): for c in _closed: if c == n: continue UpperCAmelCase_ = current.g + 1 UpperCAmelCase_ , UpperCAmelCase_ = n.position UpperCAmelCase_ , UpperCAmelCase_ = goal.position UpperCAmelCase_ = (ya - ya) ** 2 + (xa - xa) ** 2 UpperCAmelCase_ = n.h + n.g for c in _open: if c == n and c.f < n.f: continue _open.append(snake_case_ ) UpperCAmelCase_ = [] while current.parent is not None: path.append(current.position ) UpperCAmelCase_ = current.parent path.append(current.position ) return path[::-1] if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =Gridworld() # Start position and goal SCREAMING_SNAKE_CASE_: Any =Cell() SCREAMING_SNAKE_CASE_: Optional[int] =(0, 0) SCREAMING_SNAKE_CASE_: Tuple =Cell() SCREAMING_SNAKE_CASE_: Any =(4, 4) print(f"path from {start.position} to {goal.position}") SCREAMING_SNAKE_CASE_: Optional[int] =astar(world, start, goal) # Just for visual reasons. for i in s: SCREAMING_SNAKE_CASE_: str =1 print(world.w)
78
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = {v: k for k, v in idalabel.items()} UpperCAmelCase_ = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" UpperCAmelCase_ = BitConfig( conv_layer=snake_case_ , num_labels=10_00 , idalabel=snake_case_ , labelaid=snake_case_ , ) return config def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if "stem.conv" in name: UpperCAmelCase_ = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase_ = name.replace("blocks" , "layers" ) if "head.fc" in name: UpperCAmelCase_ = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): UpperCAmelCase_ = "bit." + name if "bit" not in name and "classifier" not in name: UpperCAmelCase_ = "bit.encoder." + name return name def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : int=False ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = get_config(snake_case_ ) # load original model from timm UpperCAmelCase_ = create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model UpperCAmelCase_ = timm_model.state_dict() for key in state_dict.copy().keys(): UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val.squeeze() if "head" in key else val # load HuggingFace model UpperCAmelCase_ = BitForImageClassification(snake_case_ ) model.eval() model.load_state_dict(snake_case_ ) # create image processor UpperCAmelCase_ = create_transform(**resolve_data_config({} , model=snake_case_ ) ) UpperCAmelCase_ = transform.transforms UpperCAmelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase_ = BitImageProcessor( do_resize=snake_case_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ) UpperCAmelCase_ = processor(snake_case_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): UpperCAmelCase_ = model(snake_case_ ) UpperCAmelCase_ = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
78
1
'''simple docstring''' import logging from transformers import PretrainedConfig SCREAMING_SNAKE_CASE_: Any =logging.getLogger(__name__) SCREAMING_SNAKE_CASE_: Any ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : List[Any] = """bertabs""" def __init__(self : Any , __a : int=30522 , __a : Tuple=512 , __a : Tuple=6 , __a : Dict=512 , __a : int=8 , __a : List[Any]=512 , __a : List[str]=0.2 , __a : List[Any]=6 , __a : int=768 , __a : Any=8 , __a : Dict=2048 , __a : Tuple=0.2 , **__a : Optional[int] , ): super().__init__(**__a ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_pos UpperCAmelCase_ = enc_layers UpperCAmelCase_ = enc_hidden_size UpperCAmelCase_ = enc_heads UpperCAmelCase_ = enc_ff_size UpperCAmelCase_ = enc_dropout UpperCAmelCase_ = dec_layers UpperCAmelCase_ = dec_hidden_size UpperCAmelCase_ = dec_heads UpperCAmelCase_ = dec_ff_size UpperCAmelCase_ = dec_dropout
78
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __A ( unittest.TestCase ): def _lowercase (self : List[str] ): UpperCAmelCase_ = 0 def _lowercase (self : Tuple ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(__a , __a ) def _lowercase (self : str ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Dict ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop("image_processor_type" ) UpperCAmelCase_ = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved UpperCAmelCase_ = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _lowercase (self : int ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Tuple ): with self.assertRaisesRegex( __a , "clip-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" ) def _lowercase (self : Optional[int] ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , revision="aaaaaa" ) def _lowercase (self : Union[str, Any] ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def _lowercase (self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def _lowercase (self : Optional[int] ): try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : Optional[int] ): class __A ( UpperCamelCase__ ): a__ : str = True try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
78
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 SCREAMING_SNAKE_CASE_: Union[str, Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'hustvl/yolos-small': 'https://huggingface.co/hustvl/yolos-small/resolve/main/config.json', # See all YOLOS models at https://huggingface.co/models?filter=yolos } class __A ( UpperCamelCase__ ): a__ : List[Any] = """yolos""" def __init__(self : Optional[Any] , __a : Tuple=768 , __a : Tuple=12 , __a : Tuple=12 , __a : Dict=3072 , __a : Optional[int]="gelu" , __a : Optional[Any]=0.0 , __a : Dict=0.0 , __a : List[str]=0.02 , __a : str=1E-12 , __a : str=[512, 864] , __a : Optional[int]=16 , __a : int=3 , __a : Dict=True , __a : int=100 , __a : Optional[int]=True , __a : Any=False , __a : str=1 , __a : int=5 , __a : Any=2 , __a : List[str]=5 , __a : Optional[Any]=2 , __a : List[Any]=0.1 , **__a : Optional[Any] , ): super().__init__(**__a ) UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_act UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = image_size UpperCAmelCase_ = patch_size UpperCAmelCase_ = num_channels UpperCAmelCase_ = qkv_bias UpperCAmelCase_ = num_detection_tokens UpperCAmelCase_ = use_mid_position_embeddings UpperCAmelCase_ = auxiliary_loss # Hungarian matcher UpperCAmelCase_ = class_cost UpperCAmelCase_ = bbox_cost UpperCAmelCase_ = giou_cost # Loss coefficients UpperCAmelCase_ = bbox_loss_coefficient UpperCAmelCase_ = giou_loss_coefficient UpperCAmelCase_ = eos_coefficient class __A ( UpperCamelCase__ ): a__ : Optional[Any] = version.parse("""1.11""" ) @property def _lowercase (self : Tuple ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def _lowercase (self : Tuple ): return 1E-4 @property def _lowercase (self : Any ): return 12
78
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Tuple =False, False, False @dataclass class __A : a__ : Optional[int] = None a__ : bool = True a__ : bool = True a__ : Optional[str] = None # Automatically constructed a__ : ClassVar[str] = "dict" a__ : ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) a__ : str = field(default="""Audio""" , init=UpperCamelCase__ , repr=UpperCamelCase__ ) def __call__(self : Optional[Any] ): return self.pa_type def _lowercase (self : str , __a : Union[str, bytes, dict] ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(__a , __a ): return {"bytes": None, "path": value} elif isinstance(__a , __a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes UpperCAmelCase_ = BytesIO() sf.write(__a , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) UpperCAmelCase_ = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: UpperCAmelCase_ = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32767 UpperCAmelCase_ = BytesIO(bytes() ) sf.write(__a , __a , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def _lowercase (self : Dict , __a : dict , __a : Optional[Dict[str, Union[str, bool, None]]] = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) UpperCAmelCase_ , UpperCAmelCase_ = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err UpperCAmelCase_ = xsplitext(__a )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: UpperCAmelCase_ = token_per_repo_id or {} UpperCAmelCase_ = path.split("::" )[-1] try: UpperCAmelCase_ = string_to_dict(__a , config.HUB_DATASETS_URL )["repo_id"] UpperCAmelCase_ = token_per_repo_id[repo_id] except (ValueError, KeyError): UpperCAmelCase_ = None with xopen(__a , "rb" , use_auth_token=__a ) as f: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) else: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) UpperCAmelCase_ = array.T if self.mono: UpperCAmelCase_ = librosa.to_mono(__a ) if self.sampling_rate and self.sampling_rate != sampling_rate: UpperCAmelCase_ = librosa.resample(__a , orig_sr=__a , target_sr=self.sampling_rate ) UpperCAmelCase_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _lowercase (self : Dict ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def _lowercase (self : Optional[Any] , __a : Union[pa.StringArray, pa.StructArray] ): if pa.types.is_string(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): UpperCAmelCase_ = pa.array([Audio().encode_example(__a ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCAmelCase_ = storage.field("bytes" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCAmelCase_ = storage.field("path" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(__a , self.pa_type ) def _lowercase (self : Dict , __a : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(__a : Tuple ): with xopen(__a , "rb" ) as f: UpperCAmelCase_ = f.read() return bytes_ UpperCAmelCase_ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase_ = pa.array( [os.path.basename(__a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(__a , self.pa_type )
78
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import ( BitConfig, ViTHybridConfig, ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel, ) from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: str =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Dict=False ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = [] # fmt: off # stem: rename_keys.append(("cls_token", "vit.embeddings.cls_token") ) rename_keys.append(("pos_embed", "vit.embeddings.position_embeddings") ) rename_keys.append(("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight") ) rename_keys.append(("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias") ) # backbone rename_keys.append(("patch_embed.backbone.stem.conv.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.convolution.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.weight", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.weight") ) rename_keys.append(("patch_embed.backbone.stem.norm.bias", "vit.embeddings.patch_embeddings.backbone.bit.embedder.norm.bias") ) for stage_idx in range(len(config.backbone_config.depths ) ): for layer_idx in range(config.backbone_config.depths[stage_idx] ): rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv1.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv1.weight""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.weight""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm1.bias""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm1.bias""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv2.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv2.weight""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.weight""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm2.bias""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm2.bias""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.conv3.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.conv3.weight""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.weight""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.{layer_idx}.norm3.bias""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.{layer_idx}.norm3.bias""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.conv.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.conv.weight""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.weight""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.weight""") ) rename_keys.append((f"""patch_embed.backbone.stages.{stage_idx}.blocks.0.downsample.norm.bias""", f"""vit.embeddings.patch_embeddings.backbone.bit.encoder.stages.{stage_idx}.layers.0.downsample.norm.bias""") ) # transformer encoder for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" UpperCAmelCase_ = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) # fmt: on return rename_keys def lowerCAmelCase_ ( snake_case_ : Dict , snake_case_ : Optional[Any] , snake_case_ : Optional[Any]=False ) -> Any: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: UpperCAmelCase_ = "" else: UpperCAmelCase_ = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) UpperCAmelCase_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_ = in_proj_weight[ : config.hidden_size, : ] UpperCAmelCase_ = in_proj_bias[: config.hidden_size] UpperCAmelCase_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase_ = in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase_ = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(snake_case_ , snake_case_ ) def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : int , snake_case_ : Tuple ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = dct.pop(snake_case_ ) UpperCAmelCase_ = val def lowerCAmelCase_ ( ) -> int: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : List[str] , snake_case_ : List[str] , snake_case_ : List[Any]=False ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = BitConfig( global_padding="same" , layer_type="bottleneck" , depths=(3, 4, 9) , out_features=["stage3"] , embedding_dynamic_padding=snake_case_ , ) UpperCAmelCase_ = ViTHybridConfig(backbone_config=snake_case_ , image_size=3_84 , num_labels=10_00 ) UpperCAmelCase_ = False # load original model from timm UpperCAmelCase_ = timm.create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model, remove and rename some keys UpperCAmelCase_ = timm_model.state_dict() if base_model: remove_classification_head_(snake_case_ ) UpperCAmelCase_ = create_rename_keys(snake_case_ , snake_case_ ) for src, dest in rename_keys: rename_key(snake_case_ , snake_case_ , snake_case_ ) read_in_q_k_v(snake_case_ , snake_case_ , snake_case_ ) UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = idalabel UpperCAmelCase_ = {v: k for k, v in idalabel.items()} # load HuggingFace model if vit_name[-5:] == "in21k": UpperCAmelCase_ = ViTHybridModel(snake_case_ ).eval() else: UpperCAmelCase_ = ViTHybridForImageClassification(snake_case_ ).eval() model.load_state_dict(snake_case_ ) # create image processor UpperCAmelCase_ = create_transform(**resolve_data_config({} , model=snake_case_ ) ) UpperCAmelCase_ = transform.transforms UpperCAmelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase_ = ViTHybridImageProcessor( do_resize=snake_case_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ) UpperCAmelCase_ = processor(snake_case_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): UpperCAmelCase_ = model(snake_case_ ) UpperCAmelCase_ = outputs.logits print("Predicted class:" , logits.argmax(-1 ).item() ) if base_model: UpperCAmelCase_ = timm_model.forward_features(snake_case_ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(snake_case_ , outputs.pooler_output , atol=1E-3 ) else: UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) print(f"""Saving processor to {pytorch_dump_folder_path}""" ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"""Pushing model and processor to the hub {vit_name}""" ) model.push_to_hub(f"""ybelkada/{vit_name}""" ) processor.push_to_hub(f"""ybelkada/{vit_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_r50_s16_384', type=str, help='Name of the hybrid ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to upload the model to the HuggingFace hub.' ) SCREAMING_SNAKE_CASE_: Optional[int] =parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path, args.push_to_hub)
78
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
1
'''simple docstring''' from torch import nn class __A ( nn.Module ): def __init__(self : Optional[int] , __a : List[Any] , __a : int ): super().__init__() UpperCAmelCase_ = class_size UpperCAmelCase_ = embed_size # self.mlp1 = nn.Linear(embed_size, embed_size) # self.mlp2 = (nn.Linear(embed_size, class_size)) UpperCAmelCase_ = nn.Linear(__a , __a ) def _lowercase (self : Optional[Any] , __a : Optional[Any] ): # hidden_state = nn.functional.relu(self.mlp1(hidden_state)) # hidden_state = self.mlp2(hidden_state) UpperCAmelCase_ = self.mlp(__a ) return logits
78
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any]=0.999 , snake_case_ : Tuple="cosine" , ) -> Optional[Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase_ = [] for i in range(snake_case_ ): UpperCAmelCase_ = i / num_diffusion_timesteps UpperCAmelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case_ ) / alpha_bar_fn(snake_case_ ) , snake_case_ ) ) return torch.tensor(snake_case_ , dtype=torch.floataa ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : Tuple = [e.name for e in KarrasDiffusionSchedulers] a__ : Optional[Any] = 2 @register_to_config def __init__(self : Union[str, Any] , __a : int = 1000 , __a : float = 0.0_00_85 , __a : float = 0.0_12 , __a : str = "linear" , __a : Optional[Union[np.ndarray, List[float]]] = None , __a : str = "epsilon" , __a : Optional[bool] = False , __a : Optional[bool] = False , __a : float = 1.0 , __a : str = "linspace" , __a : int = 0 , ): if trained_betas is not None: UpperCAmelCase_ = torch.tensor(__a , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase_ = torch.linspace(__a , __a , __a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="cosine" ) elif beta_schedule == "exp": UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) UpperCAmelCase_ = 1.0 - self.betas UpperCAmelCase_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__a , __a , __a ) UpperCAmelCase_ = use_karras_sigmas def _lowercase (self : Optional[Any] , __a : Union[str, Any] , __a : Tuple=None ): if schedule_timesteps is None: UpperCAmelCase_ = self.timesteps UpperCAmelCase_ = (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: UpperCAmelCase_ = 1 if len(__a ) > 1 else 0 else: UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep UpperCAmelCase_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self : List[Any] ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self : Optional[Any] , __a : torch.FloatTensor , __a : Union[float, torch.FloatTensor] , ): UpperCAmelCase_ = self.index_for_timestep(__a ) UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self : Any , __a : int , __a : Union[str, torch.device] = None , __a : Optional[int] = None , ): UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = 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": UpperCAmelCase_ = np.linspace(0 , num_train_timesteps - 1 , __a , dtype=__a )[::-1].copy() elif self.config.timestep_spacing == "leading": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(0 , __a ) * step_ratio).round()[::-1].copy().astype(__a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(__a , 0 , -step_ratio )).round().copy().astype(__a ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) UpperCAmelCase_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) UpperCAmelCase_ = np.log(__a ) UpperCAmelCase_ = np.interp(__a , np.arange(0 , len(__a ) ) , __a ) if self.config.use_karras_sigmas: UpperCAmelCase_ = self._convert_to_karras(in_sigmas=__a , num_inference_steps=self.num_inference_steps ) UpperCAmelCase_ = np.array([self._sigma_to_t(__a , __a ) for sigma in sigmas] ) UpperCAmelCase_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a ) UpperCAmelCase_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) UpperCAmelCase_ = torch.from_numpy(__a ) UpperCAmelCase_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__a ).startswith("mps" ): # mps does not support float64 UpperCAmelCase_ = timesteps.to(__a , dtype=torch.floataa ) else: UpperCAmelCase_ = timesteps.to(device=__a ) # empty dt and derivative UpperCAmelCase_ = None UpperCAmelCase_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter UpperCAmelCase_ = defaultdict(__a ) def _lowercase (self : int , __a : Optional[Any] , __a : List[str] ): # get log sigma UpperCAmelCase_ = np.log(__a ) # get distribution UpperCAmelCase_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range UpperCAmelCase_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) UpperCAmelCase_ = low_idx + 1 UpperCAmelCase_ = log_sigmas[low_idx] UpperCAmelCase_ = log_sigmas[high_idx] # interpolate sigmas UpperCAmelCase_ = (low - log_sigma) / (low - high) UpperCAmelCase_ = np.clip(__a , 0 , 1 ) # transform interpolation to time range UpperCAmelCase_ = (1 - w) * low_idx + w * high_idx UpperCAmelCase_ = t.reshape(sigma.shape ) return t def _lowercase (self : Dict , __a : torch.FloatTensor , __a : Optional[int] ): UpperCAmelCase_ = in_sigmas[-1].item() UpperCAmelCase_ = in_sigmas[0].item() UpperCAmelCase_ = 7.0 # 7.0 is the value used in the paper UpperCAmelCase_ = np.linspace(0 , 1 , __a ) UpperCAmelCase_ = sigma_min ** (1 / rho) UpperCAmelCase_ = sigma_max ** (1 / rho) UpperCAmelCase_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self : List[str] ): return self.dt is None def _lowercase (self : List[Any] , __a : Union[torch.FloatTensor, np.ndarray] , __a : Union[float, torch.FloatTensor] , __a : Union[torch.FloatTensor, np.ndarray] , __a : bool = True , ): UpperCAmelCase_ = self.index_for_timestep(__a ) # advance index counter by 1 UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method UpperCAmelCase_ = self.sigmas[step_index - 1] UpperCAmelCase_ = 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 UpperCAmelCase_ = 0 UpperCAmelCase_ = 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": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": UpperCAmelCase_ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: UpperCAmelCase_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order UpperCAmelCase_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep UpperCAmelCase_ = sigma_next - sigma_hat # store for 2nd order step UpperCAmelCase_ = derivative UpperCAmelCase_ = dt UpperCAmelCase_ = sample else: # 2. 2nd order / Heun's method UpperCAmelCase_ = (sample - pred_original_sample) / sigma_next UpperCAmelCase_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample UpperCAmelCase_ = self.dt UpperCAmelCase_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a ) def _lowercase (self : Any , __a : torch.FloatTensor , __a : torch.FloatTensor , __a : torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples UpperCAmelCase_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__a ): # mps does not support float64 UpperCAmelCase_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) UpperCAmelCase_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: UpperCAmelCase_ = self.timesteps.to(original_samples.device ) UpperCAmelCase_ = timesteps.to(original_samples.device ) UpperCAmelCase_ = [self.index_for_timestep(__a , __a ) for t in timesteps] UpperCAmelCase_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): UpperCAmelCase_ = sigma.unsqueeze(-1 ) UpperCAmelCase_ = original_samples + noise * sigma return noisy_samples def __len__(self : str ): return self.config.num_train_timesteps
78
1
'''simple docstring''' import collections from typing import List, Optional, Union from ...tokenization_utils_base import BatchEncoding from ...utils import TensorType, add_end_docstrings, add_start_docstrings, logging from ..bert.tokenization_bert_fast import BertTokenizerFast from .tokenization_dpr import DPRContextEncoderTokenizer, DPRQuestionEncoderTokenizer, DPRReaderTokenizer SCREAMING_SNAKE_CASE_: Union[str, Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: str ={'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'} SCREAMING_SNAKE_CASE_: str ={ 'vocab_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-ctx_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-ctx_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-ctx_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE_: List[Any] ={ 'vocab_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-question_encoder-single-nq-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-question_encoder-multiset-base': ( 'https://huggingface.co/facebook/dpr-question_encoder-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE_: Optional[int] ={ 'vocab_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/vocab.txt' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/vocab.txt' ), }, 'tokenizer_file': { 'facebook/dpr-reader-single-nq-base': ( 'https://huggingface.co/facebook/dpr-reader-single-nq-base/resolve/main/tokenizer.json' ), 'facebook/dpr-reader-multiset-base': ( 'https://huggingface.co/facebook/dpr-reader-multiset-base/resolve/main/tokenizer.json' ), }, } SCREAMING_SNAKE_CASE_: Optional[Any] ={ 'facebook/dpr-ctx_encoder-single-nq-base': 5_12, 'facebook/dpr-ctx_encoder-multiset-base': 5_12, } SCREAMING_SNAKE_CASE_: Optional[Any] ={ 'facebook/dpr-question_encoder-single-nq-base': 5_12, 'facebook/dpr-question_encoder-multiset-base': 5_12, } SCREAMING_SNAKE_CASE_: int ={ 'facebook/dpr-reader-single-nq-base': 5_12, 'facebook/dpr-reader-multiset-base': 5_12, } SCREAMING_SNAKE_CASE_: Optional[Any] ={ 'facebook/dpr-ctx_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-ctx_encoder-multiset-base': {'do_lower_case': True}, } SCREAMING_SNAKE_CASE_: Any ={ 'facebook/dpr-question_encoder-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-question_encoder-multiset-base': {'do_lower_case': True}, } SCREAMING_SNAKE_CASE_: List[Any] ={ 'facebook/dpr-reader-single-nq-base': {'do_lower_case': True}, 'facebook/dpr-reader-multiset-base': {'do_lower_case': True}, } class __A ( UpperCamelCase__ ): a__ : Any = VOCAB_FILES_NAMES a__ : int = CONTEXT_ENCODER_PRETRAINED_VOCAB_FILES_MAP a__ : Any = CONTEXT_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Optional[Any] = CONTEXT_ENCODER_PRETRAINED_INIT_CONFIGURATION a__ : Tuple = DPRContextEncoderTokenizer class __A ( UpperCamelCase__ ): a__ : Any = VOCAB_FILES_NAMES a__ : Tuple = QUESTION_ENCODER_PRETRAINED_VOCAB_FILES_MAP a__ : List[str] = QUESTION_ENCODER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : List[Any] = QUESTION_ENCODER_PRETRAINED_INIT_CONFIGURATION a__ : str = DPRQuestionEncoderTokenizer SCREAMING_SNAKE_CASE_: Union[str, Any] =collections.namedtuple( 'DPRSpanPrediction', ['span_score', 'relevance_score', 'doc_id', 'start_index', 'end_index', 'text'] ) SCREAMING_SNAKE_CASE_: List[Any] =collections.namedtuple('DPRReaderOutput', ['start_logits', 'end_logits', 'relevance_logits']) SCREAMING_SNAKE_CASE_: str =r'\n Return a dictionary with the token ids of the input strings and other information to give to `.decode_best_spans`.\n It converts the strings of a question and different passages (title and text) in a sequence of IDs (integers),\n using the tokenizer and vocabulary. The resulting `input_ids` is a matrix of size `(n_passages, sequence_length)`\n with the format:\n\n [CLS] <question token ids> [SEP] <titles ids> [SEP] <texts ids>\n\n Args:\n questions (`str` or `List[str]`):\n The questions to be encoded. You can specify one question for many passages. In this case, the question\n will be duplicated like `[questions] * n_passages`. Otherwise you have to specify as many questions as in\n `titles` or `texts`.\n titles (`str` or `List[str]`):\n The passages titles to be encoded. This can be a string or a list of strings if there are several passages.\n texts (`str` or `List[str]`):\n The passages texts to be encoded. This can be a string or a list of strings if there are several passages.\n padding (`bool`, `str` or [`~utils.PaddingStrategy`], *optional*, defaults to `False`):\n Activates and controls padding. Accepts the following values:\n\n - `True` or `\'longest\'`: Pad to the longest sequence in the batch (or no padding if only a single sequence\n if provided).\n - `\'max_length\'`: Pad to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided.\n - `False` or `\'do_not_pad\'` (default): No padding (i.e., can output a batch with sequences of different\n lengths).\n truncation (`bool`, `str` or [`~tokenization_utils_base.TruncationStrategy`], *optional*, defaults to `False`):\n Activates and controls truncation. Accepts the following values:\n\n - `True` or `\'longest_first\'`: Truncate to a maximum length specified with the argument `max_length` or to\n the maximum acceptable input length for the model if that argument is not provided. This will truncate\n token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch\n of pairs) is provided.\n - `\'only_first\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the first\n sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `\'only_second\'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum\n acceptable input length for the model if that argument is not provided. This will only truncate the\n second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.\n - `False` or `\'do_not_truncate\'` (default): No truncation (i.e., can output batch with sequence lengths\n greater than the model maximum admissible input size).\n max_length (`int`, *optional*):\n Controls the maximum length to use by one of the truncation/padding parameters.\n\n If left unset or set to `None`, this will use the predefined model maximum length if a maximum length\n is required by one of the truncation/padding parameters. If the model has no specific maximum input\n length (like XLNet) truncation/padding to a maximum length will be deactivated.\n return_tensors (`str` or [`~utils.TensorType`], *optional*):\n If set, will return tensors instead of list of python integers. Acceptable values are:\n\n - `\'tf\'`: Return TensorFlow `tf.constant` objects.\n - `\'pt\'`: Return PyTorch `torch.Tensor` objects.\n - `\'np\'`: Return Numpy `np.ndarray` objects.\n return_attention_mask (`bool`, *optional*):\n Whether or not to return the attention mask. If not set, will return the attention mask according to the\n specific tokenizer\'s default, defined by the `return_outputs` attribute.\n\n [What are attention masks?](../glossary#attention-mask)\n\n Return:\n `Dict[str, List[List[int]]]`: A dictionary with the following keys:\n\n - `input_ids`: List of token ids to be fed to a model.\n - `attention_mask`: List of indices specifying which tokens should be attended to by the model.\n ' @add_start_docstrings(UpperCamelCase__ ) class __A : def __call__(self : Dict , __a : Any , __a : Optional[str] = None , __a : Optional[str] = None , __a : Union[bool, str] = False , __a : Union[bool, str] = False , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Optional[bool] = None , **__a : List[str] , ): if titles is None and texts is None: return super().__call__( __a , padding=__a , truncation=__a , max_length=__a , return_tensors=__a , return_attention_mask=__a , **__a , ) elif titles is None or texts is None: UpperCAmelCase_ = titles if texts is None else texts return super().__call__( __a , __a , padding=__a , truncation=__a , max_length=__a , return_tensors=__a , return_attention_mask=__a , **__a , ) UpperCAmelCase_ = titles if not isinstance(__a , __a ) else [titles] UpperCAmelCase_ = texts if not isinstance(__a , __a ) else [texts] UpperCAmelCase_ = len(__a ) UpperCAmelCase_ = questions if not isinstance(__a , __a ) else [questions] * n_passages assert len(__a ) == len( __a ), f"""There should be as many titles than texts but got {len(__a )} titles and {len(__a )} texts.""" UpperCAmelCase_ = super().__call__(__a , __a , padding=__a , truncation=__a )["input_ids"] UpperCAmelCase_ = super().__call__(__a , add_special_tokens=__a , padding=__a , truncation=__a )["input_ids"] UpperCAmelCase_ = { "input_ids": [ (encoded_question_and_title + encoded_text)[:max_length] if max_length is not None and truncation else encoded_question_and_title + encoded_text for encoded_question_and_title, encoded_text in zip(__a , __a ) ] } if return_attention_mask is not False: UpperCAmelCase_ = [] for input_ids in encoded_inputs["input_ids"]: attention_mask.append([int(input_id != self.pad_token_id ) for input_id in input_ids] ) UpperCAmelCase_ = attention_mask return self.pad(__a , padding=__a , max_length=__a , return_tensors=__a ) def _lowercase (self : List[Any] , __a : BatchEncoding , __a : DPRReaderOutput , __a : int = 16 , __a : int = 64 , __a : int = 4 , ): UpperCAmelCase_ = reader_input["input_ids"] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = reader_output[:3] UpperCAmelCase_ = len(__a ) UpperCAmelCase_ = sorted(range(__a ) , reverse=__a , key=relevance_logits.__getitem__ ) UpperCAmelCase_ = [] for doc_id in sorted_docs: UpperCAmelCase_ = list(input_ids[doc_id] ) # assuming question & title information is at the beginning of the sequence UpperCAmelCase_ = sequence_ids.index(self.sep_token_id , 2 ) + 1 # second sep id if sequence_ids[-1] == self.pad_token_id: UpperCAmelCase_ = sequence_ids.index(self.pad_token_id ) else: UpperCAmelCase_ = len(__a ) UpperCAmelCase_ = self._get_best_spans( start_logits=start_logits[doc_id][passage_offset:sequence_len] , end_logits=end_logits[doc_id][passage_offset:sequence_len] , max_answer_length=__a , top_spans=__a , ) for start_index, end_index in best_spans: start_index += passage_offset end_index += passage_offset nbest_spans_predictions.append( DPRSpanPrediction( span_score=start_logits[doc_id][start_index] + end_logits[doc_id][end_index] , relevance_score=relevance_logits[doc_id] , doc_id=__a , start_index=__a , end_index=__a , text=self.decode(sequence_ids[start_index : end_index + 1] ) , ) ) if len(__a ) >= num_spans: break return nbest_spans_predictions[:num_spans] def _lowercase (self : Any , __a : List[int] , __a : List[int] , __a : int , __a : int , ): UpperCAmelCase_ = [] for start_index, start_score in enumerate(__a ): for answer_length, end_score in enumerate(end_logits[start_index : start_index + max_answer_length] ): scores.append(((start_index, start_index + answer_length), start_score + end_score) ) UpperCAmelCase_ = sorted(__a , key=lambda __a : x[1] , reverse=__a ) UpperCAmelCase_ = [] for (start_index, end_index), score in scores: assert start_index <= end_index, f"""Wrong span indices: [{start_index}:{end_index}]""" UpperCAmelCase_ = end_index - start_index + 1 assert length <= max_answer_length, f"""Span is too long: {length} > {max_answer_length}""" if any( start_index <= prev_start_index <= prev_end_index <= end_index or prev_start_index <= start_index <= end_index <= prev_end_index for (prev_start_index, prev_end_index) in chosen_span_intervals ): continue chosen_span_intervals.append((start_index, end_index) ) if len(__a ) == top_spans: break return chosen_span_intervals @add_end_docstrings(UpperCamelCase__ ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : str = VOCAB_FILES_NAMES a__ : str = READER_PRETRAINED_VOCAB_FILES_MAP a__ : Dict = READER_PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : List[str] = READER_PRETRAINED_INIT_CONFIGURATION a__ : Union[str, Any] = ["""input_ids""", """attention_mask"""] a__ : Optional[Any] = DPRReaderTokenizer
78
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( UpperCamelCase__ ): a__ : List[str] = """Salesforce/blip-image-captioning-base""" a__ : Optional[Any] = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : str = """image_captioner""" a__ : List[str] = AutoModelForVisionaSeq a__ : int = ["""image"""] a__ : Optional[Any] = ["""text"""] def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*__a , **__a ) def _lowercase (self : Union[str, Any] , __a : "Image" ): return self.pre_processor(images=__a , return_tensors="pt" ) def _lowercase (self : List[str] , __a : Dict ): return self.model.generate(**__a ) def _lowercase (self : int , __a : Optional[Any] ): return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
78
1
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP SCREAMING_SNAKE_CASE_: Any =False try: SCREAMING_SNAKE_CASE_: Optional[Any] =_is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class __A : def __init__(self : int , __a : str = None , __a : list = [] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = choices UpperCAmelCase_ = prompt if sys.platform == "win32": UpperCAmelCase_ = "*" else: UpperCAmelCase_ = "➔ " def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a ) else: forceWrite(self.choices[index] , __a ) def _lowercase (self : Any , __a : int ): if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def _lowercase (self : Optional[Any] , __a : Direction , __a : int = 1 ): UpperCAmelCase_ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a ) move_cursor(__a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def _lowercase (self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def _lowercase (self : Any ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def _lowercase (self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def _lowercase (self : str ): move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a )] for number in range(10 )] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = int(chr(self.current_selection ) ) UpperCAmelCase_ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __a ) else: return else: return def _lowercase (self : Optional[Any] , __a : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase_ = default_choice for i in range(len(self.choices ) ): self.print_choice(__a ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase_ = int(builtins.input() ) except ValueError: UpperCAmelCase_ = default_choice else: UpperCAmelCase_ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__a , "\n" ) return choice
78
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
1
'''simple docstring''' import unittest from transformers import MPNetConfig, is_torch_available from transformers.testing_utils import 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 ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) class __A : def __init__(self : int , __a : List[str] , __a : Union[str, Any]=13 , __a : Dict=7 , __a : List[Any]=True , __a : Optional[Any]=True , __a : Union[str, Any]=False , __a : Tuple=True , __a : Union[str, Any]=99 , __a : str=64 , __a : List[str]=5 , __a : Optional[Any]=4 , __a : Optional[int]=64 , __a : int="gelu" , __a : List[Any]=0.1 , __a : List[str]=0.1 , __a : Optional[Any]=512 , __a : Dict=16 , __a : int=2 , __a : Union[str, Any]=0.02 , __a : Dict=3 , __a : int=4 , __a : Dict=None , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = seq_length UpperCAmelCase_ = is_training UpperCAmelCase_ = use_input_mask UpperCAmelCase_ = use_token_type_ids UpperCAmelCase_ = use_labels UpperCAmelCase_ = vocab_size UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_act UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = type_vocab_size UpperCAmelCase_ = type_sequence_label_size UpperCAmelCase_ = initializer_range UpperCAmelCase_ = num_labels UpperCAmelCase_ = num_choices UpperCAmelCase_ = scope def _lowercase (self : str ): return MPNetConfig.from_pretrained("microsoft/mpnet-base" ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ = None if self.use_input_mask: UpperCAmelCase_ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None if self.use_labels: UpperCAmelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase (self : str ): return MPNetConfig( 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 , initializer_range=self.initializer_range , ) def _lowercase (self : List[Any] , __a : List[str] , __a : List[str] , __a : Optional[Any] , __a : Dict , __a : List[Any] , __a : Any ): UpperCAmelCase_ = MPNetModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , __a ) UpperCAmelCase_ = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _lowercase (self : Dict , __a : Union[str, Any] , __a : str , __a : Tuple , __a : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = MPNetForQuestionAnswering(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model( __a , attention_mask=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _lowercase (self : Optional[Any] , __a : List[str] , __a : Any , __a : List[Any] , __a : List[Any] , __a : Dict , __a : int ): UpperCAmelCase_ = self.num_labels UpperCAmelCase_ = MPNetForSequenceClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase (self : List[Any] , __a : Optional[int] , __a : int , __a : Tuple , __a : List[Any] , __a : int , __a : str ): UpperCAmelCase_ = self.num_choices UpperCAmelCase_ = MPNetForMultipleChoice(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ = model( __a , attention_mask=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase (self : Union[str, Any] , __a : Dict , __a : Any , __a : Optional[Any] , __a : Tuple , __a : List[Any] , __a : str ): UpperCAmelCase_ = self.num_labels UpperCAmelCase_ = MPNetForTokenClassification(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , attention_mask=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase (self : Dict ): UpperCAmelCase_ = self.prepare_config_and_inputs() ((UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_) , (UpperCAmelCase_)) = config_and_inputs UpperCAmelCase_ = {"input_ids": input_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : str = ( ( MPNetForMaskedLM, MPNetForMultipleChoice, MPNetForQuestionAnswering, MPNetForSequenceClassification, MPNetForTokenClassification, MPNetModel, ) if is_torch_available() else () ) a__ : Optional[Any] = ( { """feature-extraction""": MPNetModel, """fill-mask""": MPNetForMaskedLM, """question-answering""": MPNetForQuestionAnswering, """text-classification""": MPNetForSequenceClassification, """token-classification""": MPNetForTokenClassification, """zero-shot""": MPNetForSequenceClassification, } if is_torch_available() else {} ) a__ : List[Any] = False a__ : Optional[int] = True def _lowercase (self : Dict ): UpperCAmelCase_ = MPNetModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__a , hidden_size=37 ) def _lowercase (self : Dict ): self.config_tester.run_common_tests() def _lowercase (self : Tuple ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_model(*__a ) def _lowercase (self : str ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_sequence_classification(*__a ) def _lowercase (self : int ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_multiple_choice(*__a ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_token_classification(*__a ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_mpnet_for_question_answering(*__a ) @require_torch class __A ( unittest.TestCase ): @slow def _lowercase (self : int ): UpperCAmelCase_ = MPNetModel.from_pretrained("microsoft/mpnet-base" ) UpperCAmelCase_ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) UpperCAmelCase_ = model(__a )[0] UpperCAmelCase_ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __a ) UpperCAmelCase_ = torch.tensor( [[[-0.05_50, 0.19_43, -0.07_40], [-0.05_62, 0.22_11, -0.05_79], [-0.04_37, 0.33_37, -0.06_41]]] ) # compare the actual values for a slice. self.assertTrue(torch.allclose(output[:, :3, :3] , __a , atol=1E-4 ) )
78
'''simple docstring''' import copy import re class __A : a__ : Optional[int] = """hp""" a__ : Optional[Any] = {} a__ : List[Any] = None @classmethod def _lowercase (cls : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = prefix UpperCAmelCase_ = defaults cls.build_naming_info() @staticmethod def _lowercase (__a : List[Any] , __a : List[str] ): if len(__a ) == 0: return "" UpperCAmelCase_ = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__a ) + 1 ): UpperCAmelCase_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__a : Union[str, Any] ): UpperCAmelCase_ = "" while integer != 0: UpperCAmelCase_ = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase_ = 0 while True: UpperCAmelCase_ = word + "#" + int_to_alphabetic(__a ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase_ = sword break UpperCAmelCase_ = short_word UpperCAmelCase_ = word return short_word @staticmethod def _lowercase (__a : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = param_name.split("_" ) UpperCAmelCase_ = [TrialShortNamer.shortname_for_word(__a , __a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase_ = ["", "_"] for separator in separators: UpperCAmelCase_ = separator.join(__a ) if shortname not in info["reverse_short_param"]: UpperCAmelCase_ = shortname UpperCAmelCase_ = param_name return shortname return param_name @staticmethod def _lowercase (__a : int , __a : Union[str, Any] ): UpperCAmelCase_ = TrialShortNamer.shortname_for_key(__a , __a ) UpperCAmelCase_ = short_name UpperCAmelCase_ = param_name @classmethod def _lowercase (cls : Any ): if cls.NAMING_INFO is not None: return UpperCAmelCase_ = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } UpperCAmelCase_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__a , __a ) UpperCAmelCase_ = info @classmethod def _lowercase (cls : int , __a : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase_ = cls.NAMING_INFO["short_param"][k] if isinstance(__a , __a ): UpperCAmelCase_ = 1 if v else 0 UpperCAmelCase_ = "" if isinstance(__a , (int, float) ) else "-" UpperCAmelCase_ = f"""{key}{sep}{v}""" name.append(__a ) return "_".join(__a ) @classmethod def _lowercase (cls : Dict , __a : Dict ): UpperCAmelCase_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase_ = [] else: UpperCAmelCase_ = repr.split("_" ) UpperCAmelCase_ = {} for value in values: if "-" in value: UpperCAmelCase_ , UpperCAmelCase_ = value.split("-" ) else: UpperCAmelCase_ = re.sub("[0-9.]" , "" , __a ) UpperCAmelCase_ = float(re.sub("[^0-9.]" , "" , __a ) ) UpperCAmelCase_ = cls.NAMING_INFO["reverse_short_param"][p_k] UpperCAmelCase_ = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase_ = cls.DEFAULTS[k] return parameters
78
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int ) -> int: '''simple docstring''' assert isinstance(snake_case_ , snake_case_ ), f"""The input value of [n={number}] is not an integer""" if number == 1: return 2 elif number < 1: UpperCAmelCase_ = f"""The input value of [n={number}] has to be > 0""" raise ValueError(snake_case_ ) else: UpperCAmelCase_ = sylvester(number - 1 ) UpperCAmelCase_ = num - 1 UpperCAmelCase_ = num return lower * upper + 1 if __name__ == "__main__": print(f"The 8th number in Sylvester's sequence: {sylvester(8)}")
78
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ = do_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
1
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
1
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_: Dict ={ 'configuration_funnel': ['FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FunnelConfig'], 'convert_funnel_original_tf_checkpoint_to_pytorch': [], 'tokenization_funnel': ['FunnelTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Any =['FunnelTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'FunnelBaseModel', 'FunnelForMaskedLM', 'FunnelForMultipleChoice', 'FunnelForPreTraining', 'FunnelForQuestionAnswering', 'FunnelForSequenceClassification', 'FunnelForTokenClassification', 'FunnelModel', 'FunnelPreTrainedModel', 'load_tf_weights_in_funnel', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[Any] =[ 'TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFFunnelBaseModel', 'TFFunnelForMaskedLM', 'TFFunnelForMultipleChoice', 'TFFunnelForPreTraining', 'TFFunnelForQuestionAnswering', 'TFFunnelForSequenceClassification', 'TFFunnelForTokenClassification', 'TFFunnelModel', 'TFFunnelPreTrainedModel', ] if TYPE_CHECKING: from .configuration_funnel import FUNNEL_PRETRAINED_CONFIG_ARCHIVE_MAP, FunnelConfig from .tokenization_funnel import FunnelTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_funnel_fast import FunnelTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_funnel import ( FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, FunnelBaseModel, FunnelForMaskedLM, FunnelForMultipleChoice, FunnelForPreTraining, FunnelForQuestionAnswering, FunnelForSequenceClassification, FunnelForTokenClassification, FunnelModel, FunnelPreTrainedModel, load_tf_weights_in_funnel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_funnel import ( TF_FUNNEL_PRETRAINED_MODEL_ARCHIVE_LIST, TFFunnelBaseModel, TFFunnelForMaskedLM, TFFunnelForMultipleChoice, TFFunnelForPreTraining, TFFunnelForQuestionAnswering, TFFunnelForSequenceClassification, TFFunnelForTokenClassification, TFFunnelModel, TFFunnelPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Tuple =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
1
'''simple docstring''' import importlib import os import sys # This is required to make the module import works (when the python process is running from the root of the repo) sys.path.append('.') def lowerCAmelCase_ ( snake_case_ : List[str] ) -> str: '''simple docstring''' UpperCAmelCase_ = test_file.split(os.path.sep ) if components[0:2] != ["tests", "models"]: raise ValueError( "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " f"""{test_file} instead.""" ) UpperCAmelCase_ = components[-1] if not test_fn.endswith("py" ): raise ValueError(f"""`test_file` should be a python file. Got {test_fn} instead.""" ) if not test_fn.startswith("test_modeling_" ): raise ValueError( f"""`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.""" ) UpperCAmelCase_ = components[:-1] + [test_fn.replace(".py" , "" )] UpperCAmelCase_ = ".".join(snake_case_ ) return test_module_path def lowerCAmelCase_ ( snake_case_ : Any ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = get_module_path(snake_case_ ) UpperCAmelCase_ = importlib.import_module(snake_case_ ) return test_module def lowerCAmelCase_ ( snake_case_ : Dict ) -> str: '''simple docstring''' UpperCAmelCase_ = [] UpperCAmelCase_ = get_test_module(snake_case_ ) for attr in dir(snake_case_ ): if attr.endswith("ModelTester" ): tester_classes.append(getattr(snake_case_ , snake_case_ ) ) # sort with class names return sorted(snake_case_ , key=lambda snake_case_ : x.__name__ ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ = [] UpperCAmelCase_ = get_test_module(snake_case_ ) for attr in dir(snake_case_ ): UpperCAmelCase_ = getattr(snake_case_ , snake_case_ ) # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking # `all_model_classes` is not empty (which also excludes other special classes). UpperCAmelCase_ = getattr(snake_case_ , "all_model_classes" , [] ) if len(snake_case_ ) > 0: test_classes.append(snake_case_ ) # sort with class names return sorted(snake_case_ , key=lambda snake_case_ : x.__name__ ) def lowerCAmelCase_ ( snake_case_ : List[str] ) -> Any: '''simple docstring''' UpperCAmelCase_ = get_test_classes(snake_case_ ) UpperCAmelCase_ = set() for test_class in test_classes: model_classes.update(test_class.all_model_classes ) # sort with class names return sorted(snake_case_ , key=lambda snake_case_ : x.__name__ ) def lowerCAmelCase_ ( snake_case_ : str ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = test_class() if hasattr(snake_case_ , "setUp" ): test.setUp() UpperCAmelCase_ = None if hasattr(snake_case_ , "model_tester" ): # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. if test.model_tester is not None: UpperCAmelCase_ = test.model_tester.__class__ return model_tester def lowerCAmelCase_ ( snake_case_ : List[str] , snake_case_ : Optional[int] ) -> str: '''simple docstring''' UpperCAmelCase_ = get_test_classes(snake_case_ ) UpperCAmelCase_ = [] for test_class in test_classes: if model_class in test_class.all_model_classes: target_test_classes.append(snake_case_ ) # sort with class names return sorted(snake_case_ , key=lambda snake_case_ : x.__name__ ) def lowerCAmelCase_ ( snake_case_ : Dict , snake_case_ : str ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = get_test_classes_for_model(snake_case_ , snake_case_ ) UpperCAmelCase_ = [] for test_class in test_classes: UpperCAmelCase_ = get_model_tester_from_test_class(snake_case_ ) if tester_class is not None: tester_classes.append(snake_case_ ) # sort with class names return sorted(snake_case_ , key=lambda snake_case_ : x.__name__ ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ = get_test_classes(snake_case_ ) UpperCAmelCase_ = {test_class: get_model_tester_from_test_class(snake_case_ ) for test_class in test_classes} return test_tester_mapping def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> str: '''simple docstring''' UpperCAmelCase_ = get_model_classes(snake_case_ ) UpperCAmelCase_ = { model_class: get_test_classes_for_model(snake_case_ , snake_case_ ) for model_class in model_classes } return model_test_mapping def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = get_model_classes(snake_case_ ) UpperCAmelCase_ = { model_class: get_tester_classes_for_model(snake_case_ , snake_case_ ) for model_class in model_classes } return model_to_tester_mapping def lowerCAmelCase_ ( snake_case_ : int ) -> List[str]: '''simple docstring''' if isinstance(snake_case_ , snake_case_ ): return o elif isinstance(snake_case_ , snake_case_ ): return o.__name__ elif isinstance(snake_case_ , (list, tuple) ): return [to_json(snake_case_ ) for x in o] elif isinstance(snake_case_ , snake_case_ ): return {to_json(snake_case_ ): to_json(snake_case_ ) for k, v in o.items()} else: return o
78
'''simple docstring''' import requests def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None: '''simple docstring''' UpperCAmelCase_ = {"Content-Type": "application/json"} UpperCAmelCase_ = requests.post(snake_case_ , json={"text": message_body} , headers=snake_case_ ) if response.status_code != 2_00: UpperCAmelCase_ = ( "Request to slack returned an error " f"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(snake_case_ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
78
1
'''simple docstring''' import sacrebleu as scb from packaging import version from sacrebleu import TER import datasets SCREAMING_SNAKE_CASE_: Optional[Any] ='\\n@inproceedings{snover-etal-2006-study,\n title = "A Study of Translation Edit Rate with Targeted Human Annotation",\n author = "Snover, Matthew and\n Dorr, Bonnie and\n Schwartz, Rich and\n Micciulla, Linnea and\n Makhoul, John",\n booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",\n month = aug # " 8-12",\n year = "2006",\n address = "Cambridge, Massachusetts, USA",\n publisher = "Association for Machine Translation in the Americas",\n url = "https://aclanthology.org/2006.amta-papers.25",\n pages = "223--231",\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' SCREAMING_SNAKE_CASE_: List[Any] ='\\nTER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a\nhypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu\n(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found\nhere: https://github.com/jhclark/tercom.\n\nThe implementation here is slightly different from sacrebleu in terms of the required input format. The length of\nthe references and hypotheses lists need to be the same, so you may need to transpose your references compared to\nsacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534\n\nSee the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.\n' SCREAMING_SNAKE_CASE_: Optional[Any] ='\nProduces TER scores alongside the number of edits and reference length.\n\nArgs:\n predictions (list of str): The system stream (a sequence of segments).\n references (list of list of str): A list of one or more reference streams (each a sequence of segments).\n normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.\n support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,\n as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.\n Only applies if `normalized = True`. Defaults to `False`.\n case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.\n\nReturns:\n \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)\n \'num_edits\' (int): The cumulative number of edits\n \'ref_length\' (float): The cumulative average reference length\n\nExamples:\n Example 1:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}\n\n Example 2:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}\n\n Example 3:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... normalized=True,\n ... case_sensitive=True)\n >>> print(results)\n {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}\n\n Example 4:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}\n\n Example 5:\n >>> predictions = ["does this sentence match??",\n ... "what about this sentence?",\n ... "What did the TER metric user say to the developer?"]\n >>> references = [["does this sentence match", "does this sentence match!?!"],\n ... ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],\n ... ["Your jokes are...", "...TERrible"]]\n >>> ter = datasets.load_metric("ter")\n >>> results = ter.compute(predictions=predictions,\n ... references=references,\n ... ignore_punct=True,\n ... case_sensitive=False)\n >>> print(results)\n {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def _lowercase (self : int ): if version.parse(scb.__version__ ) < version.parse("1.4.12" ): raise ImportWarning( "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n" "You can install it with `pip install \"sacrebleu>=1.4.12\"`." ) return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , homepage="http://www.cs.umd.edu/~snover/tercom/" , 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/mjpost/sacreBLEU#ter"] , reference_urls=[ "https://github.com/jhclark/tercom", ] , ) def _lowercase (self : Optional[Any] , __a : str , __a : List[Any] , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , ): UpperCAmelCase_ = len(references[0] ) if any(len(__a ) != references_per_prediction for refs in references ): raise ValueError("Sacrebleu requires the same number of references for each prediction" ) UpperCAmelCase_ = [[refs[i] for refs in references] for i in range(__a )] UpperCAmelCase_ = TER( normalized=__a , no_punct=__a , asian_support=__a , case_sensitive=__a , ) UpperCAmelCase_ = sb_ter.corpus_score(__a , __a ) return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}
78
'''simple docstring''' from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : CLIPSegForImageSegmentation , __a : CLIPSegProcessor , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = 1 UpperCAmelCase_ = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = True UpperCAmelCase_ = FrozenDict(__a ) if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _lowercase (self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _lowercase (self : int ): self.enable_attention_slicing(__a ) def _lowercase (self : Optional[Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : Optional[int] ): if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_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() def __call__(self : Dict , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, PIL.Image.Image] , __a : str , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): UpperCAmelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) UpperCAmelCase_ = self.segmentation_model(**__a ) UpperCAmelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCAmelCase_ = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCAmelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
78
1
'''simple docstring''' import qiskit def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) -> qiskit.result.counts.Counts: '''simple docstring''' UpperCAmelCase_ = qiskit.Aer.get_backend("aer_simulator" ) # Create a Quantum Circuit acting on the q register UpperCAmelCase_ = qiskit.QuantumCircuit(snake_case_ , snake_case_ ) # Map the quantum measurement to the classical bits circuit.measure([0] , [0] ) # Execute the circuit on the simulator UpperCAmelCase_ = qiskit.execute(snake_case_ , snake_case_ , shots=10_00 ) # Return the histogram data of the results of the experiment. return job.result().get_counts(snake_case_ ) if __name__ == "__main__": print(f"Total count for various states are: {single_qubit_measure(1, 1)}")
78
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' if number < 0: raise ValueError("number must not be negative" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case_ : list ) -> float: '''simple docstring''' if not nums: raise ValueError("List is empty" ) return sum(snake_case_ ) / len(snake_case_ ) if __name__ == "__main__": import doctest doctest.testmod()
78
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __A : a__ : int a__ : TreeNode | None = None a__ : TreeNode | None = None SCREAMING_SNAKE_CASE_: Union[str, Any] =namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase_ ( snake_case_ : TreeNode | None ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case_ ) != count_coins(snake_case_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(snake_case_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.left ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.right ) UpperCAmelCase_ = 1 - left_distrib_excess UpperCAmelCase_ = 1 - right_distrib_excess UpperCAmelCase_ = ( left_distrib_moves + right_distrib_moves + abs(snake_case_ ) + abs(snake_case_ ) ) UpperCAmelCase_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case_ , snake_case_ ) return get_distrib(snake_case_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' from __future__ import annotations from collections.abc import Iterator from typing import Generic, TypeVar SCREAMING_SNAKE_CASE_: int =TypeVar('T') class __A ( Generic[T] ): def __init__(self : Union[str, Any] , __a : T ): UpperCAmelCase_ = data UpperCAmelCase_ = None def __str__(self : Any ): return f"""{self.data}""" class __A ( Generic[T] ): def __init__(self : List[str] ): UpperCAmelCase_ = None def __iter__(self : List[Any] ): UpperCAmelCase_ = self.top while node: yield node.data UpperCAmelCase_ = node.next def __str__(self : str ): return "->".join([str(__a ) for item in self] ) def __len__(self : str ): return len(tuple(iter(self ) ) ) def _lowercase (self : str ): return self.top is None def _lowercase (self : Optional[Any] , __a : T ): UpperCAmelCase_ = Node(__a ) if not self.is_empty(): UpperCAmelCase_ = self.top UpperCAmelCase_ = node def _lowercase (self : List[str] ): if self.is_empty(): raise IndexError("pop from empty stack" ) assert isinstance(self.top , __a ) UpperCAmelCase_ = self.top UpperCAmelCase_ = self.top.next return pop_node.data def _lowercase (self : Any ): if self.is_empty(): raise IndexError("peek from empty stack" ) assert self.top is not None return self.top.data def _lowercase (self : List[str] ): UpperCAmelCase_ = None if __name__ == "__main__": from doctest import testmod testmod()
78
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE_: int =logging.getLogger() def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCAmelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> str: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = os.path.join(snake_case_ , "all_results.json" ) if os.path.exists(snake_case_ ): with open(snake_case_ , "r" ) as f: UpperCAmelCase_ = json.load(snake_case_ ) else: raise ValueError(f"""can't find {path}""" ) return results def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = torch.cuda.is_available() and torch_device == "cuda" return is_using_cuda and is_apex_available() SCREAMING_SNAKE_CASE_: Any =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __A ( UpperCamelCase__ ): @classmethod def _lowercase (cls : Any ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = os.path.join(cls.tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) UpperCAmelCase_ = ["accelerate", "launch", "--config_file", cls.configPath] @classmethod def _lowercase (cls : int ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "glue_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "clm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "mlm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCAmelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertLess(result["train_loss"] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "ner_no_trainer" ) ) ) @unittest.skip(reason="Fix me @muellerzr" ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : int ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["eval_f1"] , 28 ) self.assertGreaterEqual(result["eval_exact"] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "qa_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : str ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , "swag_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_rouge1"] , 10 ) self.assertGreaterEqual(result["eval_rouge2"] , 2 ) self.assertGreaterEqual(result["eval_rougeL"] , 7 ) self.assertGreaterEqual(result["eval_rougeLsum"] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "summarization_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : List[str] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_bleu"] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "translation_no_trainer" ) ) ) @slow def _lowercase (self : Dict ): UpperCAmelCase_ = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_overall_accuracy"] , 0.10 ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Any ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result["eval_accuracy"] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , "step_1" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "image_classification_no_trainer" ) ) )
78
1
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case_ : list[int] , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> None: '''simple docstring''' if (direction == 1 and array[indexa] > array[indexa]) or ( direction == 0 and array[indexa] < array[indexa] ): UpperCAmelCase_ , UpperCAmelCase_ = array[indexa], array[indexa] def lowerCAmelCase_ ( snake_case_ : list[int] , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> None: '''simple docstring''' if length > 1: UpperCAmelCase_ = int(length / 2 ) for i in range(snake_case_ , low + middle ): comp_and_swap(snake_case_ , snake_case_ , i + middle , snake_case_ ) bitonic_merge(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) bitonic_merge(snake_case_ , low + middle , snake_case_ , snake_case_ ) def lowerCAmelCase_ ( snake_case_ : list[int] , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> None: '''simple docstring''' if length > 1: UpperCAmelCase_ = int(length / 2 ) bitonic_sort(snake_case_ , snake_case_ , snake_case_ , 1 ) bitonic_sort(snake_case_ , low + middle , snake_case_ , 0 ) bitonic_merge(snake_case_ , snake_case_ , snake_case_ , snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: List[Any] =input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE_: int =[int(item.strip()) for item in user_input.split(',')] bitonic_sort(unsorted, 0, len(unsorted), 1) print('\nSorted array in ascending order is: ', end='') print(*unsorted, sep=', ') bitonic_merge(unsorted, 0, len(unsorted), 0) print('Sorted array in descending order is: ', end='') print(*unsorted, sep=', ')
78
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP SCREAMING_SNAKE_CASE_: Any =False try: SCREAMING_SNAKE_CASE_: Optional[Any] =_is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class __A : def __init__(self : int , __a : str = None , __a : list = [] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = choices UpperCAmelCase_ = prompt if sys.platform == "win32": UpperCAmelCase_ = "*" else: UpperCAmelCase_ = "➔ " def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a ) else: forceWrite(self.choices[index] , __a ) def _lowercase (self : Any , __a : int ): if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def _lowercase (self : Optional[Any] , __a : Direction , __a : int = 1 ): UpperCAmelCase_ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a ) move_cursor(__a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def _lowercase (self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def _lowercase (self : Any ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def _lowercase (self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def _lowercase (self : str ): move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a )] for number in range(10 )] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = int(chr(self.current_selection ) ) UpperCAmelCase_ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __a ) else: return else: return def _lowercase (self : Optional[Any] , __a : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase_ = default_choice for i in range(len(self.choices ) ): self.print_choice(__a ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase_ = int(builtins.input() ) except ValueError: UpperCAmelCase_ = default_choice else: UpperCAmelCase_ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__a , "\n" ) return choice
78
1
'''simple docstring''' import os from shutil import copyfile from typing import List, Optional, Tuple from ...tokenization_utils import AddedToken from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import is_sentencepiece_available, logging if is_sentencepiece_available(): from .tokenization_rembert import RemBertTokenizer else: SCREAMING_SNAKE_CASE_: Union[str, Any] =None SCREAMING_SNAKE_CASE_: Any =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Dict ={'vocab_file': 'sentencepiece.model', 'tokenizer_file': 'tokenizer.json'} SCREAMING_SNAKE_CASE_: Optional[int] ={ 'vocab_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/sentencepiece.model', }, 'tokenizer_file': { 'google/rembert': 'https://huggingface.co/google/rembert/resolve/main/tokenizer.json', }, } SCREAMING_SNAKE_CASE_: int ={ 'google/rembert': 2_56, } SCREAMING_SNAKE_CASE_: Optional[Any] ='▁' class __A ( UpperCamelCase__ ): a__ : Optional[Any] = VOCAB_FILES_NAMES a__ : Dict = PRETRAINED_VOCAB_FILES_MAP a__ : Any = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Any = RemBertTokenizer def __init__(self : Dict , __a : List[Any]=None , __a : List[Any]=None , __a : Dict=True , __a : Any=True , __a : Optional[Any]=False , __a : List[Any]="[CLS]" , __a : Dict="[SEP]" , __a : str="<unk>" , __a : int="[SEP]" , __a : Dict="<pad>" , __a : List[str]="[CLS]" , __a : Optional[int]="[MASK]" , **__a : List[Any] , ): # Mask token behave like a normal word, i.e. include the space before it UpperCAmelCase_ = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else mask_token super().__init__( __a , tokenizer_file=__a , do_lower_case=__a , remove_space=__a , keep_accents=__a , bos_token=__a , eos_token=__a , unk_token=__a , sep_token=__a , pad_token=__a , cls_token=__a , mask_token=__a , **__a , ) UpperCAmelCase_ = do_lower_case UpperCAmelCase_ = remove_space UpperCAmelCase_ = keep_accents UpperCAmelCase_ = vocab_file UpperCAmelCase_ = False if not self.vocab_file else True def _lowercase (self : List[str] , __a : List[int] , __a : Optional[List[int]] = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [self.cls_token_id] if token_ids_a is None: return cls + token_ids_a + sep return cls + token_ids_a + sep + token_ids_a + sep def _lowercase (self : Tuple , __a : List[int] , __a : Optional[List[int]] = None , __a : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( "You should not supply a second sequence if the provided sequence of " "ids is already formatted with special tokens for the model." ) return [1 if x in [self.sep_token_id, self.cls_token_id] else 0 for x in token_ids_a] if token_ids_a is not None: return [1] + ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] return [1] + ([0] * len(__a )) + [1] def _lowercase (self : Any , __a : List[int] , __a : Optional[List[int]] = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [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 _lowercase (self : Dict , __a : str , __a : Optional[str] = None ): if not os.path.isdir(__a ): logger.error("Vocabulary path ({}) should be a directory".format(__a ) ) return UpperCAmelCase_ = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__a ): copyfile(self.vocab_file , __a ) return (out_vocab_file,)
78
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_: Optional[int] ={'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['BeitFeatureExtractor'] SCREAMING_SNAKE_CASE_: int =['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: int =[ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
1
'''simple docstring''' from collections import namedtuple import requests from lxml import html # type: ignore SCREAMING_SNAKE_CASE_: str =namedtuple('covid_data', 'cases deaths recovered') def lowerCAmelCase_ ( snake_case_ : str = "https://www.worldometers.info/coronavirus/" ) -> covid_data: '''simple docstring''' UpperCAmelCase_ = "//div[@class = \"maincounter-number\"]/span/text()" return covid_data(*html.fromstring(requests.get(snake_case_ ).content ).xpath(snake_case_ ) ) SCREAMING_SNAKE_CASE_: List[Any] ='Total COVID-19 cases in the world: {}\nTotal deaths due to COVID-19 in the world: {}\nTotal COVID-19 patients recovered in the world: {}' print(fmt.format(*covid_stats()))
78
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed SCREAMING_SNAKE_CASE_: Any ={ 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCAmelCase_ ( snake_case_ : Any ) -> str: '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCAmelCase_ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False elif args.student_type == "gpt2": UpperCAmelCase_ = False def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=snake_case_ , required=snake_case_ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=snake_case_ , required=snake_case_ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=snake_case_ , choices=["distilbert", "roberta", "gpt2"] , required=snake_case_ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=snake_case_ , required=snake_case_ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=snake_case_ , type=snake_case_ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=snake_case_ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=snake_case_ , required=snake_case_ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=snake_case_ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=snake_case_ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=snake_case_ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=snake_case_ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=snake_case_ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=snake_case_ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=snake_case_ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=snake_case_ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=snake_case_ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=snake_case_ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=snake_case_ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=snake_case_ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=snake_case_ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=snake_case_ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=snake_case_ , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=snake_case_ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=snake_case_ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5E-4 , type=snake_case_ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1E-6 , type=snake_case_ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=snake_case_ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=snake_case_ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=snake_case_ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=snake_case_ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=snake_case_ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=snake_case_ , default=56 , help="Random seed" ) parser.add_argument("--log_interval" , type=snake_case_ , default=5_00 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=snake_case_ , default=40_00 , help="Checkpoint interval." ) UpperCAmelCase_ = parser.parse_args() sanity_checks(snake_case_ ) # ARGS # init_gpu_params(snake_case_ ) set_seed(snake_case_ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(f"""Param: {args}""" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(snake_case_ ) , snake_case_ , indent=4 ) git_log(args.dump_path ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.student_type] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCAmelCase_ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCAmelCase_ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCAmelCase_ = tokenizer.all_special_tokens.index(snake_case_ ) UpperCAmelCase_ = tokenizer.all_special_ids[idx] logger.info(f"""Special tokens {special_tok_ids}""" ) UpperCAmelCase_ = special_tok_ids UpperCAmelCase_ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"""Loading data from {args.data_file}""" ) with open(args.data_file , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) if args.mlm: logger.info(f"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) UpperCAmelCase_ = np.maximum(snake_case_ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCAmelCase_ = 0.0 # do not predict special tokens UpperCAmelCase_ = torch.from_numpy(snake_case_ ) else: UpperCAmelCase_ = None UpperCAmelCase_ = LmSeqsDataset(params=snake_case_ , data=snake_case_ ) logger.info("Data loader created." ) # STUDENT # logger.info(f"""Loading student config from {args.student_config}""" ) UpperCAmelCase_ = student_config_class.from_pretrained(args.student_config ) UpperCAmelCase_ = True if args.student_pretrained_weights is not None: logger.info(f"""Loading pretrained weights from {args.student_pretrained_weights}""" ) UpperCAmelCase_ = student_model_class.from_pretrained(args.student_pretrained_weights , config=snake_case_ ) else: UpperCAmelCase_ = student_model_class(snake_case_ ) if args.n_gpu > 0: student.to(f"""cuda:{args.local_rank}""" ) logger.info("Student loaded." ) # TEACHER # UpperCAmelCase_ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=snake_case_ ) if args.n_gpu > 0: teacher.to(f"""cuda:{args.local_rank}""" ) logger.info(f"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(snake_case_ , snake_case_ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(snake_case_ , snake_case_ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCAmelCase_ = Distiller( params=snake_case_ , dataset=snake_case_ , token_probs=snake_case_ , student=snake_case_ , teacher=snake_case_ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
78
1
'''simple docstring''' import os from typing import BinaryIO, Optional, Union import numpy as np import pyarrow.parquet as pq from .. import Audio, Dataset, Features, Image, NamedSplit, Value, config from ..features.features import FeatureType, _visit from ..formatting import query_table from ..packaged_modules import _PACKAGED_DATASETS_MODULES from ..packaged_modules.parquet.parquet import Parquet from ..utils import logging from ..utils.typing import NestedDataStructureLike, PathLike from .abc import AbstractDatasetReader def lowerCAmelCase_ ( snake_case_ : Features ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = np.inf def set_batch_size(snake_case_ : FeatureType ) -> None: nonlocal batch_size if isinstance(snake_case_ , snake_case_ ): UpperCAmelCase_ = min(snake_case_ , config.PARQUET_ROW_GROUP_SIZE_FOR_IMAGE_DATASETS ) elif isinstance(snake_case_ , snake_case_ ): UpperCAmelCase_ = min(snake_case_ , config.PARQUET_ROW_GROUP_SIZE_FOR_AUDIO_DATASETS ) elif isinstance(snake_case_ , snake_case_ ) and feature.dtype == "binary": UpperCAmelCase_ = min(snake_case_ , config.PARQUET_ROW_GROUP_SIZE_FOR_BINARY_DATASETS ) _visit(snake_case_ , snake_case_ ) return None if batch_size is np.inf else batch_size class __A ( UpperCamelCase__ ): def __init__(self : Tuple , __a : NestedDataStructureLike[PathLike] , __a : Optional[NamedSplit] = None , __a : Optional[Features] = None , __a : str = None , __a : bool = False , __a : bool = False , __a : Optional[int] = None , **__a : Dict , ): super().__init__( __a , split=__a , features=__a , cache_dir=__a , keep_in_memory=__a , streaming=__a , num_proc=__a , **__a , ) UpperCAmelCase_ = path_or_paths if isinstance(__a , __a ) else {self.split: path_or_paths} UpperCAmelCase_ = _PACKAGED_DATASETS_MODULES["parquet"][1] UpperCAmelCase_ = Parquet( cache_dir=__a , data_files=__a , features=__a , hash=__a , **__a , ) def _lowercase (self : str ): # Build iterable dataset if self.streaming: UpperCAmelCase_ = self.builder.as_streaming_dataset(split=self.split ) # Build regular (map-style) dataset else: UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None self.builder.download_and_prepare( download_config=__a , download_mode=__a , verification_mode=__a , base_path=__a , num_proc=self.num_proc , ) UpperCAmelCase_ = self.builder.as_dataset( split=self.split , verification_mode=__a , in_memory=self.keep_in_memory ) return dataset class __A : def __init__(self : List[Any] , __a : Dataset , __a : Union[PathLike, BinaryIO] , __a : Optional[int] = None , **__a : Optional[int] , ): UpperCAmelCase_ = dataset UpperCAmelCase_ = path_or_buf UpperCAmelCase_ = batch_size or get_writer_batch_size(dataset.features ) UpperCAmelCase_ = parquet_writer_kwargs def _lowercase (self : str ): UpperCAmelCase_ = self.batch_size if self.batch_size else config.DEFAULT_MAX_BATCH_SIZE if isinstance(self.path_or_buf , (str, bytes, os.PathLike) ): with open(self.path_or_buf , "wb+" ) as buffer: UpperCAmelCase_ = self._write(file_obj=__a , batch_size=__a , **self.parquet_writer_kwargs ) else: UpperCAmelCase_ = self._write(file_obj=self.path_or_buf , batch_size=__a , **self.parquet_writer_kwargs ) return written def _lowercase (self : int , __a : BinaryIO , __a : int , **__a : Union[str, Any] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = parquet_writer_kwargs.pop("path_or_buf" , __a ) UpperCAmelCase_ = self.dataset.features.arrow_schema UpperCAmelCase_ = pq.ParquetWriter(__a , schema=__a , **__a ) for offset in logging.tqdm( range(0 , len(self.dataset ) , __a ) , unit="ba" , disable=not logging.is_progress_bar_enabled() , desc="Creating parquet from Arrow format" , ): UpperCAmelCase_ = query_table( table=self.dataset._data , key=slice(__a , offset + batch_size ) , indices=self.dataset._indices if self.dataset._indices is not None else None , ) writer.write_table(__a ) written += batch.nbytes writer.close() return written
78
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : int = AutoencoderKL a__ : Optional[Any] = """sample""" a__ : Union[str, Any] = 1e-2 @property def _lowercase (self : Optional[int] ): UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = (32, 32) UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(__a ) return {"sample": image} @property def _lowercase (self : Any ): return (3, 32, 32) @property def _lowercase (self : Dict ): return (3, 32, 32) def _lowercase (self : int ): UpperCAmelCase_ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def _lowercase (self : int ): pass def _lowercase (self : int ): pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase (self : List[Any] ): # enable deterministic behavior for gradient checkpointing UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**__a ) model.to(__a ) assert not model.is_gradient_checkpointing and model.training UpperCAmelCase_ = model(**__a ).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() UpperCAmelCase_ = torch.randn_like(__a ) UpperCAmelCase_ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCAmelCase_ = self.model_class(**__a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCAmelCase_ = model_a(**__a ).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() UpperCAmelCase_ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) UpperCAmelCase_ = dict(model.named_parameters() ) UpperCAmelCase_ = 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 _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__a ) self.assertIsNotNone(__a ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__a ) UpperCAmelCase_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) UpperCAmelCase_ = model.to(__a ) model.eval() if torch_device == "mps": UpperCAmelCase_ = torch.manual_seed(0 ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCAmelCase_ = image.to(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , sample_posterior=__a , generator=__a ).sample UpperCAmelCase_ = 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": UpperCAmelCase_ = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": UpperCAmelCase_ = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: UpperCAmelCase_ = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__a , __a , rtol=1E-2 ) ) @slow class __A ( unittest.TestCase ): def _lowercase (self : Dict , __a : Dict , __a : int ): return f"""gaussian_noise_s={seed}_shape={"_".join([str(__a ) for s in shape] )}.npy""" def _lowercase (self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] , __a : Optional[Any]=0 , __a : str=(4, 3, 512, 512) , __a : List[str]=False ): UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a ) ) ).to(__a ).to(__a ) return image def _lowercase (self : List[Any] , __a : Union[str, Any]="CompVis/stable-diffusion-v1-4" , __a : List[Any]=False ): UpperCAmelCase_ = "fp16" if fpaa else None UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = AutoencoderKL.from_pretrained( __a , subfolder="vae" , torch_dtype=__a , revision=__a , ) model.to(__a ).eval() return model def _lowercase (self : List[Any] , __a : List[Any]=0 ): if torch_device == "mps": return torch.manual_seed(__a ) return torch.Generator(device=__a ).manual_seed(__a ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Dict , __a : Optional[int] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , fpaa=__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : int , __a : int , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , 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 _lowercase (self : List[str] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , 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 _lowercase (self : Union[str, Any] , __a : Dict ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase (self : Tuple , __a : List[Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model.encode(__a ).latent_dist UpperCAmelCase_ = dist.sample(generator=__a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCAmelCase_ = sample[0, -1, -3:, -3:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) UpperCAmelCase_ = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(__a , __a , atol=__a )
78
1
'''simple docstring''' 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 # and perform gradient accumulation # # 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 run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## SCREAMING_SNAKE_CASE_: Union[str, Any] =16 SCREAMING_SNAKE_CASE_: List[str] =32 def lowerCAmelCase_ ( snake_case_ : Accelerator , snake_case_ : int = 16 ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ = AutoTokenizer.from_pretrained("bert-base-cased" ) UpperCAmelCase_ = load_dataset("glue" , "mrpc" ) def tokenize_function(snake_case_ : List[Any] ): # max_length=None => use the model max length (it's actually the default) UpperCAmelCase_ = tokenizer(examples["sentence1"] , examples["sentence2"] , truncation=snake_case_ , max_length=snake_case_ ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): UpperCAmelCase_ = datasets.map( snake_case_ , batched=snake_case_ , remove_columns=["idx", "sentence1", "sentence2"] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library UpperCAmelCase_ = tokenized_datasets.rename_column("label" , "labels" ) def collate_fn(snake_case_ : List[Any] ): # On TPU it's best to pad everything to the same length or training will be very slow. UpperCAmelCase_ = 1_28 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": UpperCAmelCase_ = 16 elif accelerator.mixed_precision != "no": UpperCAmelCase_ = 8 else: UpperCAmelCase_ = None return tokenizer.pad( snake_case_ , padding="longest" , max_length=snake_case_ , pad_to_multiple_of=snake_case_ , return_tensors="pt" , ) # Instantiate dataloaders. UpperCAmelCase_ = DataLoader( tokenized_datasets["train"] , shuffle=snake_case_ , collate_fn=snake_case_ , batch_size=snake_case_ ) UpperCAmelCase_ = DataLoader( tokenized_datasets["validation"] , shuffle=snake_case_ , collate_fn=snake_case_ , batch_size=snake_case_ ) 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 SCREAMING_SNAKE_CASE_: Tuple =mocked_dataloaders # noqa: F811 def lowerCAmelCase_ ( snake_case_ : Union[str, Any] , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if os.environ.get("TESTING_MOCKED_DATALOADERS" , snake_case_ ) == "1": UpperCAmelCase_ = 2 # New Code # UpperCAmelCase_ = int(args.gradient_accumulation_steps ) # Initialize accelerator UpperCAmelCase_ = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , gradient_accumulation_steps=snake_case_ ) if accelerator.distributed_type == DistributedType.TPU and gradient_accumulation_steps > 1: raise NotImplementedError( "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs UpperCAmelCase_ = config["lr"] UpperCAmelCase_ = int(config["num_epochs"] ) UpperCAmelCase_ = int(config["seed"] ) UpperCAmelCase_ = int(config["batch_size"] ) UpperCAmelCase_ = evaluate.load("glue" , "mrpc" ) set_seed(snake_case_ ) UpperCAmelCase_ , UpperCAmelCase_ = get_dataloaders(snake_case_ , snake_case_ ) # Instantiate the model (we build the model here so that the seed also control new weights initialization) UpperCAmelCase_ = AutoModelForSequenceClassification.from_pretrained("bert-base-cased" , return_dict=snake_case_ ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). UpperCAmelCase_ = model.to(accelerator.device ) # Instantiate optimizer UpperCAmelCase_ = AdamW(params=model.parameters() , lr=snake_case_ ) # Instantiate scheduler UpperCAmelCase_ = get_linear_schedule_with_warmup( optimizer=snake_case_ , num_warmup_steps=1_00 , num_training_steps=(len(snake_case_ ) * num_epochs) , ) # 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. UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare( snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) # Now we train the model for epoch in range(snake_case_ ): model.train() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) # New code # # We use the new `accumulate` context manager to perform gradient accumulation # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. with accelerator.accumulate(snake_case_ ): UpperCAmelCase_ = model(**snake_case_ ) UpperCAmelCase_ = output.loss accelerator.backward(snake_case_ ) optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(snake_case_ ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) with torch.no_grad(): UpperCAmelCase_ = model(**snake_case_ ) UpperCAmelCase_ = outputs.logits.argmax(dim=-1 ) UpperCAmelCase_ , UpperCAmelCase_ = accelerator.gather_for_metrics((predictions, batch["labels"]) ) metric.add_batch( predictions=snake_case_ , references=snake_case_ , ) UpperCAmelCase_ = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , snake_case_ ) def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser(description="Simple example of training script." ) parser.add_argument( "--mixed_precision" , type=snake_case_ , default=snake_case_ , choices=["no", "fp16", "bf16", "fp8"] , help="Whether to use mixed precision. Choose" "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." "and an Nvidia Ampere GPU." , ) # New Code # parser.add_argument( "--gradient_accumulation_steps" , type=snake_case_ , default=1 , help="The number of minibatches to be ran before gradients are accumulated." , ) parser.add_argument("--cpu" , action="store_true" , help="If passed, will train on the CPU." ) UpperCAmelCase_ = parser.parse_args() UpperCAmelCase_ = {"lr": 2E-5, "num_epochs": 3, "seed": 42, "batch_size": 16} training_function(snake_case_ , snake_case_ ) if __name__ == "__main__": main()
78
'''simple docstring''' import logging from transformers import PretrainedConfig SCREAMING_SNAKE_CASE_: Any =logging.getLogger(__name__) SCREAMING_SNAKE_CASE_: Any ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : List[Any] = """bertabs""" def __init__(self : Any , __a : int=30522 , __a : Tuple=512 , __a : Tuple=6 , __a : Dict=512 , __a : int=8 , __a : List[Any]=512 , __a : List[str]=0.2 , __a : List[Any]=6 , __a : int=768 , __a : Any=8 , __a : Dict=2048 , __a : Tuple=0.2 , **__a : Optional[int] , ): super().__init__(**__a ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_pos UpperCAmelCase_ = enc_layers UpperCAmelCase_ = enc_hidden_size UpperCAmelCase_ = enc_heads UpperCAmelCase_ = enc_ff_size UpperCAmelCase_ = enc_dropout UpperCAmelCase_ = dec_layers UpperCAmelCase_ = dec_hidden_size UpperCAmelCase_ = dec_heads UpperCAmelCase_ = dec_ff_size UpperCAmelCase_ = dec_dropout
78
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE_: int ={} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: List[Any] =['BartphoTokenizer'] if TYPE_CHECKING: try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bartpho import BartphoTokenizer else: import sys SCREAMING_SNAKE_CASE_: Tuple =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = {v: k for k, v in idalabel.items()} UpperCAmelCase_ = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" UpperCAmelCase_ = BitConfig( conv_layer=snake_case_ , num_labels=10_00 , idalabel=snake_case_ , labelaid=snake_case_ , ) return config def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if "stem.conv" in name: UpperCAmelCase_ = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase_ = name.replace("blocks" , "layers" ) if "head.fc" in name: UpperCAmelCase_ = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): UpperCAmelCase_ = "bit." + name if "bit" not in name and "classifier" not in name: UpperCAmelCase_ = "bit.encoder." + name return name def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : int=False ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = get_config(snake_case_ ) # load original model from timm UpperCAmelCase_ = create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model UpperCAmelCase_ = timm_model.state_dict() for key in state_dict.copy().keys(): UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val.squeeze() if "head" in key else val # load HuggingFace model UpperCAmelCase_ = BitForImageClassification(snake_case_ ) model.eval() model.load_state_dict(snake_case_ ) # create image processor UpperCAmelCase_ = create_transform(**resolve_data_config({} , model=snake_case_ ) ) UpperCAmelCase_ = transform.transforms UpperCAmelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase_ = BitImageProcessor( do_resize=snake_case_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ) UpperCAmelCase_ = processor(snake_case_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): UpperCAmelCase_ = model(snake_case_ ) UpperCAmelCase_ = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
78
1
'''simple docstring''' import unittest from transformers import AlbertConfig, is_torch_available from transformers.models.auto import get_values from transformers.testing_utils import require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import ( MODEL_FOR_PRETRAINING_MAPPING, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForPreTraining, AlbertForQuestionAnswering, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertModel, ) from transformers.models.albert.modeling_albert import ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST class __A : def __init__(self : List[str] , __a : Union[str, Any] , __a : int=13 , __a : List[Any]=7 , __a : List[Any]=True , __a : Dict=True , __a : Optional[Any]=True , __a : int=True , __a : Dict=99 , __a : str=16 , __a : List[str]=36 , __a : Tuple=6 , __a : List[str]=6 , __a : Tuple=6 , __a : Dict=37 , __a : Dict="gelu" , __a : Union[str, Any]=0.1 , __a : Any=0.1 , __a : str=512 , __a : Dict=16 , __a : int=2 , __a : List[str]=0.02 , __a : List[str]=3 , __a : int=4 , __a : Union[str, Any]=None , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = seq_length UpperCAmelCase_ = is_training UpperCAmelCase_ = use_input_mask UpperCAmelCase_ = use_token_type_ids UpperCAmelCase_ = use_labels UpperCAmelCase_ = vocab_size UpperCAmelCase_ = embedding_size UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_hidden_groups UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_act UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = type_vocab_size UpperCAmelCase_ = type_sequence_label_size UpperCAmelCase_ = initializer_range UpperCAmelCase_ = num_labels UpperCAmelCase_ = num_choices UpperCAmelCase_ = scope def _lowercase (self : List[str] ): UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ = None if self.use_input_mask: UpperCAmelCase_ = random_attention_mask([self.batch_size, self.seq_length] ) UpperCAmelCase_ = None if self.use_token_type_ids: UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.type_vocab_size ) UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None if self.use_labels: UpperCAmelCase_ = ids_tensor([self.batch_size] , self.type_sequence_label_size ) UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) UpperCAmelCase_ = ids_tensor([self.batch_size] , self.num_choices ) UpperCAmelCase_ = self.get_config() return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels def _lowercase (self : int ): return AlbertConfig( 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 , num_hidden_groups=self.num_hidden_groups , ) def _lowercase (self : int , __a : Tuple , __a : Dict , __a : List[Any] , __a : Tuple , __a : int , __a : Tuple , __a : Optional[Any] ): UpperCAmelCase_ = AlbertModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , attention_mask=__a , token_type_ids=__a ) UpperCAmelCase_ = model(__a , token_type_ids=__a ) UpperCAmelCase_ = model(__a ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) self.parent.assertEqual(result.pooler_output.shape , (self.batch_size, self.hidden_size) ) def _lowercase (self : Optional[Any] , __a : Optional[int] , __a : Optional[int] , __a : List[str] , __a : Tuple , __a : List[Any] , __a : Union[str, Any] , __a : Optional[int] ): UpperCAmelCase_ = AlbertForPreTraining(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , sentence_order_label=__a , ) self.parent.assertEqual(result.prediction_logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) self.parent.assertEqual(result.sop_logits.shape , (self.batch_size, config.num_labels) ) def _lowercase (self : Optional[int] , __a : Tuple , __a : int , __a : Tuple , __a : Tuple , __a : List[str] , __a : int , __a : Optional[Any] ): UpperCAmelCase_ = AlbertForMaskedLM(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.vocab_size) ) def _lowercase (self : Dict , __a : Optional[int] , __a : Optional[Any] , __a : Dict , __a : Tuple , __a : Optional[Any] , __a : List[str] , __a : List[str] ): UpperCAmelCase_ = AlbertForQuestionAnswering(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model( __a , attention_mask=__a , token_type_ids=__a , start_positions=__a , end_positions=__a , ) self.parent.assertEqual(result.start_logits.shape , (self.batch_size, self.seq_length) ) self.parent.assertEqual(result.end_logits.shape , (self.batch_size, self.seq_length) ) def _lowercase (self : str , __a : List[str] , __a : Optional[Any] , __a : List[str] , __a : List[str] , __a : Tuple , __a : List[Any] , __a : Any ): UpperCAmelCase_ = self.num_labels UpperCAmelCase_ = AlbertForSequenceClassification(__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_labels) ) def _lowercase (self : Tuple , __a : int , __a : int , __a : Optional[Any] , __a : Optional[int] , __a : Optional[int] , __a : Tuple , __a : List[str] ): UpperCAmelCase_ = self.num_labels UpperCAmelCase_ = AlbertForTokenClassification(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(__a , attention_mask=__a , token_type_ids=__a , labels=__a ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.seq_length, self.num_labels) ) def _lowercase (self : List[Any] , __a : Union[str, Any] , __a : List[Any] , __a : str , __a : Tuple , __a : Dict , __a : Any , __a : Tuple ): UpperCAmelCase_ = self.num_choices UpperCAmelCase_ = AlbertForMultipleChoice(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = input_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ = token_type_ids.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ = input_mask.unsqueeze(1 ).expand(-1 , self.num_choices , -1 ).contiguous() UpperCAmelCase_ = model( __a , attention_mask=__a , token_type_ids=__a , labels=__a , ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.num_choices) ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.prepare_config_and_inputs() ( ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ( UpperCAmelCase_ ) , ) = config_and_inputs UpperCAmelCase_ = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask} return config, inputs_dict @require_torch class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : Tuple = ( ( AlbertModel, AlbertForPreTraining, AlbertForMaskedLM, AlbertForMultipleChoice, AlbertForSequenceClassification, AlbertForTokenClassification, AlbertForQuestionAnswering, ) if is_torch_available() else () ) a__ : Any = ( { """feature-extraction""": AlbertModel, """fill-mask""": AlbertForMaskedLM, """question-answering""": AlbertForQuestionAnswering, """text-classification""": AlbertForSequenceClassification, """token-classification""": AlbertForTokenClassification, """zero-shot""": AlbertForSequenceClassification, } if is_torch_available() else {} ) a__ : str = True def _lowercase (self : Tuple , __a : List[Any] , __a : Tuple , __a : str=False ): UpperCAmelCase_ = super()._prepare_for_class(__a , __a , return_labels=__a ) if return_labels: if model_class in get_values(__a ): UpperCAmelCase_ = torch.zeros( (self.model_tester.batch_size, self.model_tester.seq_length) , dtype=torch.long , device=__a ) UpperCAmelCase_ = torch.zeros( self.model_tester.batch_size , dtype=torch.long , device=__a ) return inputs_dict def _lowercase (self : List[str] ): UpperCAmelCase_ = AlbertModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__a , hidden_size=37 ) def _lowercase (self : List[Any] ): self.config_tester.run_common_tests() def _lowercase (self : Dict ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__a ) def _lowercase (self : Tuple ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_pretraining(*__a ) def _lowercase (self : str ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_lm(*__a ) def _lowercase (self : Tuple ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_multiple_choice(*__a ) def _lowercase (self : str ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_question_answering(*__a ) def _lowercase (self : Dict ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_sequence_classification(*__a ) def _lowercase (self : Tuple ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() for type in ["absolute", "relative_key", "relative_key_query"]: UpperCAmelCase_ = type self.model_tester.create_and_check_model(*__a ) @slow def _lowercase (self : Tuple ): for model_name in ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: UpperCAmelCase_ = AlbertModel.from_pretrained(__a ) self.assertIsNotNone(__a ) @require_torch class __A ( unittest.TestCase ): @slow def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = AlbertModel.from_pretrained("albert-base-v2" ) UpperCAmelCase_ = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 1588, 2]] ) UpperCAmelCase_ = torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) with torch.no_grad(): UpperCAmelCase_ = model(__a , attention_mask=__a )[0] UpperCAmelCase_ = torch.Size((1, 11, 768) ) self.assertEqual(output.shape , __a ) UpperCAmelCase_ = torch.tensor( [[[-0.65_13, 1.50_35, -0.27_66], [-0.65_15, 1.50_46, -0.27_80], [-0.65_12, 1.50_49, -0.27_84]]] ) self.assertTrue(torch.allclose(output[:, 1:4, 1:4] , __a , atol=1E-4 ) )
78
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __A ( unittest.TestCase ): def _lowercase (self : List[str] ): UpperCAmelCase_ = 0 def _lowercase (self : Tuple ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(__a , __a ) def _lowercase (self : str ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Dict ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop("image_processor_type" ) UpperCAmelCase_ = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved UpperCAmelCase_ = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _lowercase (self : int ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Tuple ): with self.assertRaisesRegex( __a , "clip-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" ) def _lowercase (self : Optional[int] ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , revision="aaaaaa" ) def _lowercase (self : Union[str, Any] ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def _lowercase (self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def _lowercase (self : Optional[int] ): try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : Optional[int] ): class __A ( UpperCamelCase__ ): a__ : str = True try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
78
1
'''simple docstring''' import time from contextlib import contextmanager from pathlib import Path import pytest import requests from huggingface_hub.hf_api import HfApi, HfFolder SCREAMING_SNAKE_CASE_: Union[str, Any] ='__DUMMY_TRANSFORMERS_USER__' SCREAMING_SNAKE_CASE_: Optional[Any] ='Dummy User' SCREAMING_SNAKE_CASE_: Tuple ='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' SCREAMING_SNAKE_CASE_: str ='https://hub-ci.huggingface.co' SCREAMING_SNAKE_CASE_: Dict =CI_HUB_ENDPOINT + '/datasets/{repo_id}/resolve/{revision}/{path}' SCREAMING_SNAKE_CASE_: List[Any] =CI_HUB_ENDPOINT + '/{repo_id}/resolve/{revision}/{filename}' SCREAMING_SNAKE_CASE_: List[str] =Path('~/.huggingface/hub_ci_token').expanduser() @pytest.fixture def lowerCAmelCase_ ( snake_case_ : int ) -> int: '''simple docstring''' monkeypatch.setattr( "huggingface_hub.file_download.HUGGINGFACE_CO_URL_TEMPLATE" , snake_case_ ) @pytest.fixture def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' monkeypatch.setattr("datasets.config.HF_ENDPOINT" , snake_case_ ) monkeypatch.setattr("datasets.config.HUB_DATASETS_URL" , snake_case_ ) @pytest.fixture def lowerCAmelCase_ ( snake_case_ : Dict ) -> Optional[Any]: '''simple docstring''' monkeypatch.setattr("huggingface_hub.hf_api.HfFolder.path_token" , snake_case_ ) @pytest.fixture def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Optional[int] ) -> int: '''simple docstring''' HfFolder.save_token(snake_case_ ) yield HfFolder.delete_token() @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' return HfApi(endpoint=snake_case_ ) @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( snake_case_ : HfApi ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = HfFolder.get_token() HfFolder.save_token(snake_case_ ) yield CI_HUB_USER_TOKEN if previous_token is not None: HfFolder.save_token(snake_case_ ) @pytest.fixture def lowerCAmelCase_ ( snake_case_ : int ) -> Dict: '''simple docstring''' def _cleanup_repo(snake_case_ : str ): hf_api.delete_repo(snake_case_ , token=snake_case_ , repo_type="dataset" ) return _cleanup_repo @pytest.fixture def lowerCAmelCase_ ( snake_case_ : Dict ) -> Optional[Any]: '''simple docstring''' @contextmanager def _temporary_repo(snake_case_ : Optional[Any] ): try: yield repo_id finally: cleanup_repo(snake_case_ ) return _temporary_repo @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( snake_case_ : HfApi , snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = f"""repo_txt_data-{int(time.time() * 1_0E3 )}""" UpperCAmelCase_ = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(snake_case_ , token=snake_case_ , repo_type="dataset" , private=snake_case_ ) hf_api.upload_file( token=snake_case_ , path_or_fileobj=str(snake_case_ ) , path_in_repo="data/text_data.txt" , repo_id=snake_case_ , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(snake_case_ , token=snake_case_ , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any] , snake_case_ : Union[str, Any] ) -> Any: '''simple docstring''' return hf_private_dataset_repo_txt_data_ @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( snake_case_ : HfApi , snake_case_ : Tuple , snake_case_ : List[Any] ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = f"""repo_zipped_txt_data-{int(time.time() * 1_0E3 )}""" UpperCAmelCase_ = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(snake_case_ , token=snake_case_ , repo_type="dataset" , private=snake_case_ ) hf_api.upload_file( token=snake_case_ , path_or_fileobj=str(snake_case_ ) , path_in_repo="data.zip" , repo_id=snake_case_ , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(snake_case_ , token=snake_case_ , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Union[str, Any] , snake_case_ : List[str] ) -> int: '''simple docstring''' return hf_private_dataset_repo_zipped_txt_data_ @pytest.fixture(scope="session" ) def lowerCAmelCase_ ( snake_case_ : HfApi , snake_case_ : str , snake_case_ : Dict ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = f"""repo_zipped_img_data-{int(time.time() * 1_0E3 )}""" UpperCAmelCase_ = f"""{CI_HUB_USER}/{repo_name}""" hf_api.create_repo(snake_case_ , token=snake_case_ , repo_type="dataset" , private=snake_case_ ) hf_api.upload_file( token=snake_case_ , path_or_fileobj=str(snake_case_ ) , path_in_repo="data.zip" , repo_id=snake_case_ , repo_type="dataset" , ) yield repo_id try: hf_api.delete_repo(snake_case_ , token=snake_case_ , repo_type="dataset" ) except (requests.exceptions.HTTPError, ValueError): # catch http error and token invalid error pass @pytest.fixture() def lowerCAmelCase_ ( snake_case_ : Union[str, Any] , snake_case_ : Optional[int] , snake_case_ : Union[str, Any] ) -> List[str]: '''simple docstring''' return hf_private_dataset_repo_zipped_img_data_
78
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Tuple =False, False, False @dataclass class __A : a__ : Optional[int] = None a__ : bool = True a__ : bool = True a__ : Optional[str] = None # Automatically constructed a__ : ClassVar[str] = "dict" a__ : ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) a__ : str = field(default="""Audio""" , init=UpperCamelCase__ , repr=UpperCamelCase__ ) def __call__(self : Optional[Any] ): return self.pa_type def _lowercase (self : str , __a : Union[str, bytes, dict] ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(__a , __a ): return {"bytes": None, "path": value} elif isinstance(__a , __a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes UpperCAmelCase_ = BytesIO() sf.write(__a , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) UpperCAmelCase_ = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: UpperCAmelCase_ = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32767 UpperCAmelCase_ = BytesIO(bytes() ) sf.write(__a , __a , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def _lowercase (self : Dict , __a : dict , __a : Optional[Dict[str, Union[str, bool, None]]] = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) UpperCAmelCase_ , UpperCAmelCase_ = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err UpperCAmelCase_ = xsplitext(__a )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: UpperCAmelCase_ = token_per_repo_id or {} UpperCAmelCase_ = path.split("::" )[-1] try: UpperCAmelCase_ = string_to_dict(__a , config.HUB_DATASETS_URL )["repo_id"] UpperCAmelCase_ = token_per_repo_id[repo_id] except (ValueError, KeyError): UpperCAmelCase_ = None with xopen(__a , "rb" , use_auth_token=__a ) as f: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) else: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) UpperCAmelCase_ = array.T if self.mono: UpperCAmelCase_ = librosa.to_mono(__a ) if self.sampling_rate and self.sampling_rate != sampling_rate: UpperCAmelCase_ = librosa.resample(__a , orig_sr=__a , target_sr=self.sampling_rate ) UpperCAmelCase_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _lowercase (self : Dict ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def _lowercase (self : Optional[Any] , __a : Union[pa.StringArray, pa.StructArray] ): if pa.types.is_string(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): UpperCAmelCase_ = pa.array([Audio().encode_example(__a ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCAmelCase_ = storage.field("bytes" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCAmelCase_ = storage.field("path" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(__a , self.pa_type ) def _lowercase (self : Dict , __a : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(__a : Tuple ): with xopen(__a , "rb" ) as f: UpperCAmelCase_ = f.read() return bytes_ UpperCAmelCase_ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase_ = pa.array( [os.path.basename(__a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(__a , self.pa_type )
78
1
'''simple docstring''' import argparse import json import os import fairseq import torch from torch import nn from transformers import ( SpeechaTextaConfig, SpeechaTextaForCausalLM, SpeechaTextaTokenizer, SpeechEncoderDecoderConfig, SpeechEncoderDecoderModel, WavaVecaConfig, WavaVecaFeatureExtractor, WavaVecaModel, logging, ) logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Any =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Tuple ={ 'post_extract_proj': 'feature_projection.projection', 'encoder.pos_conv.0': 'encoder.pos_conv_embed.conv', 'self_attn.k_proj': 'encoder.layers.*.attention.k_proj', 'self_attn.v_proj': 'encoder.layers.*.attention.v_proj', 'self_attn.q_proj': 'encoder.layers.*.attention.q_proj', 'self_attn.out_proj': 'encoder.layers.*.attention.out_proj', 'self_attn_layer_norm': 'encoder.layers.*.layer_norm', 'fc1': 'encoder.layers.*.feed_forward.intermediate_dense', 'fc2': 'encoder.layers.*.feed_forward.output_dense', 'final_layer_norm': 'encoder.layers.*.final_layer_norm', 'encoder.layer_norm': 'encoder.layer_norm', 'w2v_model.layer_norm': 'feature_projection.layer_norm', 'quantizer.weight_proj': 'quantizer.weight_proj', 'quantizer.vars': 'quantizer.codevectors', 'project_q': 'project_q', 'final_proj': 'project_hid', 'w2v_encoder.proj': 'lm_head', 'mask_emb': 'masked_spec_embed', } SCREAMING_SNAKE_CASE_: Union[str, Any] =[ 'lm_head', 'quantizer.weight_proj', 'quantizer.codevectors', 'project_q', 'project_hid', ] def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Tuple , snake_case_ : Any , snake_case_ : Tuple , snake_case_ : Tuple ) -> str: '''simple docstring''' for attribute in key.split("." ): UpperCAmelCase_ = getattr(snake_case_ , snake_case_ ) if weight_type is not None: UpperCAmelCase_ = getattr(snake_case_ , snake_case_ ).shape else: UpperCAmelCase_ = hf_pointer.shape assert hf_shape == value.shape, ( f"""Shape of hf {key + "." + weight_type if weight_type is not None else ""} is {hf_shape}, but should be""" f""" {value.shape} for {full_name}""" ) if weight_type == "weight": UpperCAmelCase_ = value elif weight_type == "weight_g": UpperCAmelCase_ = value elif weight_type == "weight_v": UpperCAmelCase_ = value elif weight_type == "bias": UpperCAmelCase_ = value else: UpperCAmelCase_ = value logger.info(f"""{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.""" ) def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = [] UpperCAmelCase_ = fairseq_model.state_dict() UpperCAmelCase_ = hf_model.feature_extractor # if encoder has different dim to decoder -> use proj_weight UpperCAmelCase_ = None for name, value in fairseq_dict.items(): UpperCAmelCase_ = False if "conv_layers" in name: load_conv_layer( snake_case_ , snake_case_ , snake_case_ , snake_case_ , hf_model.config.feat_extract_norm == "group" , ) UpperCAmelCase_ = True elif name.split("." )[0] == "proj": UpperCAmelCase_ = fairseq_model.proj UpperCAmelCase_ = True else: for key, mapped_key in MAPPING.items(): if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: UpperCAmelCase_ = True if "*" in mapped_key: UpperCAmelCase_ = name.split(snake_case_ )[0].split("." )[-2] UpperCAmelCase_ = mapped_key.replace("*" , snake_case_ ) if "weight_g" in name: UpperCAmelCase_ = "weight_g" elif "weight_v" in name: UpperCAmelCase_ = "weight_v" elif "bias" in name: UpperCAmelCase_ = "bias" elif "weight" in name: UpperCAmelCase_ = "weight" else: UpperCAmelCase_ = None set_recursively(snake_case_ , snake_case_ , snake_case_ , snake_case_ , snake_case_ ) continue if not is_used: unused_weights.append(snake_case_ ) logger.warning(f"""Unused weights: {unused_weights}""" ) return proj_weight def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Any , snake_case_ : List[str] , snake_case_ : str , snake_case_ : List[Any] ) -> Any: '''simple docstring''' UpperCAmelCase_ = full_name.split("conv_layers." )[-1] UpperCAmelCase_ = name.split("." ) UpperCAmelCase_ = int(items[0] ) UpperCAmelCase_ = int(items[1] ) if type_id == 0: if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.bias.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.bias.data.shape} was found.""" ) UpperCAmelCase_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].conv.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor.conv_layers[layer_id].conv.weight.data.shape} was found.""" ) UpperCAmelCase_ = value logger.info(f"""Feat extract conv layer {layer_id} was initialized from {full_name}.""" ) elif (type_id == 2 and not use_group_norm) or (type_id == 2 and layer_id == 0 and use_group_norm): if "bias" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.bias.data.shape, ( f"""{full_name} has size {value.shape}, but {feature_extractor[layer_id].layer_norm.bias.data.shape} was""" " found." ) UpperCAmelCase_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) elif "weight" in name: assert value.shape == feature_extractor.conv_layers[layer_id].layer_norm.weight.data.shape, ( f"""{full_name} has size {value.shape}, but""" f""" {feature_extractor[layer_id].layer_norm.weight.data.shape} was found.""" ) UpperCAmelCase_ = value logger.info(f"""Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.""" ) else: unused_weights.append(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ , UpperCAmelCase_ = emb.weight.shape UpperCAmelCase_ = nn.Linear(snake_case_ , snake_case_ , bias=snake_case_ ) UpperCAmelCase_ = emb.weight.data return lin_layer def lowerCAmelCase_ ( snake_case_ : Any ) -> List[Any]: '''simple docstring''' with open(snake_case_ , "r" , encoding="utf-8" ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = [line.split(" " )[0] for line in lines] UpperCAmelCase_ = len(snake_case_ ) UpperCAmelCase_ = { "<s>": 0, "<pad>": 1, "</s>": 2, "<unk>": 3, } vocab_dict.update(dict(zip(snake_case_ , range(4 , num_words + 4 ) ) ) ) return vocab_dict @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : List[Any] , snake_case_ : int , snake_case_ : Optional[Any] , snake_case_ : int , snake_case_ : str , snake_case_ : Optional[int] , ) -> Dict: '''simple docstring''' UpperCAmelCase_ = WavaVecaConfig.from_pretrained(snake_case_ ) UpperCAmelCase_ = SpeechaTextaConfig.from_pretrained( snake_case_ , vocab_size=snake_case_ , decoder_layers=snake_case_ , do_stable_layer_norm=snake_case_ ) UpperCAmelCase_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=1_60_00 , padding_value=0 , do_normalize=snake_case_ , return_attention_mask=snake_case_ , ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) UpperCAmelCase_ = model[0].eval() # set weights for wav2vec2 encoder UpperCAmelCase_ = WavaVecaModel(snake_case_ ) UpperCAmelCase_ = recursively_load_weights_wavaveca(model.encoder , snake_case_ ) UpperCAmelCase_ = SpeechaTextaForCausalLM(snake_case_ ) UpperCAmelCase_ , UpperCAmelCase_ = hf_decoder.model.decoder.load_state_dict(model.decoder.state_dict() , strict=snake_case_ ) # set output linear layer unexpected_keys.remove("embed_out" ) UpperCAmelCase_ = nn.Parameter(model.decoder.embed_out.detach() ) # layer norm is init to identity matrix so leaving it is fine logger.warning(f"""The following keys are missing when loading the decoder weights: {missing_keys}""" ) logger.warning(f"""The following keys are unexpected when loading the decoder weights: {unexpected_keys}""" ) UpperCAmelCase_ = SpeechEncoderDecoderModel(encoder=snake_case_ , decoder=snake_case_ ) UpperCAmelCase_ = False # add projection layer UpperCAmelCase_ = nn.Parameter(projection_layer.weight ) UpperCAmelCase_ = nn.Parameter(projection_layer.bias ) UpperCAmelCase_ = create_vocab_dict(snake_case_ ) with open(os.path.join(snake_case_ , "vocab.json" ) , "w" ) as fp: json.dump(snake_case_ , snake_case_ ) UpperCAmelCase_ = SpeechaTextaTokenizer(os.path.join(snake_case_ , "vocab.json" ) ) tokenizer.save_pretrained(snake_case_ ) UpperCAmelCase_ = hf_wavavec.config.to_dict() UpperCAmelCase_ = tokenizer.pad_token_id UpperCAmelCase_ = tokenizer.bos_token_id UpperCAmelCase_ = tokenizer.eos_token_id UpperCAmelCase_ = "speech_to_text_2" UpperCAmelCase_ = "wav2vec2" UpperCAmelCase_ = SpeechEncoderDecoderConfig.from_dict(snake_case_ ) hf_wavavec.save_pretrained(snake_case_ ) feature_extractor.save_pretrained(snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[int] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to fairseq checkpoint') parser.add_argument('--dict_path', default=None, type=str, help='Path to dict of fine-tuned model') parser.add_argument( '--encoder_config_path', default='facebook/wav2vec2-large-lv60', type=str, help='Path to hf encoder wav2vec2 checkpoint config', ) parser.add_argument( '--decoder_config_path', default='facebook/s2t-small-mustc-en-fr-st', type=str, help='Path to hf decoder s2t checkpoint config', ) parser.add_argument('--vocab_size', default=1_02_24, type=int, help='Vocab size of decoder') parser.add_argument('--num_decoder_layers', default=7, type=int, help='Number of decoder layers') SCREAMING_SNAKE_CASE_: Tuple =parser.parse_args() convert_wavaveca_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.dict_path, encoder_config_path=args.encoder_config_path, decoder_config_path=args.decoder_config_path, vocab_size=args.vocab_size, num_decoder_layers=args.num_decoder_layers, )
78
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
1
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList SCREAMING_SNAKE_CASE_: Union[str, Any] =['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif'] class __A ( UpperCamelCase__ ): def __init__(self : Optional[Any] , __a : str , __a : Optional[Any] , __a : int=None , __a : str=1 ): UpperCAmelCase_ = tokenizer UpperCAmelCase_ = dataset UpperCAmelCase_ = len(__a ) if n_tasks is None else n_tasks UpperCAmelCase_ = n_copies def __iter__(self : List[Any] ): UpperCAmelCase_ = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]["prompt"].strip() ) UpperCAmelCase_ = self.tokenizer(__a , padding=__a , return_tensors="pt" ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class __A ( UpperCamelCase__ ): def __init__(self : List[Any] , __a : Any , __a : Any , __a : Dict ): UpperCAmelCase_ = start_length UpperCAmelCase_ = eof_strings UpperCAmelCase_ = tokenizer def __call__(self : Dict , __a : List[Any] , __a : int , **__a : Dict ): UpperCAmelCase_ = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) UpperCAmelCase_ = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(__a ) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = re.split("(%s)" % "|".join(snake_case_ ) , snake_case_ ) # last string should be "" return "".join(string_list[:-2] ) def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] , snake_case_ : List[str] , snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : Tuple=20 , **snake_case_ : Any ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = defaultdict(snake_case_ ) # dict of list of generated tokens for step, batch in tqdm(enumerate(snake_case_ ) ): with torch.no_grad(): UpperCAmelCase_ = batch["ids"].shape[-1] UpperCAmelCase_ = accelerator.unwrap_model(snake_case_ ).generate( input_ids=batch["ids"][:, : batch["input_len"]] , num_return_sequences=snake_case_ , **snake_case_ ) # each task is generated batch_size times UpperCAmelCase_ = batch["task_id"].repeat(snake_case_ ) UpperCAmelCase_ = accelerator.pad_across_processes( snake_case_ , dim=1 , pad_index=tokenizer.pad_token_id ) UpperCAmelCase_ , UpperCAmelCase_ = accelerator.gather((generated_tokens, generated_tasks) ) UpperCAmelCase_ = generated_tokens.cpu().numpy() UpperCAmelCase_ = generated_tasks.cpu().numpy() for task, generated_tokens in zip(snake_case_ , snake_case_ ): gen_token_dict[task].append(snake_case_ ) UpperCAmelCase_ = [[] for _ in range(snake_case_ )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: UpperCAmelCase_ = tokenizer.decode(snake_case_ , skip_special_tokens=snake_case_ , clean_up_tokenization_spaces=snake_case_ ) code_gens[task].append(remove_last_block(snake_case_ ) ) return code_gens def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = HfArgumentParser(snake_case_ ) UpperCAmelCase_ = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric UpperCAmelCase_ = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing UpperCAmelCase_ = "false" if args.num_workers is None: UpperCAmelCase_ = multiprocessing.cpu_count() # Use dataset load to feed to accelerate UpperCAmelCase_ = Accelerator() set_seed(args.seed , device_specific=snake_case_ ) # Load model and tokenizer UpperCAmelCase_ = AutoTokenizer.from_pretrained(args.model_ckpt ) UpperCAmelCase_ = tokenizer.eos_token UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings UpperCAmelCase_ = { "do_sample": args.do_sample, "temperature": args.temperature, "max_new_tokens": args.max_new_tokens, "top_p": args.top_p, "top_k": args.top_k, "stopping_criteria": StoppingCriteriaList([EndOfFunctionCriteria(0 , snake_case_ , snake_case_ )] ), } # Load evaluation dataset and metric UpperCAmelCase_ = load_dataset("openai_humaneval" ) UpperCAmelCase_ = load_metric("code_eval" ) UpperCAmelCase_ = args.num_tasks if args.num_tasks is not None else len(human_eval["test"] ) UpperCAmelCase_ = args.n_samples // args.batch_size UpperCAmelCase_ = TokenizedDataset(snake_case_ , human_eval["test"] , n_copies=snake_case_ , n_tasks=snake_case_ ) # do not confuse args.batch_size, which is actually the num_return_sequences UpperCAmelCase_ = DataLoader(snake_case_ , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: UpperCAmelCase_ = code_eval_metric.compute(references=[""] , predictions=[[""]] ) except ValueError as exception: print( "Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL=\"1\"`" " flag to enable code evaluation." ) raise exception UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare(snake_case_ , snake_case_ ) UpperCAmelCase_ = complete_code( snake_case_ , snake_case_ , snake_case_ , snake_case_ , n_tasks=snake_case_ , batch_size=args.batch_size , **snake_case_ , ) if accelerator.is_main_process: UpperCAmelCase_ = [] for task in tqdm(range(snake_case_ ) ): UpperCAmelCase_ = human_eval["test"][task]["test"] UpperCAmelCase_ = f"""check({human_eval["test"][task]["entry_point"]})""" references.append("\n" + test_func + "\n" + entry_point ) # Evaluate completions with "code_eval" metric UpperCAmelCase_ , UpperCAmelCase_ = code_eval_metric.compute( references=snake_case_ , predictions=snake_case_ , num_workers=args.num_workers ) print(f"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , "w" ) as fp: json.dump(snake_case_ , snake_case_ ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
78
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any]=0.999 , snake_case_ : Tuple="cosine" , ) -> Optional[Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase_ = [] for i in range(snake_case_ ): UpperCAmelCase_ = i / num_diffusion_timesteps UpperCAmelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case_ ) / alpha_bar_fn(snake_case_ ) , snake_case_ ) ) return torch.tensor(snake_case_ , dtype=torch.floataa ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : Tuple = [e.name for e in KarrasDiffusionSchedulers] a__ : Optional[Any] = 2 @register_to_config def __init__(self : Union[str, Any] , __a : int = 1000 , __a : float = 0.0_00_85 , __a : float = 0.0_12 , __a : str = "linear" , __a : Optional[Union[np.ndarray, List[float]]] = None , __a : str = "epsilon" , __a : Optional[bool] = False , __a : Optional[bool] = False , __a : float = 1.0 , __a : str = "linspace" , __a : int = 0 , ): if trained_betas is not None: UpperCAmelCase_ = torch.tensor(__a , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase_ = torch.linspace(__a , __a , __a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="cosine" ) elif beta_schedule == "exp": UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) UpperCAmelCase_ = 1.0 - self.betas UpperCAmelCase_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__a , __a , __a ) UpperCAmelCase_ = use_karras_sigmas def _lowercase (self : Optional[Any] , __a : Union[str, Any] , __a : Tuple=None ): if schedule_timesteps is None: UpperCAmelCase_ = self.timesteps UpperCAmelCase_ = (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: UpperCAmelCase_ = 1 if len(__a ) > 1 else 0 else: UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep UpperCAmelCase_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self : List[Any] ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self : Optional[Any] , __a : torch.FloatTensor , __a : Union[float, torch.FloatTensor] , ): UpperCAmelCase_ = self.index_for_timestep(__a ) UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self : Any , __a : int , __a : Union[str, torch.device] = None , __a : Optional[int] = None , ): UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = 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": UpperCAmelCase_ = np.linspace(0 , num_train_timesteps - 1 , __a , dtype=__a )[::-1].copy() elif self.config.timestep_spacing == "leading": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(0 , __a ) * step_ratio).round()[::-1].copy().astype(__a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(__a , 0 , -step_ratio )).round().copy().astype(__a ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) UpperCAmelCase_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) UpperCAmelCase_ = np.log(__a ) UpperCAmelCase_ = np.interp(__a , np.arange(0 , len(__a ) ) , __a ) if self.config.use_karras_sigmas: UpperCAmelCase_ = self._convert_to_karras(in_sigmas=__a , num_inference_steps=self.num_inference_steps ) UpperCAmelCase_ = np.array([self._sigma_to_t(__a , __a ) for sigma in sigmas] ) UpperCAmelCase_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a ) UpperCAmelCase_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) UpperCAmelCase_ = torch.from_numpy(__a ) UpperCAmelCase_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__a ).startswith("mps" ): # mps does not support float64 UpperCAmelCase_ = timesteps.to(__a , dtype=torch.floataa ) else: UpperCAmelCase_ = timesteps.to(device=__a ) # empty dt and derivative UpperCAmelCase_ = None UpperCAmelCase_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter UpperCAmelCase_ = defaultdict(__a ) def _lowercase (self : int , __a : Optional[Any] , __a : List[str] ): # get log sigma UpperCAmelCase_ = np.log(__a ) # get distribution UpperCAmelCase_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range UpperCAmelCase_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) UpperCAmelCase_ = low_idx + 1 UpperCAmelCase_ = log_sigmas[low_idx] UpperCAmelCase_ = log_sigmas[high_idx] # interpolate sigmas UpperCAmelCase_ = (low - log_sigma) / (low - high) UpperCAmelCase_ = np.clip(__a , 0 , 1 ) # transform interpolation to time range UpperCAmelCase_ = (1 - w) * low_idx + w * high_idx UpperCAmelCase_ = t.reshape(sigma.shape ) return t def _lowercase (self : Dict , __a : torch.FloatTensor , __a : Optional[int] ): UpperCAmelCase_ = in_sigmas[-1].item() UpperCAmelCase_ = in_sigmas[0].item() UpperCAmelCase_ = 7.0 # 7.0 is the value used in the paper UpperCAmelCase_ = np.linspace(0 , 1 , __a ) UpperCAmelCase_ = sigma_min ** (1 / rho) UpperCAmelCase_ = sigma_max ** (1 / rho) UpperCAmelCase_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self : List[str] ): return self.dt is None def _lowercase (self : List[Any] , __a : Union[torch.FloatTensor, np.ndarray] , __a : Union[float, torch.FloatTensor] , __a : Union[torch.FloatTensor, np.ndarray] , __a : bool = True , ): UpperCAmelCase_ = self.index_for_timestep(__a ) # advance index counter by 1 UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method UpperCAmelCase_ = self.sigmas[step_index - 1] UpperCAmelCase_ = 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 UpperCAmelCase_ = 0 UpperCAmelCase_ = 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": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": UpperCAmelCase_ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: UpperCAmelCase_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order UpperCAmelCase_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep UpperCAmelCase_ = sigma_next - sigma_hat # store for 2nd order step UpperCAmelCase_ = derivative UpperCAmelCase_ = dt UpperCAmelCase_ = sample else: # 2. 2nd order / Heun's method UpperCAmelCase_ = (sample - pred_original_sample) / sigma_next UpperCAmelCase_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample UpperCAmelCase_ = self.dt UpperCAmelCase_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a ) def _lowercase (self : Any , __a : torch.FloatTensor , __a : torch.FloatTensor , __a : torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples UpperCAmelCase_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__a ): # mps does not support float64 UpperCAmelCase_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) UpperCAmelCase_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: UpperCAmelCase_ = self.timesteps.to(original_samples.device ) UpperCAmelCase_ = timesteps.to(original_samples.device ) UpperCAmelCase_ = [self.index_for_timestep(__a , __a ) for t in timesteps] UpperCAmelCase_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): UpperCAmelCase_ = sigma.unsqueeze(-1 ) UpperCAmelCase_ = original_samples + noise * sigma return noisy_samples def __len__(self : str ): return self.config.num_train_timesteps
78
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = len(snake_case_ ) for i in range(length - 1 ): UpperCAmelCase_ = i for k in range(i + 1 , snake_case_ ): if collection[k] < collection[least]: UpperCAmelCase_ = k if least != i: UpperCAmelCase_ , UpperCAmelCase_ = (collection[i], collection[least]) return collection if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Tuple =input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE_: Tuple =[int(item) for item in user_input.split(',')] print(selection_sort(unsorted))
78
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( UpperCamelCase__ ): a__ : List[str] = """Salesforce/blip-image-captioning-base""" a__ : Optional[Any] = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : str = """image_captioner""" a__ : List[str] = AutoModelForVisionaSeq a__ : int = ["""image"""] a__ : Optional[Any] = ["""text"""] def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*__a , **__a ) def _lowercase (self : Union[str, Any] , __a : "Image" ): return self.pre_processor(images=__a , return_tensors="pt" ) def _lowercase (self : List[str] , __a : Dict ): return self.model.generate(**__a ) def _lowercase (self : int , __a : Optional[Any] ): return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
78
1
'''simple docstring''' import collections import importlib.util import os import re from pathlib import Path SCREAMING_SNAKE_CASE_: Optional[int] ='src/transformers' # Matches is_xxx_available() SCREAMING_SNAKE_CASE_: Any =re.compile(r'is\_([a-z_]*)_available()') # Catches a one-line _import_struct = {xxx} SCREAMING_SNAKE_CASE_: Tuple =re.compile(r'^_import_structure\s+=\s+\{([^\}]+)\}') # Catches a line with a key-values pattern: "bla": ["foo", "bar"] SCREAMING_SNAKE_CASE_: List[str] =re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') # Catches a line if not is_foo_available SCREAMING_SNAKE_CASE_: Optional[Any] =re.compile(r'^\s*if\s+not\s+is\_[a-z_]*\_available\(\)') # Catches a line _import_struct["bla"].append("foo") SCREAMING_SNAKE_CASE_: Tuple =re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') # Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] SCREAMING_SNAKE_CASE_: Tuple =re.compile(r'^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]') # Catches a line with an object between quotes and a comma: "MyModel", SCREAMING_SNAKE_CASE_: List[str] =re.compile('^\s+"([^"]+)",') # Catches a line with objects between brackets only: ["foo", "bar"], SCREAMING_SNAKE_CASE_: str =re.compile('^\s+\[([^\]]+)\]') # Catches a line with from foo import bar, bla, boo SCREAMING_SNAKE_CASE_: List[Any] =re.compile(r'\s+from\s+\S*\s+import\s+([^\(\s].*)\n') # Catches a line with try: SCREAMING_SNAKE_CASE_: List[str] =re.compile(r'^\s*try:') # Catches a line with else: SCREAMING_SNAKE_CASE_: str =re.compile(r'^\s*else:') def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> Union[str, Any]: '''simple docstring''' if _re_test_backend.search(snake_case_ ) is None: return None UpperCAmelCase_ = [b[0] for b in _re_backend.findall(snake_case_ )] backends.sort() return "_and_".join(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' with open(snake_case_ , "r" , encoding="utf-8" , newline="\n" ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = 0 while line_index < len(snake_case_ ) and not lines[line_index].startswith("_import_structure = {" ): line_index += 1 # If this is a traditional init, just return. if line_index >= len(snake_case_ ): return None # First grab the objects without a specific backend in _import_structure UpperCAmelCase_ = [] while not lines[line_index].startswith("if TYPE_CHECKING" ) and find_backend(lines[line_index] ) is None: UpperCAmelCase_ = lines[line_index] # If we have everything on a single line, let's deal with it. if _re_one_line_import_struct.search(snake_case_ ): UpperCAmelCase_ = _re_one_line_import_struct.search(snake_case_ ).groups()[0] UpperCAmelCase_ = re.findall("\[([^\]]+)\]" , snake_case_ ) for imp in imports: objects.extend([obj[1:-1] for obj in imp.split(", " )] ) line_index += 1 continue UpperCAmelCase_ = _re_import_struct_key_value.search(snake_case_ ) if single_line_import_search is not None: UpperCAmelCase_ = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", " ) if len(snake_case_ ) > 0] objects.extend(snake_case_ ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) line_index += 1 UpperCAmelCase_ = {"none": objects} # Let's continue with backend-specific objects in _import_structure while not lines[line_index].startswith("if TYPE_CHECKING" ): # If the line is an if not is_backend_available, we grab all objects associated. UpperCAmelCase_ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCAmelCase_ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCAmelCase_ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 4 ): UpperCAmelCase_ = lines[line_index] if _re_import_struct_add_one.search(snake_case_ ) is not None: objects.append(_re_import_struct_add_one.search(snake_case_ ).groups()[0] ) elif _re_import_struct_add_many.search(snake_case_ ) is not None: UpperCAmelCase_ = _re_import_struct_add_many.search(snake_case_ ).groups()[0].split(", " ) UpperCAmelCase_ = [obj[1:-1] for obj in imports if len(snake_case_ ) > 0] objects.extend(snake_case_ ) elif _re_between_brackets.search(snake_case_ ) is not None: UpperCAmelCase_ = _re_between_brackets.search(snake_case_ ).groups()[0].split(", " ) UpperCAmelCase_ = [obj[1:-1] for obj in imports if len(snake_case_ ) > 0] objects.extend(snake_case_ ) elif _re_quote_object.search(snake_case_ ) is not None: objects.append(_re_quote_object.search(snake_case_ ).groups()[0] ) elif line.startswith(" " * 8 + "\"" ): objects.append(line[9:-3] ) elif line.startswith(" " * 12 + "\"" ): objects.append(line[13:-3] ) line_index += 1 UpperCAmelCase_ = objects else: line_index += 1 # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend UpperCAmelCase_ = [] while ( line_index < len(snake_case_ ) and find_backend(lines[line_index] ) is None and not lines[line_index].startswith("else" ) ): UpperCAmelCase_ = lines[line_index] UpperCAmelCase_ = _re_import.search(snake_case_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 8 ): objects.append(line[8:-2] ) line_index += 1 UpperCAmelCase_ = {"none": objects} # Let's continue with backend-specific objects while line_index < len(snake_case_ ): # If the line is an if is_backend_available, we grab all objects associated. UpperCAmelCase_ = find_backend(lines[line_index] ) # Check if the backend declaration is inside a try block: if _re_try.search(lines[line_index - 1] ) is None: UpperCAmelCase_ = None if backend is not None: line_index += 1 # Scroll until we hit the else block of try-except-else while _re_else.search(lines[line_index] ) is None: line_index += 1 line_index += 1 UpperCAmelCase_ = [] # Until we unindent, add backend objects to the list while len(lines[line_index] ) <= 1 or lines[line_index].startswith(" " * 8 ): UpperCAmelCase_ = lines[line_index] UpperCAmelCase_ = _re_import.search(snake_case_ ) if single_line_import_search is not None: objects.extend(single_line_import_search.groups()[0].split(", " ) ) elif line.startswith(" " * 12 ): objects.append(line[12:-2] ) line_index += 1 UpperCAmelCase_ = objects else: line_index += 1 return import_dict_objects, type_hint_objects def lowerCAmelCase_ ( snake_case_ : List[str] , snake_case_ : Union[str, Any] ) -> Dict: '''simple docstring''' def find_duplicates(snake_case_ : int ): return [k for k, v in collections.Counter(snake_case_ ).items() if v > 1] if list(import_dict_objects.keys() ) != list(type_hint_objects.keys() ): return ["Both sides of the init do not have the same backends!"] UpperCAmelCase_ = [] for key in import_dict_objects.keys(): UpperCAmelCase_ = find_duplicates(import_dict_objects[key] ) if duplicate_imports: errors.append(f"""Duplicate _import_structure definitions for: {duplicate_imports}""" ) UpperCAmelCase_ = find_duplicates(type_hint_objects[key] ) if duplicate_type_hints: errors.append(f"""Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}""" ) if sorted(set(import_dict_objects[key] ) ) != sorted(set(type_hint_objects[key] ) ): UpperCAmelCase_ = "base imports" if key == "none" else f"""{key} backend""" errors.append(f"""Differences for {name}:""" ) for a in type_hint_objects[key]: if a not in import_dict_objects[key]: errors.append(f""" {a} in TYPE_HINT but not in _import_structure.""" ) for a in import_dict_objects[key]: if a not in type_hint_objects[key]: errors.append(f""" {a} in _import_structure but not in TYPE_HINT.""" ) return errors def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = [] for root, _, files in os.walk(snake_case_ ): if "__init__.py" in files: UpperCAmelCase_ = os.path.join(snake_case_ , "__init__.py" ) UpperCAmelCase_ = parse_init(snake_case_ ) if objects is not None: UpperCAmelCase_ = analyze_results(*snake_case_ ) if len(snake_case_ ) > 0: UpperCAmelCase_ = f"""Problem in {fname}, both halves do not define the same objects.\n{errors[0]}""" failures.append("\n".join(snake_case_ ) ) if len(snake_case_ ) > 0: raise ValueError("\n\n".join(snake_case_ ) ) def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = [] for path, directories, files in os.walk(snake_case_ ): for folder in directories: # Ignore private modules if folder.startswith("_" ): directories.remove(snake_case_ ) continue # Ignore leftovers from branches (empty folders apart from pycache) if len(list((Path(snake_case_ ) / folder).glob("*.py" ) ) ) == 0: continue UpperCAmelCase_ = str((Path(snake_case_ ) / folder).relative_to(snake_case_ ) ) UpperCAmelCase_ = short_path.replace(os.path.sep , "." ) submodules.append(snake_case_ ) for fname in files: if fname == "__init__.py": continue UpperCAmelCase_ = str((Path(snake_case_ ) / fname).relative_to(snake_case_ ) ) UpperCAmelCase_ = short_path.replace(".py" , "" ).replace(os.path.sep , "." ) if len(submodule.split("." ) ) == 1: submodules.append(snake_case_ ) return submodules SCREAMING_SNAKE_CASE_: Tuple =[ 'convert_pytorch_checkpoint_to_tf2', 'modeling_flax_pytorch_utils', ] def lowerCAmelCase_ ( ) -> Any: '''simple docstring''' UpperCAmelCase_ = importlib.util.spec_from_file_location( "transformers" , os.path.join(snake_case_ , "__init__.py" ) , submodule_search_locations=[PATH_TO_TRANSFORMERS] , ) UpperCAmelCase_ = spec.loader.load_module() UpperCAmelCase_ = [ module for module in get_transformers_submodules() if module not in IGNORE_SUBMODULES and module not in transformers._import_structure.keys() ] if len(snake_case_ ) > 0: UpperCAmelCase_ = "\n".join(f"""- {module}""" for module in module_not_registered ) raise ValueError( "The following submodules are not properly registered in the main init of Transformers:\n" f"""{list_of_modules}\n""" "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." ) if __name__ == "__main__": check_all_inits() check_submodules()
78
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
1
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __A : a__ : int a__ : TreeNode | None = None a__ : TreeNode | None = None SCREAMING_SNAKE_CASE_: Union[str, Any] =namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase_ ( snake_case_ : TreeNode | None ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case_ ) != count_coins(snake_case_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(snake_case_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.left ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.right ) UpperCAmelCase_ = 1 - left_distrib_excess UpperCAmelCase_ = 1 - right_distrib_excess UpperCAmelCase_ = ( left_distrib_moves + right_distrib_moves + abs(snake_case_ ) + abs(snake_case_ ) ) UpperCAmelCase_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case_ , snake_case_ ) return get_distrib(snake_case_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
78
'''simple docstring''' import copy import re class __A : a__ : Optional[int] = """hp""" a__ : Optional[Any] = {} a__ : List[Any] = None @classmethod def _lowercase (cls : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = prefix UpperCAmelCase_ = defaults cls.build_naming_info() @staticmethod def _lowercase (__a : List[Any] , __a : List[str] ): if len(__a ) == 0: return "" UpperCAmelCase_ = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__a ) + 1 ): UpperCAmelCase_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__a : Union[str, Any] ): UpperCAmelCase_ = "" while integer != 0: UpperCAmelCase_ = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase_ = 0 while True: UpperCAmelCase_ = word + "#" + int_to_alphabetic(__a ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase_ = sword break UpperCAmelCase_ = short_word UpperCAmelCase_ = word return short_word @staticmethod def _lowercase (__a : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = param_name.split("_" ) UpperCAmelCase_ = [TrialShortNamer.shortname_for_word(__a , __a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase_ = ["", "_"] for separator in separators: UpperCAmelCase_ = separator.join(__a ) if shortname not in info["reverse_short_param"]: UpperCAmelCase_ = shortname UpperCAmelCase_ = param_name return shortname return param_name @staticmethod def _lowercase (__a : int , __a : Union[str, Any] ): UpperCAmelCase_ = TrialShortNamer.shortname_for_key(__a , __a ) UpperCAmelCase_ = short_name UpperCAmelCase_ = param_name @classmethod def _lowercase (cls : Any ): if cls.NAMING_INFO is not None: return UpperCAmelCase_ = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } UpperCAmelCase_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__a , __a ) UpperCAmelCase_ = info @classmethod def _lowercase (cls : int , __a : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase_ = cls.NAMING_INFO["short_param"][k] if isinstance(__a , __a ): UpperCAmelCase_ = 1 if v else 0 UpperCAmelCase_ = "" if isinstance(__a , (int, float) ) else "-" UpperCAmelCase_ = f"""{key}{sep}{v}""" name.append(__a ) return "_".join(__a ) @classmethod def _lowercase (cls : Dict , __a : Dict ): UpperCAmelCase_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase_ = [] else: UpperCAmelCase_ = repr.split("_" ) UpperCAmelCase_ = {} for value in values: if "-" in value: UpperCAmelCase_ , UpperCAmelCase_ = value.split("-" ) else: UpperCAmelCase_ = re.sub("[0-9.]" , "" , __a ) UpperCAmelCase_ = float(re.sub("[^0-9.]" , "" , __a ) ) UpperCAmelCase_ = cls.NAMING_INFO["reverse_short_param"][p_k] UpperCAmelCase_ = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase_ = cls.DEFAULTS[k] return parameters
78
1
'''simple docstring''' from typing import List, Optional from tokenizers import ByteLevelBPETokenizer from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_blenderbot_small import BlenderbotSmallTokenizer SCREAMING_SNAKE_CASE_: List[str] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Optional[int] ={ 'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_config_file': 'tokenizer_config.json', } SCREAMING_SNAKE_CASE_: Optional[int] ={ 'vocab_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/vocab.json' }, 'merges_file': { 'facebook/blenderbot_small-90M': 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/merges.txt' }, 'tokenizer_config_file': { 'facebook/blenderbot_small-90M': ( 'https://huggingface.co/facebook/blenderbot_small-90M/resolve/main/tokenizer_config.json' ) }, } SCREAMING_SNAKE_CASE_: Union[str, Any] ={ 'facebook/blenderbot_small-90M': 5_12, } class __A ( UpperCamelCase__ ): a__ : Tuple = VOCAB_FILES_NAMES a__ : Any = PRETRAINED_VOCAB_FILES_MAP a__ : Union[str, Any] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : List[Any] = BlenderbotSmallTokenizer def __init__(self : int , __a : Dict=None , __a : int=None , __a : Union[str, Any]="<|endoftext|>" , __a : Any="<|endoftext|>" , __a : Any="<|endoftext|>" , __a : List[str]=False , __a : Optional[int]=True , **__a : Optional[int] , ): super().__init__( ByteLevelBPETokenizer( vocab=__a , merges=__a , add_prefix_space=__a , trim_offsets=__a , ) , bos_token=__a , eos_token=__a , unk_token=__a , **__a , ) UpperCAmelCase_ = add_prefix_space def _lowercase (self : List[str] , __a : str , __a : List[str]=None ): UpperCAmelCase_ = [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 _lowercase (self : Dict , __a : List[int] , __a : Optional[List[int]] = None ): UpperCAmelCase_ = [self.sep_token_id] UpperCAmelCase_ = [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]
78
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ = do_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
1
'''simple docstring''' import re import time from typing import Optional import IPython.display as disp from ..trainer_callback import TrainerCallback from ..trainer_utils import IntervalStrategy, has_length def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = int(snake_case_ ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = t // 36_00, (t // 60) % 60, t % 60 return f"""{h}:{m:02d}:{s:02d}""" if h != 0 else f"""{m:02d}:{s:02d}""" def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Dict , snake_case_ : Optional[Any] , snake_case_ : Optional[Any] , snake_case_ : int=3_00 ) -> str: '''simple docstring''' return f""" <div> {prefix} <progress value='{value}' max='{total}' style='width:{width}px; height:20px; vertical-align: middle;'></progress> {label} </div> """ def lowerCAmelCase_ ( snake_case_ : List[str] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = "<table border=\"1\" class=\"dataframe\">\n" html_code += """ <thead>\n <tr style="text-align: left;">\n""" for i in items[0]: html_code += f""" <th>{i}</th>\n""" html_code += " </tr>\n </thead>\n <tbody>\n" for line in items[1:]: html_code += " <tr>\n" for elt in line: UpperCAmelCase_ = f"""{elt:.6f}""" if isinstance(snake_case_ , snake_case_ ) else str(snake_case_ ) html_code += f""" <td>{elt}</td>\n""" html_code += " </tr>\n" html_code += " </tbody>\n</table><p>" return html_code class __A : a__ : Dict = 5 a__ : Any = 0.2 def __init__(self : Optional[Any] , __a : int , __a : Optional[str] = None , __a : bool = True , __a : Optional["NotebookTrainingTracker"] = None , __a : int = 300 , ): UpperCAmelCase_ = total UpperCAmelCase_ = "" if prefix is None else prefix UpperCAmelCase_ = leave UpperCAmelCase_ = parent UpperCAmelCase_ = width UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : str , __a : int , __a : bool = False , __a : str = None ): UpperCAmelCase_ = value if comment is not None: UpperCAmelCase_ = comment if self.last_value is None: UpperCAmelCase_ = UpperCAmelCase_ = time.time() UpperCAmelCase_ = UpperCAmelCase_ = value UpperCAmelCase_ = UpperCAmelCase_ = None UpperCAmelCase_ = self.warmup UpperCAmelCase_ = 1 self.update_bar(__a ) elif value <= self.last_value and not force_update: return elif force_update or self.first_calls > 0 or value >= min(self.last_value + self.wait_for , self.total ): if self.first_calls > 0: self.first_calls -= 1 UpperCAmelCase_ = time.time() UpperCAmelCase_ = current_time - self.start_time # We could have value = self.start_value if the update is called twixe with the same start value. if value > self.start_value: UpperCAmelCase_ = self.elapsed_time / (value - self.start_value) else: UpperCAmelCase_ = None if value >= self.total: UpperCAmelCase_ = self.total UpperCAmelCase_ = None if not self.leave: self.close() elif self.average_time_per_item is not None: UpperCAmelCase_ = self.average_time_per_item * (self.total - value) self.update_bar(__a ) UpperCAmelCase_ = value UpperCAmelCase_ = current_time if self.average_time_per_item is None: UpperCAmelCase_ = 1 else: UpperCAmelCase_ = max(int(self.update_every / self.average_time_per_item ) , 1 ) def _lowercase (self : Optional[int] , __a : Tuple , __a : List[Any]=None ): UpperCAmelCase_ = " " * (len(str(self.total ) ) - len(str(__a ) )) + str(__a ) if self.elapsed_time is None: UpperCAmelCase_ = f"""[{spaced_value}/{self.total} : < :""" elif self.predicted_remaining is None: UpperCAmelCase_ = f"""[{spaced_value}/{self.total} {format_time(self.elapsed_time )}""" else: UpperCAmelCase_ = ( f"""[{spaced_value}/{self.total} {format_time(self.elapsed_time )} <""" f""" {format_time(self.predicted_remaining )}""" ) self.label += f""", {1/self.average_time_per_item:.2f} it/s""" self.label += "]" if self.comment is None or len(self.comment ) == 0 else f""", {self.comment}]""" self.display() def _lowercase (self : Dict ): UpperCAmelCase_ = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width ) if self.parent is not None: # If this is a child bar, the parent will take care of the display. self.parent.display() return if self.output is None: UpperCAmelCase_ = disp.display(disp.HTML(self.html_code ) , display_id=__a ) else: self.output.update(disp.HTML(self.html_code ) ) def _lowercase (self : Optional[Any] ): if self.parent is None and self.output is not None: self.output.update(disp.HTML("" ) ) class __A ( UpperCamelCase__ ): def __init__(self : List[Any] , __a : List[Any] , __a : Dict=None ): super().__init__(__a ) UpperCAmelCase_ = None if column_names is None else [column_names] UpperCAmelCase_ = None def _lowercase (self : str ): UpperCAmelCase_ = html_progress_bar(self.value , self.total , self.prefix , self.label , self.width ) if self.inner_table is not None: self.html_code += text_to_html_table(self.inner_table ) if self.child_bar is not None: self.html_code += self.child_bar.html_code if self.output is None: UpperCAmelCase_ = disp.display(disp.HTML(self.html_code ) , display_id=__a ) else: self.output.update(disp.HTML(self.html_code ) ) def _lowercase (self : List[str] , __a : Union[str, Any] ): if self.inner_table is None: UpperCAmelCase_ = [list(values.keys() ), list(values.values() )] else: UpperCAmelCase_ = self.inner_table[0] if len(self.inner_table ) == 1: # We give a chance to update the column names at the first iteration for key in values.keys(): if key not in columns: columns.append(__a ) UpperCAmelCase_ = columns self.inner_table.append([values[c] for c in columns] ) def _lowercase (self : Dict , __a : Optional[int] , __a : int=None , __a : int=300 ): UpperCAmelCase_ = NotebookProgressBar(__a , prefix=__a , parent=self , width=__a ) return self.child_bar def _lowercase (self : Dict ): UpperCAmelCase_ = None self.display() class __A ( UpperCamelCase__ ): def __init__(self : Dict ): UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = False def _lowercase (self : int , __a : Optional[Any] , __a : Any , __a : List[str] , **__a : Union[str, Any] ): UpperCAmelCase_ = "Epoch" if args.evaluation_strategy == IntervalStrategy.EPOCH else "Step" UpperCAmelCase_ = 0 UpperCAmelCase_ = 0 UpperCAmelCase_ = [self.first_column] + ["Training Loss"] if args.evaluation_strategy != IntervalStrategy.NO: column_names.append("Validation Loss" ) UpperCAmelCase_ = NotebookTrainingTracker(state.max_steps , __a ) def _lowercase (self : Union[str, Any] , __a : str , __a : Dict , __a : Dict , **__a : List[Any] ): UpperCAmelCase_ = int(state.epoch ) if int(state.epoch ) == state.epoch else f"""{state.epoch:.2f}""" self.training_tracker.update( state.global_step + 1 , comment=f"""Epoch {epoch}/{state.num_train_epochs}""" , force_update=self._force_next_update , ) UpperCAmelCase_ = False def _lowercase (self : List[Any] , __a : str , __a : Optional[Any] , __a : Optional[int] , __a : Tuple=None , **__a : List[str] ): if not has_length(__a ): return if self.prediction_bar is None: if self.training_tracker is not None: UpperCAmelCase_ = self.training_tracker.add_child(len(__a ) ) else: UpperCAmelCase_ = NotebookProgressBar(len(__a ) ) self.prediction_bar.update(1 ) else: self.prediction_bar.update(self.prediction_bar.value + 1 ) def _lowercase (self : int , __a : List[str] , __a : Union[str, Any] , __a : Optional[int] , **__a : Tuple ): if self.prediction_bar is not None: self.prediction_bar.close() UpperCAmelCase_ = None def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : Any , __a : List[Any] , __a : Tuple=None , **__a : List[Any] ): # Only for when there is no evaluation if args.evaluation_strategy == IntervalStrategy.NO and "loss" in logs: UpperCAmelCase_ = {"Training Loss": logs["loss"]} # First column is necessarily Step sine we're not in epoch eval strategy UpperCAmelCase_ = state.global_step self.training_tracker.write_line(__a ) def _lowercase (self : Optional[int] , __a : str , __a : Tuple , __a : Optional[int] , __a : Union[str, Any]=None , **__a : List[Any] ): if self.training_tracker is not None: UpperCAmelCase_ = {"Training Loss": "No log", "Validation Loss": "No log"} for log in reversed(state.log_history ): if "loss" in log: UpperCAmelCase_ = log["loss"] break if self.first_column == "Epoch": UpperCAmelCase_ = int(state.epoch ) else: UpperCAmelCase_ = state.global_step UpperCAmelCase_ = "eval" for k in metrics: if k.endswith("_loss" ): UpperCAmelCase_ = re.sub(r"\_loss$" , "" , __a ) UpperCAmelCase_ = metrics.pop("total_flos" , __a ) UpperCAmelCase_ = metrics.pop("epoch" , __a ) UpperCAmelCase_ = metrics.pop(f"""{metric_key_prefix}_runtime""" , __a ) UpperCAmelCase_ = metrics.pop(f"""{metric_key_prefix}_samples_per_second""" , __a ) UpperCAmelCase_ = metrics.pop(f"""{metric_key_prefix}_steps_per_second""" , __a ) UpperCAmelCase_ = metrics.pop(f"""{metric_key_prefix}_jit_compilation_time""" , __a ) for k, v in metrics.items(): if k == f"""{metric_key_prefix}_loss""": UpperCAmelCase_ = v else: UpperCAmelCase_ = k.split("_" ) UpperCAmelCase_ = " ".join([part.capitalize() for part in splits[1:]] ) UpperCAmelCase_ = v self.training_tracker.write_line(__a ) self.training_tracker.remove_child() UpperCAmelCase_ = None # Evaluation takes a long time so we should force the next update. UpperCAmelCase_ = True def _lowercase (self : Dict , __a : Dict , __a : Any , __a : Optional[Any] , **__a : Union[str, Any] ): self.training_tracker.update( state.global_step , comment=f"""Epoch {int(state.epoch )}/{state.num_train_epochs}""" , force_update=__a ) UpperCAmelCase_ = None
78
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
1
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ = do_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' import random import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, UNetaDConditionModel, VideoToVideoSDPipeline, ) from diffusers.utils import floats_tensor, is_xformers_available, skip_mps from diffusers.utils.testing_utils import enable_full_determinism, slow, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() @skip_mps class __A ( UpperCamelCase__ , unittest.TestCase ): a__ : Union[str, Any] = VideoToVideoSDPipeline a__ : int = TEXT_GUIDED_IMAGE_VARIATION_PARAMS.union({"""video"""} ) - {"""image""", """width""", """height"""} a__ : Dict = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"""video"""} ) - {"""image"""} a__ : Any = PipelineTesterMixin.required_optional_params - {"""latents"""} a__ : Any = False # No `output_type`. a__ : Union[str, Any] = frozenset( [ """num_inference_steps""", """generator""", """latents""", """return_dict""", """callback""", """callback_steps""", ] ) def _lowercase (self : List[Any] ): torch.manual_seed(0 ) UpperCAmelCase_ = UNetaDConditionModel( block_out_channels=(32, 64, 64, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "CrossAttnDownBlock3D", "DownBlock3D") , up_block_types=("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D") , cross_attention_dim=32 , attention_head_dim=4 , ) UpperCAmelCase_ = DDIMScheduler( beta_start=0.0_00_85 , beta_end=0.0_12 , beta_schedule="scaled_linear" , clip_sample=__a , set_alpha_to_one=__a , ) torch.manual_seed(0 ) UpperCAmelCase_ = 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_ = 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 , ) UpperCAmelCase_ = CLIPTextModel(__a ) UpperCAmelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) UpperCAmelCase_ = { "unet": unet, "scheduler": scheduler, "vae": vae, "text_encoder": text_encoder, "tokenizer": tokenizer, } return components def _lowercase (self : List[Any] , __a : Optional[int] , __a : Tuple=0 ): # 3 frames UpperCAmelCase_ = floats_tensor((1, 3, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) if str(__a ).startswith("mps" ): UpperCAmelCase_ = torch.manual_seed(__a ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(__a ) UpperCAmelCase_ = { "prompt": "A painting of a squirrel eating a burger", "video": video, "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "pt", } return inputs def _lowercase (self : Tuple ): UpperCAmelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = VideoToVideoSDPipeline(**__a ) UpperCAmelCase_ = sd_pipe.to(__a ) sd_pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_dummy_inputs(__a ) UpperCAmelCase_ = "np" UpperCAmelCase_ = sd_pipe(**__a ).frames UpperCAmelCase_ = frames[0][-3:, -3:, -1] assert frames[0].shape == (32, 32, 3) UpperCAmelCase_ = np.array([106, 117, 113, 174, 137, 112, 148, 151, 131] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _lowercase (self : List[Any] ): self._test_xformers_attention_forwardGenerator_pass(test_mean_pixel_difference=__a , expected_max_diff=5E-3 ) @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _lowercase (self : List[Any] ): pass @unittest.skip(reason="Batching needs to be properly figured out first for this pipeline." ) def _lowercase (self : Optional[Any] ): pass @unittest.skip(reason="`num_images_per_prompt` argument is not supported for this pipeline." ) def _lowercase (self : str ): pass def _lowercase (self : Optional[Any] ): return super().test_progress_bar() @slow @skip_mps class __A ( unittest.TestCase ): def _lowercase (self : str ): UpperCAmelCase_ = VideoToVideoSDPipeline.from_pretrained("cerspense/zeroscope_v2_XL" , torch_dtype=torch.floataa ) pipe.enable_model_cpu_offload() # 10 frames UpperCAmelCase_ = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCAmelCase_ = torch.randn((1, 10, 3, 1024, 576) , generator=__a ) UpperCAmelCase_ = video.to("cuda" ) UpperCAmelCase_ = "Spiderman is surfing" UpperCAmelCase_ = pipe(__a , video=__a , generator=__a , num_inference_steps=3 , output_type="pt" ).frames UpperCAmelCase_ = np.array([-1.0_45_89_84, -1.1_27_92_97, -0.9_66_30_86, -0.91_50_39_06, -0.75_09_76_56] ) assert np.abs(video_frames.cpu().numpy()[0, 0, 0, 0, -5:] - expected_array ).sum() < 1E-2
78
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) -> Union[str, Any]: '''simple docstring''' if b == 0: return 1 if (b % 2) == 0: return actual_power(snake_case_ , int(b / 2 ) ) * actual_power(snake_case_ , int(b / 2 ) ) else: return a * actual_power(snake_case_ , int(b / 2 ) ) * actual_power(snake_case_ , int(b / 2 ) ) def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : int ) -> float: '''simple docstring''' if b < 0: return 1 / actual_power(snake_case_ , snake_case_ ) return actual_power(snake_case_ , snake_case_ ) if __name__ == "__main__": print(power(-2, -3))
78
'''simple docstring''' import requests def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None: '''simple docstring''' UpperCAmelCase_ = {"Content-Type": "application/json"} UpperCAmelCase_ = requests.post(snake_case_ , json={"text": message_body} , headers=snake_case_ ) if response.status_code != 2_00: UpperCAmelCase_ = ( "Request to slack returned an error " f"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(snake_case_ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
78
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import BlenderbotConfig, BlenderbotTokenizer, is_tf_available from transformers.testing_utils import require_tf, require_tokenizers, slow from transformers.utils import cached_property from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotForConditionalGeneration, TFBlenderbotModel @require_tf class __A : a__ : Optional[int] = BlenderbotConfig a__ : List[str] = {} a__ : Optional[Any] = """gelu""" def __init__(self : Tuple , __a : int , __a : List[str]=13 , __a : Union[str, Any]=7 , __a : List[str]=True , __a : str=False , __a : Union[str, Any]=99 , __a : Union[str, Any]=32 , __a : List[str]=2 , __a : List[Any]=4 , __a : List[str]=37 , __a : Optional[Any]=0.1 , __a : str=0.1 , __a : Dict=20 , __a : str=2 , __a : List[str]=1 , __a : Tuple=0 , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = seq_length UpperCAmelCase_ = is_training UpperCAmelCase_ = use_labels UpperCAmelCase_ = vocab_size UpperCAmelCase_ = hidden_size UpperCAmelCase_ = num_hidden_layers UpperCAmelCase_ = num_attention_heads UpperCAmelCase_ = intermediate_size UpperCAmelCase_ = hidden_dropout_prob UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = max_position_embeddings UpperCAmelCase_ = eos_token_id UpperCAmelCase_ = pad_token_id UpperCAmelCase_ = bos_token_id def _lowercase (self : Tuple ): UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length - 1] , self.vocab_size ) UpperCAmelCase_ = tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size ) , 1 ) UpperCAmelCase_ = tf.concat([input_ids, eos_tensor] , axis=1 ) UpperCAmelCase_ = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) UpperCAmelCase_ = self.config_cls( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , eos_token_ids=[2] , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , decoder_start_token_id=self.pad_token_id , **self.config_updates , ) UpperCAmelCase_ = prepare_blenderbot_inputs_dict(__a , __a , __a ) return config, inputs_dict def _lowercase (self : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = TFBlenderbotModel(config=__a ).get_decoder() UpperCAmelCase_ = inputs_dict["input_ids"] UpperCAmelCase_ = input_ids[:1, :] UpperCAmelCase_ = inputs_dict["attention_mask"][:1, :] UpperCAmelCase_ = inputs_dict["head_mask"] UpperCAmelCase_ = 1 # first forward pass UpperCAmelCase_ = model(__a , attention_mask=__a , head_mask=__a , use_cache=__a ) UpperCAmelCase_ , UpperCAmelCase_ = outputs.to_tuple() # create hypothetical next token and extent to next_input_ids UpperCAmelCase_ = ids_tensor((self.batch_size, 3) , config.vocab_size ) UpperCAmelCase_ = tf.cast(ids_tensor((self.batch_size, 3) , 2 ) , tf.inta ) # append to next input_ids and UpperCAmelCase_ = tf.concat([input_ids, next_tokens] , axis=-1 ) UpperCAmelCase_ = tf.concat([attention_mask, next_attn_mask] , axis=-1 ) UpperCAmelCase_ = model(__a , attention_mask=__a )[0] UpperCAmelCase_ = model(__a , attention_mask=__a , past_key_values=__a )[0] self.parent.assertEqual(next_tokens.shape[1] , output_from_past.shape[1] ) # select random slice UpperCAmelCase_ = int(ids_tensor((1,) , output_from_past.shape[-1] ) ) UpperCAmelCase_ = output_from_no_past[:, -3:, random_slice_idx] UpperCAmelCase_ = output_from_past[:, :, random_slice_idx] # test that outputs are equal for slice tf.debugging.assert_near(__a , __a , rtol=1E-3 ) def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : str , snake_case_ : Any , snake_case_ : Tuple=None , snake_case_ : Tuple=None , snake_case_ : Union[str, Any]=None , snake_case_ : Optional[Any]=None , snake_case_ : Any=None , ) -> List[Any]: '''simple docstring''' if attention_mask is None: UpperCAmelCase_ = tf.cast(tf.math.not_equal(snake_case_ , config.pad_token_id ) , tf.inta ) if decoder_attention_mask is None: UpperCAmelCase_ = tf.concat( [ tf.ones(decoder_input_ids[:, :1].shape , dtype=tf.inta ), tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:] , config.pad_token_id ) , tf.inta ), ] , axis=-1 , ) if head_mask is None: UpperCAmelCase_ = tf.ones((config.encoder_layers, config.encoder_attention_heads) ) if decoder_head_mask is None: UpperCAmelCase_ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) if cross_attn_head_mask is None: UpperCAmelCase_ = tf.ones((config.decoder_layers, config.decoder_attention_heads) ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": decoder_attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } @require_tf class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : List[Any] = (TFBlenderbotForConditionalGeneration, TFBlenderbotModel) if is_tf_available() else () a__ : int = (TFBlenderbotForConditionalGeneration,) if is_tf_available() else () a__ : Any = ( { """conversational""": TFBlenderbotForConditionalGeneration, """feature-extraction""": TFBlenderbotModel, """summarization""": TFBlenderbotForConditionalGeneration, """text2text-generation""": TFBlenderbotForConditionalGeneration, """translation""": TFBlenderbotForConditionalGeneration, } if is_tf_available() else {} ) a__ : Dict = True a__ : Union[str, Any] = False a__ : Union[str, Any] = False def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = TFBlenderbotModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__a ) def _lowercase (self : Any ): self.config_tester.run_common_tests() def _lowercase (self : Dict ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_decoder_model_past_large_inputs(*__a ) @require_tokenizers @require_tf class __A ( unittest.TestCase ): a__ : Tuple = ["""My friends are cool but they eat too many carbs."""] a__ : Tuple = """facebook/blenderbot-400M-distill""" @cached_property def _lowercase (self : Any ): return BlenderbotTokenizer.from_pretrained(self.model_name ) @cached_property def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name ) return model @slow def _lowercase (self : int ): UpperCAmelCase_ = self.tokenizer(self.src_text , return_tensors="tf" ) UpperCAmelCase_ = self.model.generate( model_inputs.input_ids , ) UpperCAmelCase_ = self.tokenizer.batch_decode(generated_ids.numpy() , skip_special_tokens=__a )[0] assert ( generated_words == " That's unfortunate. Are they trying to lose weight or are they just trying to be healthier?" )
78
'''simple docstring''' from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : CLIPSegForImageSegmentation , __a : CLIPSegProcessor , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = 1 UpperCAmelCase_ = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = True UpperCAmelCase_ = FrozenDict(__a ) if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _lowercase (self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _lowercase (self : int ): self.enable_attention_slicing(__a ) def _lowercase (self : Optional[Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : Optional[int] ): if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_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() def __call__(self : Dict , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, PIL.Image.Image] , __a : str , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): UpperCAmelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) UpperCAmelCase_ = self.segmentation_model(**__a ) UpperCAmelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCAmelCase_ = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCAmelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
78
1
'''simple docstring''' from collections import deque from .hash_table import HashTable class __A ( UpperCamelCase__ ): def __init__(self : int , *__a : Any , **__a : Union[str, Any] ): super().__init__(*__a , **__a ) def _lowercase (self : Optional[Any] , __a : Optional[int] , __a : List[Any] ): UpperCAmelCase_ = deque([] ) if self.values[key] is None else self.values[key] self.values[key].appendleft(__a ) UpperCAmelCase_ = self.values[key] def _lowercase (self : Dict ): return ( sum(self.charge_factor - len(__a ) for slot in self.values ) / self.size_table * self.charge_factor ) def _lowercase (self : int , __a : Tuple , __a : Optional[int]=None ): if not ( len(self.values[key] ) == self.charge_factor and self.values.count(__a ) == 0 ): return key return super()._collision_resolution(__a , __a )
78
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' if number < 0: raise ValueError("number must not be negative" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' import argparse import json import os from collections import OrderedDict import numpy as np import tensorflow as tf import torch def lowerCAmelCase_ ( snake_case_ : List[str] ) -> str: '''simple docstring''' UpperCAmelCase_ = os.path.join(args.tf_model_dir , "parameters.json" ) UpperCAmelCase_ = json.loads(open(snake_case_ ).read() ) if not params: raise ValueError( f"""It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file.""" ) if not args.output.endswith(".pt" ): UpperCAmelCase_ = args.output + ".pt" UpperCAmelCase_ = OrderedDict() with tf.device("/CPU:0" ): UpperCAmelCase_ = tf.train.load_checkpoint(args.tf_model_dir ) UpperCAmelCase_ = reader.get_variable_to_shape_map() for key_name in shapes.keys(): UpperCAmelCase_ = reader.get_tensor(snake_case_ ).astype(np.floataa ) if key_name.endswith("/adam_m" ) or key_name.endswith("/adam_v" ): continue if key_name.startswith("pasts/" ): if key_name.startswith("pasts/mlp" ): UpperCAmelCase_ = int(key_name[9] ) elif key_name.startswith("pasts/out" ): UpperCAmelCase_ = 8 UpperCAmelCase_ = "model.sqout.%d.weight" % (player * 2) # enter to nn.Sequencial with Tanh, so 2 at a time UpperCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.startswith("model/moe" ): UpperCAmelCase_ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/switch_gating/kernel" ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.mlp.router.classifier.weight" % player UpperCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.endswith("/softmlp/kernel" ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.soft_bypass_mlp.weight" % player UpperCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.endswith("/wo/kernel" ) or key_name.endswith("/wi/kernel" ): UpperCAmelCase_ = key_name[-9:-7] for i in range(16 ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight" % (player, i, nlayer) UpperCAmelCase_ = ( vnp[i].transpose([1, 0] ).copy() ) # In Mesh-Tensorflow, it is one array, so it is divided UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.startswith("model/mlp" ): UpperCAmelCase_ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/p1/kernel" ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.mlp.wi.weight" % player UpperCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.endswith("/p1/bias" ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.mlp.wi.bias" % player UpperCAmelCase_ = vnp.copy() # same because it is one dimensional UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.endswith("/p2/kernel" ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.mlp.wo.weight" % player UpperCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.endswith("/p2/bias" ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.mlp.wo.bias" % player UpperCAmelCase_ = vnp.copy() # same because it is one dimensional UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.startswith("model/ln" ): UpperCAmelCase_ = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.norm.bias" % player UpperCAmelCase_ = vnp.copy() # same because it is one dimensional UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.endswith("/g" ): UpperCAmelCase_ = "model.blocks.%d.feed_forward.norm.weight" % player UpperCAmelCase_ = vnp.copy() # same because it is one dimensional UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.startswith("model/att" ): UpperCAmelCase_ = int(key_name[9:].split("/" )[0] ) if key_name.endswith("/qkv/kernel" ): UpperCAmelCase_ = vnp.copy() # Compute same dimension as Mesh-tensorflow using einsum UpperCAmelCase_ = state[:, 0, :, :] UpperCAmelCase_ = state[:, 1, :, :] UpperCAmelCase_ = state[:, 2, :, :] UpperCAmelCase_ = ( state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = ( state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = ( state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]] ) .transpose([1, 0] ) .copy() ) # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = "model.blocks.%d.self_attn.self_attn.q_proj.weight" % player UpperCAmelCase_ = torch.tensor(snake_case_ ) UpperCAmelCase_ = "model.blocks.%d.self_attn.self_attn.k_proj.weight" % player UpperCAmelCase_ = torch.tensor(snake_case_ ) UpperCAmelCase_ = "model.blocks.%d.self_attn.self_attn.v_proj.weight" % player UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.endswith("/o/kernel" ): UpperCAmelCase_ = "model.blocks.%d.self_attn.self_attn.out_proj.weight" % player UpperCAmelCase_ = ( vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]] ).transpose([1, 0] ).copy() ) # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.startswith("model/an" ): UpperCAmelCase_ = int(key_name[8:].split("/" )[0] ) if key_name.endswith("/b" ): UpperCAmelCase_ = "model.blocks.%d.self_attn.norm.bias" % player UpperCAmelCase_ = vnp.copy() # same because it is one dimensional UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.endswith("/g" ): UpperCAmelCase_ = "model.blocks.%d.self_attn.norm.weight" % player UpperCAmelCase_ = vnp.copy() # same because it is one dimensional UpperCAmelCase_ = torch.tensor(snake_case_ ) elif ( key_name.startswith("model/wte" ) or key_name.startswith("model/wpe" ) or key_name.startswith("model/ete" ) ): UpperCAmelCase_ = {"wte": "embed_tokens", "wpe": "position_embeddings", "ete": "extra_position_embeddings"}[ key_name[-3:] ] UpperCAmelCase_ = "model.%s.weight" % nlayer UpperCAmelCase_ = vnp.copy() # same in embedded UpperCAmelCase_ = torch.tensor(snake_case_ ) if key_name.startswith("model/wte" ): UpperCAmelCase_ = "lm_head.weight" UpperCAmelCase_ = vnp.copy() # same in embedded UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name.startswith("model/wob" ): UpperCAmelCase_ = "final_logits_bias" UpperCAmelCase_ = vnp.copy() # same in embedded UpperCAmelCase_ = state.reshape((1, -1) ) UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name == "model/dense/kernel": UpperCAmelCase_ = "model.last_project.weight" UpperCAmelCase_ = vnp.transpose([1, 0] ).copy() # Mesh-Tensorflow is a diagonal matrix UpperCAmelCase_ = torch.tensor(snake_case_ ) elif key_name == "model/dense_1/bias": UpperCAmelCase_ = "model.last_project.bias" UpperCAmelCase_ = vnp.copy() # same because it is one dimensional UpperCAmelCase_ = torch.tensor(snake_case_ ) torch.save(snake_case_ , args.output ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Union[str, Any] =argparse.ArgumentParser( description='model converter.', formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--tf_model_dir', metavar='PATH', type=str, required=True, help='import model') parser.add_argument('--output', metavar='PATH', type=str, required=True, help='output model') SCREAMING_SNAKE_CASE_: Any =parser.parse_args() convert_tf_gptsan_to_pt(args)
78
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __A : a__ : int a__ : TreeNode | None = None a__ : TreeNode | None = None SCREAMING_SNAKE_CASE_: Union[str, Any] =namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase_ ( snake_case_ : TreeNode | None ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case_ ) != count_coins(snake_case_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(snake_case_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.left ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.right ) UpperCAmelCase_ = 1 - left_distrib_excess UpperCAmelCase_ = 1 - right_distrib_excess UpperCAmelCase_ = ( left_distrib_moves + right_distrib_moves + abs(snake_case_ ) + abs(snake_case_ ) ) UpperCAmelCase_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case_ , snake_case_ ) return get_distrib(snake_case_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' import warnings from typing import Dict, List, Optional, Tuple from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE_: Dict =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : List[Any] = ["""input_ids""", """attention_mask"""] def __init__(self : Optional[Any] , __a : int="</s>" , __a : Optional[Any]="<unk>" , __a : str="<pad>" , __a : Dict=125 , __a : Optional[Any]=None , **__a : List[Any] , ): # Add extra_ids to the special token list if extra_ids > 0 and additional_special_tokens is None: UpperCAmelCase_ = [f"""<extra_id_{i}>""" for i in range(__a )] elif extra_ids > 0 and additional_special_tokens is not None: # Check that we have the right number of extra_id special tokens UpperCAmelCase_ = len(set(filter(lambda __a : bool("extra_id" in str(__a ) ) , __a ) ) ) if extra_tokens != extra_ids: raise ValueError( f"""Both extra_ids ({extra_ids}) and additional_special_tokens ({additional_special_tokens}) are""" " provided to ByT5Tokenizer. In this case the additional_special_tokens must include the" " extra_ids tokens" ) UpperCAmelCase_ = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else pad_token UpperCAmelCase_ = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else eos_token UpperCAmelCase_ = AddedToken(__a , lstrip=__a , rstrip=__a ) if isinstance(__a , __a ) else unk_token super().__init__( eos_token=__a , unk_token=__a , pad_token=__a , extra_ids=__a , additional_special_tokens=__a , **__a , ) UpperCAmelCase_ = extra_ids UpperCAmelCase_ = 2**8 # utf is 8 bits # define special tokens dict UpperCAmelCase_ = { self.pad_token: 0, self.eos_token: 1, self.unk_token: 2, } UpperCAmelCase_ = len(self.special_tokens_encoder ) UpperCAmelCase_ = len(__a ) for i, token in enumerate(__a ): UpperCAmelCase_ = self.vocab_size + i - n UpperCAmelCase_ = {v: k for k, v in self.special_tokens_encoder.items()} @property def _lowercase (self : int ): return self._utf_vocab_size + self._num_special_tokens + self._extra_ids def _lowercase (self : Union[str, Any] , __a : List[int] , __a : Optional[List[int]] = None , __a : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__a , token_ids_a=__a , already_has_special_tokens=__a ) # normal case: some special tokens if token_ids_a is None: return ([0] * len(__a )) + [1] return ([0] * len(__a )) + [1] + ([0] * len(__a )) + [1] def _lowercase (self : int , __a : List[int] ): if len(__a ) > 0 and token_ids[-1] == self.eos_token_id: warnings.warn( f"""This sequence already has {self.eos_token}. In future versions this behavior may lead to duplicated""" " eos tokens being added." ) return token_ids else: return token_ids + [self.eos_token_id] def _lowercase (self : Tuple , __a : List[int] , __a : Optional[List[int]] = None ): UpperCAmelCase_ = [self.eos_token_id] if token_ids_a is None: return len(token_ids_a + eos ) * [0] return len(token_ids_a + eos + token_ids_a + eos ) * [0] def _lowercase (self : Union[str, Any] , __a : List[int] , __a : Optional[List[int]] = None ): UpperCAmelCase_ = self._add_eos_if_not_present(__a ) if token_ids_a is None: return token_ids_a else: UpperCAmelCase_ = self._add_eos_if_not_present(__a ) return token_ids_a + token_ids_a def _lowercase (self : List[Any] , __a : str ): UpperCAmelCase_ = [chr(__a ) for i in text.encode("utf-8" )] return tokens def _lowercase (self : Union[str, Any] , __a : Union[str, Any] ): if token in self.special_tokens_encoder: UpperCAmelCase_ = self.special_tokens_encoder[token] elif token in self.added_tokens_encoder: UpperCAmelCase_ = self.added_tokens_encoder[token] elif len(__a ) != 1: UpperCAmelCase_ = self.unk_token_id else: UpperCAmelCase_ = ord(__a ) + self._num_special_tokens return token_id def _lowercase (self : Optional[int] , __a : int ): if index in self.special_tokens_decoder: UpperCAmelCase_ = self.special_tokens_decoder[index] else: UpperCAmelCase_ = chr(index - self._num_special_tokens ) return token def _lowercase (self : Dict , __a : Optional[int] ): UpperCAmelCase_ = B"" for token in tokens: if token in self.special_tokens_decoder: UpperCAmelCase_ = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.added_tokens_decoder: UpperCAmelCase_ = self.special_tokens_decoder[token].encode("utf-8" ) elif token in self.special_tokens_encoder: UpperCAmelCase_ = token.encode("utf-8" ) elif token in self.added_tokens_encoder: UpperCAmelCase_ = token.encode("utf-8" ) else: UpperCAmelCase_ = bytes([ord(__a )] ) bstring += tok_string UpperCAmelCase_ = bstring.decode("utf-8" , errors="ignore" ) return string def _lowercase (self : Dict , __a : str , __a : Optional[str] = None ): return ()
78
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE_: int =logging.getLogger() def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCAmelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> str: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = os.path.join(snake_case_ , "all_results.json" ) if os.path.exists(snake_case_ ): with open(snake_case_ , "r" ) as f: UpperCAmelCase_ = json.load(snake_case_ ) else: raise ValueError(f"""can't find {path}""" ) return results def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = torch.cuda.is_available() and torch_device == "cuda" return is_using_cuda and is_apex_available() SCREAMING_SNAKE_CASE_: Any =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __A ( UpperCamelCase__ ): @classmethod def _lowercase (cls : Any ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = os.path.join(cls.tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) UpperCAmelCase_ = ["accelerate", "launch", "--config_file", cls.configPath] @classmethod def _lowercase (cls : int ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "glue_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "clm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "mlm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCAmelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertLess(result["train_loss"] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "ner_no_trainer" ) ) ) @unittest.skip(reason="Fix me @muellerzr" ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : int ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["eval_f1"] , 28 ) self.assertGreaterEqual(result["eval_exact"] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "qa_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : str ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , "swag_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_rouge1"] , 10 ) self.assertGreaterEqual(result["eval_rouge2"] , 2 ) self.assertGreaterEqual(result["eval_rougeL"] , 7 ) self.assertGreaterEqual(result["eval_rougeLsum"] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "summarization_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : List[str] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_bleu"] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "translation_no_trainer" ) ) ) @slow def _lowercase (self : Dict ): UpperCAmelCase_ = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_overall_accuracy"] , 0.10 ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Any ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result["eval_accuracy"] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , "step_1" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "image_classification_no_trainer" ) ) )
78
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available SCREAMING_SNAKE_CASE_: str ={ 'configuration_squeezebert': [ 'SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SqueezeBertConfig', 'SqueezeBertOnnxConfig', ], 'tokenization_squeezebert': ['SqueezeBertTokenizer'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['SqueezeBertTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Any =[ 'SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST', 'SqueezeBertForMaskedLM', 'SqueezeBertForMultipleChoice', 'SqueezeBertForQuestionAnswering', 'SqueezeBertForSequenceClassification', 'SqueezeBertForTokenClassification', 'SqueezeBertModel', 'SqueezeBertModule', 'SqueezeBertPreTrainedModel', ] if TYPE_CHECKING: from .configuration_squeezebert import ( SQUEEZEBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, SqueezeBertConfig, SqueezeBertOnnxConfig, ) from .tokenization_squeezebert import SqueezeBertTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_squeezebert_fast import SqueezeBertTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_squeezebert import ( SQUEEZEBERT_PRETRAINED_MODEL_ARCHIVE_LIST, SqueezeBertForMaskedLM, SqueezeBertForMultipleChoice, SqueezeBertForQuestionAnswering, SqueezeBertForSequenceClassification, SqueezeBertForTokenClassification, SqueezeBertModel, SqueezeBertModule, SqueezeBertPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: List[str] =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP SCREAMING_SNAKE_CASE_: Any =False try: SCREAMING_SNAKE_CASE_: Optional[Any] =_is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class __A : def __init__(self : int , __a : str = None , __a : list = [] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = choices UpperCAmelCase_ = prompt if sys.platform == "win32": UpperCAmelCase_ = "*" else: UpperCAmelCase_ = "➔ " def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a ) else: forceWrite(self.choices[index] , __a ) def _lowercase (self : Any , __a : int ): if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def _lowercase (self : Optional[Any] , __a : Direction , __a : int = 1 ): UpperCAmelCase_ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a ) move_cursor(__a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def _lowercase (self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def _lowercase (self : Any ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def _lowercase (self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def _lowercase (self : str ): move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a )] for number in range(10 )] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = int(chr(self.current_selection ) ) UpperCAmelCase_ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __a ) else: return else: return def _lowercase (self : Optional[Any] , __a : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase_ = default_choice for i in range(len(self.choices ) ): self.print_choice(__a ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase_ = int(builtins.input() ) except ValueError: UpperCAmelCase_ = default_choice else: UpperCAmelCase_ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__a , "\n" ) return choice
78
1
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __A ( unittest.TestCase ): def _lowercase (self : List[str] ): UpperCAmelCase_ = 0 def _lowercase (self : Tuple ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(__a , __a ) def _lowercase (self : str ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Dict ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop("image_processor_type" ) UpperCAmelCase_ = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved UpperCAmelCase_ = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _lowercase (self : int ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Tuple ): with self.assertRaisesRegex( __a , "clip-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" ) def _lowercase (self : Optional[int] ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , revision="aaaaaa" ) def _lowercase (self : Union[str, Any] ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def _lowercase (self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def _lowercase (self : Optional[int] ): try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : Optional[int] ): class __A ( UpperCamelCase__ ): a__ : str = True try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
78
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_: Optional[int] ={'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['BeitFeatureExtractor'] SCREAMING_SNAKE_CASE_: int =['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: int =[ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
1
'''simple docstring''' from pathlib import Path import fire def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str , snake_case_ : int ) -> int: '''simple docstring''' UpperCAmelCase_ = Path(snake_case_ ) UpperCAmelCase_ = Path(snake_case_ ) dest_dir.mkdir(exist_ok=snake_case_ ) for path in src_dir.iterdir(): UpperCAmelCase_ = [x.rstrip() for x in list(path.open().readlines() )][:n] UpperCAmelCase_ = dest_dir.joinpath(path.name ) print(snake_case_ ) dest_path.open("w" ).write("\n".join(snake_case_ ) ) if __name__ == "__main__": fire.Fire(minify)
78
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed SCREAMING_SNAKE_CASE_: Any ={ 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCAmelCase_ ( snake_case_ : Any ) -> str: '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCAmelCase_ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False elif args.student_type == "gpt2": UpperCAmelCase_ = False def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=snake_case_ , required=snake_case_ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=snake_case_ , required=snake_case_ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=snake_case_ , choices=["distilbert", "roberta", "gpt2"] , required=snake_case_ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=snake_case_ , required=snake_case_ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=snake_case_ , type=snake_case_ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=snake_case_ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=snake_case_ , required=snake_case_ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=snake_case_ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=snake_case_ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=snake_case_ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=snake_case_ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=snake_case_ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=snake_case_ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=snake_case_ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=snake_case_ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=snake_case_ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=snake_case_ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=snake_case_ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=snake_case_ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=snake_case_ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=snake_case_ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=snake_case_ , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=snake_case_ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=snake_case_ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5E-4 , type=snake_case_ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1E-6 , type=snake_case_ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=snake_case_ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=snake_case_ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=snake_case_ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=snake_case_ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=snake_case_ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=snake_case_ , default=56 , help="Random seed" ) parser.add_argument("--log_interval" , type=snake_case_ , default=5_00 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=snake_case_ , default=40_00 , help="Checkpoint interval." ) UpperCAmelCase_ = parser.parse_args() sanity_checks(snake_case_ ) # ARGS # init_gpu_params(snake_case_ ) set_seed(snake_case_ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(f"""Param: {args}""" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(snake_case_ ) , snake_case_ , indent=4 ) git_log(args.dump_path ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.student_type] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCAmelCase_ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCAmelCase_ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCAmelCase_ = tokenizer.all_special_tokens.index(snake_case_ ) UpperCAmelCase_ = tokenizer.all_special_ids[idx] logger.info(f"""Special tokens {special_tok_ids}""" ) UpperCAmelCase_ = special_tok_ids UpperCAmelCase_ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"""Loading data from {args.data_file}""" ) with open(args.data_file , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) if args.mlm: logger.info(f"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) UpperCAmelCase_ = np.maximum(snake_case_ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCAmelCase_ = 0.0 # do not predict special tokens UpperCAmelCase_ = torch.from_numpy(snake_case_ ) else: UpperCAmelCase_ = None UpperCAmelCase_ = LmSeqsDataset(params=snake_case_ , data=snake_case_ ) logger.info("Data loader created." ) # STUDENT # logger.info(f"""Loading student config from {args.student_config}""" ) UpperCAmelCase_ = student_config_class.from_pretrained(args.student_config ) UpperCAmelCase_ = True if args.student_pretrained_weights is not None: logger.info(f"""Loading pretrained weights from {args.student_pretrained_weights}""" ) UpperCAmelCase_ = student_model_class.from_pretrained(args.student_pretrained_weights , config=snake_case_ ) else: UpperCAmelCase_ = student_model_class(snake_case_ ) if args.n_gpu > 0: student.to(f"""cuda:{args.local_rank}""" ) logger.info("Student loaded." ) # TEACHER # UpperCAmelCase_ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=snake_case_ ) if args.n_gpu > 0: teacher.to(f"""cuda:{args.local_rank}""" ) logger.info(f"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(snake_case_ , snake_case_ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(snake_case_ , snake_case_ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCAmelCase_ = Distiller( params=snake_case_ , dataset=snake_case_ , token_probs=snake_case_ , student=snake_case_ , teacher=snake_case_ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
78
1
'''simple docstring''' import itertools import os from collections import Counter, defaultdict from concurrent.futures import ThreadPoolExecutor, as_completed import numpy as np import datasets from .execute import check_correctness SCREAMING_SNAKE_CASE_: Union[str, Any] ='\\n@misc{chen2021evaluating,\n title={Evaluating Large Language Models Trained on Code},\n author={Mark Chen and Jerry Tworek and Heewoo Jun and Qiming Yuan \\nand Henrique Ponde de Oliveira Pinto and Jared Kaplan and Harri Edwards \\nand Yuri Burda and Nicholas Joseph and Greg Brockman and Alex Ray \\nand Raul Puri and Gretchen Krueger and Michael Petrov and Heidy Khlaaf \\nand Girish Sastry and Pamela Mishkin and Brooke Chan and Scott Gray \\nand Nick Ryder and Mikhail Pavlov and Alethea Power and Lukasz Kaiser \\nand Mohammad Bavarian and Clemens Winter and Philippe Tillet \\nand Felipe Petroski Such and Dave Cummings and Matthias Plappert \\nand Fotios Chantzis and Elizabeth Barnes and Ariel Herbert-Voss \\nand William Hebgen Guss and Alex Nichol and Alex Paino and Nikolas Tezak \\nand Jie Tang and Igor Babuschkin and Suchir Balaji and Shantanu Jain \\nand William Saunders and Christopher Hesse and Andrew N. Carr \\nand Jan Leike and Josh Achiam and Vedant Misra and Evan Morikawa \\nand Alec Radford and Matthew Knight and Miles Brundage and Mira Murati \\nand Katie Mayer and Peter Welinder and Bob McGrew and Dario Amodei \\nand Sam McCandlish and Ilya Sutskever and Wojciech Zaremba},\n year={2021},\n eprint={2107.03374},\n archivePrefix={arXiv},\n primaryClass={cs.LG}\n}\n' SCREAMING_SNAKE_CASE_: str ='\\nThis metric implements the evaluation harness for the HumanEval problem solving dataset\ndescribed in the paper "Evaluating Large Language Models Trained on Code"\n(https://arxiv.org/abs/2107.03374).\n' SCREAMING_SNAKE_CASE_: Tuple ='\nCalculates how good are predictions given some references, using certain scores\nArgs:\n predictions: list of candidates to evaluate. Each candidates should be a list\n of strings with several code candidates to solve the problem.\n references: a list with a test for each prediction. Each test should evaluate the\n correctness of a code candidate.\n k: number of code candidates to consider in the evaluation (Default: [1, 10, 100])\n num_workers: number of workers used to evaluate the canidate programs (Default: 4).\n timeout:\nReturns:\n pass_at_k: dict with pass rates for each k\n results: dict with granular results of each unittest\nExamples:\n >>> code_eval = datasets.load_metric("code_eval")\n >>> test_cases = ["assert add(2,3)==5"]\n >>> candidates = [["def add(a,b): return a*b", "def add(a, b): return a+b"]]\n >>> pass_at_k, results = code_eval.compute(references=test_cases, predictions=candidates, k=[1, 2])\n >>> print(pass_at_k)\n {\'pass@1\': 0.5, \'pass@2\': 1.0}\n' SCREAMING_SNAKE_CASE_: Optional[int] ='\n################################################################################\n !!!WARNING!!!\n################################################################################\nThe "code_eval" metric executes untrusted model-generated code in Python.\nAlthough it is highly unlikely that model-generated code will do something\novertly malicious in response to this test suite, model-generated code may act\ndestructively due to a lack of model capability or alignment.\nUsers are strongly encouraged to sandbox this evaluation suite so that it\ndoes not perform destructive actions on their host or network. For more\ninformation on how OpenAI sandboxes its code, see the paper "Evaluating Large\nLanguage Models Trained on Code" (https://arxiv.org/abs/2107.03374).\n\nOnce you have read this disclaimer and taken appropriate precautions,\nset the environment variable HF_ALLOW_CODE_EVAL="1". Within Python you can to this\nwith:\n\n>>> import os\n>>> os.environ["HF_ALLOW_CODE_EVAL"] = "1"\n\n################################################################################\\n' SCREAMING_SNAKE_CASE_: Optional[Any] ='The MIT License\n\nCopyright (c) OpenAI (https://openai.com)\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the "Software"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class __A ( datasets.Metric ): def _lowercase (self : str ): return datasets.MetricInfo( # This is the description that will appear on the metrics page. description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { "predictions": datasets.Sequence(datasets.Value("string" ) ), "references": datasets.Value("string" ), } ) , homepage="https://github.com/openai/human-eval" , codebase_urls=["https://github.com/openai/human-eval"] , reference_urls=["https://github.com/openai/human-eval"] , license=_LICENSE , ) def _lowercase (self : Optional[Any] , __a : int , __a : Union[str, Any] , __a : str=[1, 10, 100] , __a : Optional[int]=4 , __a : List[Any]=3.0 ): if os.getenv("HF_ALLOW_CODE_EVAL" , 0 ) != "1": raise ValueError(_WARNING ) if os.name == "nt": raise NotImplementedError("This metric is currently not supported on Windows." ) with ThreadPoolExecutor(max_workers=__a ) as executor: UpperCAmelCase_ = [] UpperCAmelCase_ = Counter() UpperCAmelCase_ = 0 UpperCAmelCase_ = defaultdict(__a ) for task_id, (candidates, test_case) in enumerate(zip(__a , __a ) ): for candidate in candidates: UpperCAmelCase_ = candidate + "\n" + test_case UpperCAmelCase_ = (test_program, timeout, task_id, completion_id[task_id]) UpperCAmelCase_ = executor.submit(__a , *__a ) futures.append(__a ) completion_id[task_id] += 1 n_samples += 1 for future in as_completed(__a ): UpperCAmelCase_ = future.result() results[result["task_id"]].append((result["completion_id"], result) ) UpperCAmelCase_ , UpperCAmelCase_ = [], [] for result in results.values(): result.sort() UpperCAmelCase_ = [r[1]["passed"] for r in result] total.append(len(__a ) ) correct.append(sum(__a ) ) UpperCAmelCase_ = np.array(__a ) UpperCAmelCase_ = np.array(__a ) UpperCAmelCase_ = k UpperCAmelCase_ = {f"""pass@{k}""": estimate_pass_at_k(__a , __a , __a ).mean() for k in ks if (total >= k).all()} return pass_at_k, results def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Dict , snake_case_ : Optional[int] ) -> Tuple: '''simple docstring''' def estimator(snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> float: if n - c < k: return 1.0 return 1.0 - np.prod(1.0 - k / np.arange(n - c + 1 , n + 1 ) ) if isinstance(snake_case_ , snake_case_ ): UpperCAmelCase_ = itertools.repeat(snake_case_ , len(snake_case_ ) ) else: assert len(snake_case_ ) == len(snake_case_ ) UpperCAmelCase_ = iter(snake_case_ ) return np.array([estimator(int(snake_case_ ) , int(snake_case_ ) , snake_case_ ) for n, c in zip(snake_case_ , snake_case_ )] )
78
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : int = AutoencoderKL a__ : Optional[Any] = """sample""" a__ : Union[str, Any] = 1e-2 @property def _lowercase (self : Optional[int] ): UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = (32, 32) UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(__a ) return {"sample": image} @property def _lowercase (self : Any ): return (3, 32, 32) @property def _lowercase (self : Dict ): return (3, 32, 32) def _lowercase (self : int ): UpperCAmelCase_ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def _lowercase (self : int ): pass def _lowercase (self : int ): pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase (self : List[Any] ): # enable deterministic behavior for gradient checkpointing UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**__a ) model.to(__a ) assert not model.is_gradient_checkpointing and model.training UpperCAmelCase_ = model(**__a ).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() UpperCAmelCase_ = torch.randn_like(__a ) UpperCAmelCase_ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCAmelCase_ = self.model_class(**__a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCAmelCase_ = model_a(**__a ).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() UpperCAmelCase_ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) UpperCAmelCase_ = dict(model.named_parameters() ) UpperCAmelCase_ = 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 _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__a ) self.assertIsNotNone(__a ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__a ) UpperCAmelCase_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) UpperCAmelCase_ = model.to(__a ) model.eval() if torch_device == "mps": UpperCAmelCase_ = torch.manual_seed(0 ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCAmelCase_ = image.to(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , sample_posterior=__a , generator=__a ).sample UpperCAmelCase_ = 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": UpperCAmelCase_ = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": UpperCAmelCase_ = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: UpperCAmelCase_ = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__a , __a , rtol=1E-2 ) ) @slow class __A ( unittest.TestCase ): def _lowercase (self : Dict , __a : Dict , __a : int ): return f"""gaussian_noise_s={seed}_shape={"_".join([str(__a ) for s in shape] )}.npy""" def _lowercase (self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] , __a : Optional[Any]=0 , __a : str=(4, 3, 512, 512) , __a : List[str]=False ): UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a ) ) ).to(__a ).to(__a ) return image def _lowercase (self : List[Any] , __a : Union[str, Any]="CompVis/stable-diffusion-v1-4" , __a : List[Any]=False ): UpperCAmelCase_ = "fp16" if fpaa else None UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = AutoencoderKL.from_pretrained( __a , subfolder="vae" , torch_dtype=__a , revision=__a , ) model.to(__a ).eval() return model def _lowercase (self : List[Any] , __a : List[Any]=0 ): if torch_device == "mps": return torch.manual_seed(__a ) return torch.Generator(device=__a ).manual_seed(__a ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Dict , __a : Optional[int] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , fpaa=__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : int , __a : int , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , 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 _lowercase (self : List[str] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , 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 _lowercase (self : Union[str, Any] , __a : Dict ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase (self : Tuple , __a : List[Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model.encode(__a ).latent_dist UpperCAmelCase_ = dist.sample(generator=__a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCAmelCase_ = sample[0, -1, -3:, -3:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) UpperCAmelCase_ = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(__a , __a , atol=__a )
78
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, ) SCREAMING_SNAKE_CASE_: Tuple ={'configuration_fnet': ['FNET_PRETRAINED_CONFIG_ARCHIVE_MAP', 'FNetConfig']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[Any] =['FNetTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: List[Any] =['FNetTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: str =[ 'FNET_PRETRAINED_MODEL_ARCHIVE_LIST', 'FNetForMaskedLM', 'FNetForMultipleChoice', 'FNetForNextSentencePrediction', 'FNetForPreTraining', 'FNetForQuestionAnswering', 'FNetForSequenceClassification', 'FNetForTokenClassification', 'FNetLayer', 'FNetModel', 'FNetPreTrainedModel', ] if TYPE_CHECKING: from .configuration_fnet import FNET_PRETRAINED_CONFIG_ARCHIVE_MAP, FNetConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet import FNetTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_fnet_fast import FNetTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_fnet import ( FNET_PRETRAINED_MODEL_ARCHIVE_LIST, FNetForMaskedLM, FNetForMultipleChoice, FNetForNextSentencePrediction, FNetForPreTraining, FNetForQuestionAnswering, FNetForSequenceClassification, FNetForTokenClassification, FNetLayer, FNetModel, FNetPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: str =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
'''simple docstring''' import logging from transformers import PretrainedConfig SCREAMING_SNAKE_CASE_: Any =logging.getLogger(__name__) SCREAMING_SNAKE_CASE_: Any ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : List[Any] = """bertabs""" def __init__(self : Any , __a : int=30522 , __a : Tuple=512 , __a : Tuple=6 , __a : Dict=512 , __a : int=8 , __a : List[Any]=512 , __a : List[str]=0.2 , __a : List[Any]=6 , __a : int=768 , __a : Any=8 , __a : Dict=2048 , __a : Tuple=0.2 , **__a : Optional[int] , ): super().__init__(**__a ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_pos UpperCAmelCase_ = enc_layers UpperCAmelCase_ = enc_hidden_size UpperCAmelCase_ = enc_heads UpperCAmelCase_ = enc_ff_size UpperCAmelCase_ = enc_dropout UpperCAmelCase_ = dec_layers UpperCAmelCase_ = dec_hidden_size UpperCAmelCase_ = dec_heads UpperCAmelCase_ = dec_ff_size UpperCAmelCase_ = dec_dropout
78
1
'''simple docstring''' import os def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = os.path.dirname(os.path.realpath(snake_case_ ) ) UpperCAmelCase_ = os.path.join(snake_case_ , "triangle.txt" ) with open(snake_case_ ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = [] for line in triangle: UpperCAmelCase_ = [] for number in line.strip().split(" " ): numbers_from_line.append(int(snake_case_ ) ) a.append(snake_case_ ) for i in range(1 , len(snake_case_ ) ): for j in range(len(a[i] ) ): UpperCAmelCase_ = a[i - 1][j] if j != len(a[i - 1] ) else 0 UpperCAmelCase_ = a[i - 1][j - 1] if j > 0 else 0 a[i][j] += max(snake_case_ , snake_case_ ) return max(a[-1] ) if __name__ == "__main__": print(solution())
78
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = {v: k for k, v in idalabel.items()} UpperCAmelCase_ = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" UpperCAmelCase_ = BitConfig( conv_layer=snake_case_ , num_labels=10_00 , idalabel=snake_case_ , labelaid=snake_case_ , ) return config def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if "stem.conv" in name: UpperCAmelCase_ = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase_ = name.replace("blocks" , "layers" ) if "head.fc" in name: UpperCAmelCase_ = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): UpperCAmelCase_ = "bit." + name if "bit" not in name and "classifier" not in name: UpperCAmelCase_ = "bit.encoder." + name return name def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : int=False ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = get_config(snake_case_ ) # load original model from timm UpperCAmelCase_ = create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model UpperCAmelCase_ = timm_model.state_dict() for key in state_dict.copy().keys(): UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val.squeeze() if "head" in key else val # load HuggingFace model UpperCAmelCase_ = BitForImageClassification(snake_case_ ) model.eval() model.load_state_dict(snake_case_ ) # create image processor UpperCAmelCase_ = create_transform(**resolve_data_config({} , model=snake_case_ ) ) UpperCAmelCase_ = transform.transforms UpperCAmelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase_ = BitImageProcessor( do_resize=snake_case_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ) UpperCAmelCase_ = processor(snake_case_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): UpperCAmelCase_ = model(snake_case_ ) UpperCAmelCase_ = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
78
1
'''simple docstring''' from collections import namedtuple SCREAMING_SNAKE_CASE_: Optional[int] =namedtuple('from_to', 'from_ to') SCREAMING_SNAKE_CASE_: str ={ 'cubicmeter': from_to(1, 1), 'litre': from_to(0.001, 10_00), 'kilolitre': from_to(1, 1), 'gallon': from_to(0.00454, 264.172), 'cubicyard': from_to(0.76455, 1.30795), 'cubicfoot': from_to(0.028, 35.3147), 'cup': from_to(0.000236588, 4226.75), } def lowerCAmelCase_ ( snake_case_ : float , snake_case_ : str , snake_case_ : str ) -> float: '''simple docstring''' if from_type not in METRIC_CONVERSION: raise ValueError( f"""Invalid 'from_type' value: {from_type!r} Supported values are:\n""" + ", ".join(snake_case_ ) ) if to_type not in METRIC_CONVERSION: raise ValueError( f"""Invalid 'to_type' value: {to_type!r}. Supported values are:\n""" + ", ".join(snake_case_ ) ) return value * METRIC_CONVERSION[from_type].from_ * METRIC_CONVERSION[to_type].to if __name__ == "__main__": import doctest doctest.testmod()
78
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __A ( unittest.TestCase ): def _lowercase (self : List[str] ): UpperCAmelCase_ = 0 def _lowercase (self : Tuple ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(__a , __a ) def _lowercase (self : str ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Dict ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop("image_processor_type" ) UpperCAmelCase_ = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved UpperCAmelCase_ = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _lowercase (self : int ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Tuple ): with self.assertRaisesRegex( __a , "clip-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" ) def _lowercase (self : Optional[int] ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , revision="aaaaaa" ) def _lowercase (self : Union[str, Any] ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def _lowercase (self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def _lowercase (self : Optional[int] ): try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : Optional[int] ): class __A ( UpperCamelCase__ ): a__ : str = True try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
78
1
'''simple docstring''' from abc import ABC, abstractmethod from typing import Optional, Union from .. import Dataset, DatasetDict, Features, IterableDataset, IterableDatasetDict, NamedSplit from ..utils.typing import NestedDataStructureLike, PathLike class __A ( UpperCamelCase__ ): def __init__(self : int , __a : Optional[NestedDataStructureLike[PathLike]] = None , __a : Optional[NamedSplit] = None , __a : Optional[Features] = None , __a : str = None , __a : bool = False , __a : bool = False , __a : Optional[int] = None , **__a : Optional[Any] , ): UpperCAmelCase_ = path_or_paths UpperCAmelCase_ = split if split or isinstance(__a , __a ) else "train" UpperCAmelCase_ = features UpperCAmelCase_ = cache_dir UpperCAmelCase_ = keep_in_memory UpperCAmelCase_ = streaming UpperCAmelCase_ = num_proc UpperCAmelCase_ = kwargs @abstractmethod def _lowercase (self : Tuple ): pass class __A ( UpperCamelCase__ ): def __init__(self : Union[str, Any] , __a : Optional[Features] = None , __a : str = None , __a : bool = False , __a : bool = False , __a : Optional[int] = None , **__a : Any , ): UpperCAmelCase_ = features UpperCAmelCase_ = cache_dir UpperCAmelCase_ = keep_in_memory UpperCAmelCase_ = streaming UpperCAmelCase_ = num_proc UpperCAmelCase_ = kwargs @abstractmethod def _lowercase (self : List[str] ): pass
78
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Tuple =False, False, False @dataclass class __A : a__ : Optional[int] = None a__ : bool = True a__ : bool = True a__ : Optional[str] = None # Automatically constructed a__ : ClassVar[str] = "dict" a__ : ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) a__ : str = field(default="""Audio""" , init=UpperCamelCase__ , repr=UpperCamelCase__ ) def __call__(self : Optional[Any] ): return self.pa_type def _lowercase (self : str , __a : Union[str, bytes, dict] ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(__a , __a ): return {"bytes": None, "path": value} elif isinstance(__a , __a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes UpperCAmelCase_ = BytesIO() sf.write(__a , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) UpperCAmelCase_ = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: UpperCAmelCase_ = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32767 UpperCAmelCase_ = BytesIO(bytes() ) sf.write(__a , __a , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def _lowercase (self : Dict , __a : dict , __a : Optional[Dict[str, Union[str, bool, None]]] = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) UpperCAmelCase_ , UpperCAmelCase_ = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err UpperCAmelCase_ = xsplitext(__a )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: UpperCAmelCase_ = token_per_repo_id or {} UpperCAmelCase_ = path.split("::" )[-1] try: UpperCAmelCase_ = string_to_dict(__a , config.HUB_DATASETS_URL )["repo_id"] UpperCAmelCase_ = token_per_repo_id[repo_id] except (ValueError, KeyError): UpperCAmelCase_ = None with xopen(__a , "rb" , use_auth_token=__a ) as f: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) else: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) UpperCAmelCase_ = array.T if self.mono: UpperCAmelCase_ = librosa.to_mono(__a ) if self.sampling_rate and self.sampling_rate != sampling_rate: UpperCAmelCase_ = librosa.resample(__a , orig_sr=__a , target_sr=self.sampling_rate ) UpperCAmelCase_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _lowercase (self : Dict ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def _lowercase (self : Optional[Any] , __a : Union[pa.StringArray, pa.StructArray] ): if pa.types.is_string(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): UpperCAmelCase_ = pa.array([Audio().encode_example(__a ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCAmelCase_ = storage.field("bytes" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCAmelCase_ = storage.field("path" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(__a , self.pa_type ) def _lowercase (self : Dict , __a : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(__a : Tuple ): with xopen(__a , "rb" ) as f: UpperCAmelCase_ = f.read() return bytes_ UpperCAmelCase_ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase_ = pa.array( [os.path.basename(__a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(__a , self.pa_type )
78
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import ( DiffusionPipeline, UnCLIPImageVariationPipeline, UnCLIPScheduler, UNetaDConditionModel, UNetaDModel, ) from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, load_image, require_torch_gpu, skip_mps from ..pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class __A ( UpperCamelCase__ , unittest.TestCase ): a__ : Union[str, Any] = UnCLIPImageVariationPipeline a__ : Tuple = IMAGE_VARIATION_PARAMS - {"""height""", """width""", """guidance_scale"""} a__ : Union[str, Any] = IMAGE_VARIATION_BATCH_PARAMS a__ : Union[str, Any] = [ """generator""", """return_dict""", """decoder_num_inference_steps""", """super_res_num_inference_steps""", ] a__ : Any = False @property def _lowercase (self : int ): return 32 @property def _lowercase (self : Union[str, Any] ): return 32 @property def _lowercase (self : Dict ): return self.time_input_dim @property def _lowercase (self : Optional[Any] ): return self.time_input_dim * 4 @property def _lowercase (self : Tuple ): return 100 @property def _lowercase (self : List[str] ): UpperCAmelCase_ = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip" ) return tokenizer @property def _lowercase (self : Optional[int] ): torch.manual_seed(0 ) UpperCAmelCase_ = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , intermediate_size=37 , layer_norm_eps=1E-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1000 , ) return CLIPTextModelWithProjection(__a ) @property def _lowercase (self : Optional[int] ): torch.manual_seed(0 ) UpperCAmelCase_ = CLIPVisionConfig( hidden_size=self.text_embedder_hidden_size , projection_dim=self.text_embedder_hidden_size , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) return CLIPVisionModelWithProjection(__a ) @property def _lowercase (self : Dict ): torch.manual_seed(0 ) UpperCAmelCase_ = { "clip_embeddings_dim": self.text_embedder_hidden_size, "time_embed_dim": self.time_embed_dim, "cross_attention_dim": self.cross_attention_dim, } UpperCAmelCase_ = UnCLIPTextProjModel(**__a ) return model @property def _lowercase (self : int ): torch.manual_seed(0 ) UpperCAmelCase_ = { "sample_size": 32, # RGB in channels "in_channels": 3, # Out channels is double in channels because predicts mean and variance "out_channels": 6, "down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"), "up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"), "mid_block_type": "UNetMidBlock2DSimpleCrossAttn", "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "layers_per_block": 1, "cross_attention_dim": self.cross_attention_dim, "attention_head_dim": 4, "resnet_time_scale_shift": "scale_shift", "class_embed_type": "identity", } UpperCAmelCase_ = UNetaDConditionModel(**__a ) return model @property def _lowercase (self : Union[str, Any] ): return { "sample_size": 64, "layers_per_block": 1, "down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"), "up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"), "block_out_channels": (self.block_out_channels_a, self.block_out_channels_a * 2), "in_channels": 6, "out_channels": 3, } @property def _lowercase (self : int ): torch.manual_seed(0 ) UpperCAmelCase_ = UNetaDModel(**self.dummy_super_res_kwargs ) return model @property def _lowercase (self : Dict ): # seeded differently to get different unet than `self.dummy_super_res_first` torch.manual_seed(1 ) UpperCAmelCase_ = UNetaDModel(**self.dummy_super_res_kwargs ) return model def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.dummy_decoder UpperCAmelCase_ = self.dummy_text_proj UpperCAmelCase_ = self.dummy_text_encoder UpperCAmelCase_ = self.dummy_tokenizer UpperCAmelCase_ = self.dummy_super_res_first UpperCAmelCase_ = self.dummy_super_res_last UpperCAmelCase_ = UnCLIPScheduler( variance_type="learned_range" , prediction_type="epsilon" , num_train_timesteps=1000 , ) UpperCAmelCase_ = UnCLIPScheduler( variance_type="fixed_small_log" , prediction_type="epsilon" , num_train_timesteps=1000 , ) UpperCAmelCase_ = CLIPImageProcessor(crop_size=32 , size=32 ) UpperCAmelCase_ = self.dummy_image_encoder return { "decoder": decoder, "text_encoder": text_encoder, "tokenizer": tokenizer, "text_proj": text_proj, "feature_extractor": feature_extractor, "image_encoder": image_encoder, "super_res_first": super_res_first, "super_res_last": super_res_last, "decoder_scheduler": decoder_scheduler, "super_res_scheduler": super_res_scheduler, } def _lowercase (self : Optional[int] , __a : Any , __a : List[Any]=0 , __a : str=True ): UpperCAmelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) if str(__a ).startswith("mps" ): UpperCAmelCase_ = torch.manual_seed(__a ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(__a ) if pil_image: UpperCAmelCase_ = input_image * 0.5 + 0.5 UpperCAmelCase_ = input_image.clamp(0 , 1 ) UpperCAmelCase_ = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() UpperCAmelCase_ = DiffusionPipeline.numpy_to_pil(__a )[0] return { "image": input_image, "generator": generator, "decoder_num_inference_steps": 2, "super_res_num_inference_steps": 2, "output_type": "np", } def _lowercase (self : Dict ): UpperCAmelCase_ = "cpu" UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = self.pipeline_class(**__a ) UpperCAmelCase_ = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_dummy_inputs(__a , pil_image=__a ) UpperCAmelCase_ = pipe(**__a ) UpperCAmelCase_ = output.images UpperCAmelCase_ = self.get_dummy_inputs(__a , pil_image=__a ) UpperCAmelCase_ = pipe( **__a , return_dict=__a , )[0] UpperCAmelCase_ = image[0, -3:, -3:, -1] UpperCAmelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ = np.array( [ 0.99_97, 0.00_02, 0.99_97, 0.99_97, 0.99_69, 0.00_23, 0.99_97, 0.99_69, 0.99_70, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase (self : str ): UpperCAmelCase_ = "cpu" UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = self.pipeline_class(**__a ) UpperCAmelCase_ = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_dummy_inputs(__a , pil_image=__a ) UpperCAmelCase_ = pipe(**__a ) UpperCAmelCase_ = output.images UpperCAmelCase_ = self.get_dummy_inputs(__a , pil_image=__a ) UpperCAmelCase_ = pipe( **__a , return_dict=__a , )[0] UpperCAmelCase_ = image[0, -3:, -3:, -1] UpperCAmelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) UpperCAmelCase_ = np.array([0.99_97, 0.00_03, 0.99_97, 0.99_97, 0.99_70, 0.00_24, 0.99_97, 0.99_71, 0.99_71] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase (self : List[str] ): UpperCAmelCase_ = "cpu" UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = self.pipeline_class(**__a ) UpperCAmelCase_ = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_dummy_inputs(__a , pil_image=__a ) UpperCAmelCase_ = [ pipeline_inputs["image"], pipeline_inputs["image"], ] UpperCAmelCase_ = pipe(**__a ) UpperCAmelCase_ = output.images UpperCAmelCase_ = self.get_dummy_inputs(__a , pil_image=__a ) UpperCAmelCase_ = [ tuple_pipeline_inputs["image"], tuple_pipeline_inputs["image"], ] UpperCAmelCase_ = pipe( **__a , return_dict=__a , )[0] UpperCAmelCase_ = image[0, -3:, -3:, -1] UpperCAmelCase_ = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (2, 64, 64, 3) UpperCAmelCase_ = np.array( [ 0.99_97, 0.99_89, 0.00_08, 0.00_21, 0.99_60, 0.00_18, 0.00_14, 0.00_02, 0.99_33, ] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1E-2 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1E-2 def _lowercase (self : Tuple ): UpperCAmelCase_ = torch.device("cpu" ) class __A : a__ : Optional[Any] = 1 UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = self.pipeline_class(**__a ) UpperCAmelCase_ = pipe.to(__a ) pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = pipe.decoder.dtype UpperCAmelCase_ = 1 UpperCAmelCase_ = ( batch_size, pipe.decoder.config.in_channels, pipe.decoder.config.sample_size, pipe.decoder.config.sample_size, ) UpperCAmelCase_ = pipe.prepare_latents( __a , dtype=__a , device=__a , generator=__a , latents=__a , scheduler=DummyScheduler() ) UpperCAmelCase_ = ( batch_size, pipe.super_res_first.config.in_channels // 2, pipe.super_res_first.config.sample_size, pipe.super_res_first.config.sample_size, ) UpperCAmelCase_ = pipe.prepare_latents( __a , dtype=__a , device=__a , generator=__a , latents=__a , scheduler=DummyScheduler() ) UpperCAmelCase_ = self.get_dummy_inputs(__a , pil_image=__a ) UpperCAmelCase_ = pipe( **__a , decoder_latents=__a , super_res_latents=__a ).images UpperCAmelCase_ = self.get_dummy_inputs(__a , pil_image=__a ) # Don't pass image, instead pass embedding UpperCAmelCase_ = pipeline_inputs.pop("image" ) UpperCAmelCase_ = pipe.image_encoder(__a ).image_embeds UpperCAmelCase_ = pipe( **__a , decoder_latents=__a , super_res_latents=__a , image_embeddings=__a , ).images # make sure passing text embeddings manually is identical assert np.abs(img_out_a - img_out_a ).max() < 1E-4 @skip_mps def _lowercase (self : Optional[int] ): UpperCAmelCase_ = torch_device == "cpu" # Check is relaxed because there is not a torch 2.0 sliced attention added kv processor UpperCAmelCase_ = 1E-2 self._test_attention_slicing_forward_pass( test_max_difference=__a , expected_max_diff=__a ) @skip_mps def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = torch_device == "cpu" UpperCAmelCase_ = True UpperCAmelCase_ = [ "decoder_num_inference_steps", "super_res_num_inference_steps", ] self._test_inference_batch_single_identical( test_max_difference=__a , relax_max_difference=__a , additional_params_copy_to_batched_inputs=__a , ) def _lowercase (self : List[Any] ): UpperCAmelCase_ = [ "decoder_num_inference_steps", "super_res_num_inference_steps", ] if torch_device == "mps": # TODO: MPS errors with larger batch sizes UpperCAmelCase_ = [2, 3] self._test_inference_batch_consistent( batch_sizes=__a , additional_params_copy_to_batched_inputs=__a , ) else: self._test_inference_batch_consistent( additional_params_copy_to_batched_inputs=__a ) @skip_mps def _lowercase (self : Optional[Any] ): return super().test_dict_tuple_outputs_equivalent() @skip_mps def _lowercase (self : Optional[Any] ): return super().test_save_load_local() @skip_mps def _lowercase (self : int ): return super().test_save_load_optional_components() @slow @require_torch_gpu class __A ( unittest.TestCase ): def _lowercase (self : Dict ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Any ): UpperCAmelCase_ = load_image( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png" ) UpperCAmelCase_ = load_numpy( "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main" "/unclip/karlo_v1_alpha_cat_variation_fp16.npy" ) UpperCAmelCase_ = UnCLIPImageVariationPipeline.from_pretrained( "kakaobrain/karlo-v1-alpha-image-variations" , torch_dtype=torch.floataa ) UpperCAmelCase_ = pipeline.to(__a ) pipeline.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = torch.Generator(device="cpu" ).manual_seed(0 ) UpperCAmelCase_ = pipeline( __a , generator=__a , output_type="np" , ) UpperCAmelCase_ = output.images[0] assert image.shape == (256, 256, 3) assert_mean_pixel_difference(__a , __a , 15 )
78
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
1
'''simple docstring''' import functools def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> int: '''simple docstring''' UpperCAmelCase_ = len(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) @functools.cache def min_distance(snake_case_ : int , snake_case_ : int ) -> int: # if first word index is overflow - delete all from the second word if indexa >= len_worda: return len_worda - indexa # if second word index is overflow - delete all from the first word if indexa >= len_worda: return len_worda - indexa UpperCAmelCase_ = int(worda[indexa] != worda[indexa] ) # current letters not identical return min( 1 + min_distance(indexa + 1 , snake_case_ ) , 1 + min_distance(snake_case_ , indexa + 1 ) , diff + min_distance(indexa + 1 , indexa + 1 ) , ) return min_distance(0 , 0 ) if __name__ == "__main__": import doctest doctest.testmod()
78
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any]=0.999 , snake_case_ : Tuple="cosine" , ) -> Optional[Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase_ = [] for i in range(snake_case_ ): UpperCAmelCase_ = i / num_diffusion_timesteps UpperCAmelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case_ ) / alpha_bar_fn(snake_case_ ) , snake_case_ ) ) return torch.tensor(snake_case_ , dtype=torch.floataa ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : Tuple = [e.name for e in KarrasDiffusionSchedulers] a__ : Optional[Any] = 2 @register_to_config def __init__(self : Union[str, Any] , __a : int = 1000 , __a : float = 0.0_00_85 , __a : float = 0.0_12 , __a : str = "linear" , __a : Optional[Union[np.ndarray, List[float]]] = None , __a : str = "epsilon" , __a : Optional[bool] = False , __a : Optional[bool] = False , __a : float = 1.0 , __a : str = "linspace" , __a : int = 0 , ): if trained_betas is not None: UpperCAmelCase_ = torch.tensor(__a , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase_ = torch.linspace(__a , __a , __a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="cosine" ) elif beta_schedule == "exp": UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) UpperCAmelCase_ = 1.0 - self.betas UpperCAmelCase_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__a , __a , __a ) UpperCAmelCase_ = use_karras_sigmas def _lowercase (self : Optional[Any] , __a : Union[str, Any] , __a : Tuple=None ): if schedule_timesteps is None: UpperCAmelCase_ = self.timesteps UpperCAmelCase_ = (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: UpperCAmelCase_ = 1 if len(__a ) > 1 else 0 else: UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep UpperCAmelCase_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self : List[Any] ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self : Optional[Any] , __a : torch.FloatTensor , __a : Union[float, torch.FloatTensor] , ): UpperCAmelCase_ = self.index_for_timestep(__a ) UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self : Any , __a : int , __a : Union[str, torch.device] = None , __a : Optional[int] = None , ): UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = 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": UpperCAmelCase_ = np.linspace(0 , num_train_timesteps - 1 , __a , dtype=__a )[::-1].copy() elif self.config.timestep_spacing == "leading": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(0 , __a ) * step_ratio).round()[::-1].copy().astype(__a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(__a , 0 , -step_ratio )).round().copy().astype(__a ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) UpperCAmelCase_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) UpperCAmelCase_ = np.log(__a ) UpperCAmelCase_ = np.interp(__a , np.arange(0 , len(__a ) ) , __a ) if self.config.use_karras_sigmas: UpperCAmelCase_ = self._convert_to_karras(in_sigmas=__a , num_inference_steps=self.num_inference_steps ) UpperCAmelCase_ = np.array([self._sigma_to_t(__a , __a ) for sigma in sigmas] ) UpperCAmelCase_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a ) UpperCAmelCase_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) UpperCAmelCase_ = torch.from_numpy(__a ) UpperCAmelCase_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__a ).startswith("mps" ): # mps does not support float64 UpperCAmelCase_ = timesteps.to(__a , dtype=torch.floataa ) else: UpperCAmelCase_ = timesteps.to(device=__a ) # empty dt and derivative UpperCAmelCase_ = None UpperCAmelCase_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter UpperCAmelCase_ = defaultdict(__a ) def _lowercase (self : int , __a : Optional[Any] , __a : List[str] ): # get log sigma UpperCAmelCase_ = np.log(__a ) # get distribution UpperCAmelCase_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range UpperCAmelCase_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) UpperCAmelCase_ = low_idx + 1 UpperCAmelCase_ = log_sigmas[low_idx] UpperCAmelCase_ = log_sigmas[high_idx] # interpolate sigmas UpperCAmelCase_ = (low - log_sigma) / (low - high) UpperCAmelCase_ = np.clip(__a , 0 , 1 ) # transform interpolation to time range UpperCAmelCase_ = (1 - w) * low_idx + w * high_idx UpperCAmelCase_ = t.reshape(sigma.shape ) return t def _lowercase (self : Dict , __a : torch.FloatTensor , __a : Optional[int] ): UpperCAmelCase_ = in_sigmas[-1].item() UpperCAmelCase_ = in_sigmas[0].item() UpperCAmelCase_ = 7.0 # 7.0 is the value used in the paper UpperCAmelCase_ = np.linspace(0 , 1 , __a ) UpperCAmelCase_ = sigma_min ** (1 / rho) UpperCAmelCase_ = sigma_max ** (1 / rho) UpperCAmelCase_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self : List[str] ): return self.dt is None def _lowercase (self : List[Any] , __a : Union[torch.FloatTensor, np.ndarray] , __a : Union[float, torch.FloatTensor] , __a : Union[torch.FloatTensor, np.ndarray] , __a : bool = True , ): UpperCAmelCase_ = self.index_for_timestep(__a ) # advance index counter by 1 UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method UpperCAmelCase_ = self.sigmas[step_index - 1] UpperCAmelCase_ = 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 UpperCAmelCase_ = 0 UpperCAmelCase_ = 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": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": UpperCAmelCase_ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: UpperCAmelCase_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order UpperCAmelCase_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep UpperCAmelCase_ = sigma_next - sigma_hat # store for 2nd order step UpperCAmelCase_ = derivative UpperCAmelCase_ = dt UpperCAmelCase_ = sample else: # 2. 2nd order / Heun's method UpperCAmelCase_ = (sample - pred_original_sample) / sigma_next UpperCAmelCase_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample UpperCAmelCase_ = self.dt UpperCAmelCase_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a ) def _lowercase (self : Any , __a : torch.FloatTensor , __a : torch.FloatTensor , __a : torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples UpperCAmelCase_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__a ): # mps does not support float64 UpperCAmelCase_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) UpperCAmelCase_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: UpperCAmelCase_ = self.timesteps.to(original_samples.device ) UpperCAmelCase_ = timesteps.to(original_samples.device ) UpperCAmelCase_ = [self.index_for_timestep(__a , __a ) for t in timesteps] UpperCAmelCase_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): UpperCAmelCase_ = sigma.unsqueeze(-1 ) UpperCAmelCase_ = original_samples + noise * sigma return noisy_samples def __len__(self : str ): return self.config.num_train_timesteps
78
1
'''simple docstring''' import unittest from huggingface_hub import hf_hub_download from transformers import MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING, VideoMAEFeatureExtractor from transformers.pipelines import VideoClassificationPipeline, pipeline from transformers.testing_utils import ( is_pipeline_test, nested_simplify, require_decord, require_tf, require_torch, require_torch_or_tf, require_vision, ) from .test_pipelines_common import ANY @is_pipeline_test @require_torch_or_tf @require_vision @require_decord class __A ( unittest.TestCase ): a__ : Optional[Any] = MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING def _lowercase (self : Union[str, Any] , __a : Tuple , __a : str , __a : List[Any] ): UpperCAmelCase_ = hf_hub_download( repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) UpperCAmelCase_ = VideoClassificationPipeline(model=__a , image_processor=__a , top_k=2 ) UpperCAmelCase_ = [ example_video_filepath, "https://huggingface.co/datasets/nateraw/video-demo/resolve/main/archery.mp4", ] return video_classifier, examples def _lowercase (self : Tuple , __a : int , __a : Any ): for example in examples: UpperCAmelCase_ = video_classifier(__a ) self.assertEqual( __a , [ {"score": ANY(__a ), "label": ANY(__a )}, {"score": ANY(__a ), "label": ANY(__a )}, ] , ) @require_torch def _lowercase (self : Tuple ): UpperCAmelCase_ = "hf-internal-testing/tiny-random-VideoMAEForVideoClassification" UpperCAmelCase_ = VideoMAEFeatureExtractor( size={"shortest_edge": 10} , crop_size={"height": 10, "width": 10} ) UpperCAmelCase_ = pipeline( "video-classification" , model=__a , feature_extractor=__a , frame_sampling_rate=4 ) UpperCAmelCase_ = hf_hub_download(repo_id="nateraw/video-demo" , filename="archery.mp4" , repo_type="dataset" ) UpperCAmelCase_ = video_classifier(__a , top_k=2 ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [{"score": 0.51_99, "label": "LABEL_0"}, {"score": 0.48_01, "label": "LABEL_1"}] , ) UpperCAmelCase_ = video_classifier( [ video_file_path, video_file_path, ] , top_k=2 , ) self.assertEqual( nested_simplify(__a , decimals=4 ) , [ [{"score": 0.51_99, "label": "LABEL_0"}, {"score": 0.48_01, "label": "LABEL_1"}], [{"score": 0.51_99, "label": "LABEL_0"}, {"score": 0.48_01, "label": "LABEL_1"}], ] , ) @require_tf def _lowercase (self : List[str] ): pass
78
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( UpperCamelCase__ ): a__ : List[str] = """Salesforce/blip-image-captioning-base""" a__ : Optional[Any] = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : str = """image_captioner""" a__ : List[str] = AutoModelForVisionaSeq a__ : int = ["""image"""] a__ : Optional[Any] = ["""text"""] def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*__a , **__a ) def _lowercase (self : Union[str, Any] , __a : "Image" ): return self.pre_processor(images=__a , return_tensors="pt" ) def _lowercase (self : List[str] , __a : Dict ): return self.model.generate(**__a ) def _lowercase (self : int , __a : Optional[Any] ): return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
78
1
'''simple docstring''' from importlib import import_module from .logging import get_logger SCREAMING_SNAKE_CASE_: Any =get_logger(__name__) class __A : def __init__(self : str , __a : Optional[int] , __a : int=None ): UpperCAmelCase_ = attrs or [] if module is not None: for key in module.__dict__: if key in attrs or not key.startswith("__" ): setattr(self , __a , getattr(__a , __a ) ) UpperCAmelCase_ = module._original_module if isinstance(__a , _PatchedModuleObj ) else module class __A : a__ : List[Any] = [] def __init__(self : Dict , __a : List[Any] , __a : str , __a : Dict , __a : int=None ): UpperCAmelCase_ = obj UpperCAmelCase_ = target UpperCAmelCase_ = new UpperCAmelCase_ = target.split("." )[0] UpperCAmelCase_ = {} UpperCAmelCase_ = attrs or [] def __enter__(self : Union[str, Any] ): *UpperCAmelCase_ , UpperCAmelCase_ = self.target.split("." ) # Patch modules: # it's used to patch attributes of submodules like "os.path.join"; # in this case we need to patch "os" and "os.path" for i in range(len(__a ) ): try: UpperCAmelCase_ = import_module(".".join(submodules[: i + 1] ) ) except ModuleNotFoundError: continue # We iterate over all the globals in self.obj in case we find "os" or "os.path" for attr in self.obj.__dir__(): UpperCAmelCase_ = getattr(self.obj , __a ) # We don't check for the name of the global, but rather if its value *is* "os" or "os.path". # This allows to patch renamed modules like "from os import path as ospath". if obj_attr is submodule or ( (isinstance(__a , _PatchedModuleObj ) and obj_attr._original_module is submodule) ): UpperCAmelCase_ = obj_attr # patch at top level setattr(self.obj , __a , _PatchedModuleObj(__a , attrs=self.attrs ) ) UpperCAmelCase_ = getattr(self.obj , __a ) # construct lower levels patches for key in submodules[i + 1 :]: setattr(__a , __a , _PatchedModuleObj(getattr(__a , __a , __a ) , attrs=self.attrs ) ) UpperCAmelCase_ = getattr(__a , __a ) # finally set the target attribute setattr(__a , __a , self.new ) # Patch attribute itself: # it's used for builtins like "open", # and also to patch "os.path.join" we may also need to patch "join" # itself if it was imported as "from os.path import join". if submodules: # if it's an attribute of a submodule like "os.path.join" try: UpperCAmelCase_ = getattr(import_module(".".join(__a ) ) , __a ) except (AttributeError, ModuleNotFoundError): return # We iterate over all the globals in self.obj in case we find "os.path.join" for attr in self.obj.__dir__(): # We don't check for the name of the global, but rather if its value *is* "os.path.join". # This allows to patch renamed attributes like "from os.path import join as pjoin". if getattr(self.obj , __a ) is attr_value: UpperCAmelCase_ = getattr(self.obj , __a ) setattr(self.obj , __a , self.new ) elif target_attr in globals()["__builtins__"]: # if it'a s builtin like "open" UpperCAmelCase_ = globals()["__builtins__"][target_attr] setattr(self.obj , __a , self.new ) else: raise RuntimeError(f"""Tried to patch attribute {target_attr} instead of a submodule.""" ) def __exit__(self : str , *__a : Optional[int] ): for attr in list(self.original ): setattr(self.obj , __a , self.original.pop(__a ) ) def _lowercase (self : int ): self.__enter__() self._active_patches.append(self ) def _lowercase (self : int ): try: self._active_patches.remove(self ) except ValueError: # If the patch hasn't been started this will fail return None return self.__exit__()
78
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
1
'''simple docstring''' from typing import List, Optional, Union import torch from transformers import ( XLMRobertaTokenizer, ) from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) from .text_encoder import MultilingualCLIP SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) # pylint: disable=invalid-name SCREAMING_SNAKE_CASE_: List[Any] ='\n Examples:\n ```py\n >>> from diffusers import KandinskyPipeline, KandinskyPriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyPriorPipeline.from_pretrained("kandinsky-community/Kandinsky-2-1-prior")\n >>> pipe_prior.to("cuda")\n\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> negative_image_emb = out.negative_image_embeds\n\n >>> pipe = KandinskyPipeline.from_pretrained("kandinsky-community/kandinsky-2-1")\n >>> pipe.to("cuda")\n\n >>> image = pipe(\n ... prompt,\n ... image_embeds=image_emb,\n ... negative_image_embeds=negative_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=100,\n ... ).images\n\n >>> image[0].save("cat.png")\n ```\n' def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : List[str] , snake_case_ : List[str]=8 ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = h // scale_factor**2 if h % scale_factor**2 != 0: new_h += 1 UpperCAmelCase_ = w // scale_factor**2 if w % scale_factor**2 != 0: new_w += 1 return new_h * scale_factor, new_w * scale_factor class __A ( UpperCamelCase__ ): def __init__(self : Dict , __a : MultilingualCLIP , __a : XLMRobertaTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, DDPMScheduler] , __a : VQModel , ): super().__init__() self.register_modules( text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , movq=__a , ) UpperCAmelCase_ = 2 ** (len(self.movq.config.block_out_channels ) - 1) def _lowercase (self : Union[str, Any] , __a : Optional[Any] , __a : Tuple , __a : Optional[Any] , __a : Dict , __a : Tuple , __a : Dict ): if latents is None: UpperCAmelCase_ = randn_tensor(__a , generator=__a , device=__a , dtype=__a ) else: if latents.shape != shape: raise ValueError(f"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) UpperCAmelCase_ = latents.to(__a ) UpperCAmelCase_ = latents * scheduler.init_noise_sigma return latents def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] , __a : Optional[Any] , __a : Any=None , ): UpperCAmelCase_ = len(__a ) if isinstance(__a , __a ) else 1 # get prompt text embeddings UpperCAmelCase_ = self.tokenizer( __a , padding="max_length" , truncation=__a , max_length=77 , return_attention_mask=__a , add_special_tokens=__a , return_tensors="pt" , ) UpperCAmelCase_ = text_inputs.input_ids UpperCAmelCase_ = self.tokenizer(__a , padding="longest" , return_tensors="pt" ).input_ids if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__a , __a ): UpperCAmelCase_ = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1] ) 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}""" ) UpperCAmelCase_ = text_input_ids.to(__a ) UpperCAmelCase_ = text_inputs.attention_mask.to(__a ) UpperCAmelCase_ , UpperCAmelCase_ = self.text_encoder( input_ids=__a , attention_mask=__a ) UpperCAmelCase_ = prompt_embeds.repeat_interleave(__a , dim=0 ) UpperCAmelCase_ = text_encoder_hidden_states.repeat_interleave(__a , dim=0 ) UpperCAmelCase_ = text_mask.repeat_interleave(__a , dim=0 ) if do_classifier_free_guidance: UpperCAmelCase_ = 42 if negative_prompt is None: UpperCAmelCase_ = [""] * batch_size elif type(__a ) is not type(__a ): raise TypeError( f"""`negative_prompt` should be the same type to `prompt`, but got {type(__a )} !=""" f""" {type(__a )}.""" ) elif isinstance(__a , __a ): UpperCAmelCase_ = [negative_prompt] elif batch_size != len(__a ): raise ValueError( f"""`negative_prompt`: {negative_prompt} has batch size {len(__a )}, but `prompt`:""" f""" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches""" " the batch size of `prompt`." ) else: UpperCAmelCase_ = negative_prompt UpperCAmelCase_ = self.tokenizer( __a , padding="max_length" , max_length=77 , truncation=__a , return_attention_mask=__a , add_special_tokens=__a , return_tensors="pt" , ) UpperCAmelCase_ = uncond_input.input_ids.to(__a ) UpperCAmelCase_ = uncond_input.attention_mask.to(__a ) UpperCAmelCase_ , UpperCAmelCase_ = self.text_encoder( input_ids=__a , attention_mask=__a ) # duplicate unconditional embeddings for each generation per prompt, using mps friendly method UpperCAmelCase_ = negative_prompt_embeds.shape[1] UpperCAmelCase_ = negative_prompt_embeds.repeat(1 , __a ) UpperCAmelCase_ = negative_prompt_embeds.view(batch_size * num_images_per_prompt , __a ) UpperCAmelCase_ = uncond_text_encoder_hidden_states.shape[1] UpperCAmelCase_ = uncond_text_encoder_hidden_states.repeat(1 , __a , 1 ) UpperCAmelCase_ = uncond_text_encoder_hidden_states.view( batch_size * num_images_per_prompt , __a , -1 ) UpperCAmelCase_ = uncond_text_mask.repeat_interleave(__a , dim=0 ) # done duplicates # 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 UpperCAmelCase_ = torch.cat([negative_prompt_embeds, prompt_embeds] ) UpperCAmelCase_ = torch.cat([uncond_text_encoder_hidden_states, text_encoder_hidden_states] ) UpperCAmelCase_ = torch.cat([uncond_text_mask, text_mask] ) return prompt_embeds, text_encoder_hidden_states, text_mask def _lowercase (self : List[Any] , __a : Tuple=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device(f"""cuda:{gpu_id}""" ) UpperCAmelCase_ = [ self.unet, self.text_encoder, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) def _lowercase (self : Tuple , __a : List[Any]=0 ): 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." ) UpperCAmelCase_ = torch.device(f"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to("cpu" , silence_dtype_warnings=__a ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) UpperCAmelCase_ = None for cpu_offloaded_model in [self.text_encoder, self.unet, self.movq]: UpperCAmelCase_ , UpperCAmelCase_ = cpu_offload_with_hook(__a , __a , prev_module_hook=__a ) if self.safety_checker is not None: UpperCAmelCase_ , UpperCAmelCase_ = cpu_offload_with_hook(self.safety_checker , __a , prev_module_hook=__a ) # We'll offload the last model manually. UpperCAmelCase_ = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : int ): if not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_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(__a ) def __call__(self : List[str] , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, List[torch.FloatTensor]] , __a : Union[torch.FloatTensor, List[torch.FloatTensor]] , __a : Optional[Union[str, List[str]]] = None , __a : int = 512 , __a : int = 512 , __a : int = 100 , __a : float = 4.0 , __a : int = 1 , __a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , ): if isinstance(__a , __a ): UpperCAmelCase_ = 1 elif isinstance(__a , __a ): UpperCAmelCase_ = len(__a ) else: raise ValueError(f"""`prompt` has to be of type `str` or `list` but is {type(__a )}""" ) UpperCAmelCase_ = self._execution_device UpperCAmelCase_ = batch_size * num_images_per_prompt UpperCAmelCase_ = guidance_scale > 1.0 UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self._encode_prompt( __a , __a , __a , __a , __a ) if isinstance(__a , __a ): UpperCAmelCase_ = torch.cat(__a , dim=0 ) if isinstance(__a , __a ): UpperCAmelCase_ = torch.cat(__a , dim=0 ) if do_classifier_free_guidance: UpperCAmelCase_ = image_embeds.repeat_interleave(__a , dim=0 ) UpperCAmelCase_ = negative_image_embeds.repeat_interleave(__a , dim=0 ) UpperCAmelCase_ = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to( dtype=prompt_embeds.dtype , device=__a ) self.scheduler.set_timesteps(__a , device=__a ) UpperCAmelCase_ = self.scheduler.timesteps UpperCAmelCase_ = self.unet.config.in_channels UpperCAmelCase_ , UpperCAmelCase_ = get_new_h_w(__a , __a , self.movq_scale_factor ) # create initial latent UpperCAmelCase_ = self.prepare_latents( (batch_size, num_channels_latents, height, width) , text_encoder_hidden_states.dtype , __a , __a , __a , self.scheduler , ) for i, t in enumerate(self.progress_bar(__a ) ): # expand the latents if we are doing classifier free guidance UpperCAmelCase_ = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents UpperCAmelCase_ = {"text_embeds": prompt_embeds, "image_embeds": image_embeds} UpperCAmelCase_ = self.unet( sample=__a , timestep=__a , encoder_hidden_states=__a , added_cond_kwargs=__a , return_dict=__a , )[0] if do_classifier_free_guidance: UpperCAmelCase_ , UpperCAmelCase_ = noise_pred.split(latents.shape[1] , dim=1 ) UpperCAmelCase_ , UpperCAmelCase_ = noise_pred.chunk(2 ) UpperCAmelCase_ , UpperCAmelCase_ = variance_pred.chunk(2 ) UpperCAmelCase_ = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) UpperCAmelCase_ = 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"] ): UpperCAmelCase_ , UpperCAmelCase_ = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 UpperCAmelCase_ = self.scheduler.step( __a , __a , __a , generator=__a , ).prev_sample # post-processing UpperCAmelCase_ = self.movq.decode(__a , force_not_quantize=__a )["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"]: UpperCAmelCase_ = image * 0.5 + 0.5 UpperCAmelCase_ = image.clamp(0 , 1 ) UpperCAmelCase_ = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": UpperCAmelCase_ = self.numpy_to_pil(__a ) if not return_dict: return (image,) return ImagePipelineOutput(images=__a )
78
'''simple docstring''' import copy import re class __A : a__ : Optional[int] = """hp""" a__ : Optional[Any] = {} a__ : List[Any] = None @classmethod def _lowercase (cls : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = prefix UpperCAmelCase_ = defaults cls.build_naming_info() @staticmethod def _lowercase (__a : List[Any] , __a : List[str] ): if len(__a ) == 0: return "" UpperCAmelCase_ = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__a ) + 1 ): UpperCAmelCase_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__a : Union[str, Any] ): UpperCAmelCase_ = "" while integer != 0: UpperCAmelCase_ = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase_ = 0 while True: UpperCAmelCase_ = word + "#" + int_to_alphabetic(__a ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase_ = sword break UpperCAmelCase_ = short_word UpperCAmelCase_ = word return short_word @staticmethod def _lowercase (__a : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = param_name.split("_" ) UpperCAmelCase_ = [TrialShortNamer.shortname_for_word(__a , __a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase_ = ["", "_"] for separator in separators: UpperCAmelCase_ = separator.join(__a ) if shortname not in info["reverse_short_param"]: UpperCAmelCase_ = shortname UpperCAmelCase_ = param_name return shortname return param_name @staticmethod def _lowercase (__a : int , __a : Union[str, Any] ): UpperCAmelCase_ = TrialShortNamer.shortname_for_key(__a , __a ) UpperCAmelCase_ = short_name UpperCAmelCase_ = param_name @classmethod def _lowercase (cls : Any ): if cls.NAMING_INFO is not None: return UpperCAmelCase_ = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } UpperCAmelCase_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__a , __a ) UpperCAmelCase_ = info @classmethod def _lowercase (cls : int , __a : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase_ = cls.NAMING_INFO["short_param"][k] if isinstance(__a , __a ): UpperCAmelCase_ = 1 if v else 0 UpperCAmelCase_ = "" if isinstance(__a , (int, float) ) else "-" UpperCAmelCase_ = f"""{key}{sep}{v}""" name.append(__a ) return "_".join(__a ) @classmethod def _lowercase (cls : Dict , __a : Dict ): UpperCAmelCase_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase_ = [] else: UpperCAmelCase_ = repr.split("_" ) UpperCAmelCase_ = {} for value in values: if "-" in value: UpperCAmelCase_ , UpperCAmelCase_ = value.split("-" ) else: UpperCAmelCase_ = re.sub("[0-9.]" , "" , __a ) UpperCAmelCase_ = float(re.sub("[^0-9.]" , "" , __a ) ) UpperCAmelCase_ = cls.NAMING_INFO["reverse_short_param"][p_k] UpperCAmelCase_ = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase_ = cls.DEFAULTS[k] return parameters
78
1
'''simple docstring''' import os import random import sys from . import cryptomath_module as cryptoMath # noqa: N812 from . import rabin_miller as rabinMiller # noqa: N812 def lowerCAmelCase_ ( ) -> None: '''simple docstring''' print("Making key files..." ) make_key_files("rsa" , 10_24 ) print("Key files generation successful." ) def lowerCAmelCase_ ( snake_case_ : int ) -> tuple[tuple[int, int], tuple[int, int]]: '''simple docstring''' print("Generating prime p..." ) UpperCAmelCase_ = rabinMiller.generate_large_prime(snake_case_ ) print("Generating prime q..." ) UpperCAmelCase_ = rabinMiller.generate_large_prime(snake_case_ ) UpperCAmelCase_ = p * q print("Generating e that is relatively prime to (p - 1) * (q - 1)..." ) while True: UpperCAmelCase_ = random.randrange(2 ** (key_size - 1) , 2 ** (key_size) ) if cryptoMath.gcd(snake_case_ , (p - 1) * (q - 1) ) == 1: break print("Calculating d that is mod inverse of e..." ) UpperCAmelCase_ = cryptoMath.find_mod_inverse(snake_case_ , (p - 1) * (q - 1) ) UpperCAmelCase_ = (n, e) UpperCAmelCase_ = (n, d) return (public_key, private_key) def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : int ) -> None: '''simple docstring''' if os.path.exists(f"""{name}_pubkey.txt""" ) or os.path.exists(f"""{name}_privkey.txt""" ): print("\nWARNING:" ) print( f"""\"{name}_pubkey.txt\" or \"{name}_privkey.txt\" already exists. \n""" "Use a different name or delete these files and re-run this program." ) sys.exit() UpperCAmelCase_ , UpperCAmelCase_ = generate_key(snake_case_ ) print(f"""\nWriting public key to file {name}_pubkey.txt...""" ) with open(f"""{name}_pubkey.txt""" , "w" ) as out_file: out_file.write(f"""{key_size},{public_key[0]},{public_key[1]}""" ) print(f"""Writing private key to file {name}_privkey.txt...""" ) with open(f"""{name}_privkey.txt""" , "w" ) as out_file: out_file.write(f"""{key_size},{private_key[0]},{private_key[1]}""" ) if __name__ == "__main__": main()
78
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ = do_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : list ) -> float: '''simple docstring''' UpperCAmelCase_ = 0 while len(snake_case_ ) > 1: UpperCAmelCase_ = 0 # Consider two files with minimum cost to be merged for _ in range(2 ): UpperCAmelCase_ = files.index(min(snake_case_ ) ) temp += files[min_index] files.pop(snake_case_ ) files.append(snake_case_ ) optimal_merge_cost += temp return optimal_merge_cost if __name__ == "__main__": import doctest doctest.testmod()
78
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
1
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Dict , snake_case_ : Optional[Any] ) -> int: '''simple docstring''' if n == 0: return 1 elif n % 2 == 1: return (binary_exponentiation(snake_case_ , n - 1 , snake_case_ ) * a) % mod else: UpperCAmelCase_ = binary_exponentiation(snake_case_ , n / 2 , snake_case_ ) return (b * b) % mod # a prime number SCREAMING_SNAKE_CASE_: Optional[int] =7_01 SCREAMING_SNAKE_CASE_: Any =10_00_00_00_00 SCREAMING_SNAKE_CASE_: Optional[Any] =10 # using binary exponentiation function, O(log(p)): print((a / b) % p == (a * binary_exponentiation(b, p - 2, p)) % p) print((a / b) % p == (a * b ** (p - 2)) % p)
78
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' SCREAMING_SNAKE_CASE_: Optional[int] =[ 'Audio', 'Array2D', 'Array3D', 'Array4D', 'Array5D', 'ClassLabel', 'Features', 'Sequence', 'Value', 'Image', 'Translation', 'TranslationVariableLanguages', ] from .audio import Audio from .features import ArrayaD, ArrayaD, ArrayaD, ArrayaD, ClassLabel, Features, Sequence, Value from .image import Image from .translation import Translation, TranslationVariableLanguages
78
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
1
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : int = AutoencoderKL a__ : Optional[Any] = """sample""" a__ : Union[str, Any] = 1e-2 @property def _lowercase (self : Optional[int] ): UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = (32, 32) UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(__a ) return {"sample": image} @property def _lowercase (self : Any ): return (3, 32, 32) @property def _lowercase (self : Dict ): return (3, 32, 32) def _lowercase (self : int ): UpperCAmelCase_ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def _lowercase (self : int ): pass def _lowercase (self : int ): pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase (self : List[Any] ): # enable deterministic behavior for gradient checkpointing UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**__a ) model.to(__a ) assert not model.is_gradient_checkpointing and model.training UpperCAmelCase_ = model(**__a ).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() UpperCAmelCase_ = torch.randn_like(__a ) UpperCAmelCase_ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCAmelCase_ = self.model_class(**__a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCAmelCase_ = model_a(**__a ).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() UpperCAmelCase_ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) UpperCAmelCase_ = dict(model.named_parameters() ) UpperCAmelCase_ = 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 _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__a ) self.assertIsNotNone(__a ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__a ) UpperCAmelCase_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) UpperCAmelCase_ = model.to(__a ) model.eval() if torch_device == "mps": UpperCAmelCase_ = torch.manual_seed(0 ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCAmelCase_ = image.to(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , sample_posterior=__a , generator=__a ).sample UpperCAmelCase_ = 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": UpperCAmelCase_ = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": UpperCAmelCase_ = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: UpperCAmelCase_ = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__a , __a , rtol=1E-2 ) ) @slow class __A ( unittest.TestCase ): def _lowercase (self : Dict , __a : Dict , __a : int ): return f"""gaussian_noise_s={seed}_shape={"_".join([str(__a ) for s in shape] )}.npy""" def _lowercase (self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] , __a : Optional[Any]=0 , __a : str=(4, 3, 512, 512) , __a : List[str]=False ): UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a ) ) ).to(__a ).to(__a ) return image def _lowercase (self : List[Any] , __a : Union[str, Any]="CompVis/stable-diffusion-v1-4" , __a : List[Any]=False ): UpperCAmelCase_ = "fp16" if fpaa else None UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = AutoencoderKL.from_pretrained( __a , subfolder="vae" , torch_dtype=__a , revision=__a , ) model.to(__a ).eval() return model def _lowercase (self : List[Any] , __a : List[Any]=0 ): if torch_device == "mps": return torch.manual_seed(__a ) return torch.Generator(device=__a ).manual_seed(__a ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Dict , __a : Optional[int] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , fpaa=__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : int , __a : int , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , 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 _lowercase (self : List[str] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , 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 _lowercase (self : Union[str, Any] , __a : Dict ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase (self : Tuple , __a : List[Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model.encode(__a ).latent_dist UpperCAmelCase_ = dist.sample(generator=__a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCAmelCase_ = sample[0, -1, -3:, -3:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) UpperCAmelCase_ = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(__a , __a , atol=__a )
78
'''simple docstring''' import requests def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None: '''simple docstring''' UpperCAmelCase_ = {"Content-Type": "application/json"} UpperCAmelCase_ = requests.post(snake_case_ , json={"text": message_body} , headers=snake_case_ ) if response.status_code != 2_00: UpperCAmelCase_ = ( "Request to slack returned an error " f"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(snake_case_ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
78
1
'''simple docstring''' from ...utils import ( OptionalDependencyNotAvailable, is_torch_available, is_transformers_available, is_transformers_version, ) try: if not (is_transformers_available() and is_torch_available() and is_transformers_version('>=', '4.25.0')): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from ...utils.dummy_torch_and_transformers_objects import UnCLIPImageVariationPipeline, UnCLIPPipeline else: from .pipeline_unclip import UnCLIPPipeline from .pipeline_unclip_image_variation import UnCLIPImageVariationPipeline from .text_proj import UnCLIPTextProjModel
78
'''simple docstring''' from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : CLIPSegForImageSegmentation , __a : CLIPSegProcessor , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = 1 UpperCAmelCase_ = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = True UpperCAmelCase_ = FrozenDict(__a ) if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _lowercase (self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _lowercase (self : int ): self.enable_attention_slicing(__a ) def _lowercase (self : Optional[Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : Optional[int] ): if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_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() def __call__(self : Dict , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, PIL.Image.Image] , __a : str , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): UpperCAmelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) UpperCAmelCase_ = self.segmentation_model(**__a ) UpperCAmelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCAmelCase_ = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCAmelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
78
1
'''simple docstring''' from __future__ import annotations def lowerCAmelCase_ ( snake_case_ : int | str ) -> bool: '''simple docstring''' UpperCAmelCase_ = str(snake_case_ ) return n == n[::-1] def lowerCAmelCase_ ( snake_case_ : int = 1_00_00_00 ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = 0 for i in range(1 , snake_case_ ): if is_palindrome(snake_case_ ) and is_palindrome(bin(snake_case_ ).split("b" )[1] ): total += i return total if __name__ == "__main__": print(solution(int(str(input().strip()))))
78
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' if number < 0: raise ValueError("number must not be negative" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' import unittest from transformers.models.xlm_prophetnet.tokenization_xlm_prophetnet import SPIECE_UNDERLINE, XLMProphetNetTokenizer from transformers.testing_utils import get_tests_dir, require_sentencepiece, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin SCREAMING_SNAKE_CASE_: Optional[int] =get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece class __A ( UpperCamelCase__ , unittest.TestCase ): a__ : Optional[Any] = XLMProphetNetTokenizer a__ : Union[str, Any] = False a__ : Tuple = True def _lowercase (self : Any ): super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase_ = XLMProphetNetTokenizer(__a , keep_accents=__a ) tokenizer.save_pretrained(self.tmpdirname ) def _lowercase (self : str ): UpperCAmelCase_ = "[PAD]" UpperCAmelCase_ = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__a ) , __a ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__a ) , __a ) def _lowercase (self : Any ): UpperCAmelCase_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , "[PAD]" ) self.assertEqual(vocab_keys[1] , "[CLS]" ) self.assertEqual(vocab_keys[-1] , "j" ) self.assertEqual(len(__a ) , 1012 ) def _lowercase (self : int ): self.assertEqual(self.get_tokenizer().vocab_size , 1012 ) def _lowercase (self : int ): UpperCAmelCase_ = XLMProphetNetTokenizer(__a , keep_accents=__a ) UpperCAmelCase_ = tokenizer.tokenize("This is a test" ) self.assertListEqual(__a , ["▁This", "▁is", "▁a", "▁t", "est"] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__a ) , [value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]] , ) UpperCAmelCase_ = tokenizer.tokenize("I was born in 92000, and this is falsé." ) self.assertListEqual( __a , [ SPIECE_UNDERLINE + "I", SPIECE_UNDERLINE + "was", SPIECE_UNDERLINE + "b", "or", "n", SPIECE_UNDERLINE + "in", SPIECE_UNDERLINE + "", "9", "2", "0", "0", "0", ",", SPIECE_UNDERLINE + "and", SPIECE_UNDERLINE + "this", SPIECE_UNDERLINE + "is", SPIECE_UNDERLINE + "f", "al", "s", "é", ".", ] , ) UpperCAmelCase_ = tokenizer.convert_tokens_to_ids(__a ) self.assertListEqual( __a , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, -9, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, -9, 4] ] , ) UpperCAmelCase_ = tokenizer.convert_ids_to_tokens(__a ) self.assertListEqual( __a , [ 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 _lowercase (self : Optional[int] ): return XLMProphetNetTokenizer.from_pretrained("microsoft/xprophetnet-large-wiki100-cased" ) @slow def _lowercase (self : List[str] ): UpperCAmelCase_ = "Hello World!" UpperCAmelCase_ = [35389, 6672, 49, 2] self.assertListEqual(__a , self.big_tokenizer.encode(__a ) ) @slow def _lowercase (self : int ): # fmt: off UpperCAmelCase_ = {"input_ids": [[11073, 82783, 18, 26, 82783, 549, 51540, 248, 17209, 1301, 217, 20, 215186, 1325, 147, 17209, 1301, 217, 20, 56370, 53, 122020, 20, 16477, 27, 87355, 4548, 20, 4728, 78392, 17, 159969, 18, 26, 24491, 629, 15, 538, 22704, 5439, 15, 2788, 24491, 9885, 15, 43534, 605, 15, 814, 18403, 33200, 29, 15, 43534, 24458, 12410, 111, 24966, 83669, 9637, 144068, 26, 850, 22346, 27, 147, 24966, 83669, 83490, 26, 39113, 735, 27, 689, 656, 2800, 1339, 4600, 53, 122020, 115785, 34, 816, 1339, 46887, 18, 147, 53905, 1951, 42238, 41170, 17732, 834, 436, 15, 27523, 98733, 217, 147, 5542, 4981, 930, 17347, 16, 2], [20091, 629, 94, 82786, 58, 490, 20, 1528, 84, 53905, 344, 80592, 110128, 18822, 5267, 1306, 62, 152537, 308, 7997, 401, 124427, 549, 35442, 225, 109, 15055, 25748, 147, 7119, 43712, 34, 767, 135366, 18, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [592, 63784, 119466, 17, 147808, 88214, 18, 656, 81, 32, 3296, 10280, 16, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__a , model_name="microsoft/xprophetnet-large-wiki100-cased" , revision="1acad1643ddd54a44df6a1b797ada8373685d90e" , )
78
'''simple docstring''' from __future__ import annotations from collections import namedtuple from dataclasses import dataclass @dataclass class __A : a__ : int a__ : TreeNode | None = None a__ : TreeNode | None = None SCREAMING_SNAKE_CASE_: Union[str, Any] =namedtuple('CoinsDistribResult', 'moves excess') def lowerCAmelCase_ ( snake_case_ : TreeNode | None ) -> int: '''simple docstring''' if root is None: return 0 # Validation def count_nodes(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_nodes(node.left ) + count_nodes(node.right ) + 1 def count_coins(snake_case_ : TreeNode | None ) -> int: if node is None: return 0 return count_coins(node.left ) + count_coins(node.right ) + node.data if count_nodes(snake_case_ ) != count_coins(snake_case_ ): raise ValueError("The nodes number should be same as the number of coins" ) # Main calculation def get_distrib(snake_case_ : TreeNode | None ) -> CoinsDistribResult: if node is None: return CoinsDistribResult(0 , 1 ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.left ) UpperCAmelCase_ , UpperCAmelCase_ = get_distrib(node.right ) UpperCAmelCase_ = 1 - left_distrib_excess UpperCAmelCase_ = 1 - right_distrib_excess UpperCAmelCase_ = ( left_distrib_moves + right_distrib_moves + abs(snake_case_ ) + abs(snake_case_ ) ) UpperCAmelCase_ = node.data - coins_to_left - coins_to_right return CoinsDistribResult(snake_case_ , snake_case_ ) return get_distrib(snake_case_ )[0] if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' import flax.linen as nn import jax.numpy as jnp from .attention_flax import FlaxTransformeraDModel from .resnet_flax import FlaxDownsampleaD, FlaxResnetBlockaD, FlaxUpsampleaD class __A ( nn.Module ): a__ : int a__ : int a__ : float = 0.0 a__ : int = 1 a__ : int = 1 a__ : bool = True a__ : bool = False a__ : bool = False a__ : bool = False a__ : jnp.dtype = jnp.floataa def _lowercase (self : Tuple ): UpperCAmelCase_ = [] UpperCAmelCase_ = [] for i in range(self.num_layers ): UpperCAmelCase_ = self.in_channels if i == 0 else self.out_channels UpperCAmelCase_ = FlaxResnetBlockaD( in_channels=__a , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__a ) UpperCAmelCase_ = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(__a ) UpperCAmelCase_ = resnets UpperCAmelCase_ = attentions if self.add_downsample: UpperCAmelCase_ = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__(self : Tuple , __a : Optional[int] , __a : str , __a : List[str] , __a : List[Any]=True ): UpperCAmelCase_ = () for resnet, attn in zip(self.resnets , self.attentions ): UpperCAmelCase_ = resnet(__a , __a , deterministic=__a ) UpperCAmelCase_ = attn(__a , __a , deterministic=__a ) output_states += (hidden_states,) if self.add_downsample: UpperCAmelCase_ = self.downsamplers_a(__a ) output_states += (hidden_states,) return hidden_states, output_states class __A ( nn.Module ): a__ : int a__ : int a__ : float = 0.0 a__ : int = 1 a__ : bool = True a__ : jnp.dtype = jnp.floataa def _lowercase (self : Any ): UpperCAmelCase_ = [] for i in range(self.num_layers ): UpperCAmelCase_ = self.in_channels if i == 0 else self.out_channels UpperCAmelCase_ = FlaxResnetBlockaD( in_channels=__a , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__a ) UpperCAmelCase_ = resnets if self.add_downsample: UpperCAmelCase_ = FlaxDownsampleaD(self.out_channels , dtype=self.dtype ) def __call__(self : Optional[Any] , __a : Optional[Any] , __a : List[Any] , __a : Union[str, Any]=True ): UpperCAmelCase_ = () for resnet in self.resnets: UpperCAmelCase_ = resnet(__a , __a , deterministic=__a ) output_states += (hidden_states,) if self.add_downsample: UpperCAmelCase_ = self.downsamplers_a(__a ) output_states += (hidden_states,) return hidden_states, output_states class __A ( nn.Module ): a__ : int a__ : int a__ : int a__ : float = 0.0 a__ : int = 1 a__ : int = 1 a__ : bool = True a__ : bool = False a__ : bool = False a__ : bool = False a__ : jnp.dtype = jnp.floataa def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = [] UpperCAmelCase_ = [] for i in range(self.num_layers ): UpperCAmelCase_ = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCAmelCase_ = self.prev_output_channel if i == 0 else self.out_channels UpperCAmelCase_ = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__a ) UpperCAmelCase_ = FlaxTransformeraDModel( in_channels=self.out_channels , n_heads=self.num_attention_heads , d_head=self.out_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , only_cross_attention=self.only_cross_attention , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(__a ) UpperCAmelCase_ = resnets UpperCAmelCase_ = attentions if self.add_upsample: UpperCAmelCase_ = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__(self : Optional[int] , __a : Optional[int] , __a : List[str] , __a : Dict , __a : Dict , __a : List[Any]=True ): for resnet, attn in zip(self.resnets , self.attentions ): # pop res hidden states UpperCAmelCase_ = res_hidden_states_tuple[-1] UpperCAmelCase_ = res_hidden_states_tuple[:-1] UpperCAmelCase_ = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCAmelCase_ = resnet(__a , __a , deterministic=__a ) UpperCAmelCase_ = attn(__a , __a , deterministic=__a ) if self.add_upsample: UpperCAmelCase_ = self.upsamplers_a(__a ) return hidden_states class __A ( nn.Module ): a__ : int a__ : int a__ : int a__ : float = 0.0 a__ : int = 1 a__ : bool = True a__ : jnp.dtype = jnp.floataa def _lowercase (self : int ): UpperCAmelCase_ = [] for i in range(self.num_layers ): UpperCAmelCase_ = self.in_channels if (i == self.num_layers - 1) else self.out_channels UpperCAmelCase_ = self.prev_output_channel if i == 0 else self.out_channels UpperCAmelCase_ = FlaxResnetBlockaD( in_channels=resnet_in_channels + res_skip_channels , out_channels=self.out_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__a ) UpperCAmelCase_ = resnets if self.add_upsample: UpperCAmelCase_ = FlaxUpsampleaD(self.out_channels , dtype=self.dtype ) def __call__(self : str , __a : List[Any] , __a : Optional[Any] , __a : List[Any] , __a : Optional[Any]=True ): for resnet in self.resnets: # pop res hidden states UpperCAmelCase_ = res_hidden_states_tuple[-1] UpperCAmelCase_ = res_hidden_states_tuple[:-1] UpperCAmelCase_ = jnp.concatenate((hidden_states, res_hidden_states) , axis=-1 ) UpperCAmelCase_ = resnet(__a , __a , deterministic=__a ) if self.add_upsample: UpperCAmelCase_ = self.upsamplers_a(__a ) return hidden_states class __A ( nn.Module ): a__ : int a__ : float = 0.0 a__ : int = 1 a__ : int = 1 a__ : bool = False a__ : bool = False a__ : jnp.dtype = jnp.floataa def _lowercase (self : int ): # there is always at least one resnet UpperCAmelCase_ = [ FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) ] UpperCAmelCase_ = [] for _ in range(self.num_layers ): UpperCAmelCase_ = FlaxTransformeraDModel( in_channels=self.in_channels , n_heads=self.num_attention_heads , d_head=self.in_channels // self.num_attention_heads , depth=1 , use_linear_projection=self.use_linear_projection , use_memory_efficient_attention=self.use_memory_efficient_attention , dtype=self.dtype , ) attentions.append(__a ) UpperCAmelCase_ = FlaxResnetBlockaD( in_channels=self.in_channels , out_channels=self.in_channels , dropout_prob=self.dropout , dtype=self.dtype , ) resnets.append(__a ) UpperCAmelCase_ = resnets UpperCAmelCase_ = attentions def __call__(self : str , __a : Dict , __a : str , __a : str , __a : List[str]=True ): UpperCAmelCase_ = self.resnets[0](__a , __a ) for attn, resnet in zip(self.attentions , self.resnets[1:] ): UpperCAmelCase_ = attn(__a , __a , deterministic=__a ) UpperCAmelCase_ = resnet(__a , __a , deterministic=__a ) return hidden_states
78
'''simple docstring''' import argparse import json import logging import os import shutil import sys import tempfile import unittest from unittest import mock import torch from accelerate.utils import write_basic_config from transformers.testing_utils import TestCasePlus, get_gpu_count, run_command, slow, torch_device from transformers.utils import is_apex_available logging.basicConfig(level=logging.DEBUG) SCREAMING_SNAKE_CASE_: int =logging.getLogger() def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser() parser.add_argument("-f" ) UpperCAmelCase_ = parser.parse_args() return args.f def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> str: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = os.path.join(snake_case_ , "all_results.json" ) if os.path.exists(snake_case_ ): with open(snake_case_ , "r" ) as f: UpperCAmelCase_ = json.load(snake_case_ ) else: raise ValueError(f"""can't find {path}""" ) return results def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = torch.cuda.is_available() and torch_device == "cuda" return is_using_cuda and is_apex_available() SCREAMING_SNAKE_CASE_: Any =logging.StreamHandler(sys.stdout) logger.addHandler(stream_handler) class __A ( UpperCamelCase__ ): @classmethod def _lowercase (cls : Any ): # Write Accelerate config, will pick up on CPU, GPU, and multi-GPU UpperCAmelCase_ = tempfile.mkdtemp() UpperCAmelCase_ = os.path.join(cls.tmpdir , "default_config.yml" ) write_basic_config(save_location=cls.configPath ) UpperCAmelCase_ = ["accelerate", "launch", "--config_file", cls.configPath] @classmethod def _lowercase (cls : int ): shutil.rmtree(cls.tmpdir ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/text-classification/run_glue_no_trainer.py --model_name_or_path distilbert-base-uncased --output_dir {tmp_dir} --train_file ./tests/fixtures/tests_samples/MRPC/train.csv --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --learning_rate=1e-4 --seed=42 --checkpointing_steps epoch --with_tracking """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "glue_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_clm_no_trainer.py --model_name_or_path distilgpt2 --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --block_size 128 --per_device_train_batch_size 5 --per_device_eval_batch_size 5 --num_train_epochs 2 --output_dir {tmp_dir} --checkpointing_steps epoch --with_tracking """.split() if torch.cuda.device_count() > 1: # Skipping because there are not enough batches to train the model + would need a drop_last to work. return run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 100 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "clm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/language-modeling/run_mlm_no_trainer.py --model_name_or_path distilroberta-base --train_file ./tests/fixtures/sample_text.txt --validation_file ./tests/fixtures/sample_text.txt --output_dir {tmp_dir} --num_train_epochs=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertLess(result["perplexity"] , 42 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "mlm_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[Any] ): # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu UpperCAmelCase_ = 7 if get_gpu_count() > 1 else 2 UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/token-classification/run_ner_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/conll/sample.json --validation_file tests/fixtures/tests_samples/conll/sample.json --output_dir {tmp_dir} --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=2 --num_train_epochs={epochs} --seed 7 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.75 ) self.assertLess(result["train_loss"] , 0.5 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "ner_no_trainer" ) ) ) @unittest.skip(reason="Fix me @muellerzr" ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : int ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/question-answering/run_qa_no_trainer.py --model_name_or_path bert-base-uncased --version_2_with_negative --train_file tests/fixtures/tests_samples/SQUAD/sample.json --validation_file tests/fixtures/tests_samples/SQUAD/sample.json --output_dir {tmp_dir} --seed=42 --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # Because we use --version_2_with_negative the testing script uses SQuAD v2 metrics. self.assertGreaterEqual(result["eval_f1"] , 28 ) self.assertGreaterEqual(result["eval_exact"] , 28 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "qa_no_trainer" ) ) ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : str ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/multiple-choice/run_swag_no_trainer.py --model_name_or_path bert-base-uncased --train_file tests/fixtures/tests_samples/swag/sample.json --validation_file tests/fixtures/tests_samples/swag/sample.json --output_dir {tmp_dir} --max_train_steps=20 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_accuracy"] , 0.8 ) self.assertTrue(os.path.exists(os.path.join(__a , "swag_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/summarization/run_summarization_no_trainer.py --model_name_or_path t5-small --train_file tests/fixtures/tests_samples/xsum/sample.json --validation_file tests/fixtures/tests_samples/xsum/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_rouge1"] , 10 ) self.assertGreaterEqual(result["eval_rouge2"] , 2 ) self.assertGreaterEqual(result["eval_rougeL"] , 7 ) self.assertGreaterEqual(result["eval_rougeLsum"] , 7 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "summarization_no_trainer" ) ) ) @slow @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : List[str] ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/translation/run_translation_no_trainer.py --model_name_or_path sshleifer/student_marian_en_ro_6_1 --source_lang en --target_lang ro --train_file tests/fixtures/tests_samples/wmt16/sample.json --validation_file tests/fixtures/tests_samples/wmt16/sample.json --output_dir {tmp_dir} --max_train_steps=50 --num_warmup_steps=8 --num_beams=6 --learning_rate=3e-3 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --source_lang en_XX --target_lang ro_RO --checkpointing_steps epoch --with_tracking """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_bleu"] , 30 ) self.assertTrue(os.path.exists(os.path.join(__a , "epoch_0" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "translation_no_trainer" ) ) ) @slow def _lowercase (self : Dict ): UpperCAmelCase_ = logging.StreamHandler(sys.stdout ) logger.addHandler(__a ) UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py --dataset_name huggingface/semantic-segmentation-test-sample --output_dir {tmp_dir} --max_train_steps=10 --num_warmup_steps=2 --learning_rate=2e-4 --per_device_train_batch_size=2 --per_device_eval_batch_size=1 --checkpointing_steps epoch """.split() run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) self.assertGreaterEqual(result["eval_overall_accuracy"] , 0.10 ) @mock.patch.dict(os.environ , {"WANDB_MODE": "offline"} ) def _lowercase (self : Any ): UpperCAmelCase_ = self.get_auto_remove_tmp_dir() UpperCAmelCase_ = f""" {self.examples_dir}/pytorch/image-classification/run_image_classification_no_trainer.py --model_name_or_path google/vit-base-patch16-224-in21k --dataset_name hf-internal-testing/cats_vs_dogs_sample --learning_rate 1e-4 --per_device_train_batch_size 2 --per_device_eval_batch_size 1 --max_train_steps 2 --train_val_split 0.1 --seed 42 --output_dir {tmp_dir} --with_tracking --checkpointing_steps 1 """.split() if is_cuda_and_apex_available(): testargs.append("--fp16" ) run_command(self._launch_args + testargs ) UpperCAmelCase_ = get_results(__a ) # The base model scores a 25% self.assertGreaterEqual(result["eval_accuracy"] , 0.6 ) self.assertTrue(os.path.exists(os.path.join(__a , "step_1" ) ) ) self.assertTrue(os.path.exists(os.path.join(__a , "image_classification_no_trainer" ) ) )
78
1
'''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 __A ( unittest.TestCase ): a__ : Optional[Any] = MODEL_FOR_CAUSAL_LM_MAPPING a__ : int = TF_MODEL_FOR_CAUSAL_LM_MAPPING @require_torch def _lowercase (self : str ): UpperCAmelCase_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="pt" ) # Using `do_sample=False` to force deterministic output UpperCAmelCase_ = text_generator("This is a test" , do_sample=__a ) self.assertEqual( __a , [ { "generated_text": ( "This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope." " oscope. FiliFili@@" ) } ] , ) UpperCAmelCase_ = text_generator(["This is a test", "This is a second test"] ) self.assertEqual( __a , [ [ { "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@@" ) } ], ] , ) UpperCAmelCase_ = text_generator("This is a test" , do_sample=__a , num_return_sequences=2 , return_tensors=__a ) self.assertEqual( __a , [ {"generated_token_ids": ANY(__a )}, {"generated_token_ids": ANY(__a )}, ] , ) UpperCAmelCase_ = text_generator.model.config.eos_token_id UpperCAmelCase_ = "<pad>" UpperCAmelCase_ = text_generator( ["This is a test", "This is a second test"] , do_sample=__a , num_return_sequences=2 , batch_size=2 , return_tensors=__a , ) self.assertEqual( __a , [ [ {"generated_token_ids": ANY(__a )}, {"generated_token_ids": ANY(__a )}, ], [ {"generated_token_ids": ANY(__a )}, {"generated_token_ids": ANY(__a )}, ], ] , ) @require_tf def _lowercase (self : Optional[int] ): UpperCAmelCase_ = pipeline(task="text-generation" , model="sshleifer/tiny-ctrl" , framework="tf" ) # Using `do_sample=False` to force deterministic output UpperCAmelCase_ = text_generator("This is a test" , do_sample=__a ) self.assertEqual( __a , [ { "generated_text": ( "This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵" " please," ) } ] , ) UpperCAmelCase_ = text_generator(["This is a test", "This is a second test"] , do_sample=__a ) self.assertEqual( __a , [ [ { "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 _lowercase (self : Tuple , __a : List[str] , __a : List[Any] , __a : Union[str, Any] ): UpperCAmelCase_ = TextGenerationPipeline(model=__a , tokenizer=__a ) return text_generator, ["This is a test", "Another test"] def _lowercase (self : Optional[int] ): UpperCAmelCase_ = "Hello I believe in" UpperCAmelCase_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) UpperCAmelCase_ = text_generator(__a ) self.assertEqual( __a , [{"generated_text": "Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"}] , ) UpperCAmelCase_ = text_generator(__a , stop_sequence=" fe" ) self.assertEqual(__a , [{"generated_text": "Hello I believe in fe"}] ) def _lowercase (self : List[str] , __a : List[Any] , __a : List[str] ): UpperCAmelCase_ = text_generator.model UpperCAmelCase_ = text_generator.tokenizer UpperCAmelCase_ = text_generator("This is a test" ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) UpperCAmelCase_ = text_generator("This is a test" , return_full_text=__a ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) UpperCAmelCase_ = pipeline(task="text-generation" , model=__a , tokenizer=__a , return_full_text=__a ) UpperCAmelCase_ = text_generator("This is a test" ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) self.assertNotIn("This is a test" , outputs[0]["generated_text"] ) UpperCAmelCase_ = text_generator("This is a test" , return_full_text=__a ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) self.assertTrue(outputs[0]["generated_text"].startswith("This is a test" ) ) UpperCAmelCase_ = text_generator(["This is great !", "Something else"] , num_return_sequences=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) if text_generator.tokenizer.pad_token is not None: UpperCAmelCase_ = text_generator( ["This is great !", "Something else"] , num_return_sequences=2 , batch_size=2 , do_sample=__a ) self.assertEqual( __a , [ [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], [{"generated_text": ANY(__a )}, {"generated_text": ANY(__a )}], ] , ) with self.assertRaises(__a ): UpperCAmelCase_ = text_generator("test" , return_full_text=__a , return_text=__a ) with self.assertRaises(__a ): UpperCAmelCase_ = text_generator("test" , return_full_text=__a , return_tensors=__a ) with self.assertRaises(__a ): UpperCAmelCase_ = text_generator("test" , return_text=__a , return_tensors=__a ) # 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__ ): UpperCAmelCase_ = text_generator("" ) self.assertEqual(__a , [{"generated_text": ANY(__a )}] ) else: with self.assertRaises((ValueError, AssertionError) ): UpperCAmelCase_ = 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. UpperCAmelCase_ = ["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 ) UpperCAmelCase_ = text_generator("This is a test" * 500 , handle_long_generation="hole" , max_new_tokens=20 ) # Hole strategy cannot work with self.assertRaises(__a ): 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 _lowercase (self : Tuple ): import torch # Classic `model_kwargs` UpperCAmelCase_ = 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 ) UpperCAmelCase_ = pipe("This is a test" ) self.assertEqual( __a , [ { "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.) UpperCAmelCase_ = 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 ) UpperCAmelCase_ = pipe("This is a test" ) self.assertEqual( __a , [ { "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 UpperCAmelCase_ = 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 ) UpperCAmelCase_ = pipe("This is a test" ) self.assertEqual( __a , [ { "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 _lowercase (self : List[str] ): import torch UpperCAmelCase_ = 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 _lowercase (self : int ): import torch UpperCAmelCase_ = pipeline(model="hf-internal-testing/tiny-random-bloom" , device_map="auto" , torch_dtype=torch.floataa ) pipe("This is a test" , do_sample=__a , top_p=0.5 ) def _lowercase (self : List[str] ): UpperCAmelCase_ = "Hello world" UpperCAmelCase_ = pipeline("text-generation" , model="hf-internal-testing/tiny-random-gpt2" ) if text_generator.model.framework == "tf": UpperCAmelCase_ = logging.get_logger("transformers.generation.tf_utils" ) else: UpperCAmelCase_ = logging.get_logger("transformers.generation.utils" ) UpperCAmelCase_ = "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(__a ) as cl: UpperCAmelCase_ = text_generator(__a , max_length=10 , max_new_tokens=1 ) self.assertIn(__a , cl.out ) # The user only sets one -> no warning with CaptureLogger(__a ) as cl: UpperCAmelCase_ = text_generator(__a , max_new_tokens=1 ) self.assertNotIn(__a , cl.out ) with CaptureLogger(__a ) as cl: UpperCAmelCase_ = text_generator(__a , max_length=10 ) self.assertNotIn(__a , cl.out )
78
'''simple docstring''' import builtins import sys from ...utils.imports import _is_package_available from . import cursor, input from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor from .keymap import KEYMAP SCREAMING_SNAKE_CASE_: Any =False try: SCREAMING_SNAKE_CASE_: Optional[Any] =_is_package_available('google.colab') except ModuleNotFoundError: pass @input.register class __A : def __init__(self : int , __a : str = None , __a : list = [] ): UpperCAmelCase_ = 0 UpperCAmelCase_ = choices UpperCAmelCase_ = prompt if sys.platform == "win32": UpperCAmelCase_ = "*" else: UpperCAmelCase_ = "➔ " def _lowercase (self : Union[str, Any] , __a : Optional[int] , __a : str = "" ): if sys.platform != "win32": writeColor(self.choices[index] , 32 , __a ) else: forceWrite(self.choices[index] , __a ) def _lowercase (self : Any , __a : int ): if index == self.position: forceWrite(f""" {self.arrow_char} """ ) self.write_choice(__a ) else: forceWrite(f""" {self.choices[index]}""" ) reset_cursor() def _lowercase (self : Optional[Any] , __a : Direction , __a : int = 1 ): UpperCAmelCase_ = self.position if direction == Direction.DOWN: if self.position + 1 >= len(self.choices ): return self.position += num_spaces else: if self.position - 1 < 0: return self.position -= num_spaces clear_line() self.print_choice(__a ) move_cursor(__a , direction.name ) self.print_choice(self.position ) @input.mark(KEYMAP["up"] ) def _lowercase (self : Dict ): self.move_direction(Direction.UP ) @input.mark(KEYMAP["down"] ) def _lowercase (self : Any ): self.move_direction(Direction.DOWN ) @input.mark(KEYMAP["newline"] ) def _lowercase (self : Optional[Any] ): move_cursor(len(self.choices ) - self.position , "DOWN" ) return self.position @input.mark(KEYMAP["interrupt"] ) def _lowercase (self : str ): move_cursor(len(self.choices ) - self.position , "DOWN" ) raise KeyboardInterrupt @input.mark_multiple(*[KEYMAP[str(__a )] for number in range(10 )] ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = int(chr(self.current_selection ) ) UpperCAmelCase_ = index - self.position if index == self.position: return if index < len(self.choices ): if self.position > index: self.move_direction(Direction.UP , -movement ) elif self.position < index: self.move_direction(Direction.DOWN , __a ) else: return else: return def _lowercase (self : Optional[Any] , __a : int = 0 ): if self.prompt: linebreak() forceWrite(self.prompt , "\n" ) if in_colab: forceWrite("Please input a choice index (starting from 0), and press enter" , "\n" ) else: forceWrite("Please select a choice using the arrow or number keys, and selecting with enter" , "\n" ) UpperCAmelCase_ = default_choice for i in range(len(self.choices ) ): self.print_choice(__a ) forceWrite("\n" ) move_cursor(len(self.choices ) - self.position , "UP" ) with cursor.hide(): while True: if in_colab: try: UpperCAmelCase_ = int(builtins.input() ) except ValueError: UpperCAmelCase_ = default_choice else: UpperCAmelCase_ = self.handle_input() if choice is not None: reset_cursor() for _ in range(len(self.choices ) + 1 ): move_cursor(1 , "UP" ) clear_line() self.write_choice(__a , "\n" ) return choice
78
1
'''simple docstring''' 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 __A : def __init__(self : Tuple , __a : Dict , __a : Union[str, Any]=2 , __a : List[Any]=True , __a : str=False , __a : List[Any]=10 , __a : Optional[int]=3 , __a : Any=32 * 4 , __a : Any=32 * 6 , __a : Optional[int]=4 , __a : Optional[Any]=32 , ): UpperCAmelCase_ = parent UpperCAmelCase_ = batch_size UpperCAmelCase_ = is_training UpperCAmelCase_ = use_auxiliary_loss UpperCAmelCase_ = num_queries UpperCAmelCase_ = num_channels UpperCAmelCase_ = min_size UpperCAmelCase_ = max_size UpperCAmelCase_ = num_labels UpperCAmelCase_ = mask_feature_size def _lowercase (self : Dict ): UpperCAmelCase_ = floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size] ).to( __a ) UpperCAmelCase_ = torch.ones([self.batch_size, self.min_size, self.max_size] , device=__a ) UpperCAmelCase_ = ( torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] , device=__a ) > 0.5 ).float() UpperCAmelCase_ = (torch.rand((self.batch_size, self.num_labels) , device=__a ) > 0.5).long() UpperCAmelCase_ = self.get_config() return config, pixel_values, pixel_mask, mask_labels, class_labels def _lowercase (self : Union[str, Any] ): 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 _lowercase (self : List[str] ): UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_config_and_inputs() UpperCAmelCase_ = {"pixel_values": pixel_values, "pixel_mask": pixel_mask} return config, inputs_dict def _lowercase (self : int , __a : int , __a : Union[str, Any] ): UpperCAmelCase_ = output.encoder_hidden_states UpperCAmelCase_ = output.pixel_decoder_hidden_states UpperCAmelCase_ = output.transformer_decoder_hidden_states self.parent.assertTrue(len(__a ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__a ) , len(config.backbone_config.depths ) ) self.parent.assertTrue(len(__a ) , config.decoder_config.decoder_layers ) def _lowercase (self : Tuple , __a : Union[str, Any] , __a : Any , __a : Union[str, Any] , __a : Any=False ): with torch.no_grad(): UpperCAmelCase_ = MaskFormerModel(config=__a ) model.to(__a ) model.eval() UpperCAmelCase_ = model(pixel_values=__a , pixel_mask=__a ) UpperCAmelCase_ = model(__a , output_hidden_states=__a ) # 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(__a , __a ) def _lowercase (self : Optional[Any] , __a : int , __a : List[str] , __a : Dict , __a : Any , __a : Optional[Any] ): UpperCAmelCase_ = MaskFormerForInstanceSegmentation(config=__a ) model.to(__a ) model.eval() def comm_check_on_output(__a : Any ): # 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(): UpperCAmelCase_ = model(pixel_values=__a , pixel_mask=__a ) UpperCAmelCase_ = model(__a ) comm_check_on_output(__a ) UpperCAmelCase_ = model( pixel_values=__a , pixel_mask=__a , mask_labels=__a , class_labels=__a ) comm_check_on_output(__a ) self.parent.assertTrue(result.loss is not None ) self.parent.assertEqual(result.loss.shape , torch.Size([1] ) ) @require_torch class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : List[str] = (MaskFormerModel, MaskFormerForInstanceSegmentation) if is_torch_available() else () a__ : List[Any] = ( {"""feature-extraction""": MaskFormerModel, """image-segmentation""": MaskFormerForInstanceSegmentation} if is_torch_available() else {} ) a__ : Optional[int] = False a__ : str = False a__ : Dict = False a__ : List[Any] = False def _lowercase (self : int ): UpperCAmelCase_ = MaskFormerModelTester(self ) UpperCAmelCase_ = ConfigTester(self , config_class=__a , has_text_modality=__a ) def _lowercase (self : Optional[Any] ): self.config_tester.run_common_tests() def _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(__a , **__a , output_hidden_states=__a ) def _lowercase (self : int ): UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_maskformer_instance_segmentation_head_model(*__a ) @unittest.skip(reason="MaskFormer does not use inputs_embeds" ) def _lowercase (self : str ): pass @unittest.skip(reason="MaskFormer does not have a get_input_embeddings method" ) def _lowercase (self : Any ): pass @unittest.skip(reason="MaskFormer is not a generative model" ) def _lowercase (self : str ): pass @unittest.skip(reason="MaskFormer does not use token embeddings" ) def _lowercase (self : Any ): pass @require_torch_multi_gpu @unittest.skip( reason="MaskFormer has some layers using `add_module` which doesn't work well with `nn.DataParallel`" ) def _lowercase (self : List[Any] ): pass @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests." ) def _lowercase (self : str ): pass def _lowercase (self : int ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__a ) UpperCAmelCase_ = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic UpperCAmelCase_ = [*signature.parameters.keys()] UpperCAmelCase_ = ["pixel_values"] self.assertListEqual(arg_names[:1] , __a ) @slow def _lowercase (self : List[str] ): for model_name in ["facebook/maskformer-swin-small-coco"]: UpperCAmelCase_ = MaskFormerModel.from_pretrained(__a ) self.assertIsNotNone(__a ) def _lowercase (self : Any ): UpperCAmelCase_ = (self.model_tester.min_size,) * 2 UpperCAmelCase_ = { "pixel_values": torch.randn((2, 3, *size) , device=__a ), "mask_labels": torch.randn((2, 10, *size) , device=__a ), "class_labels": torch.zeros(2 , 10 , device=__a ).long(), } UpperCAmelCase_ = MaskFormerForInstanceSegmentation(MaskFormerConfig() ).to(__a ) UpperCAmelCase_ = model(**__a ) self.assertTrue(outputs.loss is not None ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.create_and_check_maskformer_model(__a , **__a , output_hidden_states=__a ) def _lowercase (self : List[str] ): UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: UpperCAmelCase_ = model_class(__a ).to(__a ) UpperCAmelCase_ = model(**__a , output_attentions=__a ) self.assertTrue(outputs.attentions is not None ) def _lowercase (self : List[Any] ): if not self.model_tester.is_training: return # only MaskFormerForInstanceSegmentation has the loss UpperCAmelCase_ = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_ = model_class(__a ) model.to(__a ) model.train() UpperCAmelCase_ = model(__a , mask_labels=__a , class_labels=__a ).loss loss.backward() def _lowercase (self : Optional[Any] ): # only MaskFormerForInstanceSegmentation has the loss UpperCAmelCase_ = self.all_model_classes[1] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = self.model_tester.prepare_config_and_inputs() UpperCAmelCase_ = True UpperCAmelCase_ = True UpperCAmelCase_ = model_class(__a ) model.to(__a ) model.train() UpperCAmelCase_ = model(__a , mask_labels=__a , class_labels=__a ) UpperCAmelCase_ = outputs.encoder_hidden_states[0] encoder_hidden_states.retain_grad() UpperCAmelCase_ = 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 UpperCAmelCase_ = outputs.transformer_decoder_hidden_states[0] transformer_decoder_hidden_states.retain_grad() UpperCAmelCase_ = outputs.attentions[0] attentions.retain_grad() outputs.loss.backward(retain_graph=__a ) self.assertIsNotNone(encoder_hidden_states.grad ) self.assertIsNotNone(pixel_decoder_hidden_states.grad ) self.assertIsNotNone(transformer_decoder_hidden_states.grad ) self.assertIsNotNone(attentions.grad ) SCREAMING_SNAKE_CASE_: int =1E-4 def lowerCAmelCase_ ( ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_vision @slow class __A ( unittest.TestCase ): @cached_property def _lowercase (self : str ): return ( MaskFormerImageProcessor.from_pretrained("facebook/maskformer-swin-small-coco" ) if is_vision_available() else None ) def _lowercase (self : str ): UpperCAmelCase_ = MaskFormerModel.from_pretrained("facebook/maskformer-swin-small-coco" ).to(__a ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(__a , return_tensors="pt" ).to(__a ) UpperCAmelCase_ = 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(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCAmelCase_ = model(**__a ) UpperCAmelCase_ = torch.tensor( [[-0.04_82, 0.92_28, 0.49_51], [-0.25_47, 0.80_17, 0.85_27], [-0.00_69, 0.33_85, -0.00_89]] ).to(__a ) self.assertTrue( torch.allclose( outputs.encoder_last_hidden_state[0, 0, :3, :3] , __a , atol=__a ) ) UpperCAmelCase_ = torch.tensor( [[-0.84_22, -0.84_34, -0.97_18], [-1.01_44, -0.55_65, -0.41_95], [-1.00_38, -0.44_84, -0.19_61]] ).to(__a ) self.assertTrue( torch.allclose( outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] , __a , atol=__a ) ) UpperCAmelCase_ = torch.tensor( [[0.28_52, -0.01_59, 0.97_35], [0.62_54, 0.18_58, 0.85_29], [-0.06_80, -0.41_16, 1.84_13]] ).to(__a ) self.assertTrue( torch.allclose( outputs.transformer_decoder_last_hidden_state[0, :3, :3] , __a , atol=__a ) ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(__a ) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(__a , return_tensors="pt" ).to(__a ) UpperCAmelCase_ = 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(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCAmelCase_ = model(**__a ) # masks_queries_logits UpperCAmelCase_ = 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) , ) UpperCAmelCase_ = [ [-1.3_73_71_24, -1.7_72_49_37, -1.9_36_42_33], [-1.5_97_72_81, -1.9_86_79_39, -2.1_52_36_95], [-1.5_79_53_98, -1.9_26_98_32, -2.09_39_42], ] UpperCAmelCase_ = torch.tensor(__a ).to(__a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __a , atol=__a ) ) # class_queries_logits UpperCAmelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) UpperCAmelCase_ = torch.tensor( [ [1.6512E00, -5.2572E00, -3.3519E00], [3.6169E-02, -5.9025E00, -2.9313E00], [1.0766E-04, -7.7630E00, -5.1263E00], ] ).to(__a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , atol=__a ) ) def _lowercase (self : Tuple ): UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-resnet101-coco-stuff" ) .to(__a ) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = image_processor(__a , return_tensors="pt" ).to(__a ) UpperCAmelCase_ = 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(__a , (1, 3, 800, 1088) ) with torch.no_grad(): UpperCAmelCase_ = model(**__a ) # masks_queries_logits UpperCAmelCase_ = 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) , ) UpperCAmelCase_ = [[-0.90_46, -2.63_66, -4.60_62], [-3.41_79, -5.78_90, -8.80_57], [-4.91_79, -7.65_60, -10.77_11]] UpperCAmelCase_ = torch.tensor(__a ).to(__a ) self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] , __a , atol=__a ) ) # class_queries_logits UpperCAmelCase_ = outputs.class_queries_logits self.assertEqual( class_queries_logits.shape , (1, model.config.decoder_config.num_queries, model.config.num_labels + 1) ) UpperCAmelCase_ = torch.tensor( [[4.71_88, -3.25_85, -2.88_57], [6.68_71, -2.91_81, -1.24_87], [7.24_49, -2.27_64, -2.18_74]] ).to(__a ) self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] , __a , atol=__a ) ) def _lowercase (self : List[str] ): UpperCAmelCase_ = ( MaskFormerForInstanceSegmentation.from_pretrained("facebook/maskformer-swin-small-coco" ) .to(__a ) .eval() ) UpperCAmelCase_ = self.default_image_processor UpperCAmelCase_ = image_processor( [np.zeros((3, 800, 1333) ), np.zeros((3, 800, 1333) )] , segmentation_maps=[np.zeros((384, 384) ).astype(np.floataa ), np.zeros((384, 384) ).astype(np.floataa )] , return_tensors="pt" , ) UpperCAmelCase_ = inputs["pixel_values"].to(__a ) UpperCAmelCase_ = [el.to(__a ) for el in inputs["mask_labels"]] UpperCAmelCase_ = [el.to(__a ) for el in inputs["class_labels"]] with torch.no_grad(): UpperCAmelCase_ = model(**__a ) self.assertTrue(outputs.loss is not None )
78
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_: Optional[int] ={'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['BeitFeatureExtractor'] SCREAMING_SNAKE_CASE_: int =['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: int =[ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
1
'''simple docstring''' import inspect import os import unittest import torch import accelerate from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_multi_gpu from accelerate.utils import patch_environment class __A ( unittest.TestCase ): def _lowercase (self : Optional[int] ): UpperCAmelCase_ = inspect.getfile(accelerate.test_utils ) UpperCAmelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_script.py"] ) UpperCAmelCase_ = os.path.sep.join( mod_file.split(os.path.sep )[:-1] + ["scripts", "test_distributed_data_loop.py"] ) UpperCAmelCase_ = os.path.sep.join(mod_file.split(os.path.sep )[:-1] + ["scripts", "test_ops.py"] ) @require_multi_gpu def _lowercase (self : Any ): print(f"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase_ = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.test_file_path] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() ) @require_multi_gpu def _lowercase (self : List[Any] ): print(f"""Found {torch.cuda.device_count()} devices.""" ) UpperCAmelCase_ = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.operation_file_path] print(f"""Command: {cmd}""" ) with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() ) @require_multi_gpu def _lowercase (self : Dict ): UpperCAmelCase_ = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", inspect.getfile(self.__class__ )] with patch_environment(omp_num_threads=1 ): execute_subprocess_async(__a , env=os.environ.copy() ) @require_multi_gpu def _lowercase (self : Dict ): print(f"""Found {torch.cuda.device_count()} devices, using 2 devices only""" ) UpperCAmelCase_ = ["torchrun", f"""--nproc_per_node={torch.cuda.device_count()}""", self.data_loop_file_path] with patch_environment(omp_num_threads=1 , cuda_visible_devices="0,1" ): execute_subprocess_async(__a , env=os.environ.copy() ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Dict =Accelerator() SCREAMING_SNAKE_CASE_: Dict =(accelerator.state.process_index + 2, 10) SCREAMING_SNAKE_CASE_: Union[str, Any] =torch.randint(0, 10, shape).to(accelerator.device) SCREAMING_SNAKE_CASE_: Optional[Any] ='' SCREAMING_SNAKE_CASE_: Union[str, Any] =accelerator.pad_across_processes(tensor) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." if not torch.equal(tensora[: accelerator.state.process_index + 2], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[accelerator.state.process_index + 2 :] == 0): error_msg += "Padding was not done with the right value (0)." SCREAMING_SNAKE_CASE_: List[str] =accelerator.pad_across_processes(tensor, pad_first=True) if tensora.shape[0] != accelerator.state.num_processes + 1: error_msg += f"Found shape {tensora.shape} but should have {accelerator.state.num_processes + 1} at dim 0." SCREAMING_SNAKE_CASE_: List[str] =accelerator.state.num_processes - accelerator.state.process_index - 1 if not torch.equal(tensora[index:], tensor): error_msg += "Tensors have different values." if not torch.all(tensora[:index] == 0): error_msg += "Padding was not done with the right value (0)." # Raise error at the end to make sure we don't stop at the first failure. if len(error_msg) > 0: raise ValueError(error_msg)
78
'''simple docstring''' import argparse import json import os import pickle import shutil import numpy as np import torch from distiller import Distiller from lm_seqs_dataset import LmSeqsDataset from transformers import ( BertConfig, BertForMaskedLM, BertTokenizer, DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer, GPTaConfig, GPTaLMHeadModel, GPTaTokenizer, RobertaConfig, RobertaForMaskedLM, RobertaTokenizer, ) from utils import git_log, init_gpu_params, logger, set_seed SCREAMING_SNAKE_CASE_: Any ={ 'distilbert': (DistilBertConfig, DistilBertForMaskedLM, DistilBertTokenizer), 'roberta': (RobertaConfig, RobertaForMaskedLM, RobertaTokenizer), 'bert': (BertConfig, BertForMaskedLM, BertTokenizer), 'gpt2': (GPTaConfig, GPTaLMHeadModel, GPTaTokenizer), } def lowerCAmelCase_ ( snake_case_ : Any ) -> str: '''simple docstring''' assert (args.mlm and args.alpha_mlm > 0.0) or (not args.mlm and args.alpha_mlm == 0.0) assert (args.alpha_mlm > 0.0 and args.alpha_clm == 0.0) or (args.alpha_mlm == 0.0 and args.alpha_clm > 0.0) if args.mlm: assert os.path.isfile(args.token_counts ) assert (args.student_type in ["roberta", "distilbert"]) and (args.teacher_type in ["roberta", "bert"]) else: assert (args.student_type in ["gpt2"]) and (args.teacher_type in ["gpt2"]) assert args.teacher_type == args.student_type or ( args.student_type == "distilbert" and args.teacher_type == "bert" ) assert os.path.isfile(args.student_config ) if args.student_pretrained_weights is not None: assert os.path.isfile(args.student_pretrained_weights ) if args.freeze_token_type_embds: assert args.student_type in ["roberta"] assert args.alpha_ce >= 0.0 assert args.alpha_mlm >= 0.0 assert args.alpha_clm >= 0.0 assert args.alpha_mse >= 0.0 assert args.alpha_cos >= 0.0 assert args.alpha_ce + args.alpha_mlm + args.alpha_clm + args.alpha_mse + args.alpha_cos > 0.0 def lowerCAmelCase_ ( snake_case_ : Optional[Any] , snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False elif args.student_type == "gpt2": UpperCAmelCase_ = False def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] ) -> Tuple: '''simple docstring''' if args.student_type == "roberta": UpperCAmelCase_ = False def lowerCAmelCase_ ( ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = argparse.ArgumentParser(description="Training" ) parser.add_argument("--force" , action="store_true" , help="Overwrite dump_path if it already exists." ) parser.add_argument( "--dump_path" , type=snake_case_ , required=snake_case_ , help="The output directory (log, checkpoints, parameters, etc.)" ) parser.add_argument( "--data_file" , type=snake_case_ , required=snake_case_ , help="The binarized file (tokenized + tokens_to_ids) and grouped by sequence." , ) parser.add_argument( "--student_type" , type=snake_case_ , choices=["distilbert", "roberta", "gpt2"] , required=snake_case_ , help="The student type (DistilBERT, RoBERTa)." , ) parser.add_argument("--student_config" , type=snake_case_ , required=snake_case_ , help="Path to the student configuration." ) parser.add_argument( "--student_pretrained_weights" , default=snake_case_ , type=snake_case_ , help="Load student initialization checkpoint." ) parser.add_argument( "--teacher_type" , choices=["bert", "roberta", "gpt2"] , required=snake_case_ , help="Teacher type (BERT, RoBERTa)." ) parser.add_argument("--teacher_name" , type=snake_case_ , required=snake_case_ , help="The teacher model." ) parser.add_argument("--temperature" , default=2.0 , type=snake_case_ , help="Temperature for the softmax temperature." ) parser.add_argument( "--alpha_ce" , default=0.5 , type=snake_case_ , help="Linear weight for the distillation loss. Must be >=0." ) parser.add_argument( "--alpha_mlm" , default=0.0 , type=snake_case_ , help="Linear weight for the MLM loss. Must be >=0. Should be used in conjunction with `mlm` flag." , ) parser.add_argument("--alpha_clm" , default=0.5 , type=snake_case_ , help="Linear weight for the CLM loss. Must be >=0." ) parser.add_argument("--alpha_mse" , default=0.0 , type=snake_case_ , help="Linear weight of the MSE loss. Must be >=0." ) parser.add_argument( "--alpha_cos" , default=0.0 , type=snake_case_ , help="Linear weight of the cosine embedding loss. Must be >=0." ) parser.add_argument( "--mlm" , action="store_true" , help="The LM step: MLM or CLM. If `mlm` is True, the MLM is used over CLM." ) parser.add_argument( "--mlm_mask_prop" , default=0.15 , type=snake_case_ , help="Proportion of tokens for which we need to make a prediction." , ) parser.add_argument("--word_mask" , default=0.8 , type=snake_case_ , help="Proportion of tokens to mask out." ) parser.add_argument("--word_keep" , default=0.1 , type=snake_case_ , help="Proportion of tokens to keep." ) parser.add_argument("--word_rand" , default=0.1 , type=snake_case_ , help="Proportion of tokens to randomly replace." ) parser.add_argument( "--mlm_smoothing" , default=0.7 , type=snake_case_ , help="Smoothing parameter to emphasize more rare tokens (see XLM, similar to word2vec)." , ) parser.add_argument("--token_counts" , type=snake_case_ , help="The token counts in the data_file for MLM." ) parser.add_argument( "--restrict_ce_to_mask" , action="store_true" , help="If true, compute the distillation loss only the [MLM] prediction distribution." , ) parser.add_argument( "--freeze_pos_embs" , action="store_true" , help="Freeze positional embeddings during distillation. For student_type in ['roberta', 'gpt2'] only." , ) parser.add_argument( "--freeze_token_type_embds" , action="store_true" , help="Freeze token type embeddings during distillation if existent. For student_type in ['roberta'] only." , ) parser.add_argument("--n_epoch" , type=snake_case_ , default=3 , help="Number of pass on the whole dataset." ) parser.add_argument("--batch_size" , type=snake_case_ , default=5 , help="Batch size (for each process)." ) parser.add_argument( "--group_by_size" , action="store_false" , help="If true, group sequences that have similar length into the same batch. Default is true." , ) parser.add_argument( "--gradient_accumulation_steps" , type=snake_case_ , default=50 , help="Gradient accumulation for larger training batches." , ) parser.add_argument("--warmup_prop" , default=0.05 , type=snake_case_ , help="Linear warmup proportion." ) parser.add_argument("--weight_decay" , default=0.0 , type=snake_case_ , help="Weight decay if we apply some." ) parser.add_argument("--learning_rate" , default=5E-4 , type=snake_case_ , help="The initial learning rate for Adam." ) parser.add_argument("--adam_epsilon" , default=1E-6 , type=snake_case_ , help="Epsilon for Adam optimizer." ) parser.add_argument("--max_grad_norm" , default=5.0 , type=snake_case_ , help="Max gradient norm." ) parser.add_argument("--initializer_range" , default=0.02 , type=snake_case_ , help="Random initialization range." ) parser.add_argument( "--fp16" , action="store_true" , help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit" , ) parser.add_argument( "--fp16_opt_level" , type=snake_case_ , default="O1" , help=( "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']." "See details at https://nvidia.github.io/apex/amp.html" ) , ) parser.add_argument("--n_gpu" , type=snake_case_ , default=1 , help="Number of GPUs in the node." ) parser.add_argument("--local_rank" , type=snake_case_ , default=-1 , help="Distributed training - Local rank" ) parser.add_argument("--seed" , type=snake_case_ , default=56 , help="Random seed" ) parser.add_argument("--log_interval" , type=snake_case_ , default=5_00 , help="Tensorboard logging interval." ) parser.add_argument("--checkpoint_interval" , type=snake_case_ , default=40_00 , help="Checkpoint interval." ) UpperCAmelCase_ = parser.parse_args() sanity_checks(snake_case_ ) # ARGS # init_gpu_params(snake_case_ ) set_seed(snake_case_ ) if args.is_master: if os.path.exists(args.dump_path ): if not args.force: raise ValueError( f"""Serialization dir {args.dump_path} already exists, but you have not precised wheter to overwrite""" " itUse `--force` if you want to overwrite it" ) else: shutil.rmtree(args.dump_path ) if not os.path.exists(args.dump_path ): os.makedirs(args.dump_path ) logger.info(f"""Experiment will be dumped and logged in {args.dump_path}""" ) # SAVE PARAMS # logger.info(f"""Param: {args}""" ) with open(os.path.join(args.dump_path , "parameters.json" ) , "w" ) as f: json.dump(vars(snake_case_ ) , snake_case_ , indent=4 ) git_log(args.dump_path ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.student_type] UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = MODEL_CLASSES[args.teacher_type] # TOKENIZER # UpperCAmelCase_ = teacher_tokenizer_class.from_pretrained(args.teacher_name ) UpperCAmelCase_ = {} for tok_name, tok_symbol in tokenizer.special_tokens_map.items(): UpperCAmelCase_ = tokenizer.all_special_tokens.index(snake_case_ ) UpperCAmelCase_ = tokenizer.all_special_ids[idx] logger.info(f"""Special tokens {special_tok_ids}""" ) UpperCAmelCase_ = special_tok_ids UpperCAmelCase_ = tokenizer.max_model_input_sizes[args.teacher_name] # DATA LOADER # logger.info(f"""Loading data from {args.data_file}""" ) with open(args.data_file , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) if args.mlm: logger.info(f"""Loading token counts from {args.token_counts} (already pre-computed)""" ) with open(args.token_counts , "rb" ) as fp: UpperCAmelCase_ = pickle.load(snake_case_ ) UpperCAmelCase_ = np.maximum(snake_case_ , 1 ) ** -args.mlm_smoothing for idx in special_tok_ids.values(): UpperCAmelCase_ = 0.0 # do not predict special tokens UpperCAmelCase_ = torch.from_numpy(snake_case_ ) else: UpperCAmelCase_ = None UpperCAmelCase_ = LmSeqsDataset(params=snake_case_ , data=snake_case_ ) logger.info("Data loader created." ) # STUDENT # logger.info(f"""Loading student config from {args.student_config}""" ) UpperCAmelCase_ = student_config_class.from_pretrained(args.student_config ) UpperCAmelCase_ = True if args.student_pretrained_weights is not None: logger.info(f"""Loading pretrained weights from {args.student_pretrained_weights}""" ) UpperCAmelCase_ = student_model_class.from_pretrained(args.student_pretrained_weights , config=snake_case_ ) else: UpperCAmelCase_ = student_model_class(snake_case_ ) if args.n_gpu > 0: student.to(f"""cuda:{args.local_rank}""" ) logger.info("Student loaded." ) # TEACHER # UpperCAmelCase_ = teacher_model_class.from_pretrained(args.teacher_name , output_hidden_states=snake_case_ ) if args.n_gpu > 0: teacher.to(f"""cuda:{args.local_rank}""" ) logger.info(f"""Teacher loaded from {args.teacher_name}.""" ) # FREEZING # if args.freeze_pos_embs: freeze_pos_embeddings(snake_case_ , snake_case_ ) if args.freeze_token_type_embds: freeze_token_type_embeddings(snake_case_ , snake_case_ ) # SANITY CHECKS # assert student.config.vocab_size == teacher.config.vocab_size assert student.config.hidden_size == teacher.config.hidden_size assert student.config.max_position_embeddings == teacher.config.max_position_embeddings if args.mlm: assert token_probs.size(0 ) == stu_architecture_config.vocab_size # DISTILLER # torch.cuda.empty_cache() UpperCAmelCase_ = Distiller( params=snake_case_ , dataset=snake_case_ , token_probs=snake_case_ , student=snake_case_ , teacher=snake_case_ ) distiller.train() logger.info("Let's go get some drinks." ) if __name__ == "__main__": main()
78
1
'''simple docstring''' import logging from pathlib import Path import numpy as np import pytorch_lightning as pl import torch from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint from pytorch_lightning.utilities import rank_zero_only from utils_rag import save_json def lowerCAmelCase_ ( snake_case_ : Optional[int] ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = filter(lambda snake_case_ : p.requires_grad , model.parameters() ) UpperCAmelCase_ = sum([np.prod(p.size() ) for p in model_parameters] ) return params SCREAMING_SNAKE_CASE_: Tuple =logging.getLogger(__name__) def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' if metric == "rouge2": UpperCAmelCase_ = "{val_avg_rouge2:.4f}-{step_count}" elif metric == "bleu": UpperCAmelCase_ = "{val_avg_bleu:.4f}-{step_count}" elif metric == "em": UpperCAmelCase_ = "{val_avg_em:.4f}-{step_count}" else: raise NotImplementedError( f"""seq2seq callbacks only support rouge2 and bleu, got {metric}, You can make your own by adding to this""" " function." ) UpperCAmelCase_ = ModelCheckpoint( dirpath=snake_case_ , filename=snake_case_ , monitor=f"""val_{metric}""" , mode="max" , save_top_k=3 , every_n_epochs=1 , ) return checkpoint_callback def lowerCAmelCase_ ( snake_case_ : Union[str, Any] , snake_case_ : Optional[int] ) -> Any: '''simple docstring''' return EarlyStopping( monitor=f"""val_{metric}""" , mode="min" if "loss" in metric else "max" , patience=snake_case_ , verbose=snake_case_ , ) class __A ( pl.Callback ): def _lowercase (self : Optional[Any] , __a : Optional[int] , __a : Any ): UpperCAmelCase_ = {f"""lr_group_{i}""": param["lr"] for i, param in enumerate(pl_module.trainer.optimizers[0].param_groups )} pl_module.logger.log_metrics(__a ) @rank_zero_only def _lowercase (self : str , __a : pl.Trainer , __a : pl.LightningModule , __a : str , __a : Optional[Any]=True ): logger.info(f"""***** {type_path} results at step {trainer.global_step:05d} *****""" ) UpperCAmelCase_ = trainer.callback_metrics trainer.logger.log_metrics({k: v for k, v in metrics.items() if k not in ["log", "progress_bar", "preds"]} ) # Log results UpperCAmelCase_ = Path(pl_module.hparams.output_dir ) if type_path == "test": UpperCAmelCase_ = od / "test_results.txt" UpperCAmelCase_ = od / "test_generations.txt" else: # this never gets hit. I prefer not to save intermediate generations, and results are in metrics.json # If people want this it will be easy enough to add back. UpperCAmelCase_ = od / f"""{type_path}_results/{trainer.global_step:05d}.txt""" UpperCAmelCase_ = od / f"""{type_path}_generations/{trainer.global_step:05d}.txt""" results_file.parent.mkdir(exist_ok=__a ) generations_file.parent.mkdir(exist_ok=__a ) with open(__a , "a+" ) as writer: for key in sorted(__a ): if key in ["log", "progress_bar", "preds"]: continue UpperCAmelCase_ = metrics[key] if isinstance(__a , torch.Tensor ): UpperCAmelCase_ = val.item() UpperCAmelCase_ = f"""{key}: {val:.6f}\n""" writer.write(__a ) if not save_generations: return if "preds" in metrics: UpperCAmelCase_ = "\n".join(metrics["preds"] ) generations_file.open("w+" ).write(__a ) @rank_zero_only def _lowercase (self : int , __a : Optional[int] , __a : List[Any] ): try: UpperCAmelCase_ = pl_module.model.model.num_parameters() except AttributeError: UpperCAmelCase_ = pl_module.model.num_parameters() UpperCAmelCase_ = count_trainable_parameters(__a ) # mp stands for million parameters trainer.logger.log_metrics({"n_params": npars, "mp": npars / 1E6, "grad_mp": n_trainable_pars / 1E6} ) @rank_zero_only def _lowercase (self : Optional[Any] , __a : pl.Trainer , __a : pl.LightningModule ): save_json(pl_module.metrics , pl_module.metrics_save_path ) return self._write_logs(__a , __a , "test" ) @rank_zero_only def _lowercase (self : List[Any] , __a : pl.Trainer , __a : int ): save_json(pl_module.metrics , pl_module.metrics_save_path ) # Uncommenting this will save val generations # return self._write_logs(trainer, pl_module, "valid")
78
'''simple docstring''' import gc import unittest import torch from parameterized import parameterized from diffusers import AutoencoderKL from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import enable_full_determinism from .test_modeling_common import ModelTesterMixin, UNetTesterMixin enable_full_determinism() class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : int = AutoencoderKL a__ : Optional[Any] = """sample""" a__ : Union[str, Any] = 1e-2 @property def _lowercase (self : Optional[int] ): UpperCAmelCase_ = 4 UpperCAmelCase_ = 3 UpperCAmelCase_ = (32, 32) UpperCAmelCase_ = floats_tensor((batch_size, num_channels) + sizes ).to(__a ) return {"sample": image} @property def _lowercase (self : Any ): return (3, 32, 32) @property def _lowercase (self : Dict ): return (3, 32, 32) def _lowercase (self : int ): UpperCAmelCase_ = { "block_out_channels": [32, 64], "in_channels": 3, "out_channels": 3, "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"], "up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"], "latent_channels": 4, } UpperCAmelCase_ = self.dummy_input return init_dict, inputs_dict def _lowercase (self : int ): pass def _lowercase (self : int ): pass @unittest.skipIf(torch_device == "mps" , "Gradient checkpointing skipped on MPS" ) def _lowercase (self : List[Any] ): # enable deterministic behavior for gradient checkpointing UpperCAmelCase_ , UpperCAmelCase_ = self.prepare_init_args_and_inputs_for_common() UpperCAmelCase_ = self.model_class(**__a ) model.to(__a ) assert not model.is_gradient_checkpointing and model.training UpperCAmelCase_ = model(**__a ).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() UpperCAmelCase_ = torch.randn_like(__a ) UpperCAmelCase_ = (out - labels).mean() loss.backward() # re-instantiate the model now enabling gradient checkpointing UpperCAmelCase_ = self.model_class(**__a ) # clone model model_a.load_state_dict(model.state_dict() ) model_a.to(__a ) model_a.enable_gradient_checkpointing() assert model_a.is_gradient_checkpointing and model_a.training UpperCAmelCase_ = model_a(**__a ).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() UpperCAmelCase_ = (out_a - labels).mean() loss_a.backward() # compare the output and parameters gradients self.assertTrue((loss - loss_a).abs() < 1E-5 ) UpperCAmelCase_ = dict(model.named_parameters() ) UpperCAmelCase_ = 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 _lowercase (self : Any ): UpperCAmelCase_ , UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" , output_loading_info=__a ) self.assertIsNotNone(__a ) self.assertEqual(len(loading_info["missing_keys"] ) , 0 ) model.to(__a ) UpperCAmelCase_ = model(**self.dummy_input ) assert image is not None, "Make sure output is not None" def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy" ) UpperCAmelCase_ = model.to(__a ) model.eval() if torch_device == "mps": UpperCAmelCase_ = torch.manual_seed(0 ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(0 ) UpperCAmelCase_ = torch.randn( 1 , model.config.in_channels , model.config.sample_size , model.config.sample_size , generator=torch.manual_seed(0 ) , ) UpperCAmelCase_ = image.to(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , sample_posterior=__a , generator=__a ).sample UpperCAmelCase_ = 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": UpperCAmelCase_ = torch.tensor( [ -4.0078E-01, -3.8323E-04, -1.2681E-01, -1.1462E-01, 2.0095E-01, 1.0893E-01, -8.8247E-02, -3.0361E-01, -9.8644E-03, ] ) elif torch_device == "cpu": UpperCAmelCase_ = torch.tensor( [-0.13_52, 0.08_78, 0.04_19, -0.08_18, -0.10_69, 0.06_88, -0.14_58, -0.44_46, -0.00_26] ) else: UpperCAmelCase_ = torch.tensor( [-0.24_21, 0.46_42, 0.25_07, -0.04_38, 0.06_82, 0.31_60, -0.20_18, -0.07_27, 0.24_85] ) self.assertTrue(torch_all_close(__a , __a , rtol=1E-2 ) ) @slow class __A ( unittest.TestCase ): def _lowercase (self : Dict , __a : Dict , __a : int ): return f"""gaussian_noise_s={seed}_shape={"_".join([str(__a ) for s in shape] )}.npy""" def _lowercase (self : str ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] , __a : Optional[Any]=0 , __a : str=(4, 3, 512, 512) , __a : List[str]=False ): UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = torch.from_numpy(load_hf_numpy(self.get_file_format(__a , __a ) ) ).to(__a ).to(__a ) return image def _lowercase (self : List[Any] , __a : Union[str, Any]="CompVis/stable-diffusion-v1-4" , __a : List[Any]=False ): UpperCAmelCase_ = "fp16" if fpaa else None UpperCAmelCase_ = torch.floataa if fpaa else torch.floataa UpperCAmelCase_ = AutoencoderKL.from_pretrained( __a , subfolder="vae" , torch_dtype=__a , revision=__a , ) model.to(__a ).eval() return model def _lowercase (self : List[Any] , __a : List[Any]=0 ): if torch_device == "mps": return torch.manual_seed(__a ) return torch.Generator(device=__a ).manual_seed(__a ) @parameterized.expand( [ # fmt: off [33, [-0.16_03, 0.98_78, -0.04_95, -0.07_90, -0.27_09, 0.83_75, -0.20_60, -0.08_24], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_76, 0.11_68, 0.13_32, -0.48_40, -0.25_08, -0.07_91, -0.04_93, -0.40_89], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : List[Any] , __a : Dict , __a : Optional[int] , __a : List[str] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [33, [-0.05_13, 0.02_89, 1.37_99, 0.21_66, -0.25_73, -0.08_71, 0.51_03, -0.09_99]], [47, [-0.41_28, -0.13_20, -0.37_04, 0.19_65, -0.41_16, -0.23_32, -0.33_40, 0.22_47]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Dict , __a : Optional[int] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , fpaa=__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a , generator=__a , sample_posterior=__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.16_09, 0.98_66, -0.04_87, -0.07_77, -0.27_16, 0.83_68, -0.20_55, -0.08_14], [-0.23_95, 0.00_98, 0.01_02, -0.07_09, -0.28_40, -0.02_74, -0.07_18, -0.18_24]], [47, [-0.23_77, 0.11_47, 0.13_33, -0.48_41, -0.25_06, -0.08_05, -0.04_91, -0.40_85], [0.03_50, 0.08_47, 0.04_67, 0.03_44, -0.08_42, -0.05_47, -0.06_33, -0.11_31]], # fmt: on ] ) def _lowercase (self : str , __a : int , __a : Union[str, Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) with torch.no_grad(): UpperCAmelCase_ = model(__a ).sample assert sample.shape == image.shape UpperCAmelCase_ = sample[-1, -2:, -2:, :2].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice ) assert torch_all_close(__a , __a , atol=3E-3 ) @parameterized.expand( [ # fmt: off [13, [-0.20_51, -0.18_03, -0.23_11, -0.21_14, -0.32_92, -0.35_74, -0.29_53, -0.33_23]], [37, [-0.26_32, -0.26_25, -0.21_99, -0.27_41, -0.45_39, -0.49_90, -0.37_20, -0.49_25]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : int , __a : int , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , atol=1E-3 ) @parameterized.expand( [ # fmt: off [27, [-0.03_69, 0.02_07, -0.07_76, -0.06_82, -0.17_47, -0.19_30, -0.14_65, -0.20_39]], [16, [-0.16_28, -0.21_34, -0.27_47, -0.26_42, -0.37_74, -0.44_04, -0.36_87, -0.42_77]], # fmt: on ] ) @require_torch_gpu def _lowercase (self : Union[str, Any] , __a : List[str] , __a : Optional[Any] ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] UpperCAmelCase_ = sample[-1, -2:, :2, -2:].flatten().float().cpu() UpperCAmelCase_ = torch.tensor(__a ) assert torch_all_close(__a , __a , 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 _lowercase (self : List[str] , __a : int ): UpperCAmelCase_ = self.get_sd_vae_model(fpaa=__a ) UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) , fpaa=__a ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , 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 _lowercase (self : Union[str, Any] , __a : Dict ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a , shape=(3, 4, 64, 64) ) with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample model.enable_xformers_memory_efficient_attention() with torch.no_grad(): UpperCAmelCase_ = model.decode(__a ).sample assert list(sample.shape ) == [3, 3, 512, 512] assert torch_all_close(__a , __a , atol=1E-2 ) @parameterized.expand( [ # fmt: off [33, [-0.30_01, 0.09_18, -2.69_84, -3.97_20, -3.20_99, -5.03_53, 1.73_38, -0.20_65, 3.42_67]], [47, [-1.50_30, -4.38_71, -6.03_55, -9.11_57, -1.66_61, -2.78_53, 2.16_07, -5.08_23, 2.56_33]], # fmt: on ] ) def _lowercase (self : Tuple , __a : List[Any] , __a : List[Any] ): UpperCAmelCase_ = self.get_sd_vae_model() UpperCAmelCase_ = self.get_sd_image(__a ) UpperCAmelCase_ = self.get_generator(__a ) with torch.no_grad(): UpperCAmelCase_ = model.encode(__a ).latent_dist UpperCAmelCase_ = dist.sample(generator=__a ) assert list(sample.shape ) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]] UpperCAmelCase_ = sample[0, -1, -3:, -3:].flatten().cpu() UpperCAmelCase_ = torch.tensor(__a ) UpperCAmelCase_ = 3E-3 if torch_device != "mps" else 1E-2 assert torch_all_close(__a , __a , atol=__a )
78
1
'''simple docstring''' import random import unittest import torch from diffusers import IFInpaintingSuperResolutionPipeline from diffusers.utils import floats_tensor from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import skip_mps, torch_device from ..pipeline_params import ( TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin from . import IFPipelineTesterMixin @skip_mps class __A ( UpperCamelCase__ , UpperCamelCase__ , unittest.TestCase ): a__ : List[str] = IFInpaintingSuperResolutionPipeline a__ : Any = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"""width""", """height"""} a__ : Any = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"""original_image"""} ) a__ : Tuple = PipelineTesterMixin.required_optional_params - {"""latents"""} def _lowercase (self : List[str] ): return self._get_superresolution_dummy_components() def _lowercase (self : Optional[int] , __a : int , __a : Tuple=0 ): if str(__a ).startswith("mps" ): UpperCAmelCase_ = torch.manual_seed(__a ) else: UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(__a ) UpperCAmelCase_ = floats_tensor((1, 3, 16, 16) , rng=random.Random(__a ) ).to(__a ) UpperCAmelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) UpperCAmelCase_ = floats_tensor((1, 3, 32, 32) , rng=random.Random(__a ) ).to(__a ) UpperCAmelCase_ = { "prompt": "A painting of a squirrel eating a burger", "image": image, "original_image": original_image, "mask_image": mask_image, "generator": generator, "num_inference_steps": 2, "output_type": "numpy", } return inputs @unittest.skipIf( torch_device != "cuda" or not is_xformers_available() , reason="XFormers attention is only available with CUDA and `xformers` installed" , ) def _lowercase (self : int ): self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) def _lowercase (self : Optional[Any] ): self._test_save_load_optional_components() @unittest.skipIf(torch_device != "cuda" , reason="float16 requires CUDA" ) def _lowercase (self : str ): # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder super().test_save_load_floataa(expected_max_diff=1E-1 ) def _lowercase (self : str ): self._test_attention_slicing_forward_pass(expected_max_diff=1E-2 ) def _lowercase (self : int ): self._test_save_load_local() def _lowercase (self : Optional[int] ): self._test_inference_batch_single_identical( expected_max_diff=1E-2 , )
78
'''simple docstring''' import logging from transformers import PretrainedConfig SCREAMING_SNAKE_CASE_: Any =logging.getLogger(__name__) SCREAMING_SNAKE_CASE_: Any ={ 'bertabs-finetuned-cnndm': 'https://huggingface.co/remi/bertabs-finetuned-cnndm-extractive-abstractive-summarization/resolve/main/config.json', } class __A ( UpperCamelCase__ ): a__ : List[Any] = """bertabs""" def __init__(self : Any , __a : int=30522 , __a : Tuple=512 , __a : Tuple=6 , __a : Dict=512 , __a : int=8 , __a : List[Any]=512 , __a : List[str]=0.2 , __a : List[Any]=6 , __a : int=768 , __a : Any=8 , __a : Dict=2048 , __a : Tuple=0.2 , **__a : Optional[int] , ): super().__init__(**__a ) UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_pos UpperCAmelCase_ = enc_layers UpperCAmelCase_ = enc_hidden_size UpperCAmelCase_ = enc_heads UpperCAmelCase_ = enc_ff_size UpperCAmelCase_ = enc_dropout UpperCAmelCase_ = dec_layers UpperCAmelCase_ = dec_hidden_size UpperCAmelCase_ = dec_heads UpperCAmelCase_ = dec_ff_size UpperCAmelCase_ = dec_dropout
78
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_torch_available, is_vision_available, ) SCREAMING_SNAKE_CASE_: Optional[int] ={'configuration_beit': ['BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BeitConfig', 'BeitOnnxConfig']} try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =['BeitFeatureExtractor'] SCREAMING_SNAKE_CASE_: int =['BeitImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: Optional[int] =[ 'BEIT_PRETRAINED_MODEL_ARCHIVE_LIST', 'BeitForImageClassification', 'BeitForMaskedImageModeling', 'BeitForSemanticSegmentation', 'BeitModel', 'BeitPreTrainedModel', ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE_: int =[ 'FlaxBeitForImageClassification', 'FlaxBeitForMaskedImageModeling', 'FlaxBeitModel', 'FlaxBeitPreTrainedModel', ] if TYPE_CHECKING: from .configuration_beit import BEIT_PRETRAINED_CONFIG_ARCHIVE_MAP, BeitConfig, BeitOnnxConfig try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_beit import BeitFeatureExtractor from .image_processing_beit import BeitImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_beit import ( BEIT_PRETRAINED_MODEL_ARCHIVE_LIST, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation, BeitModel, BeitPreTrainedModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_beit import ( FlaxBeitForImageClassification, FlaxBeitForMaskedImageModeling, FlaxBeitModel, FlaxBeitPreTrainedModel, ) else: import sys SCREAMING_SNAKE_CASE_: Dict =_LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
78
'''simple docstring''' import argparse import json from pathlib import Path import requests import torch from huggingface_hub import hf_hub_download from PIL import Image from timm import create_model from timm.data import resolve_data_config from timm.data.transforms_factory import create_transform from transformers import BitConfig, BitForImageClassification, BitImageProcessor from transformers.image_utils import PILImageResampling from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> int: '''simple docstring''' UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = {v: k for k, v in idalabel.items()} UpperCAmelCase_ = "std_conv" if "bit" in model_name else False # note that when using BiT as backbone for ViT-hybrid checkpoints, # one needs to additionally set config.layer_type = "bottleneck", config.stem_type = "same", # config.conv_layer = "std_conv_same" UpperCAmelCase_ = BitConfig( conv_layer=snake_case_ , num_labels=10_00 , idalabel=snake_case_ , labelaid=snake_case_ , ) return config def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[int]: '''simple docstring''' if "stem.conv" in name: UpperCAmelCase_ = name.replace("stem.conv" , "bit.embedder.convolution" ) if "blocks" in name: UpperCAmelCase_ = name.replace("blocks" , "layers" ) if "head.fc" in name: UpperCAmelCase_ = name.replace("head.fc" , "classifier.1" ) if name.startswith("norm" ): UpperCAmelCase_ = "bit." + name if "bit" not in name and "classifier" not in name: UpperCAmelCase_ = "bit.encoder." + name return name def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : Tuple , snake_case_ : Optional[Any] , snake_case_ : int=False ) -> List[Any]: '''simple docstring''' UpperCAmelCase_ = get_config(snake_case_ ) # load original model from timm UpperCAmelCase_ = create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model UpperCAmelCase_ = timm_model.state_dict() for key in state_dict.copy().keys(): UpperCAmelCase_ = state_dict.pop(snake_case_ ) UpperCAmelCase_ = val.squeeze() if "head" in key else val # load HuggingFace model UpperCAmelCase_ = BitForImageClassification(snake_case_ ) model.eval() model.load_state_dict(snake_case_ ) # create image processor UpperCAmelCase_ = create_transform(**resolve_data_config({} , model=snake_case_ ) ) UpperCAmelCase_ = transform.transforms UpperCAmelCase_ = { "bilinear": PILImageResampling.BILINEAR, "bicubic": PILImageResampling.BICUBIC, "nearest": PILImageResampling.NEAREST, } UpperCAmelCase_ = BitImageProcessor( do_resize=snake_case_ , size={"shortest_edge": timm_transforms[0].size} , resample=pillow_resamplings[timm_transforms[0].interpolation.value] , do_center_crop=snake_case_ , crop_size={"height": timm_transforms[1].size[0], "width": timm_transforms[1].size[1]} , do_normalize=snake_case_ , image_mean=timm_transforms[-1].mean.tolist() , image_std=timm_transforms[-1].std.tolist() , ) UpperCAmelCase_ = prepare_img() UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ) UpperCAmelCase_ = processor(snake_case_ , return_tensors="pt" ).pixel_values # verify pixel values assert torch.allclose(snake_case_ , snake_case_ ) # verify logits with torch.no_grad(): UpperCAmelCase_ = model(snake_case_ ) UpperCAmelCase_ = outputs.logits print("Logits:" , logits[0, :3] ) print("Predicted class:" , model.config.idalabel[logits.argmax(-1 ).item()] ) UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) print("Looks ok!" ) if pytorch_dump_folder_path is not None: Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {model_name} and processor to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) processor.save_pretrained(snake_case_ ) if push_to_hub: print(f"""Pushing model {model_name} and processor to the hub""" ) model.push_to_hub(f"""ybelkada/{model_name}""" ) processor.push_to_hub(f"""ybelkada/{model_name}""" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: int =argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='resnetv2_50x1_bitm', type=str, help='Name of the BiT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) parser.add_argument( '--push_to_hub', action='store_true', help='Whether to push the model to the hub.', ) SCREAMING_SNAKE_CASE_: Union[str, Any] =parser.parse_args() convert_bit_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)
78
1
'''simple docstring''' from typing import List, Union import numpy as np from ..utils import add_end_docstrings, 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_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_DEPTH_ESTIMATION_MAPPING SCREAMING_SNAKE_CASE_: Union[str, Any] =logging.get_logger(__name__) @add_end_docstrings(UpperCamelCase__ ) class __A ( UpperCamelCase__ ): def __init__(self : List[Any] , *__a : List[str] , **__a : int ): super().__init__(*__a , **__a ) requires_backends(self , "vision" ) self.check_model_type(__a ) def __call__(self : Optional[Any] , __a : Union[str, List[str], "Image.Image", List["Image.Image"]] , **__a : List[str] ): return super().__call__(__a , **__a ) def _lowercase (self : Union[str, Any] , **__a : Optional[int] ): return {}, {}, {} def _lowercase (self : Union[str, Any] , __a : Union[str, Any] ): UpperCAmelCase_ = load_image(__a ) UpperCAmelCase_ = image.size UpperCAmelCase_ = self.image_processor(images=__a , return_tensors=self.framework ) return model_inputs def _lowercase (self : Any , __a : Tuple ): UpperCAmelCase_ = self.model(**__a ) return model_outputs def _lowercase (self : Optional[Any] , __a : List[str] ): UpperCAmelCase_ = model_outputs.predicted_depth UpperCAmelCase_ = torch.nn.functional.interpolate( predicted_depth.unsqueeze(1 ) , size=self.image_size[::-1] , mode="bicubic" , align_corners=__a ) UpperCAmelCase_ = prediction.squeeze().cpu().numpy() UpperCAmelCase_ = (output * 255 / np.max(__a )).astype("uint8" ) UpperCAmelCase_ = Image.fromarray(__a ) UpperCAmelCase_ = {} UpperCAmelCase_ = predicted_depth UpperCAmelCase_ = depth return output_dict
78
'''simple docstring''' import json import sys import tempfile import unittest from pathlib import Path import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, AutoConfig, AutoImageProcessor, CLIPConfig, CLIPImageProcessor, ) from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils')) from test_module.custom_configuration import CustomConfig # noqa E402 from test_module.custom_image_processing import CustomImageProcessor # noqa E402 class __A ( unittest.TestCase ): def _lowercase (self : List[str] ): UpperCAmelCase_ = 0 def _lowercase (self : Tuple ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("openai/clip-vit-base-patch32" ) self.assertIsInstance(__a , __a ) def _lowercase (self : str ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Dict ): # Ensure we can load the image processor from the feature extractor config with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : List[str] ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = CLIPConfig() # Create a dummy config file with image_proceesor_type UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) # remove image_processor_type to make sure config.json alone is enough to load image processor locally UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ).to_dict() config_dict.pop("image_processor_type" ) UpperCAmelCase_ = CLIPImageProcessor(**__a ) # save in new folder model_config.save_pretrained(__a ) config.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) # make sure private variable is not incorrectly saved UpperCAmelCase_ = json.loads(config.to_json_string() ) self.assertTrue("_processor_class" not in dict_as_saved ) self.assertIsInstance(__a , __a ) def _lowercase (self : int ): with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" json.dump( {"image_processor_type": "CLIPImageProcessor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) def _lowercase (self : Tuple ): with self.assertRaisesRegex( __a , "clip-base is not a local folder and is not a valid model identifier" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("clip-base" ) def _lowercase (self : Optional[int] ): with self.assertRaisesRegex( __a , r"aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)" ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , revision="aaaaaa" ) def _lowercase (self : Union[str, Any] ): with self.assertRaisesRegex( __a , "hf-internal-testing/config-no-model does not appear to have a file named preprocessor_config.json." , ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/config-no-model" ) def _lowercase (self : List[Any] ): # If remote code is not set, we will time out when asking whether to load the model. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) # If remote code is disabled, we can't load this config. with self.assertRaises(__a ): UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) # Test image processor can be reloaded. with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a , trust_remote_code=__a ) self.assertEqual(reloaded_image_processor.__class__.__name__ , "NewImageProcessor" ) def _lowercase (self : Optional[int] ): try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # Trying to register something existing in the Transformers library will raise an error with self.assertRaises(__a ): AutoImageProcessor.register(__a , __a ) with tempfile.TemporaryDirectory() as tmpdirname: UpperCAmelCase_ = Path(__a ) / "preprocessor_config.json" UpperCAmelCase_ = Path(__a ) / "config.json" json.dump( {"feature_extractor_type": "CLIPFeatureExtractor", "processor_class": "CLIPProcessor"} , open(__a , "w" ) , ) json.dump({"model_type": "clip"} , open(__a , "w" ) ) UpperCAmelCase_ = CustomImageProcessor.from_pretrained(__a ) # Now that the config is registered, it can be used as any other config with the auto-API with tempfile.TemporaryDirectory() as tmp_dir: image_processor.save_pretrained(__a ) UpperCAmelCase_ = AutoImageProcessor.from_pretrained(__a ) self.assertIsInstance(__a , __a ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig] def _lowercase (self : Optional[int] ): class __A ( UpperCamelCase__ ): a__ : str = True try: AutoConfig.register("custom" , __a ) AutoImageProcessor.register(__a , __a ) # If remote code is not set, the default is to use local UpperCAmelCase_ = AutoImageProcessor.from_pretrained("hf-internal-testing/test_dynamic_image_processor" ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote code is disabled, we load the local one. UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(image_processor.is_local ) # If remote is enabled, we load from the Hub UpperCAmelCase_ = AutoImageProcessor.from_pretrained( "hf-internal-testing/test_dynamic_image_processor" , trust_remote_code=__a ) self.assertEqual(image_processor.__class__.__name__ , "NewImageProcessor" ) self.assertTrue(not hasattr(__a , "is_local" ) ) finally: if "custom" in CONFIG_MAPPING._extra_content: del CONFIG_MAPPING._extra_content["custom"] if CustomConfig in IMAGE_PROCESSOR_MAPPING._extra_content: del IMAGE_PROCESSOR_MAPPING._extra_content[CustomConfig]
78
1
'''simple docstring''' from typing import Dict, List, Optional, Tuple, Union import torch from ...models import AutoencoderKL, TransformeraDModel from ...schedulers import KarrasDiffusionSchedulers from ...utils import randn_tensor from ..pipeline_utils import DiffusionPipeline, ImagePipelineOutput class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : TransformeraDModel , __a : AutoencoderKL , __a : KarrasDiffusionSchedulers , __a : Optional[Dict[int, str]] = None , ): super().__init__() self.register_modules(transformer=__a , vae=__a , scheduler=__a ) # create a imagenet -> id dictionary for easier use UpperCAmelCase_ = {} if idalabel is not None: for key, value in idalabel.items(): for label in value.split("," ): UpperCAmelCase_ = int(__a ) UpperCAmelCase_ = dict(sorted(self.labels.items() ) ) def _lowercase (self : Optional[Any] , __a : Union[str, List[str]] ): if not isinstance(__a , __a ): UpperCAmelCase_ = list(__a ) for l in label: if l not in self.labels: raise ValueError( f"""{l} does not exist. Please make sure to select one of the following labels: \n {self.labels}.""" ) return [self.labels[l] for l in label] @torch.no_grad() def __call__(self : Dict , __a : List[int] , __a : float = 4.0 , __a : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __a : int = 50 , __a : Optional[str] = "pil" , __a : bool = True , ): UpperCAmelCase_ = len(__a ) UpperCAmelCase_ = self.transformer.config.sample_size UpperCAmelCase_ = self.transformer.config.in_channels UpperCAmelCase_ = randn_tensor( shape=(batch_size, latent_channels, latent_size, latent_size) , generator=__a , device=self.device , dtype=self.transformer.dtype , ) UpperCAmelCase_ = torch.cat([latents] * 2 ) if guidance_scale > 1 else latents UpperCAmelCase_ = torch.tensor(__a , device=self.device ).reshape(-1 ) UpperCAmelCase_ = torch.tensor([1000] * batch_size , device=self.device ) UpperCAmelCase_ = torch.cat([class_labels, class_null] , 0 ) if guidance_scale > 1 else class_labels # set step values self.scheduler.set_timesteps(__a ) for t in self.progress_bar(self.scheduler.timesteps ): if guidance_scale > 1: UpperCAmelCase_ = latent_model_input[: len(__a ) // 2] UpperCAmelCase_ = torch.cat([half, half] , dim=0 ) UpperCAmelCase_ = self.scheduler.scale_model_input(__a , __a ) UpperCAmelCase_ = t if not torch.is_tensor(__a ): # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can # This would be a good case for the `match` statement (Python 3.10+) UpperCAmelCase_ = latent_model_input.device.type == "mps" if isinstance(__a , __a ): UpperCAmelCase_ = torch.floataa if is_mps else torch.floataa else: UpperCAmelCase_ = torch.intaa if is_mps else torch.intaa UpperCAmelCase_ = torch.tensor([timesteps] , dtype=__a , device=latent_model_input.device ) elif len(timesteps.shape ) == 0: UpperCAmelCase_ = timesteps[None].to(latent_model_input.device ) # broadcast to batch dimension in a way that's compatible with ONNX/Core ML UpperCAmelCase_ = timesteps.expand(latent_model_input.shape[0] ) # predict noise model_output UpperCAmelCase_ = self.transformer( __a , timestep=__a , class_labels=__a ).sample # perform guidance if guidance_scale > 1: UpperCAmelCase_ , UpperCAmelCase_ = noise_pred[:, :latent_channels], noise_pred[:, latent_channels:] UpperCAmelCase_ , UpperCAmelCase_ = torch.split(__a , len(__a ) // 2 , dim=0 ) UpperCAmelCase_ = uncond_eps + guidance_scale * (cond_eps - uncond_eps) UpperCAmelCase_ = torch.cat([half_eps, half_eps] , dim=0 ) UpperCAmelCase_ = torch.cat([eps, rest] , dim=1 ) # learned sigma if self.transformer.config.out_channels // 2 == latent_channels: UpperCAmelCase_ , UpperCAmelCase_ = torch.split(__a , __a , dim=1 ) else: UpperCAmelCase_ = noise_pred # compute previous image: x_t -> x_t-1 UpperCAmelCase_ = self.scheduler.step(__a , __a , __a ).prev_sample if guidance_scale > 1: UpperCAmelCase_ , UpperCAmelCase_ = latent_model_input.chunk(2 , dim=0 ) else: UpperCAmelCase_ = latent_model_input UpperCAmelCase_ = 1 / self.vae.config.scaling_factor * latents UpperCAmelCase_ = self.vae.decode(__a ).sample UpperCAmelCase_ = (samples / 2 + 0.5).clamp(0 , 1 ) # we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16 UpperCAmelCase_ = samples.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": UpperCAmelCase_ = self.numpy_to_pil(__a ) if not return_dict: return (samples,) return ImagePipelineOutput(images=__a )
78
'''simple docstring''' import os from dataclasses import dataclass, field from io import BytesIO from typing import TYPE_CHECKING, Any, ClassVar, Dict, Optional, Union import numpy as np import pyarrow as pa from .. import config from ..download.streaming_download_manager import xopen, xsplitext from ..table import array_cast from ..utils.py_utils import no_op_if_value_is_null, string_to_dict if TYPE_CHECKING: from .features import FeatureType SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_, SCREAMING_SNAKE_CASE_: Tuple =False, False, False @dataclass class __A : a__ : Optional[int] = None a__ : bool = True a__ : bool = True a__ : Optional[str] = None # Automatically constructed a__ : ClassVar[str] = "dict" a__ : ClassVar[Any] = pa.struct({"""bytes""": pa.binary(), """path""": pa.string()} ) a__ : str = field(default="""Audio""" , init=UpperCamelCase__ , repr=UpperCamelCase__ ) def __call__(self : Optional[Any] ): return self.pa_type def _lowercase (self : str , __a : Union[str, bytes, dict] ): try: import soundfile as sf # soundfile is a dependency of librosa, needed to decode audio files. except ImportError as err: raise ImportError("To support encoding audio data, please install 'soundfile'." ) from err if isinstance(__a , __a ): return {"bytes": None, "path": value} elif isinstance(__a , __a ): return {"bytes": value, "path": None} elif "array" in value: # convert the audio array to wav bytes UpperCAmelCase_ = BytesIO() sf.write(__a , value["array"] , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} elif value.get("path" ) is not None and os.path.isfile(value["path"] ): # we set "bytes": None to not duplicate the data if they're already available locally if value["path"].endswith("pcm" ): # "PCM" only has raw audio bytes if value.get("sampling_rate" ) is None: # At least, If you want to convert "PCM-byte" to "WAV-byte", you have to know sampling rate raise KeyError("To use PCM files, please specify a 'sampling_rate' in Audio object" ) if value.get("bytes" ): # If we already had PCM-byte, we don`t have to make "read file, make bytes" (just use it!) UpperCAmelCase_ = np.frombuffer(value["bytes"] , dtype=np.intaa ).astype(np.floataa ) / 32767 else: UpperCAmelCase_ = np.memmap(value["path"] , dtype="h" , mode="r" ).astype(np.floataa ) / 32767 UpperCAmelCase_ = BytesIO(bytes() ) sf.write(__a , __a , value["sampling_rate"] , format="wav" ) return {"bytes": buffer.getvalue(), "path": None} else: return {"bytes": None, "path": value.get("path" )} elif value.get("bytes" ) is not None or value.get("path" ) is not None: # store the audio bytes, and path is used to infer the audio format using the file extension return {"bytes": value.get("bytes" ), "path": value.get("path" )} else: raise ValueError( f"""An audio sample should have one of 'path' or 'bytes' but they are missing or None in {value}.""" ) def _lowercase (self : Dict , __a : dict , __a : Optional[Dict[str, Union[str, bool, None]]] = None ): if not self.decode: raise RuntimeError("Decoding is disabled for this feature. Please use Audio(decode=True) instead." ) UpperCAmelCase_ , UpperCAmelCase_ = (value["path"], BytesIO(value["bytes"] )) if value["bytes"] is not None else (value["path"], None) if path is None and file is None: raise ValueError(f"""An audio sample should have one of 'path' or 'bytes' but both are None in {value}.""" ) try: import librosa import soundfile as sf except ImportError as err: raise ImportError("To support decoding audio files, please install 'librosa' and 'soundfile'." ) from err UpperCAmelCase_ = xsplitext(__a )[1][1:].lower() if path is not None else None if not config.IS_OPUS_SUPPORTED and audio_format == "opus": raise RuntimeError( "Decoding 'opus' files requires system library 'libsndfile'>=1.0.31, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) elif not config.IS_MP3_SUPPORTED and audio_format == "mp3": raise RuntimeError( "Decoding 'mp3' files requires system library 'libsndfile'>=1.1.0, " "You can try to update `soundfile` python library: `pip install \"soundfile>=0.12.1\"`. " ) if file is None: UpperCAmelCase_ = token_per_repo_id or {} UpperCAmelCase_ = path.split("::" )[-1] try: UpperCAmelCase_ = string_to_dict(__a , config.HUB_DATASETS_URL )["repo_id"] UpperCAmelCase_ = token_per_repo_id[repo_id] except (ValueError, KeyError): UpperCAmelCase_ = None with xopen(__a , "rb" , use_auth_token=__a ) as f: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) else: UpperCAmelCase_ , UpperCAmelCase_ = sf.read(__a ) UpperCAmelCase_ = array.T if self.mono: UpperCAmelCase_ = librosa.to_mono(__a ) if self.sampling_rate and self.sampling_rate != sampling_rate: UpperCAmelCase_ = librosa.resample(__a , orig_sr=__a , target_sr=self.sampling_rate ) UpperCAmelCase_ = self.sampling_rate return {"path": path, "array": array, "sampling_rate": sampling_rate} def _lowercase (self : Dict ): from .features import Value if self.decode: raise ValueError("Cannot flatten a decoded Audio feature." ) return { "bytes": Value("binary" ), "path": Value("string" ), } def _lowercase (self : Optional[Any] , __a : Union[pa.StringArray, pa.StructArray] ): if pa.types.is_string(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, storage] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_binary(storage.type ): UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([storage, path_array] , ["bytes", "path"] , mask=storage.is_null() ) elif pa.types.is_struct(storage.type ) and storage.type.get_all_field_indices("array" ): UpperCAmelCase_ = pa.array([Audio().encode_example(__a ) if x is not None else None for x in storage.to_pylist()] ) elif pa.types.is_struct(storage.type ): if storage.type.get_field_index("bytes" ) >= 0: UpperCAmelCase_ = storage.field("bytes" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.binary() ) if storage.type.get_field_index("path" ) >= 0: UpperCAmelCase_ = storage.field("path" ) else: UpperCAmelCase_ = pa.array([None] * len(__a ) , type=pa.string() ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=storage.is_null() ) return array_cast(__a , self.pa_type ) def _lowercase (self : Dict , __a : pa.StructArray ): @no_op_if_value_is_null def path_to_bytes(__a : Tuple ): with xopen(__a , "rb" ) as f: UpperCAmelCase_ = f.read() return bytes_ UpperCAmelCase_ = pa.array( [ (path_to_bytes(x["path"] ) if x["bytes"] is None else x["bytes"]) if x is not None else None for x in storage.to_pylist() ] , type=pa.binary() , ) UpperCAmelCase_ = pa.array( [os.path.basename(__a ) if path is not None else None for path in storage.field("path" ).to_pylist()] , type=pa.string() , ) UpperCAmelCase_ = pa.StructArray.from_arrays([bytes_array, path_array] , ["bytes", "path"] , mask=bytes_array.is_null() ) return array_cast(__a , self.pa_type )
78
1
'''simple docstring''' 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 tensorflow as tf from transformers import AutoTokenizer, TFAutoModelForSeqaSeqLM @require_tf @require_sentencepiece @require_tokenizers class __A ( unittest.TestCase ): @slow def _lowercase (self : List[Any] ): UpperCAmelCase_ = TFAutoModelForSeqaSeqLM.from_pretrained("google/mt5-small" ) UpperCAmelCase_ = AutoTokenizer.from_pretrained("google/mt5-small" ) UpperCAmelCase_ = tokenizer("Hello there" , return_tensors="tf" ).input_ids UpperCAmelCase_ = tokenizer("Hi I am" , return_tensors="tf" ).input_ids UpperCAmelCase_ = model(__a , labels=__a ).loss UpperCAmelCase_ = -tf.math.reduce_mean(__a ).numpy() UpperCAmelCase_ = -21.22_81_68 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 2E-4 )
78
'''simple docstring''' import argparse import re import requests import torch # git clone https://github.com/salesforce/BLIP.git from models.blip import blip_decoder from models.blip_itm import blip_itm from models.blip_vqa import blip_vqa from PIL import Image from torchvision import transforms from torchvision.transforms.functional import InterpolationMode from transformers import ( BertTokenizer, BlipConfig, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Optional[int] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ).convert("RGB" ) UpperCAmelCase_ = transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.4814_5466, 0.457_8275, 0.4082_1073) , (0.2686_2954, 0.2613_0258, 0.2757_7711) ), ] ) UpperCAmelCase_ = transform(snake_case_ ).unsqueeze(0 ).to(snake_case_ ) return image def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if "visual_encoder" in key: UpperCAmelCase_ = re.sub("visual_encoder*" , "vision_model.encoder" , snake_case_ ) if "blocks" in key: UpperCAmelCase_ = re.sub(R"blocks" , "layers" , snake_case_ ) if "attn" in key: UpperCAmelCase_ = re.sub(R"attn" , "self_attn" , snake_case_ ) if "norm1" in key: UpperCAmelCase_ = re.sub(R"norm1" , "layer_norm1" , snake_case_ ) if "norm2" in key: UpperCAmelCase_ = re.sub(R"norm2" , "layer_norm2" , snake_case_ ) if "encoder.norm" in key: UpperCAmelCase_ = re.sub(R"encoder.norm" , "post_layernorm" , snake_case_ ) if "encoder.patch_embed.proj" in key: UpperCAmelCase_ = re.sub(R"encoder.patch_embed.proj" , "embeddings.patch_embedding" , snake_case_ ) if "encoder.pos_embed" in key: UpperCAmelCase_ = re.sub(R"encoder.pos_embed" , "embeddings.position_embedding" , snake_case_ ) if "encoder.cls_token" in key: UpperCAmelCase_ = re.sub(R"encoder.cls_token" , "embeddings.class_embedding" , snake_case_ ) if "self_attn" in key: UpperCAmelCase_ = re.sub(R"self_attn.proj" , "self_attn.projection" , snake_case_ ) return key @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : Any=None ) -> Union[str, Any]: '''simple docstring''' if config_path is not None: UpperCAmelCase_ = BlipConfig.from_pretrained(snake_case_ ) else: UpperCAmelCase_ = BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) UpperCAmelCase_ = BlipForConditionalGeneration(snake_case_ ).eval() UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth" UpperCAmelCase_ = blip_decoder(pretrained=snake_case_ , image_size=3_84 , vit="base" ) UpperCAmelCase_ = pt_model.eval() UpperCAmelCase_ = pt_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value hf_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = 3_84 UpperCAmelCase_ = load_demo_image(image_size=snake_case_ , device="cpu" ) UpperCAmelCase_ = BertTokenizer.from_pretrained("bert-base-uncased" ) UpperCAmelCase_ = tokenizer(["a picture of"] ).input_ids UpperCAmelCase_ = hf_model.generate(snake_case_ , snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 38_61, 19_97, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] UpperCAmelCase_ = hf_model.generate(snake_case_ ) assert out[0].tolist() == [3_05_22, 10_37, 24_50, 35_64, 20_06, 19_96, 35_09, 20_07, 20_14, 38_99, 1_02] if pytorch_dump_folder_path is not None: hf_model.save_pretrained(snake_case_ ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' UpperCAmelCase_ = ( "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth" ) UpperCAmelCase_ = blip_vqa(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) vqa_model.eval() UpperCAmelCase_ = vqa_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForQuestionAnswering(snake_case_ ) hf_vqa_model.load_state_dict(snake_case_ ) UpperCAmelCase_ = ["How many dogs are in this image?"] UpperCAmelCase_ = tokenizer(snake_case_ , return_tensors="pt" ).input_ids UpperCAmelCase_ = hf_vqa_model.generate(snake_case_ , snake_case_ ) print(tokenizer.decode(answer[0] ) ) assert tokenizer.decode(answer[0] ) == "[UNK] 1 [SEP]" if pytorch_dump_folder_path is not None: hf_vqa_model.save_pretrained(pytorch_dump_folder_path + "_vqa" ) UpperCAmelCase_ = "https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth" UpperCAmelCase_ = blip_itm(pretrained=snake_case_ , image_size=snake_case_ , vit="base" ) itm_model.eval() UpperCAmelCase_ = itm_model.state_dict() for key in modified_state_dict.copy(): UpperCAmelCase_ = modified_state_dict.pop(snake_case_ ) UpperCAmelCase_ = rename_key(snake_case_ ) UpperCAmelCase_ = value UpperCAmelCase_ = BlipForImageTextRetrieval(snake_case_ ) UpperCAmelCase_ = ["A picture of a woman with a dog sitting in a beach"] UpperCAmelCase_ = tokenizer( snake_case_ , return_tensors="pt" , padding="max_length" , truncation=snake_case_ , max_length=35 , ).input_ids hf_itm_model.load_state_dict(snake_case_ ) hf_itm_model.eval() UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) UpperCAmelCase_ = hf_itm_model(snake_case_ , snake_case_ , use_itm_head=snake_case_ ) assert out[0].item() == 0.2110_6874_9427_7954 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_5698_8453_8650_5127 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + "_itm" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Optional[Any] =argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE_: int =parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
78
1
'''simple docstring''' import gc import importlib.metadata import tempfile import unittest from packaging import version from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoTokenizer, BitsAndBytesConfig, pipeline, ) from transformers.testing_utils import ( is_torch_available, require_accelerate, require_bitsandbytes, require_torch, require_torch_gpu, require_torch_multi_gpu, slow, ) def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Optional[Any]: '''simple docstring''' if model.config.model_type == "gpt2": return model.transformer.h[0].mlp.c_fc return model.transformer.h[0].mlp.dense_ah_to_h if is_torch_available(): import torch import torch.nn as nn class __A ( nn.Module ): def __init__(self : Union[str, Any] , __a : nn.Module , __a : int ): super().__init__() UpperCAmelCase_ = module UpperCAmelCase_ = nn.Sequential( nn.Linear(module.in_features , __a , bias=__a ) , nn.Linear(__a , module.out_features , bias=__a ) , ) UpperCAmelCase_ = (2.0 / (5 * min(module.in_features , module.out_features ))) ** 0.5 nn.init.normal_(self.adapter[0].weight , std=__a ) nn.init.zeros_(self.adapter[1].weight ) self.adapter.to(module.weight.device ) def _lowercase (self : Tuple , __a : Optional[Any] , *__a : int , **__a : str ): return self.module(__a , *__a , **__a ) + self.adapter(__a ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __A ( unittest.TestCase ): # We keep the constants inside the init function and model loading inside setUp function # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) # Therefore here we use only bloom-1b3 to test our module a__ : Union[str, Any] = """bigscience/bloom-1b7""" # Constant values a__ : int = 2.1_0_9_6_5_9_5_5_2_6_9_2_5_7_4 a__ : Optional[Any] = """Hello my name is""" a__ : Dict = set() EXPECTED_OUTPUTS.add("""Hello my name is John and I am a professional photographer. I""" ) EXPECTED_OUTPUTS.add("""Hello my name is John.\nI am a friend of your father.\n""" ) EXPECTED_OUTPUTS.add("""Hello my name is John Doe, I am a student at the University""" ) a__ : Optional[int] = 10 def _lowercase (self : List[str] ): # Models and tokenizer UpperCAmelCase_ = AutoTokenizer.from_pretrained(self.model_name ) class __A ( UpperCamelCase__ ): def _lowercase (self : Tuple ): super().setUp() # Models and tokenizer UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained( self.model_name , torch_dtype=torch.floataa , device_map="auto" ) UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map="auto" ) def _lowercase (self : List[Any] ): del self.model_fpaa del self.model_abit gc.collect() torch.cuda.empty_cache() def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = self.model_abit.config self.assertTrue(hasattr(__a , "quantization_config" ) ) UpperCAmelCase_ = config.to_dict() UpperCAmelCase_ = config.to_diff_dict() UpperCAmelCase_ = config.to_json_string() def _lowercase (self : Tuple ): from bitsandbytes.nn import Paramsabit UpperCAmelCase_ = self.model_fpaa.get_memory_footprint() UpperCAmelCase_ = self.model_abit.get_memory_footprint() self.assertAlmostEqual(mem_fpaa / mem_abit , self.EXPECTED_RELATIVE_DIFFERENCE ) UpperCAmelCase_ = get_some_linear_layer(self.model_abit ) self.assertTrue(linear.weight.__class__ == Paramsabit ) def _lowercase (self : List[str] ): from transformers import TaPreTrainedModel self.model_fpaa.get_memory_footprint() self.model_abit.get_memory_footprint() for name, module in self.model_abit.named_modules(): if isinstance(__a , torch.nn.Linear ): if name not in ["lm_head"] + TaPreTrainedModel._keep_in_fpaa_modules: # 4-bit parameters are packed in uint8 variables self.assertTrue(module.weight.dtype == torch.uinta ) def _lowercase (self : List[str] ): UpperCAmelCase_ = self.tokenizer(self.input_text , return_tensors="pt" ) UpperCAmelCase_ = self.model_abit.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def _lowercase (self : Optional[int] ): UpperCAmelCase_ = BitsAndBytesConfig() UpperCAmelCase_ = True UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , device_map="auto" ) UpperCAmelCase_ = self.tokenizer(self.input_text , return_tensors="pt" ) UpperCAmelCase_ = model_abit_from_config.generate( input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_sequences[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) def _lowercase (self : Tuple ): with self.assertRaises(__a ), tempfile.TemporaryDirectory() as tmpdirname: self.model_abit.save_pretrained(__a ) def _lowercase (self : Union[str, Any] ): UpperCAmelCase_ = BitsAndBytesConfig() with self.assertRaises(__a ): UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained( self.model_name , quantization_config=__a , load_in_abit=__a , device_map="auto" , bnb_abit_quant_type="nf4" , ) def _lowercase (self : List[str] ): with self.assertRaises(__a ): # Tries with `str` self.model_abit.to("cpu" ) with self.assertRaises(__a ): # Tries with a `dtype`` self.model_abit.to(torch.floataa ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.to(torch.device("cuda:0" ) ) with self.assertRaises(__a ): # Tries with a `device` self.model_abit.float() with self.assertRaises(__a ): # Tries with a `device` self.model_abit.half() # Test if we did not break anything UpperCAmelCase_ = self.tokenizer(self.input_text , return_tensors="pt" ) UpperCAmelCase_ = self.model_fpaa.to(torch.floataa ) UpperCAmelCase_ = self.model_fpaa.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) # Check this does not throw an error UpperCAmelCase_ = self.model_fpaa.to("cpu" ) # Check this does not throw an error UpperCAmelCase_ = self.model_fpaa.half() # Check this does not throw an error UpperCAmelCase_ = self.model_fpaa.float() def _lowercase (self : List[str] ): UpperCAmelCase_ = AutoModelForSeqaSeqLM.from_pretrained("t5-small" , load_in_abit=__a , device_map="auto" ) self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.floataa ) @require_bitsandbytes @require_accelerate @require_torch @require_torch_gpu @slow class __A ( unittest.TestCase ): @classmethod def _lowercase (cls : Optional[int] ): UpperCAmelCase_ = "t5-small" UpperCAmelCase_ = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense UpperCAmelCase_ = AutoTokenizer.from_pretrained(cls.model_name ) UpperCAmelCase_ = "Translate in German: Hello, my dog is cute" def _lowercase (self : Any ): gc.collect() torch.cuda.empty_cache() def _lowercase (self : List[Any] ): from transformers import TaForConditionalGeneration UpperCAmelCase_ = TaForConditionalGeneration._keep_in_fpaa_modules UpperCAmelCase_ = None # test with `t5-small` UpperCAmelCase_ = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map="auto" ) UpperCAmelCase_ = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) UpperCAmelCase_ = model.generate(**__a ) # test with `flan-t5-small` UpperCAmelCase_ = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map="auto" ) UpperCAmelCase_ = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) UpperCAmelCase_ = model.generate(**__a ) UpperCAmelCase_ = modules def _lowercase (self : str ): import bitsandbytes as bnb from transformers import TaForConditionalGeneration # test with `t5-small` UpperCAmelCase_ = TaForConditionalGeneration.from_pretrained(self.model_name , load_in_abit=__a , device_map="auto" ) # there was a bug with decoders - this test checks that it is fixed self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q , bnb.nn.Linearabit ) ) UpperCAmelCase_ = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) UpperCAmelCase_ = model.generate(**__a ) # test with `flan-t5-small` UpperCAmelCase_ = TaForConditionalGeneration.from_pretrained( self.dense_act_model_name , load_in_abit=__a , device_map="auto" ) UpperCAmelCase_ = self.tokenizer(self.input_text , return_tensors="pt" ).to(0 ) UpperCAmelCase_ = model.generate(**__a ) class __A ( UpperCamelCase__ ): def _lowercase (self : Tuple ): super().setUp() # model_name UpperCAmelCase_ = "bigscience/bloom-560m" UpperCAmelCase_ = "t5-small" # Different types of model UpperCAmelCase_ = AutoModel.from_pretrained(self.model_name , load_in_abit=__a , device_map="auto" ) # Sequence classification model UpperCAmelCase_ = AutoModelForSequenceClassification.from_pretrained( self.model_name , load_in_abit=__a , device_map="auto" ) # CausalLM model UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a , device_map="auto" ) # Seq2seq model UpperCAmelCase_ = AutoModelForSeqaSeqLM.from_pretrained( self.seq_to_seq_name , load_in_abit=__a , device_map="auto" ) def _lowercase (self : List[Any] ): del self.base_model del self.sequence_model del self.model_abit del self.seq_to_seq_model gc.collect() torch.cuda.empty_cache() def _lowercase (self : Optional[Any] ): from bitsandbytes.nn import Paramsabit self.assertTrue(self.base_model.h[-1].mlp.dense_ah_to_h.weight.__class__ == Paramsabit ) # Other heads should be nn.Parameter self.assertTrue(self.model_abit.lm_head.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter ) self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter ) class __A ( UpperCamelCase__ ): def _lowercase (self : List[Any] ): super().setUp() def _lowercase (self : Tuple ): del self.pipe gc.collect() torch.cuda.empty_cache() def _lowercase (self : List[Any] ): UpperCAmelCase_ = pipeline( "text-generation" , model=self.model_name , model_kwargs={"device_map": "auto", "load_in_4bit": True, "torch_dtype": torch.floataa} , max_new_tokens=self.MAX_NEW_TOKENS , ) # Real second forward pass UpperCAmelCase_ = self.pipe(self.input_text ) self.assertIn(pipeline_output[0]["generated_text"] , self.EXPECTED_OUTPUTS ) @require_torch_multi_gpu class __A ( UpperCamelCase__ ): def _lowercase (self : int ): super().setUp() def _lowercase (self : Any ): UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained( self.model_name , load_in_abit=__a , device_map="balanced" ) # Check correct device map self.assertEqual(set(model_parallel.hf_device_map.values() ) , {0, 1} ) # Check that inference pass works on the model UpperCAmelCase_ = self.tokenizer(self.input_text , return_tensors="pt" ) # Second real batch UpperCAmelCase_ = model_parallel.generate(input_ids=encoded_input["input_ids"].to(0 ) , max_new_tokens=10 ) self.assertIn(self.tokenizer.decode(output_parallel[0] , skip_special_tokens=__a ) , self.EXPECTED_OUTPUTS ) class __A ( UpperCamelCase__ ): def _lowercase (self : str ): UpperCAmelCase_ = "facebook/opt-350m" super().setUp() def _lowercase (self : Dict ): if version.parse(importlib.metadata.version("bitsandbytes" ) ) < version.parse("0.37.0" ): return # Step 1: freeze all parameters UpperCAmelCase_ = AutoModelForCausalLM.from_pretrained(self.model_name , load_in_abit=__a ) self.assertEqual(set(model.hf_device_map.values() ) , {torch.cuda.current_device()} ) for param in model.parameters(): UpperCAmelCase_ = False # freeze the model - train adapters later if param.ndim == 1: # cast the small parameters (e.g. layernorm) to fp32 for stability UpperCAmelCase_ = param.data.to(torch.floataa ) # Step 2: add adapters for _, module in model.named_modules(): if "OPTAttention" in repr(type(__a ) ): UpperCAmelCase_ = LoRALayer(module.q_proj , rank=16 ) UpperCAmelCase_ = LoRALayer(module.k_proj , rank=16 ) UpperCAmelCase_ = LoRALayer(module.v_proj , rank=16 ) # Step 3: dummy batch UpperCAmelCase_ = self.tokenizer("Test batch " , return_tensors="pt" ).to(0 ) # Step 4: Check if the gradient is not None with torch.cuda.amp.autocast(): UpperCAmelCase_ = model.forward(**__a ) out.logits.norm().backward() for module in model.modules(): if isinstance(__a , __a ): self.assertTrue(module.adapter[1].weight.grad is not None ) self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0 ) elif isinstance(__a , nn.Embedding ): self.assertTrue(module.weight.grad is None ) class __A ( UpperCamelCase__ ): a__ : str = """gpt2-xl""" a__ : Any = 3.3_1_9_1_8_5_4_8_5_4_1_5_2_1_8_7
78
'''simple docstring''' import math from collections import defaultdict from typing import List, Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from .scheduling_utils import KarrasDiffusionSchedulers, SchedulerMixin, SchedulerOutput def lowerCAmelCase_ ( snake_case_ : List[Any] , snake_case_ : Union[str, Any]=0.999 , snake_case_ : Tuple="cosine" , ) -> Optional[Any]: '''simple docstring''' if alpha_transform_type == "cosine": def alpha_bar_fn(snake_case_ : Optional[int] ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(snake_case_ : Optional[Any] ): return math.exp(t * -12.0 ) else: raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}""" ) UpperCAmelCase_ = [] for i in range(snake_case_ ): UpperCAmelCase_ = i / num_diffusion_timesteps UpperCAmelCase_ = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(snake_case_ ) / alpha_bar_fn(snake_case_ ) , snake_case_ ) ) return torch.tensor(snake_case_ , dtype=torch.floataa ) class __A ( UpperCamelCase__ , UpperCamelCase__ ): a__ : Tuple = [e.name for e in KarrasDiffusionSchedulers] a__ : Optional[Any] = 2 @register_to_config def __init__(self : Union[str, Any] , __a : int = 1000 , __a : float = 0.0_00_85 , __a : float = 0.0_12 , __a : str = "linear" , __a : Optional[Union[np.ndarray, List[float]]] = None , __a : str = "epsilon" , __a : Optional[bool] = False , __a : Optional[bool] = False , __a : float = 1.0 , __a : str = "linspace" , __a : int = 0 , ): if trained_betas is not None: UpperCAmelCase_ = torch.tensor(__a , dtype=torch.floataa ) elif beta_schedule == "linear": UpperCAmelCase_ = torch.linspace(__a , __a , __a , dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. UpperCAmelCase_ = ( torch.linspace(beta_start**0.5 , beta_end**0.5 , __a , dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="cosine" ) elif beta_schedule == "exp": UpperCAmelCase_ = betas_for_alpha_bar(__a , alpha_transform_type="exp" ) else: raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}""" ) UpperCAmelCase_ = 1.0 - self.betas UpperCAmelCase_ = torch.cumprod(self.alphas , dim=0 ) # set all values self.set_timesteps(__a , __a , __a ) UpperCAmelCase_ = use_karras_sigmas def _lowercase (self : Optional[Any] , __a : Union[str, Any] , __a : Tuple=None ): if schedule_timesteps is None: UpperCAmelCase_ = self.timesteps UpperCAmelCase_ = (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: UpperCAmelCase_ = 1 if len(__a ) > 1 else 0 else: UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep UpperCAmelCase_ = self._index_counter[timestep_int] return indices[pos].item() @property def _lowercase (self : List[Any] ): # standard deviation of the initial noise distribution if self.config.timestep_spacing in ["linspace", "trailing"]: return self.sigmas.max() return (self.sigmas.max() ** 2 + 1) ** 0.5 def _lowercase (self : Optional[Any] , __a : torch.FloatTensor , __a : Union[float, torch.FloatTensor] , ): UpperCAmelCase_ = self.index_for_timestep(__a ) UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = sample / ((sigma**2 + 1) ** 0.5) return sample def _lowercase (self : Any , __a : int , __a : Union[str, torch.device] = None , __a : Optional[int] = None , ): UpperCAmelCase_ = num_inference_steps UpperCAmelCase_ = 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": UpperCAmelCase_ = np.linspace(0 , num_train_timesteps - 1 , __a , dtype=__a )[::-1].copy() elif self.config.timestep_spacing == "leading": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(0 , __a ) * step_ratio).round()[::-1].copy().astype(__a ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": UpperCAmelCase_ = 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 UpperCAmelCase_ = (np.arange(__a , 0 , -step_ratio )).round().copy().astype(__a ) timesteps -= 1 else: raise ValueError( f"""{self.config.timestep_spacing} is not supported. Please make sure to choose one of 'linspace', 'leading' or 'trailing'.""" ) UpperCAmelCase_ = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) UpperCAmelCase_ = np.log(__a ) UpperCAmelCase_ = np.interp(__a , np.arange(0 , len(__a ) ) , __a ) if self.config.use_karras_sigmas: UpperCAmelCase_ = self._convert_to_karras(in_sigmas=__a , num_inference_steps=self.num_inference_steps ) UpperCAmelCase_ = np.array([self._sigma_to_t(__a , __a ) for sigma in sigmas] ) UpperCAmelCase_ = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a ) UpperCAmelCase_ = torch.cat([sigmas[:1], sigmas[1:-1].repeat_interleave(2 ), sigmas[-1:]] ) UpperCAmelCase_ = torch.from_numpy(__a ) UpperCAmelCase_ = torch.cat([timesteps[:1], timesteps[1:].repeat_interleave(2 )] ) if str(__a ).startswith("mps" ): # mps does not support float64 UpperCAmelCase_ = timesteps.to(__a , dtype=torch.floataa ) else: UpperCAmelCase_ = timesteps.to(device=__a ) # empty dt and derivative UpperCAmelCase_ = None UpperCAmelCase_ = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter UpperCAmelCase_ = defaultdict(__a ) def _lowercase (self : int , __a : Optional[Any] , __a : List[str] ): # get log sigma UpperCAmelCase_ = np.log(__a ) # get distribution UpperCAmelCase_ = log_sigma - log_sigmas[:, np.newaxis] # get sigmas range UpperCAmelCase_ = np.cumsum((dists >= 0) , axis=0 ).argmax(axis=0 ).clip(max=log_sigmas.shape[0] - 2 ) UpperCAmelCase_ = low_idx + 1 UpperCAmelCase_ = log_sigmas[low_idx] UpperCAmelCase_ = log_sigmas[high_idx] # interpolate sigmas UpperCAmelCase_ = (low - log_sigma) / (low - high) UpperCAmelCase_ = np.clip(__a , 0 , 1 ) # transform interpolation to time range UpperCAmelCase_ = (1 - w) * low_idx + w * high_idx UpperCAmelCase_ = t.reshape(sigma.shape ) return t def _lowercase (self : Dict , __a : torch.FloatTensor , __a : Optional[int] ): UpperCAmelCase_ = in_sigmas[-1].item() UpperCAmelCase_ = in_sigmas[0].item() UpperCAmelCase_ = 7.0 # 7.0 is the value used in the paper UpperCAmelCase_ = np.linspace(0 , 1 , __a ) UpperCAmelCase_ = sigma_min ** (1 / rho) UpperCAmelCase_ = sigma_max ** (1 / rho) UpperCAmelCase_ = (max_inv_rho + ramp * (min_inv_rho - max_inv_rho)) ** rho return sigmas @property def _lowercase (self : List[str] ): return self.dt is None def _lowercase (self : List[Any] , __a : Union[torch.FloatTensor, np.ndarray] , __a : Union[float, torch.FloatTensor] , __a : Union[torch.FloatTensor, np.ndarray] , __a : bool = True , ): UpperCAmelCase_ = self.index_for_timestep(__a ) # advance index counter by 1 UpperCAmelCase_ = timestep.cpu().item() if torch.is_tensor(__a ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: UpperCAmelCase_ = self.sigmas[step_index] UpperCAmelCase_ = self.sigmas[step_index + 1] else: # 2nd order / Heun's method UpperCAmelCase_ = self.sigmas[step_index - 1] UpperCAmelCase_ = 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 UpperCAmelCase_ = 0 UpperCAmelCase_ = 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": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": UpperCAmelCase_ = sigma_hat if self.state_in_first_order else sigma_next UpperCAmelCase_ = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": UpperCAmelCase_ = model_output else: raise ValueError( f"""prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`""" ) if self.config.clip_sample: UpperCAmelCase_ = pred_original_sample.clamp( -self.config.clip_sample_range , self.config.clip_sample_range ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order UpperCAmelCase_ = (sample - pred_original_sample) / sigma_hat # 3. delta timestep UpperCAmelCase_ = sigma_next - sigma_hat # store for 2nd order step UpperCAmelCase_ = derivative UpperCAmelCase_ = dt UpperCAmelCase_ = sample else: # 2. 2nd order / Heun's method UpperCAmelCase_ = (sample - pred_original_sample) / sigma_next UpperCAmelCase_ = (self.prev_derivative + derivative) / 2 # 3. take prev timestep & sample UpperCAmelCase_ = self.dt UpperCAmelCase_ = self.sample # free dt and derivative # Note, this puts the scheduler in "first order mode" UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = None UpperCAmelCase_ = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=__a ) def _lowercase (self : Any , __a : torch.FloatTensor , __a : torch.FloatTensor , __a : torch.FloatTensor , ): # Make sure sigmas and timesteps have the same device and dtype as original_samples UpperCAmelCase_ = self.sigmas.to(device=original_samples.device , dtype=original_samples.dtype ) if original_samples.device.type == "mps" and torch.is_floating_point(__a ): # mps does not support float64 UpperCAmelCase_ = self.timesteps.to(original_samples.device , dtype=torch.floataa ) UpperCAmelCase_ = timesteps.to(original_samples.device , dtype=torch.floataa ) else: UpperCAmelCase_ = self.timesteps.to(original_samples.device ) UpperCAmelCase_ = timesteps.to(original_samples.device ) UpperCAmelCase_ = [self.index_for_timestep(__a , __a ) for t in timesteps] UpperCAmelCase_ = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): UpperCAmelCase_ = sigma.unsqueeze(-1 ) UpperCAmelCase_ = original_samples + noise * sigma return noisy_samples def __len__(self : str ): return self.config.num_train_timesteps
78
1
'''simple docstring''' import collections import json import os import re from typing import TYPE_CHECKING, List, Optional, Tuple import numpy as np from ...tokenization_utils_fast import PreTrainedTokenizer from ...utils import logging if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={'vocab_file': 'vocab.txt', 'emoji_file': 'emoji.json'} SCREAMING_SNAKE_CASE_: List[Any] ={ 'vocab_file': { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/vocab.txt', }, 'emoji_file': { 'abeja/gpt-neox-japanese-2.7b': 'https://huggingface.co/abeja/gpt-neox-japanese-2.7b/resolve/main/emoji.json', }, } SCREAMING_SNAKE_CASE_: Optional[Any] ={ 'abeja/gpt-neox-japanese-2.7b': 20_48, } def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Tuple ) -> int: '''simple docstring''' with open(snake_case_ , "r" , encoding="utf-8" ) as f: UpperCAmelCase_ = json.loads(f.read() ) UpperCAmelCase_ = collections.OrderedDict() UpperCAmelCase_ = collections.OrderedDict() UpperCAmelCase_ = collections.OrderedDict() with open(snake_case_ , "r" , encoding="utf-8" ) as f: UpperCAmelCase_ = f.readlines() UpperCAmelCase_ = [[t.rstrip("\n" )] if (t == "," or "," not in t) else t.rstrip("\n" ).split("," ) for t in token] for idx, b in enumerate(snake_case_ ): UpperCAmelCase_ = b UpperCAmelCase_ = idx for wd in b: UpperCAmelCase_ = idx return vocab, raw_vocab, ids_to_tokens, emoji class __A ( UpperCamelCase__ ): a__ : int = VOCAB_FILES_NAMES a__ : List[Any] = PRETRAINED_VOCAB_FILES_MAP a__ : Optional[int] = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES a__ : Tuple = ["""input_ids""", """attention_mask"""] def __init__(self : int , __a : Any , __a : int , __a : Optional[Any]="<|endoftext|>" , __a : Optional[Any]="<|endoftext|>" , __a : Optional[Any]="<|startoftext|>" , __a : int="<|endoftext|>" , __a : Tuple=False , **__a : Tuple , ): super().__init__( unk_token=__a , pad_token=__a , bos_token=__a , eos_token=__a , do_clean_text=__a , **__a , ) if not os.path.isfile(__a ): raise ValueError( f"""Can't find a vocabulary file at path '{vocab_file}'. To load the vocabulary from a Google pretrained""" " model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`" ) if not os.path.isfile(__a ): raise ValueError( f"""Can't find a emoji file at path '{emoji_file}'. To load the emoji information from a Google""" " pretrained model use `tokenizer = GPTNeoXJapaneseokenizer.from_pretrained(PRETRAINED_MODEL_NAME)`" ) UpperCAmelCase_ = do_clean_text UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = load_vocab_and_emoji(__a , __a ) UpperCAmelCase_ = SubWordJapaneseTokenizer( vocab=self.vocab , ids_to_tokens=self.ids_to_tokens , emoji=self.emoji ) @property def _lowercase (self : int ): # self.vocab contains support for character fluctuation unique to Japanese, and has a large number of vocab return len(self.raw_vocab ) def _lowercase (self : Union[str, Any] ): return dict(self.raw_vocab , **self.added_tokens_encoder ) def _lowercase (self : Optional[int] , __a : List[str] ): return self.subword_tokenizer.tokenize(__a , clean=self.do_clean_text ) def _lowercase (self : Any , __a : List[Any] ): return self.vocab.get(__a , self.vocab.get(self.unk_token ) ) def _lowercase (self : Tuple , __a : Tuple ): return self.subword_tokenizer.convert_id_to_token(__a ) def _lowercase (self : Optional[Any] , __a : Optional[int] ): UpperCAmelCase_ = "".join(__a ).strip() return out_string def _lowercase (self : Any , __a : "Conversation" ): UpperCAmelCase_ = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__a , add_special_tokens=__a ) + [self.eos_token_id] ) if len(__a ) > self.model_max_length: UpperCAmelCase_ = input_ids[-self.model_max_length :] return input_ids def _lowercase (self : Optional[Any] , __a : str , __a : Optional[str] = None ): UpperCAmelCase_ = 0 if os.path.isdir(__a ): UpperCAmelCase_ = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) UpperCAmelCase_ = os.path.join( __a , (filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["emoji_file"] ) else: UpperCAmelCase_ = ( (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["vocab_file"] ) UpperCAmelCase_ = ( (filename_prefix + "-" if filename_prefix else "") + save_directory + VOCAB_FILES_NAMES["emoji_file"] ) with open(__a , "w" , encoding="utf-8" ) as writer: for token_index, token in self.ids_to_tokens.items(): if index != token_index: logger.warning( f"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" " Please check that the vocabulary is not corrupted!" ) UpperCAmelCase_ = token_index writer.write(",".join(__a ) + "\n" ) index += 1 with open(__a , "w" , encoding="utf-8" ) as writer: json.dump(self.emoji , __a ) return vocab_file, emoji_file class __A ( UpperCamelCase__ ): def __init__(self : Optional[Any] , __a : str , __a : Tuple , __a : Optional[int] ): UpperCAmelCase_ = vocab # same as swe UpperCAmelCase_ = ids_to_tokens # same as bpe UpperCAmelCase_ = emoji UpperCAmelCase_ = np.max([len(__a ) for w in self.vocab.keys()] ) UpperCAmelCase_ = re.compile(r"(https?|ftp)(:\/\/[-_\.!~*\'()a-zA-Z0-9;\/?:\@&=\+$,%#]+)" ) UpperCAmelCase_ = re.compile(r"[A-Za-z0-9\._+]*@[\-_0-9A-Za-z]+(\.[A-Za-z]+)*" ) UpperCAmelCase_ = re.compile(r"[\(]{0,1}[0-9]{2,4}[\)\-\(]{0,1}[0-9]{2,4}[\)\-]{0,1}[0-9]{3,4}" ) UpperCAmelCase_ = re.compile( r"([12]\d{3}[/\-年])*(0?[1-9]|1[0-2])[/\-月]((0?[1-9]|[12][0-9]|3[01])日?)*(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*" ) UpperCAmelCase_ = re.compile( r"(明治|大正|昭和|平成|令和|㍾|㍽|㍼|㍻|\u32ff)\d{1,2}年(0?[1-9]|1[0-2])月(0?[1-9]|[12][0-9]|3[01])日(\d{1,2}|:|\d{1,2}時|\d{1,2}分|\(日\)|\(月\)|\(火\)|\(水\)|\(木\)|\(金\)|\(土\)|㈰|㈪|㈫|㈬|㈭|㈮|㈯)*" ) UpperCAmelCase_ = re.compile( r"((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*億)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*万)*((0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*千)*(0|[1-9]\d*|[1-9]\d{0,2}(,\d{3})+)*(千円|万円|千万円|円|千ドル|万ドル|千万ドル|ドル|千ユーロ|万ユーロ|千万ユーロ|ユーロ)+(\(税込\)|\(税抜\)|\+tax)*" ) UpperCAmelCase_ = "─━│┃┄┅┆┇┈┉┊┋┌┍┎┏┐┑┒┓└┕┖┗┘┙┚┛├┝┞┟┠┡┢┣┤┥┦┧┨┩┪┫┬┭┮┯┰┱┲┳┴┵┶┷┸┹┺┻┼┽┾┿╀╁╂╃╄╅╆╇╈╉╊╋╌╍╎╏═║╒╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳╴╵╶╷╸╹╺╻╼╽╾╿" UpperCAmelCase_ = "▀▁▂▃▄▅▆▇█▉▊▋▌▍▎▏▐░▒▓▔▕▖▗▘▙▚▛▜▝▞▟" UpperCAmelCase_ = str.maketrans({k: "<BLOCK>" for k in keisen + blocks} ) def __len__(self : Dict ): return len(self.ids_to_tokens ) def _lowercase (self : Union[str, Any] , __a : Optional[int] ): UpperCAmelCase_ = self.content_repattera.sub("<URL>" , __a ) UpperCAmelCase_ = self.content_repattera.sub("<EMAIL>" , __a ) UpperCAmelCase_ = self.content_repattera.sub("<TEL>" , __a ) UpperCAmelCase_ = self.content_repattera.sub("<DATE>" , __a ) UpperCAmelCase_ = self.content_repattera.sub("<DATE>" , __a ) UpperCAmelCase_ = self.content_repattera.sub("<PRICE>" , __a ) UpperCAmelCase_ = content.translate(self.content_transa ) while "<BLOCK><BLOCK>" in content: UpperCAmelCase_ = content.replace("<BLOCK><BLOCK>" , "<BLOCK>" ) return content def _lowercase (self : List[str] , __a : Union[str, Any] , __a : str=False ): UpperCAmelCase_ = text.replace(" " , "<SP>" ) UpperCAmelCase_ = text.replace(" " , "<SP>" ) UpperCAmelCase_ = text.replace("\r\n" , "<BR>" ) UpperCAmelCase_ = text.replace("\n" , "<BR>" ) UpperCAmelCase_ = text.replace("\r" , "<BR>" ) UpperCAmelCase_ = text.replace("\t" , "<TAB>" ) UpperCAmelCase_ = text.replace("—" , "ー" ) UpperCAmelCase_ = text.replace("−" , "ー" ) for k, v in self.emoji["emoji"].items(): if k in text: UpperCAmelCase_ = text.replace(__a , __a ) if clean: UpperCAmelCase_ = self.clean_text(__a ) def check_simbol(__a : Union[str, Any] ): UpperCAmelCase_ = x.encode() if len(__a ) == 1 and len(__a ) == 2: UpperCAmelCase_ = (int(e[0] ) << 8) + int(e[1] ) if ( (c >= 0Xc2_a1 and c <= 0Xc2_bf) or (c >= 0Xc7_80 and c <= 0Xc7_83) or (c >= 0Xca_b9 and c <= 0Xcb_bf) or (c >= 0Xcc_80 and c <= 0Xcd_a2) ): return True return False def checkuae(__a : Dict ): UpperCAmelCase_ = x.encode() if len(__a ) == 1 and len(__a ) == 3: UpperCAmelCase_ = (int(e[0] ) << 16) + (int(e[1] ) << 8) + int(e[2] ) if c >= 0Xe2_80_80 and c <= 0Xe2_b0_7f: return True return False UpperCAmelCase_ = 0 UpperCAmelCase_ = [] while pos < len(__a ): UpperCAmelCase_ = min(len(__a ) , pos + self.maxlen + 1 ) if text[pos] == "<" else pos + 3 UpperCAmelCase_ = [] # (token_id, token, pos) for e in range(__a , __a , -1 ): UpperCAmelCase_ = text[pos:e] if wd in self.vocab: if wd[0] == "<" and len(__a ) > 2: UpperCAmelCase_ = [(self.vocab[wd], wd, e)] break else: candidates.append((self.vocab[wd], wd, e) ) if len(__a ) > 0: # the smallest token_id is adopted UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = sorted(__a , key=lambda __a : x[0] )[0] result.append(__a ) UpperCAmelCase_ = e else: UpperCAmelCase_ = pos + 1 UpperCAmelCase_ = text[pos:end] if check_simbol(__a ): result.append("<KIGOU>" ) elif checkuae(__a ): result.append("<U2000U2BFF>" ) else: for i in wd.encode("utf-8" ): result.append("<|byte%d|>" % i ) UpperCAmelCase_ = end return result def _lowercase (self : Dict , __a : Tuple , __a : Optional[Any]="\n" ): UpperCAmelCase_ = [] UpperCAmelCase_ = [] UpperCAmelCase_ = self.ids_to_tokens[index][0] if word[:6] == "<|byte" and word[-2:] == "|>": byte_tokens.append(int(word[6:-2] ) ) else: if len(__a ) > 0: words.append(bytearray(__a ).decode("utf-8" , errors="replace" ) ) UpperCAmelCase_ = [] if word[:7] == "<|emoji" and word[-2:] == "|>": words.append(self.emoji["emoji_inv"][word] ) elif word == "<SP>": words.append(" " ) elif word == "<BR>": words.append(__a ) elif word == "<TAB>": words.append("\t" ) elif word == "<BLOCK>": words.append("▀" ) elif word == "<KIGOU>": words.append("ǀ" ) elif word == "<U2000U2BFF>": words.append("‖" ) else: words.append(__a ) if len(__a ) > 0: words.append(bytearray(__a ).decode("utf-8" , errors="replace" ) ) UpperCAmelCase_ = "".join(__a ) return text
78
'''simple docstring''' # Copyright 2023 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ..models.auto import AutoModelForVisionaSeq from ..utils import requires_backends from .base import PipelineTool if TYPE_CHECKING: from PIL import Image class __A ( UpperCamelCase__ ): a__ : List[str] = """Salesforce/blip-image-captioning-base""" a__ : Optional[Any] = ( """This is a tool that generates a description of an image. It takes an input named `image` which should be the """ """image to caption, and returns a text that contains the description in English.""" ) a__ : str = """image_captioner""" a__ : List[str] = AutoModelForVisionaSeq a__ : int = ["""image"""] a__ : Optional[Any] = ["""text"""] def __init__(self : Any , *__a : Dict , **__a : Union[str, Any] ): requires_backends(self , ["vision"] ) super().__init__(*__a , **__a ) def _lowercase (self : Union[str, Any] , __a : "Image" ): return self.pre_processor(images=__a , return_tensors="pt" ) def _lowercase (self : List[str] , __a : Dict ): return self.model.generate(**__a ) def _lowercase (self : int , __a : Optional[Any] ): return self.pre_processor.batch_decode(__a , skip_special_tokens=__a )[0].strip()
78
1
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
'''simple docstring''' import logging import math from functools import partial from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union import torch from .tensor_utils import tensor_tree_map, tree_map def lowerCAmelCase_ ( snake_case_ : Union[dict, list, tuple, torch.Tensor] ) -> List[Tuple[int, ...]]: '''simple docstring''' UpperCAmelCase_ = [] if isinstance(snake_case_ , snake_case_ ): for v in tree.values(): shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , (list, tuple) ): for t in tree: shapes.extend(_fetch_dims(snake_case_ ) ) elif isinstance(snake_case_ , torch.Tensor ): shapes.append(tree.shape ) else: raise ValueError("Not supported" ) return shapes @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Tuple[int, ...] ) -> Tuple[int, ...]: '''simple docstring''' UpperCAmelCase_ = [] for d in reversed(snake_case_ ): idx.append(flat_idx % d ) UpperCAmelCase_ = flat_idx // d return tuple(reversed(snake_case_ ) ) @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Sequence[int] , snake_case_ : Optional[Sequence[bool]] = None , snake_case_ : Optional[Sequence[bool]] = None , ) -> List[Tuple[slice, ...]]: '''simple docstring''' def reduce_edge_list(snake_case_ : List[bool] ) -> None: UpperCAmelCase_ = True for i in range(len(snake_case_ ) ): UpperCAmelCase_ = -1 * (i + 1) l[reversed_idx] &= tally UpperCAmelCase_ = l[reversed_idx] if start_edges is None: UpperCAmelCase_ = [s == 0 for s in start] reduce_edge_list(snake_case_ ) if end_edges is None: UpperCAmelCase_ = [e == (d - 1) for e, d in zip(snake_case_ , snake_case_ )] reduce_edge_list(snake_case_ ) # Base cases. Either start/end are empty and we're done, or the final, # one-dimensional tensor can be simply sliced if len(snake_case_ ) == 0: return [()] elif len(snake_case_ ) == 1: return [(slice(start[0] , end[0] + 1 ),)] UpperCAmelCase_ = [] UpperCAmelCase_ = [] # Dimensions common to start and end can be selected directly for s, e in zip(snake_case_ , snake_case_ ): if s == e: path_list.append(slice(snake_case_ , s + 1 ) ) else: break UpperCAmelCase_ = tuple(snake_case_ ) UpperCAmelCase_ = len(snake_case_ ) # start == end, and we're done if divergence_idx == len(snake_case_ ): return [path] def upper() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = start[divergence_idx] return tuple( path + (slice(snake_case_ , sdi + 1 ),) + s for s in _get_minimal_slice_set( start[divergence_idx + 1 :] , [d - 1 for d in dims[divergence_idx + 1 :]] , dims[divergence_idx + 1 :] , start_edges=start_edges[divergence_idx + 1 :] , end_edges=[True for _ in end_edges[divergence_idx + 1 :]] , ) ) def lower() -> Tuple[Tuple[slice, ...], ...]: assert start_edges is not None assert end_edges is not None UpperCAmelCase_ = end[divergence_idx] return tuple( path + (slice(snake_case_ , edi + 1 ),) + s for s in _get_minimal_slice_set( [0 for _ in start[divergence_idx + 1 :]] , end[divergence_idx + 1 :] , dims[divergence_idx + 1 :] , start_edges=[True for _ in start_edges[divergence_idx + 1 :]] , end_edges=end_edges[divergence_idx + 1 :] , ) ) # If both start and end are at the edges of the subtree rooted at # divergence_idx, we can just select the whole subtree at once if start_edges[divergence_idx] and end_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] + 1 ),) ) # If just start is at the edge, we can grab almost all of the subtree, # treating only the ragged bottom edge as an edge case elif start_edges[divergence_idx]: slices.append(path + (slice(start[divergence_idx] , end[divergence_idx] ),) ) slices.extend(lower() ) # Analogous to the previous case, but the top is ragged this time elif end_edges[divergence_idx]: slices.extend(upper() ) slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] + 1 ),) ) # If both sides of the range are ragged, we need to handle both sides # separately. If there's contiguous meat in between them, we can index it # in one big chunk else: slices.extend(upper() ) UpperCAmelCase_ = end[divergence_idx] - start[divergence_idx] if middle_ground > 1: slices.append(path + (slice(start[divergence_idx] + 1 , end[divergence_idx] ),) ) slices.extend(lower() ) return slices @torch.jit.ignore def lowerCAmelCase_ ( snake_case_ : torch.Tensor , snake_case_ : int , snake_case_ : int , snake_case_ : int ) -> torch.Tensor: '''simple docstring''' UpperCAmelCase_ = t.shape[:no_batch_dims] UpperCAmelCase_ = list(_flat_idx_to_idx(snake_case_ , snake_case_ ) ) # _get_minimal_slice_set is inclusive UpperCAmelCase_ = list(_flat_idx_to_idx(flat_end - 1 , snake_case_ ) ) # Get an ordered list of slices to perform UpperCAmelCase_ = _get_minimal_slice_set( snake_case_ , snake_case_ , snake_case_ , ) UpperCAmelCase_ = [t[s] for s in slices] return torch.cat([s.view((-1,) + t.shape[no_batch_dims:] ) for s in sliced_tensors] ) def lowerCAmelCase_ ( snake_case_ : Callable , snake_case_ : Dict[str, Any] , snake_case_ : int , snake_case_ : int , snake_case_ : bool = False , snake_case_ : Any = None , snake_case_ : bool = False , ) -> Any: '''simple docstring''' if not (len(snake_case_ ) > 0): raise ValueError("Must provide at least one input" ) UpperCAmelCase_ = [shape[:no_batch_dims] for shape in _fetch_dims(snake_case_ )] UpperCAmelCase_ = tuple([max(snake_case_ ) for s in zip(*snake_case_ )] ) def _prep_inputs(snake_case_ : torch.Tensor ) -> torch.Tensor: if not low_mem: if not sum(t.shape[:no_batch_dims] ) == no_batch_dims: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) UpperCAmelCase_ = t.reshape(-1 , *t.shape[no_batch_dims:] ) else: UpperCAmelCase_ = t.expand(orig_batch_dims + t.shape[no_batch_dims:] ) return t UpperCAmelCase_ = tensor_tree_map(_prep_inputs , snake_case_ ) UpperCAmelCase_ = None if _out is not None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view([-1] + list(t.shape[no_batch_dims:] ) ) , _out ) UpperCAmelCase_ = 1 for d in orig_batch_dims: flat_batch_dim *= d UpperCAmelCase_ = flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0) def _select_chunk(snake_case_ : torch.Tensor ) -> torch.Tensor: return t[i : i + chunk_size] if t.shape[0] != 1 else t UpperCAmelCase_ = 0 UpperCAmelCase_ = prepped_outputs for _ in range(snake_case_ ): # Chunk the input if not low_mem: UpperCAmelCase_ = _select_chunk else: UpperCAmelCase_ = partial( _chunk_slice , flat_start=snake_case_ , flat_end=min(snake_case_ , i + chunk_size ) , no_batch_dims=len(snake_case_ ) , ) UpperCAmelCase_ = tensor_tree_map(snake_case_ , snake_case_ ) # Run the layer on the chunk UpperCAmelCase_ = layer(**snake_case_ ) # Allocate space for the output if out is None: UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.new_zeros((flat_batch_dim,) + t.shape[1:] ) , snake_case_ ) # Put the chunk in its pre-allocated space if isinstance(snake_case_ , snake_case_ ): def assign(snake_case_ : dict , snake_case_ : dict ) -> None: for k, v in da.items(): if isinstance(snake_case_ , snake_case_ ): assign(snake_case_ , da[k] ) else: if _add_into_out: v[i : i + chunk_size] += da[k] else: UpperCAmelCase_ = da[k] assign(snake_case_ , snake_case_ ) elif isinstance(snake_case_ , snake_case_ ): for xa, xa in zip(snake_case_ , snake_case_ ): if _add_into_out: xa[i : i + chunk_size] += xa else: UpperCAmelCase_ = xa elif isinstance(snake_case_ , torch.Tensor ): if _add_into_out: out[i : i + chunk_size] += output_chunk else: UpperCAmelCase_ = output_chunk else: raise ValueError("Not supported" ) i += chunk_size UpperCAmelCase_ = tensor_tree_map(lambda snake_case_ : t.view(orig_batch_dims + t.shape[1:] ) , snake_case_ ) return out class __A : def __init__(self : Dict , __a : int = 512 , ): UpperCAmelCase_ = max_chunk_size UpperCAmelCase_ = None UpperCAmelCase_ = None def _lowercase (self : List[Any] , __a : Callable , __a : tuple , __a : int ): logging.info("Tuning chunk size..." ) if min_chunk_size >= self.max_chunk_size: return min_chunk_size UpperCAmelCase_ = [2**l for l in range(int(math.log(self.max_chunk_size , 2 ) ) + 1 )] UpperCAmelCase_ = [c for c in candidates if c > min_chunk_size] UpperCAmelCase_ = [min_chunk_size] + candidates candidates[-1] += 4 def test_chunk_size(__a : int ) -> bool: try: with torch.no_grad(): fn(*__a , chunk_size=__a ) return True except RuntimeError: return False UpperCAmelCase_ = 0 UpperCAmelCase_ = len(__a ) - 1 while i > min_viable_chunk_size_index: UpperCAmelCase_ = test_chunk_size(candidates[i] ) if not viable: UpperCAmelCase_ = (min_viable_chunk_size_index + i) // 2 else: UpperCAmelCase_ = i UpperCAmelCase_ = (i + len(__a ) - 1) // 2 return candidates[min_viable_chunk_size_index] def _lowercase (self : int , __a : Iterable , __a : Iterable ): UpperCAmelCase_ = True for aa, aa in zip(__a , __a ): assert type(__a ) == type(__a ) if isinstance(__a , (list, tuple) ): consistent &= self._compare_arg_caches(__a , __a ) elif isinstance(__a , __a ): UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] UpperCAmelCase_ = [v for _, v in sorted(aa.items() , key=lambda __a : x[0] )] consistent &= self._compare_arg_caches(__a , __a ) else: consistent &= aa == aa return consistent def _lowercase (self : List[str] , __a : Callable , __a : tuple , __a : int , ): UpperCAmelCase_ = True UpperCAmelCase_ = tree_map(lambda __a : a.shape if isinstance(__a , torch.Tensor ) else a , __a , __a ) if self.cached_arg_data is not None: # If args have changed shape/value, we need to re-tune assert len(self.cached_arg_data ) == len(__a ) UpperCAmelCase_ = self._compare_arg_caches(self.cached_arg_data , __a ) else: # Otherwise, we can reuse the precomputed value UpperCAmelCase_ = False if not consistent: UpperCAmelCase_ = self._determine_favorable_chunk_size( __a , __a , __a , ) UpperCAmelCase_ = arg_data assert self.cached_chunk_size is not None return self.cached_chunk_size
78
1
'''simple docstring''' import os from typing import Dict, List, Union import tensorflow as tf from keras_nlp.tokenizers import BytePairTokenizer from tensorflow_text import pad_model_inputs from .tokenization_gpta import GPTaTokenizer class __A ( tf.keras.layers.Layer ): def __init__(self : Any , __a : Dict[str, int] , __a : List[str] , __a : int = None , __a : int = None ): super().__init__() UpperCAmelCase_ = pad_token_id UpperCAmelCase_ = max_length UpperCAmelCase_ = vocab UpperCAmelCase_ = merges UpperCAmelCase_ = BytePairTokenizer(__a , __a , sequence_length=__a ) @classmethod def _lowercase (cls : str , __a : GPTaTokenizer , *__a : Tuple , **__a : Tuple ): UpperCAmelCase_ = [" ".join(__a ) for m in tokenizer.bpe_ranks.keys()] UpperCAmelCase_ = tokenizer.get_vocab() return cls(__a , __a , *__a , **__a ) @classmethod def _lowercase (cls : Union[str, Any] , __a : Union[str, os.PathLike] , *__a : str , **__a : Union[str, Any] ): UpperCAmelCase_ = GPTaTokenizer.from_pretrained(__a , *__a , **__a ) return cls.from_tokenizer(__a , *__a , **__a ) @classmethod def _lowercase (cls : Optional[Any] , __a : Any ): return cls(**__a ) def _lowercase (self : str ): return { "vocab": self.vocab, "merges": self.merges, "max_length": self.max_length, "pad_token_id": self.pad_token_id, } def _lowercase (self : str , __a : Any , __a : int = None ): UpperCAmelCase_ = self.tf_tokenizer(__a ) UpperCAmelCase_ = tf.ones_like(__a ) if self.pad_token_id is not None: # pad the tokens up to max length UpperCAmelCase_ = max_length if max_length is not None else self.max_length if max_length is not None: UpperCAmelCase_ , UpperCAmelCase_ = pad_model_inputs( __a , max_seq_length=__a , pad_value=self.pad_token_id ) return {"attention_mask": attention_mask, "input_ids": input_ids}
78
'''simple docstring''' import copy import re class __A : a__ : Optional[int] = """hp""" a__ : Optional[Any] = {} a__ : List[Any] = None @classmethod def _lowercase (cls : Optional[int] , __a : str , __a : Tuple ): UpperCAmelCase_ = prefix UpperCAmelCase_ = defaults cls.build_naming_info() @staticmethod def _lowercase (__a : List[Any] , __a : List[str] ): if len(__a ) == 0: return "" UpperCAmelCase_ = None if any(char.isdigit() for char in word ): raise Exception(f"""Parameters should not contain numbers: '{word}' contains a number""" ) if word in info["short_word"]: return info["short_word"][word] for prefix_len in range(1 , len(__a ) + 1 ): UpperCAmelCase_ = word[:prefix_len] if prefix in info["reverse_short_word"]: continue else: UpperCAmelCase_ = prefix break if short_word is None: # Paranoid fallback def int_to_alphabetic(__a : Union[str, Any] ): UpperCAmelCase_ = "" while integer != 0: UpperCAmelCase_ = chr(ord("A" ) + integer % 10 ) + s integer //= 10 return s UpperCAmelCase_ = 0 while True: UpperCAmelCase_ = word + "#" + int_to_alphabetic(__a ) if sword in info["reverse_short_word"]: continue else: UpperCAmelCase_ = sword break UpperCAmelCase_ = short_word UpperCAmelCase_ = word return short_word @staticmethod def _lowercase (__a : List[str] , __a : Union[str, Any] ): UpperCAmelCase_ = param_name.split("_" ) UpperCAmelCase_ = [TrialShortNamer.shortname_for_word(__a , __a ) for word in words] # We try to create a separatorless short name, but if there is a collision we have to fallback # to a separated short name UpperCAmelCase_ = ["", "_"] for separator in separators: UpperCAmelCase_ = separator.join(__a ) if shortname not in info["reverse_short_param"]: UpperCAmelCase_ = shortname UpperCAmelCase_ = param_name return shortname return param_name @staticmethod def _lowercase (__a : int , __a : Union[str, Any] ): UpperCAmelCase_ = TrialShortNamer.shortname_for_key(__a , __a ) UpperCAmelCase_ = short_name UpperCAmelCase_ = param_name @classmethod def _lowercase (cls : Any ): if cls.NAMING_INFO is not None: return UpperCAmelCase_ = { "short_word": {}, "reverse_short_word": {}, "short_param": {}, "reverse_short_param": {}, } UpperCAmelCase_ = list(cls.DEFAULTS.keys() ) for k in field_keys: cls.add_new_param_name(__a , __a ) UpperCAmelCase_ = info @classmethod def _lowercase (cls : int , __a : Optional[int] ): cls.build_naming_info() assert cls.PREFIX is not None UpperCAmelCase_ = [copy.copy(cls.PREFIX )] for k, v in params.items(): if k not in cls.DEFAULTS: raise Exception(f"""You should provide a default value for the param name {k} with value {v}""" ) if v == cls.DEFAULTS[k]: # The default value is not added to the name continue UpperCAmelCase_ = cls.NAMING_INFO["short_param"][k] if isinstance(__a , __a ): UpperCAmelCase_ = 1 if v else 0 UpperCAmelCase_ = "" if isinstance(__a , (int, float) ) else "-" UpperCAmelCase_ = f"""{key}{sep}{v}""" name.append(__a ) return "_".join(__a ) @classmethod def _lowercase (cls : Dict , __a : Dict ): UpperCAmelCase_ = repr[len(cls.PREFIX ) + 1 :] if repr == "": UpperCAmelCase_ = [] else: UpperCAmelCase_ = repr.split("_" ) UpperCAmelCase_ = {} for value in values: if "-" in value: UpperCAmelCase_ , UpperCAmelCase_ = value.split("-" ) else: UpperCAmelCase_ = re.sub("[0-9.]" , "" , __a ) UpperCAmelCase_ = float(re.sub("[^0-9.]" , "" , __a ) ) UpperCAmelCase_ = cls.NAMING_INFO["reverse_short_param"][p_k] UpperCAmelCase_ = p_v for k in cls.DEFAULTS: if k not in parameters: UpperCAmelCase_ = cls.DEFAULTS[k] return parameters
78
1
'''simple docstring''' import unittest from transformers import is_flax_available from transformers.testing_utils import require_flax, require_sentencepiece, require_tokenizers, require_torch, slow if is_flax_available(): import optax from flax.training.common_utils import onehot from transformers import AutoTokenizer, FlaxMTaForConditionalGeneration from transformers.models.ta.modeling_flax_ta import shift_tokens_right @require_torch @require_sentencepiece @require_tokenizers @require_flax class __A ( unittest.TestCase ): @slow def _lowercase (self : List[str] ): UpperCAmelCase_ = FlaxMTaForConditionalGeneration.from_pretrained("google/mt5-small" ) UpperCAmelCase_ = AutoTokenizer.from_pretrained("google/mt5-small" ) UpperCAmelCase_ = tokenizer("Hello there" , return_tensors="np" ).input_ids UpperCAmelCase_ = tokenizer("Hi I am" , return_tensors="np" ).input_ids UpperCAmelCase_ = shift_tokens_right(__a , model.config.pad_token_id , model.config.decoder_start_token_id ) UpperCAmelCase_ = model(__a , decoder_input_ids=__a ).logits UpperCAmelCase_ = optax.softmax_cross_entropy(__a , onehot(__a , logits.shape[-1] ) ).mean() UpperCAmelCase_ = -(labels.shape[-1] * loss.item()) UpperCAmelCase_ = -84.91_27 self.assertTrue(abs(mtf_score - EXPECTED_SCORE ) < 1E-4 )
78
'''simple docstring''' from typing import Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature from ...image_transforms import get_image_size, pad, rescale, to_channel_dimension_format from ...image_utils import ChannelDimension, ImageInput, make_list_of_images, to_numpy_array, valid_images from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) class __A ( UpperCamelCase__ ): a__ : Tuple = ["""pixel_values"""] def __init__(self : int , __a : bool = True , __a : Union[int, float] = 1 / 255 , __a : bool = True , __a : int = 8 , **__a : int , ): super().__init__(**__a ) UpperCAmelCase_ = do_rescale UpperCAmelCase_ = rescale_factor UpperCAmelCase_ = do_pad UpperCAmelCase_ = pad_size def _lowercase (self : Optional[int] , __a : np.ndarray , __a : float , __a : Optional[Union[str, ChannelDimension]] = None , **__a : Optional[int] ): return rescale(__a , scale=__a , data_format=__a , **__a ) def _lowercase (self : Optional[int] , __a : np.ndarray , __a : int , __a : Optional[Union[str, ChannelDimension]] = None ): UpperCAmelCase_ , UpperCAmelCase_ = get_image_size(__a ) UpperCAmelCase_ = (old_height // size + 1) * size - old_height UpperCAmelCase_ = (old_width // size + 1) * size - old_width return pad(__a , ((0, pad_height), (0, pad_width)) , mode="symmetric" , data_format=__a ) def _lowercase (self : Tuple , __a : ImageInput , __a : Optional[bool] = None , __a : Optional[float] = None , __a : Optional[bool] = None , __a : Optional[int] = None , __a : Optional[Union[str, TensorType]] = None , __a : Union[str, ChannelDimension] = ChannelDimension.FIRST , **__a : List[str] , ): UpperCAmelCase_ = do_rescale if do_rescale is not None else self.do_rescale UpperCAmelCase_ = rescale_factor if rescale_factor is not None else self.rescale_factor UpperCAmelCase_ = do_pad if do_pad is not None else self.do_pad UpperCAmelCase_ = pad_size if pad_size is not None else self.pad_size UpperCAmelCase_ = 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_rescale and rescale_factor is None: raise ValueError("Rescale factor must be specified if do_rescale is True." ) # All transformations expect numpy arrays. UpperCAmelCase_ = [to_numpy_array(__a ) for image in images] if do_rescale: UpperCAmelCase_ = [self.rescale(image=__a , scale=__a ) for image in images] if do_pad: UpperCAmelCase_ = [self.pad(__a , size=__a ) for image in images] UpperCAmelCase_ = [to_channel_dimension_format(__a , __a ) for image in images] UpperCAmelCase_ = {"pixel_values": images} return BatchFeature(data=__a , tensor_type=__a )
78
1
'''simple docstring''' def lowerCAmelCase_ ( ) -> list[list[int]]: '''simple docstring''' return [list(range(10_00 - i , -10_00 - i , -1 ) ) for i in range(10_00 )] SCREAMING_SNAKE_CASE_: Dict =generate_large_matrix() SCREAMING_SNAKE_CASE_: List[str] =( [[4, 3, 2, -1], [3, 2, 1, -1], [1, 1, -1, -2], [-1, -1, -2, -3]], [[3, 2], [1, 0]], [[7, 7, 6]], [[7, 7, 6], [-1, -2, -3]], grid, ) def lowerCAmelCase_ ( snake_case_ : list[list[int]] ) -> None: '''simple docstring''' assert all(row == sorted(snake_case_ , reverse=snake_case_ ) for row in grid ) assert all(list(snake_case_ ) == sorted(snake_case_ , reverse=snake_case_ ) for col in zip(*snake_case_ ) ) def lowerCAmelCase_ ( snake_case_ : list[int] ) -> int: '''simple docstring''' UpperCAmelCase_ = 0 UpperCAmelCase_ = len(snake_case_ ) - 1 # Edge cases such as no values or all numbers are negative. if not array or array[0] < 0: return 0 while right + 1 > left: UpperCAmelCase_ = (left + right) // 2 UpperCAmelCase_ = array[mid] # Num must be negative and the index must be greater than or equal to 0. if num < 0 and array[mid - 1] >= 0: return mid if num >= 0: UpperCAmelCase_ = mid + 1 else: UpperCAmelCase_ = mid - 1 # No negative numbers so return the last index of the array + 1 which is the length. return len(snake_case_ ) def lowerCAmelCase_ ( snake_case_ : list[list[int]] ) -> int: '''simple docstring''' UpperCAmelCase_ = 0 UpperCAmelCase_ = len(grid[0] ) for i in range(len(snake_case_ ) ): UpperCAmelCase_ = find_negative_index(grid[i][:bound] ) total += bound return (len(snake_case_ ) * len(grid[0] )) - total def lowerCAmelCase_ ( snake_case_ : list[list[int]] ) -> int: '''simple docstring''' return len([number for row in grid for number in row if number < 0] ) def lowerCAmelCase_ ( snake_case_ : list[list[int]] ) -> int: '''simple docstring''' UpperCAmelCase_ = 0 for row in grid: for i, number in enumerate(snake_case_ ): if number < 0: total += len(snake_case_ ) - i break return total def lowerCAmelCase_ ( ) -> None: '''simple docstring''' from timeit import timeit print("Running benchmarks" ) UpperCAmelCase_ = ( "from __main__ import count_negatives_binary_search, " "count_negatives_brute_force, count_negatives_brute_force_with_break, grid" ) for func in ( "count_negatives_binary_search", # took 0.7727 seconds "count_negatives_brute_force_with_break", # took 4.6505 seconds "count_negatives_brute_force", # took 12.8160 seconds ): UpperCAmelCase_ = timeit(f"""{func}(grid=grid)""" , setup=snake_case_ , number=5_00 ) print(f"""{func}() took {time:0.4f} seconds""" ) if __name__ == "__main__": import doctest doctest.testmod() benchmark()
78
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# SCREAMING_SNAKE_CASE_: Dict =[ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] SCREAMING_SNAKE_CASE_: Union[str, Any] =[] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks SCREAMING_SNAKE_CASE_: Any =f"down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 SCREAMING_SNAKE_CASE_: Optional[Any] =f"down_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: List[str] =f"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks SCREAMING_SNAKE_CASE_: Union[str, Any] =f"up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Any =f"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.attentions.{j}." SCREAMING_SNAKE_CASE_: Optional[int] =f"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 SCREAMING_SNAKE_CASE_: Union[str, Any] =f"down_blocks.{i}.downsamplers.0.conv." SCREAMING_SNAKE_CASE_: Union[str, Any] =f"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[Any] =f"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) SCREAMING_SNAKE_CASE_: int ='mid_block.attentions.0.' SCREAMING_SNAKE_CASE_: List[Any] ='middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"mid_block.resnets.{j}." SCREAMING_SNAKE_CASE_: Tuple =f"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> List[str]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: UpperCAmelCase_ = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): SCREAMING_SNAKE_CASE_: Tuple =f"encoder.down_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: int =f"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: SCREAMING_SNAKE_CASE_: int =f"down_blocks.{i}.downsamplers.0." SCREAMING_SNAKE_CASE_: str =f"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) SCREAMING_SNAKE_CASE_: int =f"up_blocks.{i}.upsamplers.0." SCREAMING_SNAKE_CASE_: List[str] =f"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): SCREAMING_SNAKE_CASE_: List[str] =f"decoder.up_blocks.{i}.resnets.{j}." SCREAMING_SNAKE_CASE_: Dict =f"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): SCREAMING_SNAKE_CASE_: Any =f"mid_block.resnets.{i}." SCREAMING_SNAKE_CASE_: Tuple =f"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) SCREAMING_SNAKE_CASE_: int =[ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCAmelCase_ ( snake_case_ : Tuple ) -> Tuple: '''simple docstring''' return w.reshape(*w.shape , 1 , 1 ) def lowerCAmelCase_ ( snake_case_ : Optional[Any] ) -> Optional[Any]: '''simple docstring''' UpperCAmelCase_ = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: UpperCAmelCase_ = v.replace(snake_case_ , snake_case_ ) UpperCAmelCase_ = v UpperCAmelCase_ = {v: vae_state_dict[k] for k, v in mapping.items()} UpperCAmelCase_ = ["q", "k", "v", "proj_out"] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) UpperCAmelCase_ = reshape_weight_for_sd(snake_case_ ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# SCREAMING_SNAKE_CASE_: List[Any] =[ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] SCREAMING_SNAKE_CASE_: Dict ={re.escape(x[1]): x[0] for x in textenc_conversion_lst} SCREAMING_SNAKE_CASE_: str =re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp SCREAMING_SNAKE_CASE_: List[Any] ={'q': 0, 'k': 1, 'v': 2} def lowerCAmelCase_ ( snake_case_ : Union[str, Any] ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = {} UpperCAmelCase_ = {} UpperCAmelCase_ = {} for k, v in text_enc_dict.items(): if ( k.endswith(".self_attn.q_proj.weight" ) or k.endswith(".self_attn.k_proj.weight" ) or k.endswith(".self_attn.v_proj.weight" ) ): UpperCAmelCase_ = k[: -len(".q_proj.weight" )] UpperCAmelCase_ = k[-len("q_proj.weight" )] if k_pre not in capture_qkv_weight: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue if ( k.endswith(".self_attn.q_proj.bias" ) or k.endswith(".self_attn.k_proj.bias" ) or k.endswith(".self_attn.v_proj.bias" ) ): UpperCAmelCase_ = k[: -len(".q_proj.bias" )] UpperCAmelCase_ = k[-len("q_proj.bias" )] if k_pre not in capture_qkv_bias: UpperCAmelCase_ = [None, None, None] UpperCAmelCase_ = v continue UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception("CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing" ) UpperCAmelCase_ = textenc_pattern.sub(lambda snake_case_ : protected[re.escape(m.group(0 ) )] , snake_case_ ) UpperCAmelCase_ = torch.cat(snake_case_ ) return new_state_dict def lowerCAmelCase_ ( snake_case_ : List[Any] ) -> Union[str, Any]: '''simple docstring''' return text_enc_dict if __name__ == "__main__": SCREAMING_SNAKE_CASE_: str =argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) SCREAMING_SNAKE_CASE_: Dict =parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors SCREAMING_SNAKE_CASE_: Any =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Dict =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') SCREAMING_SNAKE_CASE_: Union[str, Any] =osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): SCREAMING_SNAKE_CASE_: Union[str, Any] =load_file(unet_path, device='cpu') else: SCREAMING_SNAKE_CASE_: int =osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: Dict =torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(vae_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') SCREAMING_SNAKE_CASE_: str =torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): SCREAMING_SNAKE_CASE_: Tuple =load_file(text_enc_path, device='cpu') else: SCREAMING_SNAKE_CASE_: List[Any] =osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') SCREAMING_SNAKE_CASE_: Any =torch.load(text_enc_path, map_location='cpu') # Convert the UNet model SCREAMING_SNAKE_CASE_: List[Any] =convert_unet_state_dict(unet_state_dict) SCREAMING_SNAKE_CASE_: Any ={'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model SCREAMING_SNAKE_CASE_: List[Any] =convert_vae_state_dict(vae_state_dict) SCREAMING_SNAKE_CASE_: Dict ={'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper SCREAMING_SNAKE_CASE_: Dict ='text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm SCREAMING_SNAKE_CASE_: Any ={'transformer.' + k: v for k, v in text_enc_dict.items()} SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict_vaa(text_enc_dict) SCREAMING_SNAKE_CASE_: int ={'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: SCREAMING_SNAKE_CASE_: str =convert_text_enc_state_dict(text_enc_dict) SCREAMING_SNAKE_CASE_: Optional[int] ={'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint SCREAMING_SNAKE_CASE_: List[str] ={**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: SCREAMING_SNAKE_CASE_: List[str] ={k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: SCREAMING_SNAKE_CASE_: str ={'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
78
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import DeiTImageProcessor, ViTConfig, ViTForImageClassification, ViTImageProcessor, ViTModel from transformers.utils import logging logging.set_verbosity_info() SCREAMING_SNAKE_CASE_: int =logging.get_logger(__name__) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : int=False ) -> Tuple: '''simple docstring''' UpperCAmelCase_ = [] for i in range(config.num_hidden_layers ): # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms rename_keys.append((f"""blocks.{i}.norm1.weight""", f"""vit.encoder.layer.{i}.layernorm_before.weight""") ) rename_keys.append((f"""blocks.{i}.norm1.bias""", f"""vit.encoder.layer.{i}.layernorm_before.bias""") ) rename_keys.append((f"""blocks.{i}.attn.proj.weight""", f"""vit.encoder.layer.{i}.attention.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.attn.proj.bias""", f"""vit.encoder.layer.{i}.attention.output.dense.bias""") ) rename_keys.append((f"""blocks.{i}.norm2.weight""", f"""vit.encoder.layer.{i}.layernorm_after.weight""") ) rename_keys.append((f"""blocks.{i}.norm2.bias""", f"""vit.encoder.layer.{i}.layernorm_after.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.weight""", f"""vit.encoder.layer.{i}.intermediate.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc1.bias""", f"""vit.encoder.layer.{i}.intermediate.dense.bias""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.weight""", f"""vit.encoder.layer.{i}.output.dense.weight""") ) rename_keys.append((f"""blocks.{i}.mlp.fc2.bias""", f"""vit.encoder.layer.{i}.output.dense.bias""") ) # projection layer + position embeddings rename_keys.extend( [ ("cls_token", "vit.embeddings.cls_token"), ("patch_embed.proj.weight", "vit.embeddings.patch_embeddings.projection.weight"), ("patch_embed.proj.bias", "vit.embeddings.patch_embeddings.projection.bias"), ("pos_embed", "vit.embeddings.position_embeddings"), ] ) if base_model: # layernorm + pooler rename_keys.extend( [ ("norm.weight", "layernorm.weight"), ("norm.bias", "layernorm.bias"), ("pre_logits.fc.weight", "pooler.dense.weight"), ("pre_logits.fc.bias", "pooler.dense.bias"), ] ) # if just the base model, we should remove "vit" from all keys that start with "vit" UpperCAmelCase_ = [(pair[0], pair[1][4:]) if pair[1].startswith("vit" ) else pair for pair in rename_keys] else: # layernorm + classification head rename_keys.extend( [ ("norm.weight", "vit.layernorm.weight"), ("norm.bias", "vit.layernorm.bias"), ("head.weight", "classifier.weight"), ("head.bias", "classifier.bias"), ] ) return rename_keys def lowerCAmelCase_ ( snake_case_ : Optional[int] , snake_case_ : List[Any] , snake_case_ : Union[str, Any]=False ) -> Union[str, Any]: '''simple docstring''' for i in range(config.num_hidden_layers ): if base_model: UpperCAmelCase_ = "" else: UpperCAmelCase_ = "vit." # read in weights + bias of input projection layer (in timm, this is a single matrix + bias) UpperCAmelCase_ = state_dict.pop(f"""blocks.{i}.attn.qkv.weight""" ) UpperCAmelCase_ = state_dict.pop(f"""blocks.{i}.attn.qkv.bias""" ) # next, add query, keys and values (in that order) to the state dict UpperCAmelCase_ = in_proj_weight[ : config.hidden_size, : ] UpperCAmelCase_ = in_proj_bias[: config.hidden_size] UpperCAmelCase_ = in_proj_weight[ config.hidden_size : config.hidden_size * 2, : ] UpperCAmelCase_ = in_proj_bias[ config.hidden_size : config.hidden_size * 2 ] UpperCAmelCase_ = in_proj_weight[ -config.hidden_size :, : ] UpperCAmelCase_ = in_proj_bias[-config.hidden_size :] def lowerCAmelCase_ ( snake_case_ : int ) -> Union[str, Any]: '''simple docstring''' UpperCAmelCase_ = ["head.weight", "head.bias"] for k in ignore_keys: state_dict.pop(snake_case_ , snake_case_ ) def lowerCAmelCase_ ( snake_case_ : Any , snake_case_ : Any , snake_case_ : Any ) -> Optional[int]: '''simple docstring''' UpperCAmelCase_ = dct.pop(snake_case_ ) UpperCAmelCase_ = val def lowerCAmelCase_ ( ) -> Dict: '''simple docstring''' UpperCAmelCase_ = "http://images.cocodataset.org/val2017/000000039769.jpg" UpperCAmelCase_ = Image.open(requests.get(snake_case_ , stream=snake_case_ ).raw ) return im @torch.no_grad() def lowerCAmelCase_ ( snake_case_ : int , snake_case_ : Union[str, Any] ) -> Dict: '''simple docstring''' UpperCAmelCase_ = ViTConfig() UpperCAmelCase_ = False # dataset (ImageNet-21k only or also fine-tuned on ImageNet 2012), patch_size and image_size if vit_name[-5:] == "in21k": UpperCAmelCase_ = True UpperCAmelCase_ = int(vit_name[-12:-10] ) UpperCAmelCase_ = int(vit_name[-9:-6] ) else: UpperCAmelCase_ = 10_00 UpperCAmelCase_ = "huggingface/label-files" UpperCAmelCase_ = "imagenet-1k-id2label.json" UpperCAmelCase_ = json.load(open(hf_hub_download(snake_case_ , snake_case_ , repo_type="dataset" ) , "r" ) ) UpperCAmelCase_ = {int(snake_case_ ): v for k, v in idalabel.items()} UpperCAmelCase_ = idalabel UpperCAmelCase_ = {v: k for k, v in idalabel.items()} UpperCAmelCase_ = int(vit_name[-6:-4] ) UpperCAmelCase_ = int(vit_name[-3:] ) # size of the architecture if "deit" in vit_name: if vit_name[9:].startswith("tiny" ): UpperCAmelCase_ = 1_92 UpperCAmelCase_ = 7_68 UpperCAmelCase_ = 12 UpperCAmelCase_ = 3 elif vit_name[9:].startswith("small" ): UpperCAmelCase_ = 3_84 UpperCAmelCase_ = 15_36 UpperCAmelCase_ = 12 UpperCAmelCase_ = 6 else: pass else: if vit_name[4:].startswith("small" ): UpperCAmelCase_ = 7_68 UpperCAmelCase_ = 23_04 UpperCAmelCase_ = 8 UpperCAmelCase_ = 8 elif vit_name[4:].startswith("base" ): pass elif vit_name[4:].startswith("large" ): UpperCAmelCase_ = 10_24 UpperCAmelCase_ = 40_96 UpperCAmelCase_ = 24 UpperCAmelCase_ = 16 elif vit_name[4:].startswith("huge" ): UpperCAmelCase_ = 12_80 UpperCAmelCase_ = 51_20 UpperCAmelCase_ = 32 UpperCAmelCase_ = 16 # load original model from timm UpperCAmelCase_ = timm.create_model(snake_case_ , pretrained=snake_case_ ) timm_model.eval() # load state_dict of original model, remove and rename some keys UpperCAmelCase_ = timm_model.state_dict() if base_model: remove_classification_head_(snake_case_ ) UpperCAmelCase_ = create_rename_keys(snake_case_ , snake_case_ ) for src, dest in rename_keys: rename_key(snake_case_ , snake_case_ , snake_case_ ) read_in_q_k_v(snake_case_ , snake_case_ , snake_case_ ) # load HuggingFace model if vit_name[-5:] == "in21k": UpperCAmelCase_ = ViTModel(snake_case_ ).eval() else: UpperCAmelCase_ = ViTForImageClassification(snake_case_ ).eval() model.load_state_dict(snake_case_ ) # Check outputs on an image, prepared by ViTImageProcessor/DeiTImageProcessor if "deit" in vit_name: UpperCAmelCase_ = DeiTImageProcessor(size=config.image_size ) else: UpperCAmelCase_ = ViTImageProcessor(size=config.image_size ) UpperCAmelCase_ = image_processor(images=prepare_img() , return_tensors="pt" ) UpperCAmelCase_ = encoding["pixel_values"] UpperCAmelCase_ = model(snake_case_ ) if base_model: UpperCAmelCase_ = timm_model.forward_features(snake_case_ ) assert timm_pooled_output.shape == outputs.pooler_output.shape assert torch.allclose(snake_case_ , outputs.pooler_output , atol=1E-3 ) else: UpperCAmelCase_ = timm_model(snake_case_ ) assert timm_logits.shape == outputs.logits.shape assert torch.allclose(snake_case_ , outputs.logits , atol=1E-3 ) Path(snake_case_ ).mkdir(exist_ok=snake_case_ ) print(f"""Saving model {vit_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(snake_case_ ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(snake_case_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE_: Dict =argparse.ArgumentParser() # Required parameters parser.add_argument( '--vit_name', default='vit_base_patch16_224', type=str, help='Name of the ViT timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) SCREAMING_SNAKE_CASE_: List[str] =parser.parse_args() convert_vit_checkpoint(args.vit_name, args.pytorch_dump_folder_path)
78
'''simple docstring''' import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ : ndarray ) -> float: '''simple docstring''' return np.dot(snake_case_ , snake_case_ ) class __A : def __init__(self : int , *, __a : float = np.inf , __a : str = "linear" , __a : float = 0.0 , ): UpperCAmelCase_ = regularization UpperCAmelCase_ = gamma if kernel == "linear": UpperCAmelCase_ = self.__linear elif kernel == "rbf": if self.gamma == 0: raise ValueError("rbf kernel requires gamma" ) if not isinstance(self.gamma , (float, int) ): raise ValueError("gamma must be float or int" ) if not self.gamma > 0: raise ValueError("gamma must be > 0" ) UpperCAmelCase_ = self.__rbf # in the future, there could be a default value like in sklearn # sklear: def_gamma = 1/(n_features * X.var()) (wiki) # previously it was 1/(n_features) else: UpperCAmelCase_ = f"""Unknown kernel: {kernel}""" raise ValueError(__a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.dot(__a , __a ) def _lowercase (self : Optional[int] , __a : ndarray , __a : ndarray ): return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def _lowercase (self : str , __a : list[ndarray] , __a : ndarray ): UpperCAmelCase_ = observations UpperCAmelCase_ = classes # using Wolfe's Dual to calculate w. # Primal problem: minimize 1/2*norm_squared(w) # constraint: yn(w . xn + b) >= 1 # # With l a vector # Dual problem: maximize sum_n(ln) - # 1/2 * sum_n(sum_m(ln*lm*yn*ym*xn . xm)) # constraint: self.C >= ln >= 0 # and sum_n(ln*yn) = 0 # Then we get w using w = sum_n(ln*yn*xn) # At the end we can get b ~= mean(yn - w . xn) # # Since we use kernels, we only need l_star to calculate b # and to classify observations ((UpperCAmelCase_) , ) = np.shape(__a ) def to_minimize(__a : ndarray ) -> float: UpperCAmelCase_ = 0 ((UpperCAmelCase_) , ) = np.shape(__a ) for i in range(__a ): for j in range(__a ): s += ( candidate[i] * candidate[j] * classes[i] * classes[j] * self.kernel(observations[i] , observations[j] ) ) return 1 / 2 * s - sum(__a ) UpperCAmelCase_ = LinearConstraint(__a , 0 , 0 ) UpperCAmelCase_ = Bounds(0 , self.regularization ) UpperCAmelCase_ = minimize( __a , np.ones(__a ) , bounds=__a , constraints=[ly_contraint] ).x UpperCAmelCase_ = l_star # calculating mean offset of separation plane to points UpperCAmelCase_ = 0 for i in range(__a ): for j in range(__a ): s += classes[i] - classes[i] * self.optimum[i] * self.kernel( observations[i] , observations[j] ) UpperCAmelCase_ = s / n def _lowercase (self : Optional[int] , __a : ndarray ): UpperCAmelCase_ = sum( self.optimum[n] * self.classes[n] * self.kernel(self.observations[n] , __a ) for n in range(len(self.classes ) ) ) return 1 if s + self.offset >= 0 else -1 if __name__ == "__main__": import doctest doctest.testmod()
78
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging SCREAMING_SNAKE_CASE_: Tuple =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Tuple ={ 'Visual-Attention-Network/van-base': ( 'https://huggingface.co/Visual-Attention-Network/van-base/blob/main/config.json' ), } class __A ( UpperCamelCase__ ): a__ : Optional[Any] = """van""" def __init__(self : List[Any] , __a : Tuple=224 , __a : Any=3 , __a : Any=[7, 3, 3, 3] , __a : Optional[int]=[4, 2, 2, 2] , __a : Optional[int]=[64, 128, 320, 512] , __a : List[Any]=[3, 3, 12, 3] , __a : Optional[int]=[8, 8, 4, 4] , __a : Union[str, Any]="gelu" , __a : Union[str, Any]=0.02 , __a : str=1E-6 , __a : Any=1E-2 , __a : Tuple=0.0 , __a : str=0.0 , **__a : Dict , ): super().__init__(**__a ) UpperCAmelCase_ = image_size UpperCAmelCase_ = num_channels UpperCAmelCase_ = patch_sizes UpperCAmelCase_ = strides UpperCAmelCase_ = hidden_sizes UpperCAmelCase_ = depths UpperCAmelCase_ = mlp_ratios UpperCAmelCase_ = hidden_act UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = layer_scale_init_value UpperCAmelCase_ = drop_path_rate UpperCAmelCase_ = dropout_rate
78
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
1
'''simple docstring''' from typing import Any, Dict, List, Union from ..utils import add_end_docstrings, is_torch_available, is_vision_available, logging, requires_backends from .base import PIPELINE_INIT_ARGS, Pipeline if is_vision_available(): from ..image_utils import load_image if is_torch_available(): import torch from ..models.auto.modeling_auto import MODEL_FOR_OBJECT_DETECTION_MAPPING, MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING SCREAMING_SNAKE_CASE_: Any =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Any =Dict[str, Any] SCREAMING_SNAKE_CASE_: Any =List[Prediction] @add_end_docstrings(UpperCamelCase__ ) class __A ( UpperCamelCase__ ): def __init__(self : str , *__a : Union[str, Any] , **__a : Dict ): super().__init__(*__a , **__a ) if self.framework == "tf": raise ValueError(f"""The {self.__class__} is only available in PyTorch.""" ) requires_backends(self , "vision" ) self.check_model_type( dict(MODEL_FOR_OBJECT_DETECTION_MAPPING.items() + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.items() ) ) def _lowercase (self : List[str] , **__a : List[str] ): UpperCAmelCase_ = {} if "threshold" in kwargs: UpperCAmelCase_ = kwargs["threshold"] return {}, {}, postprocess_kwargs def __call__(self : int , *__a : Optional[Any] , **__a : int ): return super().__call__(*__a , **__a ) def _lowercase (self : str , __a : str ): UpperCAmelCase_ = load_image(__a ) UpperCAmelCase_ = torch.IntTensor([[image.height, image.width]] ) UpperCAmelCase_ = self.image_processor(images=[image] , return_tensors="pt" ) if self.tokenizer is not None: UpperCAmelCase_ = self.tokenizer(text=inputs["words"] , boxes=inputs["boxes"] , return_tensors="pt" ) UpperCAmelCase_ = target_size return inputs def _lowercase (self : str , __a : Optional[Any] ): UpperCAmelCase_ = model_inputs.pop("target_size" ) UpperCAmelCase_ = self.model(**__a ) UpperCAmelCase_ = outputs.__class__({"target_size": target_size, **outputs} ) if self.tokenizer is not None: UpperCAmelCase_ = model_inputs["bbox"] return model_outputs def _lowercase (self : Optional[int] , __a : Tuple , __a : Optional[Any]=0.9 ): UpperCAmelCase_ = model_outputs["target_size"] if self.tokenizer is not None: # This is a LayoutLMForTokenClassification variant. # The OCR got the boxes and the model classified the words. UpperCAmelCase_ , UpperCAmelCase_ = target_size[0].tolist() def unnormalize(__a : str ): return self._get_bounding_box( torch.Tensor( [ (width * bbox[0] / 1000), (height * bbox[1] / 1000), (width * bbox[2] / 1000), (height * bbox[3] / 1000), ] ) ) UpperCAmelCase_ , UpperCAmelCase_ = model_outputs["logits"].squeeze(0 ).softmax(dim=-1 ).max(dim=-1 ) UpperCAmelCase_ = [self.model.config.idalabel[prediction] for prediction in classes.tolist()] UpperCAmelCase_ = [unnormalize(__a ) for bbox in model_outputs["bbox"].squeeze(0 )] UpperCAmelCase_ = ["score", "label", "box"] UpperCAmelCase_ = [dict(zip(__a , __a ) ) for vals in zip(scores.tolist() , __a , __a ) if vals[0] > threshold] else: # This is a regular ForObjectDetectionModel UpperCAmelCase_ = self.image_processor.post_process_object_detection(__a , __a , __a ) UpperCAmelCase_ = raw_annotations[0] UpperCAmelCase_ = raw_annotation["scores"] UpperCAmelCase_ = raw_annotation["labels"] UpperCAmelCase_ = raw_annotation["boxes"] UpperCAmelCase_ = scores.tolist() UpperCAmelCase_ = [self.model.config.idalabel[label.item()] for label in labels] UpperCAmelCase_ = [self._get_bounding_box(__a ) for box in boxes] # {"scores": [...], ...} --> [{"score":x, ...}, ...] UpperCAmelCase_ = ["score", "label", "box"] UpperCAmelCase_ = [ dict(zip(__a , __a ) ) for vals in zip(raw_annotation["scores"] , raw_annotation["labels"] , raw_annotation["boxes"] ) ] return annotation def _lowercase (self : Dict , __a : "torch.Tensor" ): if self.framework != "pt": raise ValueError("The ObjectDetectionPipeline is only available in PyTorch." ) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = box.int().tolist() UpperCAmelCase_ = { "xmin": xmin, "ymin": ymin, "xmax": xmax, "ymax": ymax, } return bbox
78
'''simple docstring''' import requests def lowerCAmelCase_ ( snake_case_ : str , snake_case_ : str ) -> None: '''simple docstring''' UpperCAmelCase_ = {"Content-Type": "application/json"} UpperCAmelCase_ = requests.post(snake_case_ , json={"text": message_body} , headers=snake_case_ ) if response.status_code != 2_00: UpperCAmelCase_ = ( "Request to slack returned an error " f"""{response.status_code}, the response is:\n{response.text}""" ) raise ValueError(snake_case_ ) if __name__ == "__main__": # Set the slack url to the one provided by Slack when you create the webhook at # https://my.slack.com/services/new/incoming-webhook/ send_slack_message('<YOUR MESSAGE BODY>', '<SLACK CHANNEL URL>')
78
1
'''simple docstring''' from collections import OrderedDict from typing import Any, Mapping, Optional, Union from ...configuration_utils import PretrainedConfig from ...feature_extraction_utils import FeatureExtractionMixin from ...onnx import OnnxConfig from ...onnx.utils import compute_effective_axis_dimension from ...tokenization_utils_base import PreTrainedTokenizerBase from ...utils import TensorType, logging SCREAMING_SNAKE_CASE_: Optional[Any] =logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: List[Any] ={ 'deepmind/language-perceiver': 'https://huggingface.co/deepmind/language-perceiver/resolve/main/config.json', # See all Perceiver models at https://huggingface.co/models?filter=perceiver } class __A ( UpperCamelCase__ ): a__ : List[Any] = """perceiver""" def __init__(self : Optional[int] , __a : Tuple=256 , __a : Optional[Any]=1280 , __a : Optional[int]=768 , __a : Any=1 , __a : List[str]=26 , __a : Dict=8 , __a : List[Any]=8 , __a : Tuple=None , __a : List[str]=None , __a : Optional[int]="kv" , __a : Union[str, Any]=1 , __a : List[str]=1 , __a : List[Any]="gelu" , __a : List[str]=0.1 , __a : str=0.02 , __a : List[str]=1E-12 , __a : Optional[int]=True , __a : Tuple=262 , __a : Dict=2048 , __a : int=56 , __a : Optional[int]=[368, 496] , __a : Any=16 , __a : Optional[Any]=1920 , __a : Any=16 , __a : str=[1, 16, 224, 224] , **__a : Any , ): super().__init__(**__a ) UpperCAmelCase_ = num_latents UpperCAmelCase_ = d_latents UpperCAmelCase_ = d_model UpperCAmelCase_ = num_blocks UpperCAmelCase_ = num_self_attends_per_block UpperCAmelCase_ = num_self_attention_heads UpperCAmelCase_ = num_cross_attention_heads UpperCAmelCase_ = qk_channels UpperCAmelCase_ = v_channels UpperCAmelCase_ = cross_attention_shape_for_attention UpperCAmelCase_ = self_attention_widening_factor UpperCAmelCase_ = cross_attention_widening_factor UpperCAmelCase_ = hidden_act UpperCAmelCase_ = attention_probs_dropout_prob UpperCAmelCase_ = initializer_range UpperCAmelCase_ = layer_norm_eps UpperCAmelCase_ = use_query_residual # masked language modeling attributes UpperCAmelCase_ = vocab_size UpperCAmelCase_ = max_position_embeddings # image classification attributes UpperCAmelCase_ = image_size # flow attributes UpperCAmelCase_ = train_size # multimodal autoencoding attributes UpperCAmelCase_ = num_frames UpperCAmelCase_ = audio_samples_per_frame UpperCAmelCase_ = samples_per_patch UpperCAmelCase_ = output_shape class __A ( UpperCamelCase__ ): @property def _lowercase (self : Dict ): if self.task == "multiple-choice": UpperCAmelCase_ = {0: "batch", 1: "choice", 2: "sequence"} else: UpperCAmelCase_ = {0: "batch", 1: "sequence"} return OrderedDict( [ ("inputs", dynamic_axis), ("attention_mask", dynamic_axis), ] ) @property def _lowercase (self : Optional[Any] ): return 1E-4 def _lowercase (self : Union[str, Any] , __a : Union["PreTrainedTokenizerBase", "FeatureExtractionMixin"] , __a : int = -1 , __a : int = -1 , __a : int = -1 , __a : bool = False , __a : Optional[TensorType] = None , __a : int = 3 , __a : int = 40 , __a : int = 40 , ): # copied from `transformers.onnx.config.OnnxConfig` and slightly altered/simplified if isinstance(__a , __a ): # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_batch , num_token_to_add=0 ) # If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX UpperCAmelCase_ = preprocessor.num_special_tokens_to_add(__a ) UpperCAmelCase_ = compute_effective_axis_dimension( __a , fixed_dimension=OnnxConfig.default_fixed_sequence , num_token_to_add=__a ) # Generate dummy inputs according to compute batch and sequence UpperCAmelCase_ = [" ".join(["a"] ) * seq_length] * batch_size UpperCAmelCase_ = dict(preprocessor(__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("input_ids" ) return inputs elif isinstance(__a , __a ) and preprocessor.model_input_names[0] == "pixel_values": # If dynamic axis (-1) we forward with a fixed dimension of 2 samples to avoid optimizations made by ONNX UpperCAmelCase_ = compute_effective_axis_dimension(__a , fixed_dimension=OnnxConfig.default_fixed_batch ) UpperCAmelCase_ = self._generate_dummy_images(__a , __a , __a , __a ) UpperCAmelCase_ = dict(preprocessor(images=__a , return_tensors=__a ) ) UpperCAmelCase_ = inputs.pop("pixel_values" ) return inputs else: raise ValueError( "Unable to generate dummy inputs for the model. Please provide a tokenizer or a preprocessor." )
78
'''simple docstring''' from typing import Callable, List, Optional, Union import PIL import torch from transformers import ( CLIPImageProcessor, CLIPSegForImageSegmentation, CLIPSegProcessor, CLIPTextModel, CLIPTokenizer, ) from diffusers import DiffusionPipeline from diffusers.configuration_utils import FrozenDict from diffusers.models import AutoencoderKL, UNetaDConditionModel from diffusers.pipelines.stable_diffusion import StableDiffusionInpaintPipeline from diffusers.pipelines.stable_diffusion.safety_checker import StableDiffusionSafetyChecker from diffusers.schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler from diffusers.utils import deprecate, is_accelerate_available, logging SCREAMING_SNAKE_CASE_: Optional[int] =logging.get_logger(__name__) # pylint: disable=invalid-name class __A ( UpperCamelCase__ ): def __init__(self : Any , __a : CLIPSegForImageSegmentation , __a : CLIPSegProcessor , __a : AutoencoderKL , __a : CLIPTextModel , __a : CLIPTokenizer , __a : UNetaDConditionModel , __a : Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler] , __a : StableDiffusionSafetyChecker , __a : CLIPImageProcessor , ): super().__init__() if hasattr(scheduler.config , "steps_offset" ) and scheduler.config.steps_offset != 1: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`""" f""" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure """ "to update the config accordingly as leaving `steps_offset` might led to incorrect results" " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub," " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`" " file" ) deprecate("steps_offset!=1" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = 1 UpperCAmelCase_ = FrozenDict(__a ) if hasattr(scheduler.config , "skip_prk_steps" ) and scheduler.config.skip_prk_steps is False: UpperCAmelCase_ = ( f"""The configuration file of this scheduler: {scheduler} has not set the configuration""" " `skip_prk_steps`. `skip_prk_steps` should be set to True in the configuration file. Please make" " sure to update the config accordingly as not setting `skip_prk_steps` in the config might lead to" " incorrect results in future versions. If you have downloaded this checkpoint from the Hugging Face" " Hub, it would be very nice if you could open a Pull request for the" " `scheduler/scheduler_config.json` file" ) deprecate("skip_prk_steps not set" , "1.0.0" , __a , standard_warn=__a ) UpperCAmelCase_ = dict(scheduler.config ) UpperCAmelCase_ = True UpperCAmelCase_ = FrozenDict(__a ) if safety_checker is None: logger.warning( f"""You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure""" " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered" " results in services or applications open to the public. Both the diffusers team and Hugging Face" " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling" " it only for use-cases that involve analyzing network behavior or auditing its results. For more" " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ." ) self.register_modules( segmentation_model=__a , segmentation_processor=__a , vae=__a , text_encoder=__a , tokenizer=__a , unet=__a , scheduler=__a , safety_checker=__a , feature_extractor=__a , ) def _lowercase (self : str , __a : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory UpperCAmelCase_ = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__a ) def _lowercase (self : int ): self.enable_attention_slicing(__a ) def _lowercase (self : Optional[Any] ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError("Please install accelerate via `pip install accelerate`" ) UpperCAmelCase_ = torch.device("cuda" ) for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae, self.safety_checker]: if cpu_offloaded_model is not None: cpu_offload(__a , __a ) @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def _lowercase (self : Optional[int] ): if self.device != torch.device("meta" ) or not hasattr(self.unet , "_hf_hook" ): return self.device for module in self.unet.modules(): if ( hasattr(__a , "_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() def __call__(self : Dict , __a : Union[str, List[str]] , __a : Union[torch.FloatTensor, PIL.Image.Image] , __a : str , __a : int = 512 , __a : int = 512 , __a : int = 50 , __a : float = 7.5 , __a : Optional[Union[str, List[str]]] = None , __a : Optional[int] = 1 , __a : float = 0.0 , __a : Optional[torch.Generator] = None , __a : Optional[torch.FloatTensor] = None , __a : Optional[str] = "pil" , __a : bool = True , __a : Optional[Callable[[int, int, torch.FloatTensor], None]] = None , __a : int = 1 , **__a : int , ): UpperCAmelCase_ = self.segmentation_processor( text=[text] , images=[image] , padding="max_length" , return_tensors="pt" ).to(self.device ) UpperCAmelCase_ = self.segmentation_model(**__a ) UpperCAmelCase_ = torch.sigmoid(outputs.logits ).cpu().detach().unsqueeze(-1 ).numpy() UpperCAmelCase_ = self.numpy_to_pil(__a )[0].resize(image.size ) # Run inpainting pipeline with the generated mask UpperCAmelCase_ = StableDiffusionInpaintPipeline( vae=self.vae , text_encoder=self.text_encoder , tokenizer=self.tokenizer , unet=self.unet , scheduler=self.scheduler , safety_checker=self.safety_checker , feature_extractor=self.feature_extractor , ) return inpainting_pipeline( prompt=__a , image=__a , mask_image=__a , height=__a , width=__a , num_inference_steps=__a , guidance_scale=__a , negative_prompt=__a , num_images_per_prompt=__a , eta=__a , generator=__a , latents=__a , output_type=__a , return_dict=__a , callback=__a , callback_steps=__a , )
78
1
'''simple docstring''' import itertools from dataclasses import dataclass from typing import Any, Callable, Dict, List, Optional, Union import pandas as pd import pyarrow as pa import datasets import datasets.config from datasets.features.features import require_storage_cast from datasets.table import table_cast from datasets.utils.py_utils import Literal SCREAMING_SNAKE_CASE_: Union[str, Any] =datasets.utils.logging.get_logger(__name__) SCREAMING_SNAKE_CASE_: Dict =['names', 'prefix'] SCREAMING_SNAKE_CASE_: Optional[int] =['warn_bad_lines', 'error_bad_lines', 'mangle_dupe_cols'] SCREAMING_SNAKE_CASE_: List[str] =['encoding_errors', 'on_bad_lines'] SCREAMING_SNAKE_CASE_: Any =['date_format'] @dataclass class __A ( datasets.BuilderConfig ): a__ : str = "," a__ : Optional[str] = None a__ : Optional[Union[int, List[int], str]] = "infer" a__ : Optional[List[str]] = None a__ : Optional[List[str]] = None a__ : Optional[Union[int, str, List[int], List[str]]] = None a__ : Optional[Union[List[int], List[str]]] = None a__ : Optional[str] = None a__ : bool = True a__ : Optional[Literal["c", "python", "pyarrow"]] = None a__ : Dict[Union[int, str], Callable[[Any], Any]] = None a__ : Optional[list] = None a__ : Optional[list] = None a__ : bool = False a__ : Optional[Union[int, List[int]]] = None a__ : Optional[int] = None a__ : Optional[Union[str, List[str]]] = None a__ : bool = True a__ : bool = True a__ : bool = False a__ : bool = True a__ : Optional[str] = None a__ : str = "." a__ : Optional[str] = None a__ : str = '"' a__ : int = 0 a__ : Optional[str] = None a__ : Optional[str] = None a__ : Optional[str] = None a__ : Optional[str] = None a__ : bool = True a__ : bool = True a__ : int = 0 a__ : bool = True a__ : bool = False a__ : Optional[str] = None a__ : int = 10_000 a__ : Optional[datasets.Features] = None a__ : Optional[str] = "strict" a__ : Literal["error", "warn", "skip"] = "error" a__ : Optional[str] = None def _lowercase (self : Tuple ): if self.delimiter is not None: UpperCAmelCase_ = self.delimiter if self.column_names is not None: UpperCAmelCase_ = self.column_names @property def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = { "sep": self.sep, "header": self.header, "names": self.names, "index_col": self.index_col, "usecols": self.usecols, "prefix": self.prefix, "mangle_dupe_cols": self.mangle_dupe_cols, "engine": self.engine, "converters": self.converters, "true_values": self.true_values, "false_values": self.false_values, "skipinitialspace": self.skipinitialspace, "skiprows": self.skiprows, "nrows": self.nrows, "na_values": self.na_values, "keep_default_na": self.keep_default_na, "na_filter": self.na_filter, "verbose": self.verbose, "skip_blank_lines": self.skip_blank_lines, "thousands": self.thousands, "decimal": self.decimal, "lineterminator": self.lineterminator, "quotechar": self.quotechar, "quoting": self.quoting, "escapechar": self.escapechar, "comment": self.comment, "encoding": self.encoding, "dialect": self.dialect, "error_bad_lines": self.error_bad_lines, "warn_bad_lines": self.warn_bad_lines, "skipfooter": self.skipfooter, "doublequote": self.doublequote, "memory_map": self.memory_map, "float_precision": self.float_precision, "chunksize": self.chunksize, "encoding_errors": self.encoding_errors, "on_bad_lines": self.on_bad_lines, "date_format": self.date_format, } # some kwargs must not be passed if they don't have a default value # some others are deprecated and we can also not pass them if they are the default value for pd_read_csv_parameter in _PANDAS_READ_CSV_NO_DEFAULT_PARAMETERS + _PANDAS_READ_CSV_DEPRECATED_PARAMETERS: if pd_read_csv_kwargs[pd_read_csv_parameter] == getattr(CsvConfig() , __a ): del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 2.0 new arguments if not (datasets.config.PANDAS_VERSION.major >= 2): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_2_0_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] # Remove 1.3 new arguments if not (datasets.config.PANDAS_VERSION.major >= 1 and datasets.config.PANDAS_VERSION.minor >= 3): for pd_read_csv_parameter in _PANDAS_READ_CSV_NEW_1_3_0_PARAMETERS: del pd_read_csv_kwargs[pd_read_csv_parameter] return pd_read_csv_kwargs class __A ( datasets.ArrowBasedBuilder ): a__ : int = CsvConfig def _lowercase (self : int ): return datasets.DatasetInfo(features=self.config.features ) def _lowercase (self : str , __a : Dict ): if not self.config.data_files: raise ValueError(f"""At least one data file must be specified, but got data_files={self.config.data_files}""" ) UpperCAmelCase_ = dl_manager.download_and_extract(self.config.data_files ) if isinstance(__a , (str, list, tuple) ): UpperCAmelCase_ = data_files if isinstance(__a , __a ): UpperCAmelCase_ = [files] UpperCAmelCase_ = [dl_manager.iter_files(__a ) for file in files] return [datasets.SplitGenerator(name=datasets.Split.TRAIN , gen_kwargs={"files": files} )] UpperCAmelCase_ = [] for split_name, files in data_files.items(): if isinstance(__a , __a ): UpperCAmelCase_ = [files] UpperCAmelCase_ = [dl_manager.iter_files(__a ) for file in files] splits.append(datasets.SplitGenerator(name=__a , gen_kwargs={"files": files} ) ) return splits def _lowercase (self : Tuple , __a : pa.Table ): if self.config.features is not None: UpperCAmelCase_ = self.config.features.arrow_schema if all(not require_storage_cast(__a ) for feature in self.config.features.values() ): # cheaper cast UpperCAmelCase_ = pa.Table.from_arrays([pa_table[field.name] for field in schema] , schema=__a ) else: # more expensive cast; allows str <-> int/float or str to Audio for example UpperCAmelCase_ = table_cast(__a , __a ) return pa_table def _lowercase (self : Tuple , __a : str ): UpperCAmelCase_ = self.config.features.arrow_schema if self.config.features else None # dtype allows reading an int column as str UpperCAmelCase_ = ( { name: dtype.to_pandas_dtype() if not require_storage_cast(__a ) else object for name, dtype, feature in zip(schema.names , schema.types , self.config.features.values() ) } if schema is not None else None ) for file_idx, file in enumerate(itertools.chain.from_iterable(__a ) ): UpperCAmelCase_ = pd.read_csv(__a , iterator=__a , dtype=__a , **self.config.pd_read_csv_kwargs ) try: for batch_idx, df in enumerate(__a ): UpperCAmelCase_ = pa.Table.from_pandas(__a ) # Uncomment for debugging (will print the Arrow table size and elements) # logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}") # logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows))) yield (file_idx, batch_idx), self._cast_table(__a ) except ValueError as e: logger.error(f"""Failed to read file '{file}' with error {type(__a )}: {e}""" ) raise
78
'''simple docstring''' def lowerCAmelCase_ ( snake_case_ : int ) -> bool: '''simple docstring''' if number < 0: raise ValueError("number must not be negative" ) return number & (number - 1) == 0 if __name__ == "__main__": import doctest doctest.testmod()
78
1