code
stringlengths
87
55.2k
code_codestyle
int64
0
349
style_context
stringlengths
135
49.1k
style_context_codestyle
int64
0
349
label
int64
0
1
import warnings from transformers import AutoTokenizer from transformers.utils import is_torch_available from transformers.utils.generic import ExplicitEnum from ...processing_utils import ProcessorMixin if is_torch_available(): import torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "char" snake_case_ = "bpe" snake_case_ = "wp" SCREAMING_SNAKE_CASE :Optional[int] = (DecodeType.CHARACTER, DecodeType.BPE, DecodeType.WORDPIECE) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = ["image_processor", "char_tokenizer"] snake_case_ = "ViTImageProcessor" snake_case_ = "MgpstrTokenizer" def __init__( self : Tuple ,A : Optional[Any]=None ,A : Optional[Any]=None ,**A : Optional[Any] ): __A = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." ,A ,) __A = kwargs.pop("feature_extractor" ) __A = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) __A = tokenizer __A = AutoTokenizer.from_pretrained("gpt2" ) __A = AutoTokenizer.from_pretrained("bert-base-uncased" ) super().__init__(A ,A ) def __call__( self : Optional[Any] ,A : Tuple=None ,A : List[str]=None ,A : Optional[Any]=None ,**A : Union[str, Any] ): if images is None and text is None: raise ValueError("You need to specify either an `images` or `text` input to process." ) if images is not None: __A = self.image_processor(A ,return_tensors=A ,**A ) if text is not None: __A = self.char_tokenizer(A ,return_tensors=A ,**A ) if text is None: return inputs elif images is None: return encodings else: __A = encodings["input_ids"] return inputs def UpperCamelCase_ ( self : Union[str, Any] ,A : Optional[Any] ): __A , __A , __A = sequences __A = char_preds.size(0 ) __A , __A = self._decode_helper(A ,"char" ) __A , __A = self._decode_helper(A ,"bpe" ) __A , __A = self._decode_helper(A ,"wp" ) __A = [] __A = [] for i in range(A ): __A = [char_scores[i], bpe_scores[i], wp_scores[i]] __A = [char_strs[i], bpe_strs[i], wp_strs[i]] __A = scores.index(max(A ) ) final_strs.append(strs[max_score_index] ) final_scores.append(scores[max_score_index] ) __A = {} __A = final_strs __A = final_scores __A = char_strs __A = bpe_strs __A = wp_strs return out def UpperCamelCase_ ( self : Tuple ,A : str ,A : Tuple ): if format == DecodeType.CHARACTER: __A = self.char_decode __A = 1 __A = "[s]" elif format == DecodeType.BPE: __A = self.bpe_decode __A = 2 __A = "#" elif format == DecodeType.WORDPIECE: __A = self.wp_decode __A = 1_02 __A = "[SEP]" else: raise ValueError(f'''Format {format} is not supported.''' ) __A , __A = [], [] __A = pred_logits.size(0 ) __A = pred_logits.size(1 ) __A , __A = pred_logits.topk(1 ,dim=-1 ,largest=A ,sorted=A ) __A = preds_index.view(-1 ,A )[:, 1:] __A = decoder(A ) __A , __A = torch.nn.functional.softmax(A ,dim=2 ).max(dim=2 ) __A = preds_max_prob[:, 1:] for index in range(A ): __A = preds_str[index].find(A ) __A = preds_str[index][:pred_eos] __A = preds_index[index].cpu().tolist() __A = pred_index.index(A ) if eos_token in pred_index else -1 __A = preds_max_prob[index][: pred_eos_index + 1] __A = pred_max_prob.cumprod(dim=0 )[-1] if pred_max_prob.nelement() != 0 else 0.0 dec_strs.append(A ) conf_scores.append(A ) return dec_strs, conf_scores def UpperCamelCase_ ( self : Tuple ,A : Optional[int] ): __A = [seq.replace(" " ,"" ) for seq in self.char_tokenizer.batch_decode(A )] return decode_strs def UpperCamelCase_ ( self : List[Any] ,A : Union[str, Any] ): return self.bpe_tokenizer.batch_decode(A ) def UpperCamelCase_ ( self : Tuple ,A : List[str] ): __A = [seq.replace(" " ,"" ) for seq in self.wp_tokenizer.batch_decode(A )] return decode_strs
15
def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = [0] * len(a_ ) __A = [] __A = [1] * len(a_ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(a_ ) ): if indegree[i] == 0: queue.append(a_ ) while queue: __A = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __A = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(a_ ) print(max(a_ ) ) # Adjacency list of Graph SCREAMING_SNAKE_CASE :List[Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
15
1
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 UpperCAmelCase ( a_ , a_=0.999 , a_="cosine" , ) -> Optional[Any]: """simple docstring""" if alpha_transform_type == "cosine": def alpha_bar_fn(a_ ): return math.cos((t + 0.008) / 1.008 * math.pi / 2 ) ** 2 elif alpha_transform_type == "exp": def alpha_bar_fn(a_ ): return math.exp(t * -12.0 ) else: raise ValueError(F'''Unsupported alpha_tranform_type: {alpha_transform_type}''' ) __A = [] for i in range(a_ ): __A = i / num_diffusion_timesteps __A = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar_fn(a_ ) / alpha_bar_fn(a_ ) , a_ ) ) return torch.tensor(a_ , dtype=torch.floataa ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = [e.name for e in KarrasDiffusionSchedulers] snake_case_ = 2 @register_to_config def __init__( self : Optional[Any] ,A : int = 10_00 ,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 : str = "linspace" ,A : int = 0 ,): if trained_betas is not None: __A = torch.tensor(A ,dtype=torch.floataa ) elif beta_schedule == "linear": __A = torch.linspace(A ,A ,A ,dtype=torch.floataa ) elif beta_schedule == "scaled_linear": # this schedule is very specific to the latent diffusion model. __A = ( torch.linspace(beta_start**0.5 ,beta_end**0.5 ,A ,dtype=torch.floataa ) ** 2 ) elif beta_schedule == "squaredcos_cap_v2": # Glide cosine schedule __A = betas_for_alpha_bar(A ) else: raise NotImplementedError(f'''{beta_schedule} does is not implemented for {self.__class__}''' ) __A = 1.0 - self.betas __A = torch.cumprod(self.alphas ,dim=0 ) # set all values self.set_timesteps(A ,A ,A ) def UpperCamelCase_ ( self : Dict ,A : List[str] ,A : List[str]=None ): if schedule_timesteps is None: __A = self.timesteps __A = (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: __A = 1 if len(A ) > 1 else 0 else: __A = timestep.cpu().item() if torch.is_tensor(A ) else timestep __A = self._index_counter[timestep_int] return indices[pos].item() @property def UpperCamelCase_ ( self : 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 UpperCamelCase_ ( self : Union[str, Any] ,A : torch.FloatTensor ,A : Union[float, torch.FloatTensor] ,): __A = self.index_for_timestep(A ) if self.state_in_first_order: __A = self.sigmas[step_index] else: __A = self.sigmas_interpol[step_index] __A = sample / ((sigma**2 + 1) ** 0.5) return sample def UpperCamelCase_ ( self : Optional[Any] ,A : int ,A : Union[str, torch.device] = None ,A : Optional[int] = None ,): __A = num_inference_steps __A = 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": __A = np.linspace(0 ,num_train_timesteps - 1 ,A ,dtype=A )[::-1].copy() elif self.config.timestep_spacing == "leading": __A = 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 __A = (np.arange(0 ,A ) * step_ratio).round()[::-1].copy().astype(A ) timesteps += self.config.steps_offset elif self.config.timestep_spacing == "trailing": __A = 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 __A = (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\'.''' ) __A = np.array(((1 - self.alphas_cumprod) / self.alphas_cumprod) ** 0.5 ) __A = torch.from_numpy(np.log(A ) ).to(A ) __A = np.interp(A ,np.arange(0 ,len(A ) ) ,A ) __A = np.concatenate([sigmas, [0.0]] ).astype(np.floataa ) __A = torch.from_numpy(A ).to(device=A ) # interpolate sigmas __A = sigmas.log().lerp(sigmas.roll(1 ).log() ,0.5 ).exp() __A = torch.cat([sigmas[:1], sigmas[1:].repeat_interleave(2 ), sigmas[-1:]] ) __A = torch.cat( [sigmas_interpol[:1], sigmas_interpol[1:].repeat_interleave(2 ), sigmas_interpol[-1:]] ) if str(A ).startswith("mps" ): # mps does not support float64 __A = torch.from_numpy(A ).to(A ,dtype=torch.floataa ) else: __A = torch.from_numpy(A ).to(A ) # interpolate timesteps __A = self.sigma_to_t(A ).to(A ,dtype=timesteps.dtype ) __A = torch.stack((timesteps_interpol[1:-1, None], timesteps[1:, None]) ,dim=-1 ).flatten() __A = torch.cat([timesteps[:1], interleaved_timesteps] ) __A = None # for exp beta schedules, such as the one for `pipeline_shap_e.py` # we need an index counter __A = defaultdict(A ) def UpperCamelCase_ ( self : Any ,A : Any ): # get log sigma __A = sigma.log() # get distribution __A = log_sigma - self.log_sigmas[:, None] # get sigmas range __A = dists.ge(0 ).cumsum(dim=0 ).argmax(dim=0 ).clamp(max=self.log_sigmas.shape[0] - 2 ) __A = low_idx + 1 __A = self.log_sigmas[low_idx] __A = self.log_sigmas[high_idx] # interpolate sigmas __A = (low - log_sigma) / (low - high) __A = w.clamp(0 ,1 ) # transform interpolation to time range __A = (1 - w) * low_idx + w * high_idx __A = t.view(sigma.shape ) return t @property def UpperCamelCase_ ( self : Dict ): return self.sample is None def UpperCamelCase_ ( self : Optional[Any] ,A : Union[torch.FloatTensor, np.ndarray] ,A : Union[float, torch.FloatTensor] ,A : Union[torch.FloatTensor, np.ndarray] ,A : bool = True ,): __A = self.index_for_timestep(A ) # advance index counter by 1 __A = timestep.cpu().item() if torch.is_tensor(A ) else timestep self._index_counter[timestep_int] += 1 if self.state_in_first_order: __A = self.sigmas[step_index] __A = self.sigmas_interpol[step_index + 1] __A = self.sigmas[step_index + 1] else: # 2nd order / KDPM2's method __A = self.sigmas[step_index - 1] __A = self.sigmas_interpol[step_index] __A = 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 __A = 0 __A = 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": __A = sigma_hat if self.state_in_first_order else sigma_interpol __A = sample - sigma_input * model_output elif self.config.prediction_type == "v_prediction": __A = sigma_hat if self.state_in_first_order else sigma_interpol __A = model_output * (-sigma_input / (sigma_input**2 + 1) ** 0.5) + ( sample / (sigma_input**2 + 1) ) elif self.config.prediction_type == "sample": raise NotImplementedError("prediction_type not implemented yet: sample" ) else: raise ValueError( f'''prediction_type given as {self.config.prediction_type} must be one of `epsilon`, or `v_prediction`''' ) if self.state_in_first_order: # 2. Convert to an ODE derivative for 1st order __A = (sample - pred_original_sample) / sigma_hat # 3. delta timestep __A = sigma_interpol - sigma_hat # store for 2nd order step __A = sample else: # DPM-Solver-2 # 2. Convert to an ODE derivative for 2nd order __A = (sample - pred_original_sample) / sigma_interpol # 3. delta timestep __A = sigma_next - sigma_hat __A = self.sample __A = None __A = sample + derivative * dt if not return_dict: return (prev_sample,) return SchedulerOutput(prev_sample=A ) def UpperCamelCase_ ( 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 __A = 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 __A = self.timesteps.to(original_samples.device ,dtype=torch.floataa ) __A = timesteps.to(original_samples.device ,dtype=torch.floataa ) else: __A = self.timesteps.to(original_samples.device ) __A = timesteps.to(original_samples.device ) __A = [self.index_for_timestep(A ,A ) for t in timesteps] __A = sigmas[step_indices].flatten() while len(sigma.shape ) < len(original_samples.shape ): __A = sigma.unsqueeze(-1 ) __A = original_samples + noise * sigma return noisy_samples def __len__( self : str ): return self.config.num_train_timesteps
15
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __A = key.replace("heads.cmd.mim_head.cls.predictions" , "mmm_image_head" ) __A = key.replace("heads.cmd.mlm_head.cls.predictions" , "mmm_text_head" ) __A = key.replace("heads.cmd.itm_head.cls" , "itm_head" ) __A = key.replace("heads.cmd.itm_head.pooler" , "itm_head.pooler" ) __A = key.replace("heads.cmd.clip_head.logit_scale" , "flava.logit_scale" ) __A = key.replace("heads.fairseq_mlm.cls.predictions" , "mlm_head" ) __A = key.replace("heads.imagenet.mim_head.cls.predictions" , "mim_head" ) __A = key.replace("mm_text_projection" , "flava.text_to_mm_projection" ) __A = key.replace("mm_image_projection" , "flava.image_to_mm_projection" ) __A = key.replace("image_encoder.module" , "flava.image_model" ) __A = key.replace("text_encoder.module" , "flava.text_model" ) __A = key.replace("mm_encoder.module.encoder.cls_token" , "flava.multimodal_model.cls_token" ) __A = key.replace("mm_encoder.module" , "flava.multimodal_model" ) __A = key.replace("text_projection" , "flava.text_projection" ) __A = key.replace("image_projection" , "flava.image_projection" ) __A = value.float() for key, value in codebook_state_dict.items(): __A = value return upgrade @torch.no_grad() def UpperCAmelCase ( a_ , a_ , a_ , a_=None ) -> Tuple: """simple docstring""" if config_path is not None: __A = FlavaConfig.from_pretrained(a_ ) else: __A = FlavaConfig() __A = FlavaForPreTraining(a_ ).eval() __A = convert_dalle_checkpoint(a_ , a_ , save_checkpoint=a_ ) if os.path.exists(a_ ): __A = torch.load(a_ , map_location="cpu" ) else: __A = torch.hub.load_state_dict_from_url(a_ , map_location="cpu" ) __A = upgrade_state_dict(a_ , a_ ) hf_model.load_state_dict(a_ ) __A = hf_model.state_dict() __A = count_parameters(a_ ) __A = count_parameters(a_ ) + count_parameters(a_ ) assert torch.allclose(a_ , a_ , atol=1E-3 ) hf_model.save_pretrained(a_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
15
1
def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" _enforce_args(a_ , a_ ) if n == 0: return 0 __A = float("-inf" ) for i in range(1 , n + 1 ): __A = max( a_ , prices[i - 1] + naive_cut_rod_recursive(n - i , a_ ) ) return max_revue def UpperCAmelCase ( a_ , a_ ) -> Union[str, Any]: """simple docstring""" _enforce_args(a_ , a_ ) __A = [float("-inf" ) for _ in range(n + 1 )] return _top_down_cut_rod_recursive(a_ , a_ , a_ ) def UpperCAmelCase ( a_ , a_ , a_ ) -> str: """simple docstring""" if max_rev[n] >= 0: return max_rev[n] elif n == 0: return 0 else: __A = float("-inf" ) for i in range(1 , n + 1 ): __A = max( a_ , prices[i - 1] + _top_down_cut_rod_recursive(n - i , a_ , a_ ) , ) __A = max_revenue return max_rev[n] def UpperCAmelCase ( a_ , a_ ) -> List[str]: """simple docstring""" _enforce_args(a_ , a_ ) # length(max_rev) = n + 1, to accommodate for the revenue obtainable from a rod of # length 0. __A = [float("-inf" ) for _ in range(n + 1 )] __A = 0 for i in range(1 , n + 1 ): __A = max_rev[i] for j in range(1 , i + 1 ): __A = max(a_ , prices[j - 1] + max_rev[i - j] ) __A = max_revenue_i return max_rev[n] def UpperCAmelCase ( a_ , a_ ) -> int: """simple docstring""" if n < 0: __A = F'''n must be greater than or equal to 0. Got n = {n}''' raise ValueError(a_ ) if n > len(a_ ): __A = ( "Each integral piece of rod must have a corresponding price. " F'''Got n = {n} but length of prices = {len(a_ )}''' ) raise ValueError(a_ ) def UpperCAmelCase ( ) -> List[str]: """simple docstring""" __A = [6, 1_0, 1_2, 1_5, 2_0, 2_3] __A = len(a_ ) # the best revenue comes from cutting the rod into 6 pieces, each # of length 1 resulting in a revenue of 6 * 6 = 36. __A = 3_6 __A = top_down_cut_rod(a_ , a_ ) __A = bottom_up_cut_rod(a_ , a_ ) __A = naive_cut_rod_recursive(a_ , a_ ) assert expected_max_revenue == max_rev_top_down assert max_rev_top_down == max_rev_bottom_up assert max_rev_bottom_up == max_rev_naive if __name__ == "__main__": main()
15
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Optional[int] = {'vocab_file': 'sentencepiece.bpe.model'} SCREAMING_SNAKE_CASE :Tuple = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', } } SCREAMING_SNAKE_CASE :List[Any] = { 'camembert-base': 512, } SCREAMING_SNAKE_CASE :List[str] = '▁' class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[Any] ,A : List[str] ,A : List[Any]="<s>" ,A : Tuple="</s>" ,A : Any="</s>" ,A : Optional[Any]="<s>" ,A : Tuple="<unk>" ,A : str="<pad>" ,A : int="<mask>" ,A : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] ,A : Optional[Dict[str, Any]] = None ,**A : Optional[Any] ,): # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,sep_token=A ,cls_token=A ,pad_token=A ,mask_token=A ,additional_special_tokens=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A ) ) __A = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> __A = {"<s>NOTUSED": 0, "<pad>": 1, "</s>NOTUSED": 2, "<unk>": 3} __A = len(self.fairseq_tokens_to_ids ) __A = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) __A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self : int ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : Dict ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Union[str, Any] ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self : Dict ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def UpperCamelCase_ ( self : int ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Dict ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(A ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : Tuple ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase_ ( self : Optional[Any] ,A : Dict ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def __getstate__( self : Dict ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Union[str, Any] ,A : Any ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,)
15
1
def UpperCAmelCase ( a_ = 1_0_0_0_0_0_0 ) -> int: """simple docstring""" __A = [i - 1 for i in range(limit + 1 )] for i in range(2 , limit + 1 ): if phi[i] == i - 1: for j in range(2 * i , limit + 1 , a_ ): phi[j] -= phi[j] // i return sum(phi[2 : limit + 1] ) if __name__ == "__main__": print(solution())
15
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return [tuple(a_ )] __A = [] def generate(a_ , a_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , a_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even __A , __A = arr[k - 1], arr[i] else: # k is odd __A , __A = arr[k - 1], arr[0] generate(k - 1 , a_ ) generate(len(a_ ) , a_ ) return res if __name__ == "__main__": SCREAMING_SNAKE_CASE :int = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :Dict = [int(item) for item in user_input.split(',')] print(heaps(arr))
15
1
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 PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Dict = '▁' SCREAMING_SNAKE_CASE :Union[str, Any] = { 'vocab_file': 'vocab.json', 'spm_file': 'sentencepiece.bpe.model', } SCREAMING_SNAKE_CASE :Optional[int] = { 'vocab_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/vocab.json' ), }, 'spm_file': { 'facebook/s2t-small-librispeech-asr': ( 'https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/sentencepiece.bpe.model' ) }, } SCREAMING_SNAKE_CASE :Optional[Any] = { 'facebook/s2t-small-librispeech-asr': 1024, } SCREAMING_SNAKE_CASE :Optional[Any] = ['pt', 'fr', 'ru', 'nl', 'ro', 'it', 'es', 'de'] SCREAMING_SNAKE_CASE :Union[str, Any] = {'mustc': MUSTC_LANGS} class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = MAX_MODEL_INPUT_SIZES snake_case_ = ["input_ids", "attention_mask"] snake_case_ = [] def __init__( self : Optional[Any] ,A : List[str] ,A : str ,A : Tuple="<s>" ,A : Dict="</s>" ,A : List[str]="<pad>" ,A : Tuple="<unk>" ,A : Dict=False ,A : Tuple=False ,A : str=None ,A : List[str]=None ,A : Optional[Dict[str, Any]] = None ,**A : str ,): __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,do_upper_case=A ,do_lower_case=A ,tgt_lang=A ,lang_codes=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = do_upper_case __A = do_lower_case __A = load_json(A ) __A = {v: k for k, v in self.encoder.items()} __A = spm_file __A = load_spm(A ,self.sp_model_kwargs ) if lang_codes is not None: __A = lang_codes __A = LANGUAGES[lang_codes] __A = [f'''<lang:{lang}>''' for lang in self.langs] __A = {lang: self.sp_model.PieceToId(f'''<lang:{lang}>''' ) for lang in self.langs} __A = self.lang_tokens __A = tgt_lang if tgt_lang is not None else self.langs[0] self.set_tgt_lang_special_tokens(self._tgt_lang ) else: __A = {} @property def UpperCamelCase_ ( self : Union[str, Any] ): return len(self.encoder ) @property def UpperCamelCase_ ( self : Union[str, Any] ): return self._tgt_lang @tgt_lang.setter def UpperCamelCase_ ( self : Union[str, Any] ,A : Union[str, Any] ): __A = new_tgt_lang self.set_tgt_lang_special_tokens(A ) def UpperCamelCase_ ( self : Optional[int] ,A : str ): __A = self.lang_code_to_id[tgt_lang] __A = [lang_code_id] def UpperCamelCase_ ( self : str ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : Optional[int] ,A : Optional[int] ): return self.encoder.get(A ,self.encoder[self.unk_token] ) def UpperCamelCase_ ( self : str ,A : int ): return self.decoder.get(A ,self.unk_token ) def UpperCamelCase_ ( self : Union[str, Any] ,A : List[str] ): __A = [] __A = "" for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: __A = self.sp_model.decode(A ) out_string += (decoded.upper() if self.do_upper_case else decoded) + token + " " __A = [] else: current_sub_tokens.append(A ) __A = self.sp_model.decode(A ) out_string += decoded.upper() if self.do_upper_case else decoded return out_string.strip() def UpperCamelCase_ ( self : List[str] ,A : List[str] ,A : Tuple=None ): if token_ids_a is None: return self.prefix_tokens + token_ids_a + [self.eos_token_id] # 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.eos_token_id] def UpperCamelCase_ ( self : Tuple ,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 ) __A = [1] * len(self.prefix_tokens ) __A = [1] 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 UpperCamelCase_ ( self : Optional[int] ): __A = self.encoder.copy() vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Tuple ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Union[str, Any] ,A : Dict ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = load_spm(self.spm_file ,self.sp_model_kwargs ) def UpperCamelCase_ ( self : Any ,A : str ,A : Optional[str] = None ): __A = Path(A ) assert save_dir.is_dir(), f'''{save_directory} should be a directory''' __A = save_dir / ( (filename_prefix + "-" if filename_prefix else "") + self.vocab_files_names["vocab_file"] ) __A = 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: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (str(A ), str(A )) def UpperCAmelCase ( a_ , a_ ) -> sentencepiece.SentencePieceProcessor: """simple docstring""" __A = sentencepiece.SentencePieceProcessor(**a_ ) spm.Load(str(a_ ) ) return spm def UpperCAmelCase ( a_ ) -> Union[Dict, List]: """simple docstring""" with open(a_ , "r" ) as f: return json.load(a_ ) def UpperCAmelCase ( a_ , a_ ) -> None: """simple docstring""" with open(a_ , "w" ) as f: json.dump(a_ , a_ , indent=2 )
15
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return lst __A = 1 while i < len(a_ ): if lst[i - 1] <= lst[i]: i += 1 else: __A , __A = lst[i], lst[i - 1] i -= 1 if i == 0: __A = 1 return lst if __name__ == "__main__": SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :List[Any] = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
15
1
class UpperCAmelCase : '''simple docstring''' def __init__( self : int ,A : int ): __A = n __A = [None] * self.n __A = 0 # index of the first element __A = 0 __A = 0 def __len__( self : Tuple ): return self.size def UpperCamelCase_ ( self : int ): return self.size == 0 def UpperCamelCase_ ( self : str ): return False if self.is_empty() else self.array[self.front] def UpperCamelCase_ ( self : Union[str, Any] ,A : Dict ): if self.size >= self.n: raise Exception("QUEUE IS FULL" ) __A = data __A = (self.rear + 1) % self.n self.size += 1 return self def UpperCamelCase_ ( self : Union[str, Any] ): if self.size == 0: raise Exception("UNDERFLOW" ) __A = self.array[self.front] __A = None __A = (self.front + 1) % self.n self.size -= 1 return temp
15
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 snake_case_ = 42 snake_case_ = None class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 2 @register_to_config def __init__( self : str ,A : float = 0.02 ,A : float = 1_00 ,A : float = 1.0_07 ,A : float = 80 ,A : float = 0.05 ,A : float = 50 ,): # standard deviation of the initial noise distribution __A = sigma_max # setable values __A = None __A = None __A = None # sigma(t_i) def UpperCamelCase_ ( self : str ,A : torch.FloatTensor ,A : Optional[int] = None ): return sample def UpperCamelCase_ ( self : Dict ,A : int ,A : Union[str, torch.device] = None ): __A = num_inference_steps __A = np.arange(0 ,self.num_inference_steps )[::-1].copy() __A = torch.from_numpy(A ).to(A ) __A = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __A = torch.tensor(A ,dtype=torch.floataa ,device=A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : torch.FloatTensor ,A : float ,A : Optional[torch.Generator] = None ): if self.config.s_min <= sigma <= self.config.s_max: __A = min(self.config.s_churn / self.num_inference_steps ,2**0.5 - 1 ) else: __A = 0 # sample eps ~ N(0, S_noise^2 * I) __A = self.config.s_noise * randn_tensor(sample.shape ,generator=A ).to(sample.device ) __A = sigma + gamma * sigma __A = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase_ ( self : Dict ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_hat + sigma_hat * model_output __A = (sample_hat - pred_original_sample) / sigma_hat __A = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : Optional[int] ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_prev + sigma_prev * model_output __A = (sample_prev - pred_original_sample) / sigma_prev __A = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : List[Any] ,A : Dict ,A : List[str] ,A : str ): raise NotImplementedError()
15
1
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel SCREAMING_SNAKE_CASE :Union[str, Any] = False SCREAMING_SNAKE_CASE :Any = True SCREAMING_SNAKE_CASE :Tuple = False if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE :Union[str, Any] = parser.parse_args() SCREAMING_SNAKE_CASE :Dict = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } SCREAMING_SNAKE_CASE :Optional[int] = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } SCREAMING_SNAKE_CASE :int = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: SCREAMING_SNAKE_CASE :Dict = reader.read() SCREAMING_SNAKE_CASE :List[str] = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): SCREAMING_SNAKE_CASE :Optional[int] = UNetaDModel(**config) else: SCREAMING_SNAKE_CASE :Optional[Any] = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel SCREAMING_SNAKE_CASE :List[str] = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) SCREAMING_SNAKE_CASE :List[str] = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: SCREAMING_SNAKE_CASE :Optional[Any] = config[key] del config[key] SCREAMING_SNAKE_CASE :Optional[Any] = [k.replace('UNetRes', '') for k in config['down_block_types']] SCREAMING_SNAKE_CASE :List[Any] = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: SCREAMING_SNAKE_CASE :Tuple = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) SCREAMING_SNAKE_CASE :Any = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue SCREAMING_SNAKE_CASE :List[str] = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: SCREAMING_SNAKE_CASE :List[Any] = param_value SCREAMING_SNAKE_CASE :str = True if not has_changed: SCREAMING_SNAKE_CASE :List[str] = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
15
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version SCREAMING_SNAKE_CASE :Union[str, Any] = get_logger(__name__) class UpperCAmelCase : '''simple docstring''' snake_case_ = "dummy_data" snake_case_ = "datasets" snake_case_ = False def __init__( self : Optional[int] ,A : str ,A : str ,A : Union[Version, str] ,A : Optional[str] = None ,A : bool = False ,A : bool = True ,A : Optional[List[Callable]] = None ,): __A = 0 __A = dataset_name __A = cache_dir __A = use_local_dummy_data __A = config # download_callbacks take a single url as input __A = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __A = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __A = str(A ) # to be downloaded __A = None __A = None @property def UpperCamelCase_ ( self : Union[str, Any] ): if self._dummy_file is None: __A = self.download_dummy_data() return self._dummy_file @property def UpperCamelCase_ ( self : Optional[Any] ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" ,self.config.name ,self.version_name ) # structure is dummy / version_name return os.path.join("dummy" ,self.version_name ) @property def UpperCamelCase_ ( self : List[Any] ): return os.path.join(self.dummy_data_folder ,"dummy_data.zip" ) def UpperCamelCase_ ( self : Tuple ): __A = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __A = cached_path( A ,cache_dir=self.cache_dir ,extract_compressed_file=A ,force_extract=A ) return os.path.join(A ,self.dummy_file_name ) @property def UpperCamelCase_ ( self : str ): return os.path.join(self.datasets_scripts_dir ,self.dataset_name ,self.dummy_zip_file ) @property def UpperCamelCase_ ( self : Any ): if self._bucket_url is None: __A = hf_github_url(self.dataset_name ,self.dummy_zip_file.replace(os.sep ,"/" ) ) return self._bucket_url @property def UpperCamelCase_ ( self : Tuple ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep ,"/" ).split("/" )[:-1] ) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,*A : Dict ): if self.load_existing_dummy_data: # dummy data is downloaded and tested __A = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __A = self.dummy_file_name # special case when data_url is a dict if isinstance(A ,A ): return self.create_dummy_data_dict(A ,A ) elif isinstance(A ,(list, tuple) ): return self.create_dummy_data_list(A ,A ) else: return self.create_dummy_data_single(A ,A ) def UpperCamelCase_ ( self : str ,A : List[Any] ,*A : List[Any] ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : List[str] ,A : List[str] ,A : Tuple ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : Any ,A : Any ,*A : Optional[Any] ,**A : List[str] ): return path def UpperCamelCase_ ( self : str ): return {} def UpperCamelCase_ ( self : int ,A : int ,A : Tuple ): __A = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A ,A ): for single_url in single_urls: download_callback(A ) else: __A = single_urls download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A ,A ): __A = [os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) for x in single_urls] else: __A = single_urls __A = os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) __A = value # make sure that values are unique if all(isinstance(A ,A ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __A = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,A : str ): __A = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __A = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" ,A ) ) for url in data_url ) __A = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __A = [data_url[0]] * len(A ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(A ) return dummy_data_list def UpperCamelCase_ ( self : str ,A : List[Any] ,A : Optional[Any] ): for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(A ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : Dict ): pass def UpperCamelCase_ ( self : Optional[Any] ,A : List[Any] ): def _iter_archive_members(A : Optional[Any] ): # this preserves the order of the members inside the ZIP archive __A = Path(self.dummy_file ).parent __A = path.relative_to(A ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __A = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A ) __A = Path(A ) __A = _iter_archive_members(A ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(A ).as_posix(), file_path.open("rb" ) def UpperCamelCase_ ( self : List[Any] ,A : Any ): if not isinstance(A ,A ): __A = [paths] for path in paths: if os.path.isfile(A ): if os.path.basename(A ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(A ): if os.path.basename(A ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(A ): if filename.startswith((".", "__") ): continue yield os.path.join(A ,A )
15
1
import numpy as np import pandas as pd from sklearn.preprocessing import Normalizer from sklearn.svm import SVR from statsmodels.tsa.statespace.sarimax import SARIMAX def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ ) -> float: """simple docstring""" __A = np.array([[1, item, train_mtch[i]] for i, item in enumerate(a_ )] ) __A = np.array(a_ ) __A = np.dot(np.dot(np.linalg.inv(np.dot(x.transpose() , a_ ) ) , x.transpose() ) , a_ ) return abs(beta[0] + test_dt[0] * beta[1] + test_mtch[0] + beta[2] ) def UpperCAmelCase ( a_ , a_ , a_ ) -> float: """simple docstring""" __A = (1, 2, 1) __A = (1, 1, 0, 7) __A = SARIMAX( a_ , exog=a_ , order=a_ , seasonal_order=a_ ) __A = model.fit(disp=a_ , maxiter=6_0_0 , method="nm" ) __A = model_fit.predict(1 , len(a_ ) , exog=[test_match] ) return result[0] def UpperCAmelCase ( a_ , a_ , a_ ) -> float: """simple docstring""" __A = SVR(kernel="rbf" , C=1 , gamma=0.1 , epsilon=0.1 ) regressor.fit(a_ , a_ ) __A = regressor.predict(a_ ) return y_pred[0] def UpperCAmelCase ( a_ ) -> float: """simple docstring""" train_user.sort() __A = np.percentile(a_ , 2_5 ) __A = np.percentile(a_ , 7_5 ) __A = qa - qa __A = qa - (iqr * 0.1) return low_lim def UpperCAmelCase ( a_ , a_ ) -> bool: """simple docstring""" __A = 0 __A = 0 for i in list_vote: if i > actual_result: __A = not_safe + 1 else: if abs(abs(a_ ) - abs(a_ ) ) <= 0.1: safe += 1 else: not_safe += 1 return safe > not_safe if __name__ == "__main__": # data_input_df = pd.read_csv("ex_data.csv", header=None) SCREAMING_SNAKE_CASE :List[str] = [[1_8231, 0.0, 1], [2_2621, 1.0, 2], [1_5675, 0.0, 3], [2_3583, 1.0, 4]] SCREAMING_SNAKE_CASE :Optional[int] = pd.DataFrame( data_input, columns=['total_user', 'total_even', 'days'] ) SCREAMING_SNAKE_CASE :Union[str, Any] = Normalizer().fit_transform(data_input_df.values) # split data SCREAMING_SNAKE_CASE :int = normalize_df[:, 2].tolist() SCREAMING_SNAKE_CASE :List[str] = normalize_df[:, 0].tolist() SCREAMING_SNAKE_CASE :List[Any] = normalize_df[:, 1].tolist() # for svr (input variable = total date and total match) SCREAMING_SNAKE_CASE :Dict = normalize_df[:, [1, 2]].tolist() SCREAMING_SNAKE_CASE :str = x[: len(x) - 1] SCREAMING_SNAKE_CASE :Any = x[len(x) - 1 :] # for linear regression & sarimax SCREAMING_SNAKE_CASE :List[Any] = total_date[: len(total_date) - 1] SCREAMING_SNAKE_CASE :Tuple = total_user[: len(total_user) - 1] SCREAMING_SNAKE_CASE :Tuple = total_match[: len(total_match) - 1] SCREAMING_SNAKE_CASE :int = total_date[len(total_date) - 1 :] SCREAMING_SNAKE_CASE :Tuple = total_user[len(total_user) - 1 :] SCREAMING_SNAKE_CASE :int = total_match[len(total_match) - 1 :] # voting system with forecasting SCREAMING_SNAKE_CASE :str = [ linear_regression_prediction( trn_date, trn_user, trn_match, tst_date, tst_match ), sarimax_predictor(trn_user, trn_match, tst_match), support_vector_regressor(x_train, x_test, trn_user), ] # check the safety of today's data SCREAMING_SNAKE_CASE :Dict = '' if data_safety_checker(res_vote, tst_user) else 'not ' print('Today\'s data is {not_str}safe.')
15
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE :List[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :List[str] = ['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 :Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
15
1
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml SCREAMING_SNAKE_CASE :Optional[int] = NewType('DataClass', Any) SCREAMING_SNAKE_CASE :int = NewType('DataClassType', Any) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" if isinstance(a_ , a_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def UpperCAmelCase ( a_ ) -> Callable[[str], Any]: """simple docstring""" __A = {str(a_ ): choice for choice in choices} return lambda a_ : str_to_choice.get(a_ , a_ ) def UpperCAmelCase ( *, a_ = None , a_ = None , a_ = dataclasses.MISSING , a_ = dataclasses.MISSING , a_ = None , **a_ , ) -> dataclasses.Field: """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls __A = {} if aliases is not None: __A = aliases if help is not None: __A = help return dataclasses.field(metadata=a_ , default=a_ , default_factory=a_ , **a_ ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 def __init__( self : Union[str, Any] ,A : Union[DataClassType, Iterable[DataClassType]] ,**A : List[Any] ): # To make the default appear when using --help if "formatter_class" not in kwargs: __A = ArgumentDefaultsHelpFormatter super().__init__(**A ) if dataclasses.is_dataclass(A ): __A = [dataclass_types] __A = list(A ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A ) @staticmethod def UpperCamelCase_ ( A : ArgumentParser ,A : dataclasses.Field ): __A = f'''--{field.name}''' __A = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type ,A ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) __A = kwargs.pop("aliases" ,[] ) if isinstance(A ,A ): __A = [aliases] __A = getattr(field.type ,"__origin__" ,field.type ) if origin_type is Union or (hasattr(A ,"UnionType" ) and isinstance(A ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." f''' Problem encountered in field \'{field.name}\'.''' ) if type(A ) not in field.type.__args__: # filter `str` in Union __A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] __A = getattr(field.type ,"__origin__" ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) __A = ( field.type.__args__[0] if isinstance(A ,field.type.__args__[1] ) else field.type.__args__[1] ) __A = getattr(field.type ,"__origin__" ,field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) __A = {} if origin_type is Literal or (isinstance(field.type ,A ) and issubclass(field.type ,A )): if origin_type is Literal: __A = field.type.__args__ else: __A = [x.value for x in field.type] __A = make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: __A = field.default else: __A = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument __A = copy(A ) # Hack because type=bool in argparse does not behave as we want. __A = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. __A = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way __A = default # This tells argparse we accept 0 or 1 value after --field_name __A = "?" # This is the value that will get picked if we do --field_name (without value) __A = True elif isclass(A ) and issubclass(A ,A ): __A = field.type.__args__[0] __A = "+" if field.default_factory is not dataclasses.MISSING: __A = field.default_factory() elif field.default is dataclasses.MISSING: __A = True else: __A = field.type if field.default is not dataclasses.MISSING: __A = field.default elif field.default_factory is not dataclasses.MISSING: __A = field.default_factory() else: __A = True parser.add_argument(A ,*A ,**A ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): __A = False parser.add_argument(f'''--no_{field.name}''' ,action="store_false" ,dest=field.name ,**A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : DataClassType ): if hasattr(A ,"_argument_group_name" ): __A = self.add_argument_group(dtype._argument_group_name ) else: __A = self try: __A = get_type_hints(A ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(A ): __A = ".".join(map(A ,sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(A ): if not field.init: continue __A = type_hints[field.name] self._parse_dataclass_field(A ,A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : List[Any]=None ,A : List[Any]=False ,A : Optional[Any]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=None ,): if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): __A = [] if args_filename: args_files.append(Path(A ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values __A = ArgumentParser() args_file_parser.add_argument(A ,type=A ,action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) __A , __A = args_file_parser.parse_known_args(args=A ) __A = vars(A ).get(args_file_flag.lstrip("-" ) ,A ) if cmd_args_file_paths: args_files.extend([Path(A ) for p in cmd_args_file_paths] ) __A = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last __A = file_args + args if args is not None else file_args + sys.argv[1:] __A , __A = self.parse_known_args(args=A ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in vars(A ).items() if k in keys} for k in keys: delattr(A ,A ) __A = dtype(**A ) outputs.append(A ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def UpperCamelCase_ ( self : Dict ,A : Dict[str, Any] ,A : bool = False ): __A = set(args.keys() ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) __A = dtype(**A ) outputs.append(A ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(A )}''' ) return tuple(A ) def UpperCamelCase_ ( self : List[str] ,A : str ,A : bool = False ): with open(Path(A ) ,encoding="utf-8" ) as open_json_file: __A = json.loads(open_json_file.read() ) __A = self.parse_dict(A ,allow_extra_keys=A ) return tuple(A ) def UpperCamelCase_ ( self : int ,A : str ,A : bool = False ): __A = self.parse_dict(yaml.safe_load(Path(A ).read_text() ) ,allow_extra_keys=A ) return tuple(A )
15
from typing import Dict, Optional import numpy as np import datasets SCREAMING_SNAKE_CASE :List[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' SCREAMING_SNAKE_CASE :List[str] = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' SCREAMING_SNAKE_CASE :str = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Tuple: """simple docstring""" if label_map is not None: for old_id, new_id in label_map.items(): __A = new_id # turn into Numpy arrays __A = np.array(a_ ) __A = np.array(a_ ) if reduce_labels: __A = 2_5_5 __A = label - 1 __A = 2_5_5 __A = label != ignore_index __A = np.not_equal(a_ , a_ ) __A = pred_label[mask] __A = np.array(a_ )[mask] __A = pred_label[pred_label == label] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Union[str, Any]: """simple docstring""" __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(a_ , a_ ): __A , __A , __A , __A = intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = None , a_ = False , ) -> str: """simple docstring""" __A , __A , __A , __A = total_intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) # compute metrics __A = {} __A = total_area_intersect.sum() / total_area_label.sum() __A = total_area_intersect / total_area_union __A = total_area_intersect / total_area_label __A = np.nanmean(a_ ) __A = np.nanmean(a_ ) __A = all_acc __A = iou __A = acc if nan_to_num is not None: __A = {metric: np.nan_to_num(a_ , nan=a_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), } ) ,reference_urls=[ "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py" ] ,) def UpperCamelCase_ ( self : int ,A : Optional[Any] ,A : Optional[Any] ,A : int ,A : bool ,A : Optional[int] = None ,A : Optional[Dict[int, int]] = None ,A : bool = False ,): __A = mean_iou( results=A ,gt_seg_maps=A ,num_labels=A ,ignore_index=A ,nan_to_num=A ,label_map=A ,reduce_labels=A ,) return iou_result
15
1
# Author: OMKAR PATHAK, Nwachukwu Chidiebere # Use a Python dictionary to construct the graph. from __future__ import annotations from pprint import pformat from typing import Generic, TypeVar SCREAMING_SNAKE_CASE :Dict = TypeVar('T') class UpperCAmelCase ( Generic[T] ): '''simple docstring''' def __init__( self : List[str] ,A : bool = True ): __A = {} # dictionary of lists __A = directed def UpperCamelCase_ ( self : str ,A : T ,A : T ): if not self.directed: # For undirected graphs # if both source vertex and destination vertex are both present in the # adjacency list, add destination vertex to source vertex list of adjacent # vertices and add source vertex to destination vertex list of adjacent # vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(A ) self.adj_list[destination_vertex].append(A ) # if only source vertex is present in adjacency list, add destination vertex # to source vertex list of adjacent vertices, then create a new vertex with # destination vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(A ) __A = [source_vertex] # if only destination vertex is present in adjacency list, add source vertex # to destination vertex list of adjacent vertices, then create a new vertex # with source vertex as key and assign a list containing the source vertex # as it's first adjacent vertex. elif destination_vertex in self.adj_list: self.adj_list[destination_vertex].append(A ) __A = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and assign a list # containing the destination vertex as it's first adjacent vertex also # create a new vertex with destination vertex as key and assign a list # containing the source vertex as it's first adjacent vertex. else: __A = [destination_vertex] __A = [source_vertex] else: # For directed graphs # if both source vertex and destination vertex are present in adjacency # list, add destination vertex to source vertex list of adjacent vertices. if source_vertex in self.adj_list and destination_vertex in self.adj_list: self.adj_list[source_vertex].append(A ) # if only source vertex is present in adjacency list, add destination # vertex to source vertex list of adjacent vertices and create a new vertex # with destination vertex as key, which has no adjacent vertex elif source_vertex in self.adj_list: self.adj_list[source_vertex].append(A ) __A = [] # if only destination vertex is present in adjacency list, create a new # vertex with source vertex as key and assign a list containing destination # vertex as first adjacent vertex elif destination_vertex in self.adj_list: __A = [destination_vertex] # if both source vertex and destination vertex are not present in adjacency # list, create a new vertex with source vertex as key and a list containing # destination vertex as it's first adjacent vertex. Then create a new vertex # with destination vertex as key, which has no adjacent vertex else: __A = [destination_vertex] __A = [] return self def __repr__( self : Union[str, Any] ): return pformat(self.adj_list )
15
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE :List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :List[str] = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Dict = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE :Optional[Any] = { 'AI-Sweden/gpt-sw3-126m': 2048, 'AI-Sweden/gpt-sw3-350m': 2048, 'AI-Sweden/gpt-sw3-1.6b': 2048, 'AI-Sweden/gpt-sw3-6.7b': 2048, 'AI-Sweden/gpt-sw3-20b': 2048, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[int] ,A : Optional[Any] ,A : Optional[int]=False ,A : int=False ,A : Union[str, Any]=False ,A : int=None ,A : Optional[Any]=None ,A : Union[str, Any]=None ,A : Optional[Any]=None ,A : Optional[Dict[str, Any]] = None ,**A : Tuple ,): __A = {} if sp_model_kwargs is None else sp_model_kwargs __A = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) __A = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __A = "<|endoftext|>" if eos_token is None else eos_token __A = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __A = unk_token if pad_token is None else pad_token __A = eos_token if bos_token is None else bos_token else: __A = "<pad>" if pad_token is None else pad_token __A = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=A ,remove_space=A ,keep_accents=A ,bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = do_lower_case __A = remove_space __A = keep_accents __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) # Used for whitespace normalization in input texts # fmt : off __A = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __A = re.compile( f'''[{''.join(map(A ,list(range(0 ,9 ) ) + list(range(11 ,32 ) ) + list(range(1_27 ,1_60 ) ) + [1_60, 1_73, 82_03] ) )}]''' ) def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Optional[Any] ,A : Union[str, Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCamelCase_ ( self : List[str] ): return len(self.sp_model ) def UpperCamelCase_ ( self : int ,A : str ): __A = self.non_printing_characters_re.sub("" ,A ) # Normalize whitespaces __A = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization __A = unicodedata.normalize("NFC" ,A ) return text def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,**A : Optional[int] ): __A = self.preprocess_text(A ) return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : int ): return self.sp_model.IdToPiece(A ) @staticmethod def UpperCamelCase_ ( A : str ): return out_string def UpperCamelCase_ ( self : str ,A : List[str] ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string def UpperCamelCase_ ( self : str ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : List[str] ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Union[str, Any] ,A : Union[str, List[str]] ,A : Union[str, bool] = False ): if isinstance(A ,A ): __A = self.preprocess_text(A ) __A = self.sp_model.encode(A ) else: __A = [self.preprocess_text(A ) for t in text] __A = self.sp_model.encode(A ) if return_tensors is True or return_tensors == "pt": __A = torch.tensor(A ) return token_ids def UpperCamelCase_ ( self : List[Any] ,A : Union[int, List[int]] ): return self.sp_model.decode(A ) def UpperCamelCase_ ( self : List[str] ,A : "Conversation" ): __A = [f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __A = ( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(A ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=A )
15
1
import os import tempfile from functools import partial from unittest import TestCase from unittest.mock import patch import numpy as np import pytest from datasets.arrow_dataset import Dataset from datasets.search import ElasticSearchIndex, FaissIndex, MissingIndex from .utils import require_elasticsearch, require_faiss SCREAMING_SNAKE_CASE :Dict = pytest.mark.integration @require_faiss class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Tuple ): __A = Dataset.from_dict({"filename": ["my_name-train" + "_" + str(A ) for x in np.arange(30 ).tolist()]} ) return dset def UpperCamelCase_ ( self : Optional[Any] ): import faiss __A = self._create_dummy_dataset() __A = dset.map( lambda A ,A : {"vecs": i * np.ones(5 ,dtype=np.floataa )} ,with_indices=A ,keep_in_memory=A ) __A = dset.add_faiss_index("vecs" ,batch_size=1_00 ,metric_type=faiss.METRIC_INNER_PRODUCT ) __A , __A = dset.get_nearest_examples("vecs" ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] ,"my_name-train_29" ) dset.drop_index("vecs" ) def UpperCamelCase_ ( self : Tuple ): import faiss __A = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name="vecs" ,batch_size=1_00 ,metric_type=faiss.METRIC_INNER_PRODUCT ,) __A , __A = dset.get_nearest_examples("vecs" ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] ,"my_name-train_29" ) def UpperCamelCase_ ( self : List[str] ): import faiss __A = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name="vecs" ,metric_type=faiss.METRIC_INNER_PRODUCT ,) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A ) as tmp_file: dset.save_faiss_index("vecs" ,tmp_file.name ) dset.load_faiss_index("vecs2" ,tmp_file.name ) os.unlink(tmp_file.name ) __A , __A = dset.get_nearest_examples("vecs2" ,np.ones(5 ,dtype=np.floataa ) ) self.assertEqual(examples["filename"][0] ,"my_name-train_29" ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = self._create_dummy_dataset() dset.add_faiss_index_from_external_arrays( external_arrays=np.ones((30, 5) ) * np.arange(30 ).reshape(-1 ,1 ) ,index_name="vecs" ) dset.drop_index("vecs" ) self.assertRaises(A ,partial(dset.get_nearest_examples ,"vecs2" ,np.ones(5 ,dtype=np.floataa ) ) ) def UpperCamelCase_ ( self : Dict ): from elasticsearch import Elasticsearch __A = self._create_dummy_dataset() with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: __A = {"acknowledged": True} mocked_bulk.return_value([(True, None)] * 30 ) __A = {"hits": {"hits": [{"_score": 1, "_id": 29}]}} __A = Elasticsearch() dset.add_elasticsearch_index("filename" ,es_client=A ) __A , __A = dset.get_nearest_examples("filename" ,"my_name-train_29" ) self.assertEqual(examples["filename"][0] ,"my_name-train_29" ) @require_faiss class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Optional[int] ): import faiss __A = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) # add vectors index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsNotNone(index.faiss_index ) self.assertEqual(index.faiss_index.ntotal ,5 ) index.add_vectors(np.zeros((5, 5) ,dtype=np.floataa ) ) self.assertEqual(index.faiss_index.ntotal ,10 ) # single query __A = np.zeros(5 ,dtype=np.floataa ) __A = 1 __A , __A = index.search(A ) self.assertRaises(A ,index.search ,query.reshape(-1 ,1 ) ) self.assertGreater(scores[0] ,0 ) self.assertEqual(indices[0] ,1 ) # batched queries __A = np.eye(5 ,dtype=np.floataa )[::-1] __A , __A = index.search_batch(A ) self.assertRaises(A ,index.search_batch ,queries[0] ) __A = [scores[0] for scores in total_scores] __A = [indices[0] for indices in total_indices] self.assertGreater(np.min(A ) ,0 ) self.assertListEqual([4, 3, 2, 1, 0] ,A ) def UpperCamelCase_ ( self : Tuple ): import faiss __A = FaissIndex(string_factory="Flat" ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexFlat ) __A = FaissIndex(string_factory="LSH" ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexLSH ) with self.assertRaises(A ): __A = FaissIndex(string_factory="Flat" ,custom_index=faiss.IndexFlat(5 ) ) def UpperCamelCase_ ( self : Any ): import faiss __A = faiss.IndexFlat(5 ) __A = FaissIndex(custom_index=A ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) self.assertIsInstance(index.faiss_index ,faiss.IndexFlat ) def UpperCamelCase_ ( self : Union[str, Any] ): import faiss __A = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 ,dtype=np.floataa ) ) # Setting delete=False and unlinking manually is not pretty... but it is required on Windows to # ensure somewhat stable behaviour. If we don't, we get PermissionErrors. This is an age-old issue. # see https://bugs.python.org/issue14243 and # https://stackoverflow.com/questions/23212435/permission-denied-to-write-to-my-temporary-file/23212515 with tempfile.NamedTemporaryFile(delete=A ) as tmp_file: index.save(tmp_file.name ) __A = FaissIndex.load(tmp_file.name ) os.unlink(tmp_file.name ) __A = np.zeros(5 ,dtype=np.floataa ) __A = 1 __A , __A = index.search(A ) self.assertGreater(scores[0] ,0 ) self.assertEqual(indices[0] ,1 ) @require_faiss def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" import faiss __A = FaissIndex(metric_type=faiss.METRIC_INNER_PRODUCT ) index.add_vectors(np.eye(5 , dtype=np.floataa ) ) __A = "index.faiss" __A = F'''mock://{index_name}''' index.save(a_ , storage_options=mockfs.storage_options ) __A = FaissIndex.load(a_ , storage_options=mockfs.storage_options ) __A = np.zeros(5 , dtype=np.floataa ) __A = 1 __A , __A = index.search(a_ ) assert scores[0] > 0 assert indices[0] == 1 @require_elasticsearch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def UpperCamelCase_ ( self : Dict ): from elasticsearch import Elasticsearch with patch("elasticsearch.Elasticsearch.search" ) as mocked_search, patch( "elasticsearch.client.IndicesClient.create" ) as mocked_index_create, patch("elasticsearch.helpers.streaming_bulk" ) as mocked_bulk: __A = Elasticsearch() __A = {"acknowledged": True} __A = ElasticSearchIndex(es_client=A ) mocked_bulk.return_value([(True, None)] * 3 ) index.add_documents(["foo", "bar", "foobar"] ) # single query __A = "foo" __A = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} __A , __A = index.search(A ) self.assertEqual(scores[0] ,1 ) self.assertEqual(indices[0] ,0 ) # single query with timeout __A = "foo" __A = {"hits": {"hits": [{"_score": 1, "_id": 0}]}} __A , __A = index.search(A ,request_timeout=30 ) self.assertEqual(scores[0] ,1 ) self.assertEqual(indices[0] ,0 ) # batched queries __A = ["foo", "bar", "foobar"] __A = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} __A , __A = index.search_batch(A ) __A = [scores[0] for scores in total_scores] __A = [indices[0] for indices in total_indices] self.assertGreater(np.min(A ) ,0 ) self.assertListEqual([1, 1, 1] ,A ) # batched queries with timeout __A = ["foo", "bar", "foobar"] __A = {"hits": {"hits": [{"_score": 1, "_id": 1}]}} __A , __A = index.search_batch(A ,request_timeout=30 ) __A = [scores[0] for scores in total_scores] __A = [indices[0] for indices in total_indices] self.assertGreater(np.min(A ) ,0 ) self.assertListEqual([1, 1, 1] ,A )
15
import numpy as np def UpperCAmelCase ( a_ , a_ , a_ = 1E-12 , a_ = 1_0_0 , ) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(a_ )[0] == np.shape(a_ )[1] # Ensure proper dimensionality. assert np.shape(a_ )[0] == np.shape(a_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a_ ) == np.iscomplexobj(a_ ) __A = np.iscomplexobj(a_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __A = False __A = 0 __A = 0 __A = 1E12 while not convergence: # Multiple matrix by the vector. __A = np.dot(a_ , a_ ) # Normalize the resulting output vector. __A = w / np.linalg.norm(a_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __A = vector.conj().T if is_complex else vector.T __A = np.dot(a_ , np.dot(a_ , a_ ) ) # Check convergence. __A = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __A = True __A = lambda_ if is_complex: __A = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase ( ) -> None: """simple docstring""" __A = np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]] ) __A = np.array([4_1, 4, 2_0] ) __A = real_input_matrix.astype(np.complexaaa ) __A = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __A = np.array([4_1, 4, 2_0] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __A = real_input_matrix __A = real_vector elif problem_type == "complex": __A = complex_input_matrix __A = complex_vector # Our implementation. __A , __A = power_iteration(a_ , a_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __A , __A = np.linalg.eigh(a_ ) # Last eigenvalue is the maximum one. __A = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __A = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a_ ) - np.abs(a_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
1
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __A = key.replace("heads.cmd.mim_head.cls.predictions" , "mmm_image_head" ) __A = key.replace("heads.cmd.mlm_head.cls.predictions" , "mmm_text_head" ) __A = key.replace("heads.cmd.itm_head.cls" , "itm_head" ) __A = key.replace("heads.cmd.itm_head.pooler" , "itm_head.pooler" ) __A = key.replace("heads.cmd.clip_head.logit_scale" , "flava.logit_scale" ) __A = key.replace("heads.fairseq_mlm.cls.predictions" , "mlm_head" ) __A = key.replace("heads.imagenet.mim_head.cls.predictions" , "mim_head" ) __A = key.replace("mm_text_projection" , "flava.text_to_mm_projection" ) __A = key.replace("mm_image_projection" , "flava.image_to_mm_projection" ) __A = key.replace("image_encoder.module" , "flava.image_model" ) __A = key.replace("text_encoder.module" , "flava.text_model" ) __A = key.replace("mm_encoder.module.encoder.cls_token" , "flava.multimodal_model.cls_token" ) __A = key.replace("mm_encoder.module" , "flava.multimodal_model" ) __A = key.replace("text_projection" , "flava.text_projection" ) __A = key.replace("image_projection" , "flava.image_projection" ) __A = value.float() for key, value in codebook_state_dict.items(): __A = value return upgrade @torch.no_grad() def UpperCAmelCase ( a_ , a_ , a_ , a_=None ) -> Tuple: """simple docstring""" if config_path is not None: __A = FlavaConfig.from_pretrained(a_ ) else: __A = FlavaConfig() __A = FlavaForPreTraining(a_ ).eval() __A = convert_dalle_checkpoint(a_ , a_ , save_checkpoint=a_ ) if os.path.exists(a_ ): __A = torch.load(a_ , map_location="cpu" ) else: __A = torch.hub.load_state_dict_from_url(a_ , map_location="cpu" ) __A = upgrade_state_dict(a_ , a_ ) hf_model.load_state_dict(a_ ) __A = hf_model.state_dict() __A = count_parameters(a_ ) __A = count_parameters(a_ ) + count_parameters(a_ ) assert torch.allclose(a_ , a_ , atol=1E-3 ) hf_model.save_pretrained(a_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
15
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig SCREAMING_SNAKE_CASE :str = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE :str = 'RegNetConfig' # Base docstring SCREAMING_SNAKE_CASE :List[str] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Union[str, Any] = [1, 1088, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE :Optional[int] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Any = 'tabby, tabby cat' SCREAMING_SNAKE_CASE :Optional[int] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : int ,A : int = 3 ,A : int = 1 ,A : int = 1 ,A : Optional[str] = "relu" ,**A : Dict ,): super().__init__(**A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __A = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=A ,strides=A ,padding="VALID" ,groups=A ,use_bias=A ,name="convolution" ,) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) __A = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : List[Any] ,A : Any ): __A = self.convolution(self.padding(A ) ) __A = self.normalization(A ) __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : RegNetConfig ,**A : str ): super().__init__(**A ) __A = config.num_channels __A = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name="embedder" ,) def UpperCamelCase_ ( self : Tuple ,A : Optional[Any] ): __A = shape_list(A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __A = tf.transpose(A ,perm=(0, 2, 3, 1) ) __A = self.embedder(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Optional[int] ,A : int ,A : int = 2 ,**A : Tuple ): super().__init__(**A ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=1 ,strides=A ,use_bias=A ,name="convolution" ) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) def UpperCamelCase_ ( self : Union[str, Any] ,A : tf.Tensor ,A : bool = False ): return self.normalization(self.convolution(A ) ,training=A ) class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Dict ,A : int ,A : int ,**A : str ): super().__init__(**A ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) __A = [ tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="relu" ,name="attention.0" ), tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="sigmoid" ,name="attention.2" ), ] def UpperCamelCase_ ( self : Dict ,A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __A = self.pooler(A ) for layer_module in self.attention: __A = layer_module(A ) __A = hidden_state * pooled return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : Optional[int] ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.2" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : int ,A : Optional[int] ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : str ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetSELayer(A ,reduced_channels=int(round(in_channels / 4 ) ) ,name="layer.2" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.3" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict ,A : Any ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 2 ,A : int = 2 ,**A : Optional[int] ): super().__init__(**A ) __A = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __A = [ # downsampling is done in the first layer with stride of 2 layer(A ,A ,A ,stride=A ,name="layers.0" ), *[layer(A ,A ,A ,name=f'''layers.{i+1}''' ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Any ,A : List[str] ): for layer_module in self.layers: __A = layer_module(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any ,A : RegNetConfig ,**A : List[str] ): super().__init__(**A ) __A = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( A ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name="stages.0" ,) ) __A = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(A ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(A ,A ,A ,depth=A ,name=f'''stages.{i+1}''' ) ) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor ,A : bool = False ,A : bool = True ): __A = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __A = hidden_states + (hidden_state,) __A = stage_module(A ) if output_hidden_states: __A = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=A ,hidden_states=A ) @keras_serializable class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' snake_case_ = RegNetConfig def __init__( self : int ,A : Optional[int] ,**A : Dict ): super().__init__(**A ) __A = config __A = TFRegNetEmbeddings(A ,name="embedder" ) __A = TFRegNetEncoder(A ,name="encoder" ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) @unpack_inputs def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : bool = False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.embedder(A ,training=A ) __A = self.encoder( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = encoder_outputs[0] __A = self.pooler(A ) # Change to NCHW output format have uniformity in the modules __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __A = tuple([tf.transpose(A ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A ,pooler_output=A ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = RegNetConfig snake_case_ = "regnet" snake_case_ = "pixel_values" @property def UpperCamelCase_ ( self : Optional[Any] ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} SCREAMING_SNAKE_CASE :Dict = R'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' SCREAMING_SNAKE_CASE :Dict = R'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,*A : List[Any] ,**A : str ): super().__init__(A ,*A ,**A ) __A = TFRegNetMainLayer(A ,name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=A ,config_class=_CONFIG_FOR_DOC ,modality="vision" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : int=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( pixel_values=A ,output_hidden_states=A ,return_dict=A ,training=A ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Optional[int] ,A : RegNetConfig ,*A : str ,**A : Tuple ): super().__init__(A ,*A ,**A ) __A = config.num_labels __A = TFRegNetMainLayer(A ,name="regnet" ) # classification head __A = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=A ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor = None ,A : tf.Tensor = None ,A : bool = None ,A : bool = None ,A : Union[str, Any]=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = outputs.pooler_output if return_dict else outputs[1] __A = self.classifier[0](A ) __A = self.classifier[1](A ) __A = None if labels is None else self.hf_compute_loss(labels=A ,logits=A ) if not return_dict: __A = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=A ,logits=A ,hidden_states=outputs.hidden_states )
15
1
import copy import os from collections import OrderedDict from typing import TYPE_CHECKING, Any, Dict, Mapping, Optional, Union if TYPE_CHECKING: from ...processing_utils import ProcessorMixin from ...utils import TensorType from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE :Dict = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Optional[Any] = { 'google/owlvit-base-patch32': 'https://huggingface.co/google/owlvit-base-patch32/resolve/main/config.json', 'google/owlvit-base-patch16': 'https://huggingface.co/google/owlvit-base-patch16/resolve/main/config.json', 'google/owlvit-large-patch14': 'https://huggingface.co/google/owlvit-large-patch14/resolve/main/config.json', } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "owlvit_text_model" def __init__( self : Dict ,A : Any=4_94_08 ,A : Optional[Any]=5_12 ,A : Optional[Any]=20_48 ,A : int=12 ,A : List[Any]=8 ,A : str=16 ,A : Dict="quick_gelu" ,A : str=1E-5 ,A : Dict=0.0 ,A : str=0.02 ,A : List[Any]=1.0 ,A : List[Any]=0 ,A : int=4_94_06 ,A : List[Any]=4_94_07 ,**A : List[str] ,): super().__init__(pad_token_id=A ,bos_token_id=A ,eos_token_id=A ,**A ) __A = vocab_size __A = hidden_size __A = intermediate_size __A = num_hidden_layers __A = num_attention_heads __A = max_position_embeddings __A = hidden_act __A = layer_norm_eps __A = attention_dropout __A = initializer_range __A = initializer_factor @classmethod def UpperCamelCase_ ( cls : List[str] ,A : Union[str, os.PathLike] ,**A : Optional[Any] ): cls._set_token_in_kwargs(A ) __A , __A = cls.get_config_dict(A ,**A ) # get the text config dict if we are loading from OwlViTConfig if config_dict.get("model_type" ) == "owlvit": __A = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls ,"model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(A ,**A ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "owlvit_vision_model" def __init__( self : List[Any] ,A : str=7_68 ,A : Tuple=30_72 ,A : List[str]=12 ,A : str=12 ,A : List[str]=3 ,A : List[str]=7_68 ,A : Optional[Any]=32 ,A : Optional[int]="quick_gelu" ,A : List[str]=1E-5 ,A : Optional[int]=0.0 ,A : Union[str, Any]=0.02 ,A : Optional[Any]=1.0 ,**A : Union[str, Any] ,): super().__init__(**A ) __A = hidden_size __A = intermediate_size __A = num_hidden_layers __A = num_attention_heads __A = num_channels __A = image_size __A = patch_size __A = hidden_act __A = layer_norm_eps __A = attention_dropout __A = initializer_range __A = initializer_factor @classmethod def UpperCamelCase_ ( cls : Union[str, Any] ,A : Union[str, os.PathLike] ,**A : List[Any] ): cls._set_token_in_kwargs(A ) __A , __A = cls.get_config_dict(A ,**A ) # get the vision config dict if we are loading from OwlViTConfig if config_dict.get("model_type" ) == "owlvit": __A = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls ,"model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(A ,**A ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "owlvit" snake_case_ = True def __init__( self : Any ,A : List[Any]=None ,A : Tuple=None ,A : Optional[Any]=5_12 ,A : Tuple=2.65_92 ,A : Dict=True ,**A : Optional[Any] ,): super().__init__(**A ) if text_config is None: __A = {} logger.info("text_config is None. Initializing the OwlViTTextConfig with default values." ) if vision_config is None: __A = {} logger.info("vision_config is None. initializing the OwlViTVisionConfig with default values." ) __A = OwlViTTextConfig(**A ) __A = OwlViTVisionConfig(**A ) __A = projection_dim __A = logit_scale_init_value __A = return_dict __A = 1.0 @classmethod def UpperCamelCase_ ( cls : List[Any] ,A : Union[str, os.PathLike] ,**A : List[Any] ): cls._set_token_in_kwargs(A ) __A , __A = cls.get_config_dict(A ,**A ) if "model_type" in config_dict and hasattr(cls ,"model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type ''' f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.''' ) return cls.from_dict(A ,**A ) @classmethod def UpperCamelCase_ ( cls : Dict ,A : Dict ,A : Dict ,**A : Any ): __A = {} __A = text_config __A = vision_config return cls.from_dict(A ,**A ) def UpperCamelCase_ ( self : Any ): __A = copy.deepcopy(self.__dict__ ) __A = self.text_config.to_dict() __A = self.vision_config.to_dict() __A = self.__class__.model_type return output class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' @property def UpperCamelCase_ ( self : Dict ): return OrderedDict( [ ("input_ids", {0: "batch", 1: "sequence"}), ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ("attention_mask", {0: "batch", 1: "sequence"}), ] ) @property def UpperCamelCase_ ( self : List[str] ): return OrderedDict( [ ("logits_per_image", {0: "batch"}), ("logits_per_text", {0: "batch"}), ("text_embeds", {0: "batch"}), ("image_embeds", {0: "batch"}), ] ) @property def UpperCamelCase_ ( self : Dict ): return 1E-4 def UpperCamelCase_ ( self : Union[str, Any] ,A : "ProcessorMixin" ,A : int = -1 ,A : int = -1 ,A : Optional["TensorType"] = None ,): __A = super().generate_dummy_inputs( processor.tokenizer ,batch_size=A ,seq_length=A ,framework=A ) __A = super().generate_dummy_inputs( processor.image_processor ,batch_size=A ,framework=A ) return {**text_input_dict, **image_input_dict} @property def UpperCamelCase_ ( self : Any ): return 14
15
import math def UpperCAmelCase ( a_ , a_ = 0 , a_ = 0 ) -> list: """simple docstring""" __A = end or len(a_ ) for i in range(a_ , a_ ): __A = i __A = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: __A = array[temp_index - 1] temp_index -= 1 __A = temp_index_value return array def UpperCAmelCase ( a_ , a_ , a_ ) -> None: # Max Heap """simple docstring""" __A = index __A = 2 * index + 1 # Left Node __A = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: __A = left_index if right_index < heap_size and array[largest] < array[right_index]: __A = right_index if largest != index: __A , __A = array[largest], array[index] heapify(a_ , a_ , a_ ) def UpperCAmelCase ( a_ ) -> list: """simple docstring""" __A = len(a_ ) for i in range(n // 2 , -1 , -1 ): heapify(a_ , a_ , a_ ) for i in range(n - 1 , 0 , -1 ): __A , __A = array[0], array[i] heapify(a_ , 0 , a_ ) return array def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" __A = low __A = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i __A , __A = array[j], array[i] i += 1 def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) == 0: return array __A = 2 * math.ceil(math.loga(len(a_ ) ) ) __A = 1_6 return intro_sort(a_ , 0 , len(a_ ) , a_ , a_ ) def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ ) -> list: """simple docstring""" while end - start > size_threshold: if max_depth == 0: return heap_sort(a_ ) max_depth -= 1 __A = median_of_a(a_ , a_ , start + ((end - start) // 2) + 1 , end - 1 ) __A = partition(a_ , a_ , a_ , a_ ) intro_sort(a_ , a_ , a_ , a_ , a_ ) __A = p return insertion_sort(a_ , a_ , a_ ) if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma : ').strip() SCREAMING_SNAKE_CASE :str = [float(item) for item in user_input.split(',')] print(sort(unsorted))
15
1
from math import ceil def UpperCAmelCase ( a_ = 1_0_0_1 ) -> int: """simple docstring""" __A = 1 for i in range(1 , int(ceil(n / 2.0 ) ) ): __A = 2 * i + 1 __A = 2 * i __A = total + 4 * odd**2 - 6 * even return total if __name__ == "__main__": import sys if len(sys.argv) == 1: print(solution()) else: try: SCREAMING_SNAKE_CASE :Tuple = int(sys.argv[1]) print(solution(n)) except ValueError: print('Invalid entry - please enter a number')
15
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml SCREAMING_SNAKE_CASE :Optional[int] = NewType('DataClass', Any) SCREAMING_SNAKE_CASE :int = NewType('DataClassType', Any) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" if isinstance(a_ , a_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def UpperCAmelCase ( a_ ) -> Callable[[str], Any]: """simple docstring""" __A = {str(a_ ): choice for choice in choices} return lambda a_ : str_to_choice.get(a_ , a_ ) def UpperCAmelCase ( *, a_ = None , a_ = None , a_ = dataclasses.MISSING , a_ = dataclasses.MISSING , a_ = None , **a_ , ) -> dataclasses.Field: """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls __A = {} if aliases is not None: __A = aliases if help is not None: __A = help return dataclasses.field(metadata=a_ , default=a_ , default_factory=a_ , **a_ ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 def __init__( self : Union[str, Any] ,A : Union[DataClassType, Iterable[DataClassType]] ,**A : List[Any] ): # To make the default appear when using --help if "formatter_class" not in kwargs: __A = ArgumentDefaultsHelpFormatter super().__init__(**A ) if dataclasses.is_dataclass(A ): __A = [dataclass_types] __A = list(A ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A ) @staticmethod def UpperCamelCase_ ( A : ArgumentParser ,A : dataclasses.Field ): __A = f'''--{field.name}''' __A = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type ,A ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) __A = kwargs.pop("aliases" ,[] ) if isinstance(A ,A ): __A = [aliases] __A = getattr(field.type ,"__origin__" ,field.type ) if origin_type is Union or (hasattr(A ,"UnionType" ) and isinstance(A ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." f''' Problem encountered in field \'{field.name}\'.''' ) if type(A ) not in field.type.__args__: # filter `str` in Union __A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] __A = getattr(field.type ,"__origin__" ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) __A = ( field.type.__args__[0] if isinstance(A ,field.type.__args__[1] ) else field.type.__args__[1] ) __A = getattr(field.type ,"__origin__" ,field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) __A = {} if origin_type is Literal or (isinstance(field.type ,A ) and issubclass(field.type ,A )): if origin_type is Literal: __A = field.type.__args__ else: __A = [x.value for x in field.type] __A = make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: __A = field.default else: __A = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument __A = copy(A ) # Hack because type=bool in argparse does not behave as we want. __A = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. __A = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way __A = default # This tells argparse we accept 0 or 1 value after --field_name __A = "?" # This is the value that will get picked if we do --field_name (without value) __A = True elif isclass(A ) and issubclass(A ,A ): __A = field.type.__args__[0] __A = "+" if field.default_factory is not dataclasses.MISSING: __A = field.default_factory() elif field.default is dataclasses.MISSING: __A = True else: __A = field.type if field.default is not dataclasses.MISSING: __A = field.default elif field.default_factory is not dataclasses.MISSING: __A = field.default_factory() else: __A = True parser.add_argument(A ,*A ,**A ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): __A = False parser.add_argument(f'''--no_{field.name}''' ,action="store_false" ,dest=field.name ,**A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : DataClassType ): if hasattr(A ,"_argument_group_name" ): __A = self.add_argument_group(dtype._argument_group_name ) else: __A = self try: __A = get_type_hints(A ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(A ): __A = ".".join(map(A ,sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(A ): if not field.init: continue __A = type_hints[field.name] self._parse_dataclass_field(A ,A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : List[Any]=None ,A : List[Any]=False ,A : Optional[Any]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=None ,): if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): __A = [] if args_filename: args_files.append(Path(A ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values __A = ArgumentParser() args_file_parser.add_argument(A ,type=A ,action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) __A , __A = args_file_parser.parse_known_args(args=A ) __A = vars(A ).get(args_file_flag.lstrip("-" ) ,A ) if cmd_args_file_paths: args_files.extend([Path(A ) for p in cmd_args_file_paths] ) __A = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last __A = file_args + args if args is not None else file_args + sys.argv[1:] __A , __A = self.parse_known_args(args=A ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in vars(A ).items() if k in keys} for k in keys: delattr(A ,A ) __A = dtype(**A ) outputs.append(A ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def UpperCamelCase_ ( self : Dict ,A : Dict[str, Any] ,A : bool = False ): __A = set(args.keys() ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) __A = dtype(**A ) outputs.append(A ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(A )}''' ) return tuple(A ) def UpperCamelCase_ ( self : List[str] ,A : str ,A : bool = False ): with open(Path(A ) ,encoding="utf-8" ) as open_json_file: __A = json.loads(open_json_file.read() ) __A = self.parse_dict(A ,allow_extra_keys=A ) return tuple(A ) def UpperCamelCase_ ( self : int ,A : str ,A : bool = False ): __A = self.parse_dict(yaml.safe_load(Path(A ).read_text() ) ,allow_extra_keys=A ) return tuple(A )
15
1
import inspect import unittest from transformers import BitConfig from transformers.testing_utils import require_torch, require_vision, slow, torch_device from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_backbone_common import BackboneTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import BitBackbone, BitForImageClassification, BitImageProcessor, BitModel from transformers.models.bit.modeling_bit import BIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image class UpperCAmelCase : '''simple docstring''' def __init__( self : List[Any] ,A : List[str] ,A : List[Any]=3 ,A : Any=32 ,A : Optional[int]=3 ,A : Optional[int]=10 ,A : Optional[Any]=[8, 16, 32, 64] ,A : Optional[Any]=[1, 1, 2, 1] ,A : Any=True ,A : str=True ,A : Any="relu" ,A : Dict=3 ,A : Optional[Any]=None ,A : Dict=["stage2", "stage3", "stage4"] ,A : List[str]=[2, 3, 4] ,A : Union[str, Any]=1 ,): __A = parent __A = batch_size __A = image_size __A = num_channels __A = embeddings_size __A = hidden_sizes __A = depths __A = is_training __A = use_labels __A = hidden_act __A = num_labels __A = scope __A = len(A ) __A = out_features __A = out_indices __A = num_groups def UpperCamelCase_ ( self : Any ): __A = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) __A = None if self.use_labels: __A = ids_tensor([self.batch_size] ,self.num_labels ) __A = self.get_config() return config, pixel_values, labels def UpperCamelCase_ ( self : Tuple ): return BitConfig( num_channels=self.num_channels ,embeddings_size=self.embeddings_size ,hidden_sizes=self.hidden_sizes ,depths=self.depths ,hidden_act=self.hidden_act ,num_labels=self.num_labels ,out_features=self.out_features ,out_indices=self.out_indices ,num_groups=self.num_groups ,) def UpperCamelCase_ ( self : Dict ,A : int ,A : Dict ,A : List[Any] ): __A = BitModel(config=A ) model.to(A ) model.eval() __A = model(A ) self.parent.assertEqual( result.last_hidden_state.shape ,(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32) ,) def UpperCamelCase_ ( self : Union[str, Any] ,A : List[Any] ,A : List[str] ,A : Tuple ): __A = self.num_labels __A = BitForImageClassification(A ) model.to(A ) model.eval() __A = model(A ,labels=A ) self.parent.assertEqual(result.logits.shape ,(self.batch_size, self.num_labels) ) def UpperCamelCase_ ( self : Optional[Any] ,A : List[Any] ,A : List[str] ,A : List[str] ): __A = BitBackbone(config=A ) model.to(A ) model.eval() __A = model(A ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,len(config.out_features ) ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[1], 4, 4] ) # verify channels self.parent.assertEqual(len(model.channels ) ,len(config.out_features ) ) self.parent.assertListEqual(model.channels ,config.hidden_sizes[1:] ) # verify backbone works with out_features=None __A = None __A = BitBackbone(config=A ) model.to(A ) model.eval() __A = model(A ) # verify feature maps self.parent.assertEqual(len(result.feature_maps ) ,1 ) self.parent.assertListEqual(list(result.feature_maps[0].shape ) ,[self.batch_size, self.hidden_sizes[-1], 1, 1] ) # verify channels self.parent.assertEqual(len(model.channels ) ,1 ) self.parent.assertListEqual(model.channels ,[config.hidden_sizes[-1]] ) def UpperCamelCase_ ( self : Optional[int] ): __A = self.prepare_config_and_inputs() __A , __A , __A = config_and_inputs __A = {"pixel_values": pixel_values} return config, inputs_dict @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (BitModel, BitForImageClassification, BitBackbone) if is_torch_available() else () snake_case_ = ( {"feature-extraction": BitModel, "image-classification": BitForImageClassification} if is_torch_available() else {} ) snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False snake_case_ = False def UpperCamelCase_ ( self : Optional[int] ): __A = BitModelTester(self ) __A = ConfigTester(self ,config_class=A ,has_text_modality=A ) def UpperCamelCase_ ( self : Optional[int] ): self.create_and_test_config_common_properties() self.config_tester.create_and_test_config_to_json_string() self.config_tester.create_and_test_config_to_json_file() self.config_tester.create_and_test_config_from_and_save_pretrained() self.config_tester.create_and_test_config_with_num_labels() self.config_tester.check_config_can_be_init_without_params() self.config_tester.check_config_arguments_init() def UpperCamelCase_ ( self : Optional[int] ): return @unittest.skip(reason="Bit does not output attentions" ) def UpperCamelCase_ ( self : Any ): pass @unittest.skip(reason="Bit does not use inputs_embeds" ) def UpperCamelCase_ ( self : List[Any] ): pass @unittest.skip(reason="Bit does not support input and output embeddings" ) def UpperCamelCase_ ( self : List[str] ): pass def UpperCamelCase_ ( self : Union[str, Any] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(A ) __A = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic __A = [*signature.parameters.keys()] __A = ["pixel_values"] self.assertListEqual(arg_names[:1] ,A ) def UpperCamelCase_ ( self : Tuple ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*A ) def UpperCamelCase_ ( self : Optional[Any] ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_backbone(*A ) def UpperCamelCase_ ( self : List[str] ): __A , __A = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: __A = model_class(config=A ) for name, module in model.named_modules(): if isinstance(A ,(nn.BatchNormad, nn.GroupNorm) ): self.assertTrue( torch.all(module.weight == 1 ) ,msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' ,) self.assertTrue( torch.all(module.bias == 0 ) ,msg=f'''Parameter {name} of model {model_class} seems not properly initialized''' ,) def UpperCamelCase_ ( self : Tuple ): def check_hidden_states_output(A : Any ,A : List[str] ,A : Tuple ): __A = model_class(A ) model.to(A ) model.eval() with torch.no_grad(): __A = model(**self._prepare_for_class(A ,A ) ) __A = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states __A = self.model_tester.num_stages self.assertEqual(len(A ) ,expected_num_stages + 1 ) # Bit's feature maps are of shape (batch_size, num_channels, height, width) self.assertListEqual( list(hidden_states[0].shape[-2:] ) ,[self.model_tester.image_size // 4, self.model_tester.image_size // 4] ,) __A , __A = self.model_tester.prepare_config_and_inputs_for_common() __A = ["preactivation", "bottleneck"] for model_class in self.all_model_classes: for layer_type in layers_type: __A = layer_type __A = True check_hidden_states_output(A ,A ,A ) # check that output_hidden_states also work using config del inputs_dict["output_hidden_states"] __A = True check_hidden_states_output(A ,A ,A ) @unittest.skip(reason="Bit does not use feedforward chunking" ) def UpperCamelCase_ ( self : Optional[int] ): pass def UpperCamelCase_ ( self : int ): __A = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*A ) @slow def UpperCamelCase_ ( self : List[str] ): for model_name in BIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __A = BitModel.from_pretrained(A ) self.assertIsNotNone(A ) def UpperCAmelCase ( ) -> int: """simple docstring""" __A = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png" ) return image @require_torch @require_vision class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @cached_property def UpperCamelCase_ ( self : List[str] ): return ( BitImageProcessor.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ) if is_vision_available() else None ) @slow def UpperCamelCase_ ( self : Any ): __A = BitForImageClassification.from_pretrained(BIT_PRETRAINED_MODEL_ARCHIVE_LIST[0] ).to(A ) __A = self.default_image_processor __A = prepare_img() __A = image_processor(images=A ,return_tensors="pt" ).to(A ) # forward pass with torch.no_grad(): __A = model(**A ) # verify the logits __A = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape ,A ) __A = torch.tensor([[-0.65_26, -0.52_63, -1.43_98]] ).to(A ) self.assertTrue(torch.allclose(outputs.logits[0, :3] ,A ,atol=1E-4 ) ) @require_torch class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = (BitBackbone,) if is_torch_available() else () snake_case_ = BitConfig snake_case_ = False def UpperCamelCase_ ( self : Optional[int] ): __A = BitModelTester(self )
15
SCREAMING_SNAKE_CASE :Any = 256 # Modulus to hash a string SCREAMING_SNAKE_CASE :Union[str, Any] = 100_0003 def UpperCAmelCase ( a_ , a_ ) -> bool: """simple docstring""" __A = len(a_ ) __A = len(a_ ) if p_len > t_len: return False __A = 0 __A = 0 __A = 1 # Calculating the hash of pattern and substring of text for i in range(a_ ): __A = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus __A = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue __A = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash __A = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def UpperCAmelCase ( ) -> None: """simple docstring""" __A = "abc1abc12" __A = "alskfjaldsabc1abc1abc12k23adsfabcabc" __A = "alskfjaldsk23adsfabcabc" assert rabin_karp(a_ , a_ ) and not rabin_karp(a_ , a_ ) # Test 2) __A = "ABABX" __A = "ABABZABABYABABX" assert rabin_karp(a_ , a_ ) # Test 3) __A = "AAAB" __A = "ABAAAAAB" assert rabin_karp(a_ , a_ ) # Test 4) __A = "abcdabcy" __A = "abcxabcdabxabcdabcdabcy" assert rabin_karp(a_ , a_ ) # Test 5) __A = "Lü" __A = "Lüsai" assert rabin_karp(a_ , a_ ) __A = "Lue" assert not rabin_karp(a_ , a_ ) print("Success." ) if __name__ == "__main__": test_rabin_karp()
15
1
import numpy as np def UpperCAmelCase ( a_ , a_ , a_ = 1E-12 , a_ = 1_0_0 , ) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(a_ )[0] == np.shape(a_ )[1] # Ensure proper dimensionality. assert np.shape(a_ )[0] == np.shape(a_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a_ ) == np.iscomplexobj(a_ ) __A = np.iscomplexobj(a_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __A = False __A = 0 __A = 0 __A = 1E12 while not convergence: # Multiple matrix by the vector. __A = np.dot(a_ , a_ ) # Normalize the resulting output vector. __A = w / np.linalg.norm(a_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __A = vector.conj().T if is_complex else vector.T __A = np.dot(a_ , np.dot(a_ , a_ ) ) # Check convergence. __A = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __A = True __A = lambda_ if is_complex: __A = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase ( ) -> None: """simple docstring""" __A = np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]] ) __A = np.array([4_1, 4, 2_0] ) __A = real_input_matrix.astype(np.complexaaa ) __A = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __A = np.array([4_1, 4, 2_0] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __A = real_input_matrix __A = real_vector elif problem_type == "complex": __A = complex_input_matrix __A = complex_vector # Our implementation. __A , __A = power_iteration(a_ , a_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __A , __A = np.linalg.eigh(a_ ) # Last eigenvalue is the maximum one. __A = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __A = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a_ ) - np.abs(a_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel SCREAMING_SNAKE_CASE :Union[str, Any] = False SCREAMING_SNAKE_CASE :Any = True SCREAMING_SNAKE_CASE :Tuple = False if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE :Union[str, Any] = parser.parse_args() SCREAMING_SNAKE_CASE :Dict = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } SCREAMING_SNAKE_CASE :Optional[int] = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } SCREAMING_SNAKE_CASE :int = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: SCREAMING_SNAKE_CASE :Dict = reader.read() SCREAMING_SNAKE_CASE :List[str] = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): SCREAMING_SNAKE_CASE :Optional[int] = UNetaDModel(**config) else: SCREAMING_SNAKE_CASE :Optional[Any] = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel SCREAMING_SNAKE_CASE :List[str] = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) SCREAMING_SNAKE_CASE :List[str] = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: SCREAMING_SNAKE_CASE :Optional[Any] = config[key] del config[key] SCREAMING_SNAKE_CASE :Optional[Any] = [k.replace('UNetRes', '') for k in config['down_block_types']] SCREAMING_SNAKE_CASE :List[Any] = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: SCREAMING_SNAKE_CASE :Tuple = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) SCREAMING_SNAKE_CASE :Any = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue SCREAMING_SNAKE_CASE :List[str] = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: SCREAMING_SNAKE_CASE :List[Any] = param_value SCREAMING_SNAKE_CASE :str = True if not has_changed: SCREAMING_SNAKE_CASE :List[str] = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
15
1
import numpy as np import torch from torch.nn import CrossEntropyLoss from transformers import AutoModelForCausalLM, AutoTokenizer import datasets from datasets import logging SCREAMING_SNAKE_CASE :str = '\\n\n' SCREAMING_SNAKE_CASE :List[str] = '\nPerplexity (PPL) is one of the most common metrics for evaluating language models.\nIt is defined as the exponentiated average negative log-likelihood of a sequence.\n\nFor more information, see https://huggingface.co/docs/transformers/perplexity\n' SCREAMING_SNAKE_CASE :Dict = '\nArgs:\n model_id (str): model used for calculating Perplexity\n NOTE: Perplexity can only be calculated for causal language models.\n This includes models such as gpt2, causal variations of bert,\n causal versions of t5, and more (the full list can be found\n in the AutoModelForCausalLM documentation here:\n https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )\n\n input_texts (list of str): input text, each separate text snippet\n is one list entry.\n batch_size (int): the batch size to run texts through the model. Defaults to 16.\n add_start_token (bool): whether to add the start token to the texts,\n so the perplexity can include the probability of the first word. Defaults to True.\n device (str): device to run on, defaults to \'cuda\' when available\nReturns:\n perplexity: dictionary containing the perplexity scores for the texts\n in the input list, as well as the mean perplexity. If one of the input texts is\n longer than the max input length of the model, then it is truncated to the\n max length for the perplexity computation.\nExamples:\n Example 1:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... add_start_token=False,\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 78.22\n >>> print(round(results["perplexities"][0], 2))\n 11.11\n\n Example 2:\n >>> perplexity = datasets.load_metric("perplexity")\n >>> input_texts = datasets.load_dataset("wikitext",\n ... "wikitext-2-raw-v1",\n ... split="test")["text"][:50] # doctest:+ELLIPSIS\n [...]\n >>> input_texts = [s for s in input_texts if s!=\'\']\n >>> results = perplexity.compute(model_id=\'gpt2\',\n ... input_texts=input_texts) # doctest:+ELLIPSIS\n >>> print(list(results.keys()))\n [\'perplexities\', \'mean_perplexity\']\n >>> print(round(results["mean_perplexity"], 2))\n 60.35\n >>> print(round(results["perplexities"][0], 2))\n 81.12\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : Union[str, Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( { "input_texts": datasets.Value("string" ), } ) ,reference_urls=["https://huggingface.co/docs/transformers/perplexity"] ,) def UpperCamelCase_ ( self : Optional[int] ,A : Optional[Any] ,A : int ,A : int = 16 ,A : bool = True ,A : Optional[int]=None ): if device is not None: assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu." if device == "gpu": __A = "cuda" else: __A = "cuda" if torch.cuda.is_available() else "cpu" __A = AutoModelForCausalLM.from_pretrained(A ) __A = model.to(A ) __A = AutoTokenizer.from_pretrained(A ) # if batch_size > 1 (which generally leads to padding being required), and # if there is not an already assigned pad_token, assign an existing # special token to also be the padding token if tokenizer.pad_token is None and batch_size > 1: __A = list(tokenizer.special_tokens_map_extended.values() ) # check that the model already has at least one special token defined assert ( len(A ) > 0 ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1." # assign one of the special tokens to also be the pad token tokenizer.add_special_tokens({"pad_token": existing_special_tokens[0]} ) if add_start_token: # leave room for <BOS> token to be added: assert ( tokenizer.bos_token is not None ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False" __A = model.config.max_length - 1 else: __A = model.config.max_length __A = tokenizer( A ,add_special_tokens=A ,padding=A ,truncation=A ,max_length=A ,return_tensors="pt" ,return_attention_mask=A ,).to(A ) __A = encodings["input_ids"] __A = encodings["attention_mask"] # check that each input is long enough: if add_start_token: assert torch.all(torch.ge(attn_masks.sum(1 ) ,1 ) ), "Each input text must be at least one token long." else: assert torch.all( torch.ge(attn_masks.sum(1 ) ,2 ) ), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings." __A = [] __A = CrossEntropyLoss(reduction="none" ) for start_index in logging.tqdm(range(0 ,len(A ) ,A ) ): __A = min(start_index + batch_size ,len(A ) ) __A = encoded_texts[start_index:end_index] __A = attn_masks[start_index:end_index] if add_start_token: __A = torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0 ) ).to(A ) __A = torch.cat([bos_tokens_tensor, encoded_batch] ,dim=1 ) __A = torch.cat( [torch.ones(bos_tokens_tensor.size() ,dtype=torch.intaa ).to(A ), attn_mask] ,dim=1 ) __A = encoded_batch with torch.no_grad(): __A = model(A ,attention_mask=A ).logits __A = out_logits[..., :-1, :].contiguous() __A = labels[..., 1:].contiguous() __A = attn_mask[..., 1:].contiguous() __A = torch.expa( (loss_fct(shift_logits.transpose(1 ,2 ) ,A ) * shift_attention_mask_batch).sum(1 ) / shift_attention_mask_batch.sum(1 ) ) ppls += perplexity_batch.tolist() return {"perplexities": ppls, "mean_perplexity": np.mean(A )}
15
import argparse import math import traceback import dateutil.parser as date_parser import requests def UpperCAmelCase ( a_ ) -> str: """simple docstring""" __A = {} __A = job["started_at"] __A = job["completed_at"] __A = date_parser.parse(a_ ) __A = date_parser.parse(a_ ) __A = round((end_datetime - start_datetime).total_seconds() / 60.0 ) __A = start __A = end __A = duration_in_min return job_info def UpperCAmelCase ( a_ , a_=None ) -> str: """simple docstring""" __A = None if token is not None: __A = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} __A = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' __A = requests.get(a_ , headers=a_ ).json() __A = {} try: job_time.update({job["name"]: extract_time_from_single_job(a_ ) for job in result["jobs"]} ) __A = math.ceil((result["total_count"] - 1_0_0) / 1_0_0 ) for i in range(a_ ): __A = requests.get(url + F'''&page={i + 2}''' , headers=a_ ).json() job_time.update({job["name"]: extract_time_from_single_job(a_ ) for job in result["jobs"]} ) return job_time except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} if __name__ == "__main__": SCREAMING_SNAKE_CASE :Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() SCREAMING_SNAKE_CASE :Union[str, Any] = get_job_time(args.workflow_run_id) SCREAMING_SNAKE_CASE :Optional[int] = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'''{k}: {v["duration"]}''')
15
1
import unittest import numpy as np from transformers import DistilBertConfig, is_flax_available from transformers.testing_utils import require_flax, slow from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax.numpy as jnp from transformers.models.distilbert.modeling_flax_distilbert import ( FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertModel, ) class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' def __init__( self : List[Any] ,A : List[str] ,A : Tuple=13 ,A : List[Any]=7 ,A : Optional[int]=True ,A : Tuple=True ,A : List[Any]=True ,A : Optional[int]=True ,A : str=99 ,A : Tuple=32 ,A : List[str]=5 ,A : Dict=4 ,A : int=37 ,A : Optional[int]="gelu" ,A : Optional[int]=0.1 ,A : Any=0.1 ,A : int=5_12 ,A : List[str]=16 ,A : List[str]=2 ,A : int=0.02 ,A : Union[str, Any]=4 ,): __A = parent __A = batch_size __A = seq_length __A = is_training __A = use_attention_mask __A = use_token_type_ids __A = use_labels __A = vocab_size __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = max_position_embeddings __A = type_vocab_size __A = type_sequence_label_size __A = initializer_range __A = num_choices def UpperCamelCase_ ( self : Tuple ): __A = ids_tensor([self.batch_size, self.seq_length] ,self.vocab_size ) __A = None if self.use_attention_mask: __A = random_attention_mask([self.batch_size, self.seq_length] ) __A = DistilBertConfig( vocab_size=self.vocab_size ,dim=self.hidden_size ,n_layers=self.num_hidden_layers ,n_heads=self.num_attention_heads ,hidden_dim=self.intermediate_size ,hidden_act=self.hidden_act ,dropout=self.hidden_dropout_prob ,attention_dropout=self.attention_probs_dropout_prob ,max_position_embeddings=self.max_position_embeddings ,initializer_range=self.initializer_range ,tie_weights_=A ,) return config, input_ids, attention_mask def UpperCamelCase_ ( self : Optional[int] ): __A = self.prepare_config_and_inputs() __A , __A , __A = config_and_inputs __A = {"input_ids": input_ids, "attention_mask": attention_mask} return config, inputs_dict @require_flax class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = ( ( FlaxDistilBertModel, FlaxDistilBertForMaskedLM, FlaxDistilBertForMultipleChoice, FlaxDistilBertForQuestionAnswering, FlaxDistilBertForSequenceClassification, FlaxDistilBertForTokenClassification, FlaxDistilBertForQuestionAnswering, ) if is_flax_available() else () ) def UpperCamelCase_ ( self : int ): __A = FlaxDistilBertModelTester(self ) @slow def UpperCamelCase_ ( self : Union[str, Any] ): for model_class_name in self.all_model_classes: __A = model_class_name.from_pretrained("distilbert-base-uncased" ) __A = model(np.ones((1, 1) ) ) self.assertIsNotNone(A ) @require_flax class UpperCAmelCase ( unittest.TestCase ): '''simple docstring''' @slow def UpperCamelCase_ ( self : str ): __A = FlaxDistilBertModel.from_pretrained("distilbert-base-uncased" ) __A = np.array([[0, 3_45, 2_32, 3_28, 7_40, 1_40, 16_95, 69, 60_78, 15_88, 2]] ) __A = np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]] ) __A = model(A ,attention_mask=A )[0] __A = (1, 11, 7_68) self.assertEqual(output.shape ,A ) __A = np.array([[[-0.16_39, 0.32_99, 0.16_48], [-0.17_46, 0.32_89, 0.17_10], [-0.18_84, 0.33_57, 0.18_10]]] ) self.assertTrue(jnp.allclose(output[:, 1:4, 1:4] ,A ,atol=1E-4 ) )
15
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" __A = args.pruning_method __A = args.threshold __A = args.model_name_or_path.rstrip("/" ) __A = args.target_model_path print(F'''Load fine-pruned model from {model_name_or_path}''' ) __A = torch.load(os.path.join(a_ , "pytorch_model.bin" ) ) __A = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __A = tensor print(F'''Copied layer {name}''' ) elif "classifier" in name or "qa_output" in name: __A = tensor print(F'''Copied layer {name}''' ) elif "bias" in name: __A = tensor print(F'''Copied layer {name}''' ) else: if pruning_method == "magnitude": __A = MagnitudeBinarizer.apply(inputs=a_ , threshold=a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "topK": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A = TopKBinarizer.apply(a_ , a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A = ThresholdBinarizer.apply(a_ , a_ , a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "l0": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A , __A = -0.1, 1.1 __A = torch.sigmoid(a_ ) __A = s * (r - l) + l __A = s_bar.clamp(min=0.0 , max=1.0 ) __A = tensor * mask print(F'''Pruned layer {name}''' ) else: raise ValueError("Unknown pruning method" ) if target_model_path is None: __A = os.path.join( os.path.dirname(a_ ) , F'''bertarized_{os.path.basename(a_ )}''' ) if not os.path.isdir(a_ ): shutil.copytree(a_ , a_ ) print(F'''\nCreated folder {target_model_path}''' ) torch.save(a_ , os.path.join(a_ , "pytorch_model.bin" ) ) print("\nPruned model saved! See you later!" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--pruning_method', choices=['l0', 'magnitude', 'topK', 'sigmoied_threshold'], type=str, required=True, help=( 'Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,' ' sigmoied_threshold = Soft movement pruning)' ), ) parser.add_argument( '--threshold', type=float, required=False, help=( 'For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.' 'For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.' 'Not needed for `l0`' ), ) parser.add_argument( '--model_name_or_path', type=str, required=True, help='Folder containing the model that was previously fine-pruned', ) parser.add_argument( '--target_model_path', default=None, type=str, required=False, help='Folder containing the model that was previously fine-pruned', ) SCREAMING_SNAKE_CASE :str = parser.parse_args() main(args)
15
1
import os import unittest from transformers import MobileBertTokenizer, MobileBertTokenizerFast from transformers.models.bert.tokenization_bert import ( VOCAB_FILES_NAMES, BasicTokenizer, WordpieceTokenizer, _is_control, _is_punctuation, _is_whitespace, ) from transformers.testing_utils import require_tokenizers, slow from ...test_tokenization_common import TokenizerTesterMixin, filter_non_english @require_tokenizers class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , unittest.TestCase ): '''simple docstring''' snake_case_ = MobileBertTokenizer snake_case_ = MobileBertTokenizerFast snake_case_ = True snake_case_ = True snake_case_ = filter_non_english snake_case_ = "google/mobilebert-uncased" def UpperCamelCase_ ( self : Optional[Any] ): super().setUp() __A = [ "[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "want", "##want", "##ed", "wa", "un", "runn", "##ing", ",", "low", "lowest", ] __A = os.path.join(self.tmpdirname ,VOCAB_FILES_NAMES["vocab_file"] ) with open(self.vocab_file ,"w" ,encoding="utf-8" ) as vocab_writer: vocab_writer.write("".join([x + "\n" for x in vocab_tokens] ) ) __A = [ (tokenizer_def[0], self.pre_trained_model_path, tokenizer_def[2]) # else the 'google/' prefix is stripped for tokenizer_def in self.tokenizers_list ] def UpperCamelCase_ ( self : Tuple ,A : List[str] ): __A = "UNwant\u00E9d,running" __A = "unwanted, running" return input_text, output_text def UpperCamelCase_ ( self : str ): __A = self.tokenizer_class(self.vocab_file ) __A = 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 UpperCamelCase_ ( self : List[Any] ): if not self.test_rust_tokenizer: return __A = self.get_tokenizer() __A = self.get_rust_tokenizer() __A = "UNwant\u00E9d,running" __A = tokenizer.tokenize(A ) __A = rust_tokenizer.tokenize(A ) self.assertListEqual(A ,A ) __A = tokenizer.encode(A ,add_special_tokens=A ) __A = rust_tokenizer.encode(A ,add_special_tokens=A ) self.assertListEqual(A ,A ) __A = self.get_rust_tokenizer() __A = tokenizer.encode(A ) __A = rust_tokenizer.encode(A ) self.assertListEqual(A ,A ) # With lower casing __A = self.get_tokenizer(do_lower_case=A ) __A = self.get_rust_tokenizer(do_lower_case=A ) __A = "UNwant\u00E9d,running" __A = tokenizer.tokenize(A ) __A = rust_tokenizer.tokenize(A ) self.assertListEqual(A ,A ) __A = tokenizer.encode(A ,add_special_tokens=A ) __A = rust_tokenizer.encode(A ,add_special_tokens=A ) self.assertListEqual(A ,A ) __A = self.get_rust_tokenizer() __A = tokenizer.encode(A ) __A = rust_tokenizer.encode(A ) self.assertListEqual(A ,A ) def UpperCamelCase_ ( self : List[str] ): __A = BasicTokenizer() self.assertListEqual(tokenizer.tokenize("ah\u535A\u63A8zz" ) ,["ah", "\u535A", "\u63A8", "zz"] ) def UpperCamelCase_ ( self : int ): __A = 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 UpperCamelCase_ ( self : Tuple ): __A = 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 UpperCamelCase_ ( self : List[Any] ): __A = 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 UpperCamelCase_ ( self : str ): __A = 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 UpperCamelCase_ ( self : List[str] ): __A = BasicTokenizer(do_lower_case=A ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? " ) ,["HeLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCamelCase_ ( self : Tuple ): __A = BasicTokenizer(do_lower_case=A ,strip_accents=A ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["HäLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = BasicTokenizer(do_lower_case=A ,strip_accents=A ) self.assertListEqual( tokenizer.tokenize(" \tHäLLo!how \n Are yoU? " ) ,["HaLLo", "!", "how", "Are", "yoU", "?"] ) def UpperCamelCase_ ( self : str ): __A = BasicTokenizer(do_lower_case=A ,never_split=["[UNK]"] ) self.assertListEqual( tokenizer.tokenize(" \tHeLLo!how \n Are yoU? [UNK]" ) ,["HeLLo", "!", "how", "Are", "yoU", "?", "[UNK]"] ) def UpperCamelCase_ ( self : Union[str, Any] ): __A = ["[UNK]", "[CLS]", "[SEP]", "want", "##want", "##ed", "wa", "un", "runn", "##ing"] __A = {} for i, token in enumerate(A ): __A = i __A = 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"] ) def UpperCamelCase_ ( self : Union[str, 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 UpperCamelCase_ ( self : Union[str, 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 UpperCamelCase_ ( self : Optional[int] ): 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(" " ) ) def UpperCamelCase_ ( self : List[Any] ): __A = self.get_tokenizer() __A = self.get_rust_tokenizer() # Example taken from the issue https://github.com/huggingface/tokenizers/issues/340 self.assertListEqual([tokenizer.tokenize(A ) for t in ["Test", "\xad", "test"]] ,[["[UNK]"], [], ["[UNK]"]] ) self.assertListEqual( [rust_tokenizer.tokenize(A ) for t in ["Test", "\xad", "test"]] ,[["[UNK]"], [], ["[UNK]"]] ) @slow def UpperCamelCase_ ( self : Any ): __A = self.tokenizer_class.from_pretrained("google/mobilebert-uncased" ) __A = tokenizer.encode("sequence builders" ,add_special_tokens=A ) __A = tokenizer.encode("multi-sequence build" ,add_special_tokens=A ) __A = tokenizer.build_inputs_with_special_tokens(A ) __A = tokenizer.build_inputs_with_special_tokens(A ,A ) assert encoded_sentence == [1_01] + text + [1_02] assert encoded_pair == [1_01] + text + [1_02] + text_a + [1_02] def UpperCamelCase_ ( self : str ): for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __A = self.rust_tokenizer_class.from_pretrained(A ,**A ) __A = f'''A, naïve {tokenizer_r.mask_token} AllenNLP sentence.''' __A = tokenizer_r.encode_plus( A ,return_attention_mask=A ,return_token_type_ids=A ,return_offsets_mapping=A ,add_special_tokens=A ,) __A = tokenizer_r.do_lower_case if hasattr(A ,"do_lower_case" ) else False __A = ( [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "A"), ((1, 2), ","), ((3, 5), "na"), ((5, 6), "##ï"), ((6, 8), "##ve"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "Allen"), ((21, 23), "##NL"), ((23, 24), "##P"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] if not do_lower_case else [ ((0, 0), tokenizer_r.cls_token), ((0, 1), "a"), ((1, 2), ","), ((3, 8), "naive"), ((9, 15), tokenizer_r.mask_token), ((16, 21), "allen"), ((21, 23), "##nl"), ((23, 24), "##p"), ((25, 33), "sentence"), ((33, 34), "."), ((0, 0), tokenizer_r.sep_token), ] ) self.assertEqual( [e[1] for e in expected_results] ,tokenizer_r.convert_ids_to_tokens(tokens["input_ids"] ) ) self.assertEqual([e[0] for e in expected_results] ,tokens["offset_mapping"] ) def UpperCamelCase_ ( self : Optional[int] ): __A = ["的", "人", "有"] __A = "".join(A ) for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): __A = True __A = self.tokenizer_class.from_pretrained(A ,**A ) __A = self.rust_tokenizer_class.from_pretrained(A ,**A ) __A = tokenizer_p.encode(A ,add_special_tokens=A ) __A = tokenizer_r.encode(A ,add_special_tokens=A ) __A = tokenizer_r.convert_ids_to_tokens(A ) __A = tokenizer_p.convert_ids_to_tokens(A ) # it is expected that each Chinese character is not preceded by "##" self.assertListEqual(A ,A ) self.assertListEqual(A ,A ) __A = False __A = self.rust_tokenizer_class.from_pretrained(A ,**A ) __A = self.tokenizer_class.from_pretrained(A ,**A ) __A = tokenizer_r.encode(A ,add_special_tokens=A ) __A = tokenizer_p.encode(A ,add_special_tokens=A ) __A = tokenizer_r.convert_ids_to_tokens(A ) __A = tokenizer_p.convert_ids_to_tokens(A ) # it is expected that only the first Chinese character is not preceded by "##". __A = [ f'''##{token}''' if idx != 0 else token for idx, token in enumerate(A ) ] self.assertListEqual(A ,A ) self.assertListEqual(A ,A )
15
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :int = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Union[str, Any] = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } SCREAMING_SNAKE_CASE :int = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] snake_case_ = [] def __init__( self : Any ,A : List[str] ,A : str="<unk>" ,A : int="<s>" ,A : Union[str, Any]="</s>" ,A : List[str]="<pad>" ,A : int="[SEP]" ,A : Optional[Any]="[MASK]" ,A : Tuple="[CLS]" ,A : Optional[Dict[str, Any]] = None ,**A : Any ,): __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else bos_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else eos_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else unk_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else pad_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else cls_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else sep_token # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sep_token=A ,mask_token=A ,cls_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) @property def UpperCamelCase_ ( self : List[str] ): return self.sp_model.get_piece_size() def UpperCamelCase_ ( self : Optional[Any] ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : str ,A : Optional[Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Tuple ): return self.sp_model.piece_to_id(A ) def UpperCamelCase_ ( self : List[Any] ,A : Tuple ): __A = self.sp_model.IdToPiece(A ) return token def UpperCamelCase_ ( self : List[Any] ,A : int ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def UpperCamelCase_ ( self : Tuple ,A : List[int] ,A : bool = False ,A : bool = None ,A : bool = True ,**A : Union[str, Any] ,): __A = kwargs.pop("use_source_tokenizer" ,A ) __A = self.convert_ids_to_tokens(A ,skip_special_tokens=A ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __A = [] __A = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(A ) ) __A = [] sub_texts.append(A ) else: current_sub_text.append(A ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(A ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: __A = re.sub(R" (\[(MASK|SEP)\])" ,R"\1" ," ".join(A ) ) else: __A = "".join(A ) __A = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __A = self.clean_up_tokenization(A ) return clean_text else: return text def UpperCamelCase_ ( self : str ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Dict ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : Optional[int] ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Any ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [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]
15
1
import logging import os from dataclasses import dataclass from enum import Enum from typing import List, Optional, Union from filelock import FileLock from transformers import PreTrainedTokenizer, is_tf_available, is_torch_available SCREAMING_SNAKE_CASE :List[str] = logging.getLogger(__name__) @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = 42 snake_case_ = 42 snake_case_ = 42 @dataclass class UpperCAmelCase : '''simple docstring''' snake_case_ = 42 snake_case_ = 42 snake_case_ = None snake_case_ = None class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "train" snake_case_ = "dev" snake_case_ = "test" class UpperCAmelCase : '''simple docstring''' @staticmethod def UpperCamelCase_ ( A : Optional[int] ,A : Union[Split, str] ): raise NotImplementedError @staticmethod def UpperCamelCase_ ( A : str ): raise NotImplementedError @staticmethod def UpperCamelCase_ ( A : List[InputExample] ,A : List[str] ,A : int ,A : PreTrainedTokenizer ,A : Tuple=False ,A : Optional[int]="[CLS]" ,A : Union[str, Any]=1 ,A : Optional[int]="[SEP]" ,A : List[Any]=False ,A : str=False ,A : List[str]=0 ,A : int=0 ,A : Tuple=-1_00 ,A : str=0 ,A : Any=True ,): __A = {label: i for i, label in enumerate(A )} __A = [] for ex_index, example in enumerate(A ): if ex_index % 1_00_00 == 0: logger.info("Writing example %d of %d" ,A ,len(A ) ) __A = [] __A = [] for word, label in zip(example.words ,example.labels ): __A = tokenizer.tokenize(A ) # bert-base-multilingual-cased sometimes output "nothing ([]) when calling tokenize with just a space. if len(A ) > 0: tokens.extend(A ) # Use the real label id for the first token of the word, and padding ids for the remaining tokens label_ids.extend([label_map[label]] + [pad_token_label_id] * (len(A ) - 1) ) # Account for [CLS] and [SEP] with "- 2" and with "- 3" for RoBERTa. __A = tokenizer.num_special_tokens_to_add() if len(A ) > max_seq_length - special_tokens_count: __A = tokens[: (max_seq_length - special_tokens_count)] __A = label_ids[: (max_seq_length - special_tokens_count)] # The convention in BERT is: # (a) For sequence pairs: # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP] # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1 # (b) For single sequences: # tokens: [CLS] the dog is hairy . [SEP] # type_ids: 0 0 0 0 0 0 0 # # Where "type_ids" are used to indicate whether this is the first # sequence or the second sequence. The embedding vectors for `type=0` and # `type=1` were learned during pre-training and are added to the wordpiece # embedding vector (and position vector). This is not *strictly* necessary # since the [SEP] token unambiguously separates the sequences, but it makes # it easier for the model to learn the concept of sequences. # # For classification tasks, the first vector (corresponding to [CLS]) is # used as the "sentence vector". Note that this only makes sense because # the entire model is fine-tuned. tokens += [sep_token] label_ids += [pad_token_label_id] if sep_token_extra: # roberta uses an extra separator b/w pairs of sentences tokens += [sep_token] label_ids += [pad_token_label_id] __A = [sequence_a_segment_id] * len(A ) if cls_token_at_end: tokens += [cls_token] label_ids += [pad_token_label_id] segment_ids += [cls_token_segment_id] else: __A = [cls_token] + tokens __A = [pad_token_label_id] + label_ids __A = [cls_token_segment_id] + segment_ids __A = tokenizer.convert_tokens_to_ids(A ) # The mask has 1 for real tokens and 0 for padding tokens. Only real # tokens are attended to. __A = [1 if mask_padding_with_zero else 0] * len(A ) # Zero-pad up to the sequence length. __A = max_seq_length - len(A ) if pad_on_left: __A = ([pad_token] * padding_length) + input_ids __A = ([0 if mask_padding_with_zero else 1] * padding_length) + input_mask __A = ([pad_token_segment_id] * padding_length) + segment_ids __A = ([pad_token_label_id] * padding_length) + label_ids else: input_ids += [pad_token] * padding_length input_mask += [0 if mask_padding_with_zero else 1] * padding_length segment_ids += [pad_token_segment_id] * padding_length label_ids += [pad_token_label_id] * padding_length assert len(A ) == max_seq_length assert len(A ) == max_seq_length assert len(A ) == max_seq_length assert len(A ) == max_seq_length if ex_index < 5: logger.info("*** Example ***" ) logger.info("guid: %s" ,example.guid ) logger.info("tokens: %s" ," ".join([str(A ) for x in tokens] ) ) logger.info("input_ids: %s" ," ".join([str(A ) for x in input_ids] ) ) logger.info("input_mask: %s" ," ".join([str(A ) for x in input_mask] ) ) logger.info("segment_ids: %s" ," ".join([str(A ) for x in segment_ids] ) ) logger.info("label_ids: %s" ," ".join([str(A ) for x in label_ids] ) ) if "token_type_ids" not in tokenizer.model_input_names: __A = None features.append( InputFeatures( input_ids=A ,attention_mask=A ,token_type_ids=A ,label_ids=A ) ) return features if is_torch_available(): import torch from torch import nn from torch.utils.data import Dataset class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 snake_case_ = nn.CrossEntropyLoss().ignore_index def __init__( self : Optional[Any] ,A : TokenClassificationTask ,A : str ,A : PreTrainedTokenizer ,A : List[str] ,A : str ,A : Optional[int] = None ,A : int=False ,A : Split = Split.train ,): # Load data features from cache or dataset file __A = os.path.join( A ,"cached_{}_{}_{}".format(mode.value ,tokenizer.__class__.__name__ ,str(A ) ) ,) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. __A = cached_features_file + ".lock" with FileLock(A ): if os.path.exists(A ) and not overwrite_cache: logger.info(f'''Loading features from cached file {cached_features_file}''' ) __A = torch.load(A ) else: logger.info(f'''Creating features from dataset file at {data_dir}''' ) __A = token_classification_task.read_examples_from_file(A ,A ) # TODO clean up all this to leverage built-in features of tokenizers __A = token_classification_task.convert_examples_to_features( A ,A ,A ,A ,cls_token_at_end=bool(model_type in ["xlnet"] ) ,cls_token=tokenizer.cls_token ,cls_token_segment_id=2 if model_type in ["xlnet"] else 0 ,sep_token=tokenizer.sep_token ,sep_token_extra=A ,pad_on_left=bool(tokenizer.padding_side == "left" ) ,pad_token=tokenizer.pad_token_id ,pad_token_segment_id=tokenizer.pad_token_type_id ,pad_token_label_id=self.pad_token_label_id ,) logger.info(f'''Saving features into cached file {cached_features_file}''' ) torch.save(self.features ,A ) def __len__( self : str ): return len(self.features ) def __getitem__( self : Optional[Any] ,A : Union[str, Any] ): return self.features[i] if is_tf_available(): import tensorflow as tf class UpperCAmelCase : '''simple docstring''' snake_case_ = 42 snake_case_ = -100 def __init__( self : Optional[Any] ,A : TokenClassificationTask ,A : str ,A : PreTrainedTokenizer ,A : List[str] ,A : str ,A : Optional[int] = None ,A : List[Any]=False ,A : Split = Split.train ,): __A = token_classification_task.read_examples_from_file(A ,A ) # TODO clean up all this to leverage built-in features of tokenizers __A = token_classification_task.convert_examples_to_features( A ,A ,A ,A ,cls_token_at_end=bool(model_type in ["xlnet"] ) ,cls_token=tokenizer.cls_token ,cls_token_segment_id=2 if model_type in ["xlnet"] else 0 ,sep_token=tokenizer.sep_token ,sep_token_extra=A ,pad_on_left=bool(tokenizer.padding_side == "left" ) ,pad_token=tokenizer.pad_token_id ,pad_token_segment_id=tokenizer.pad_token_type_id ,pad_token_label_id=self.pad_token_label_id ,) def gen(): for ex in self.features: if ex.token_type_ids is None: yield ( {"input_ids": ex.input_ids, "attention_mask": ex.attention_mask}, ex.label_ids, ) else: yield ( { "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label_ids, ) if "token_type_ids" not in tokenizer.model_input_names: __A = tf.data.Dataset.from_generator( A ,({"input_ids": tf.intaa, "attention_mask": tf.intaa}, tf.intaa) ,( {"input_ids": tf.TensorShape([None] ), "attention_mask": tf.TensorShape([None] )}, tf.TensorShape([None] ), ) ,) else: __A = tf.data.Dataset.from_generator( A ,({"input_ids": tf.intaa, "attention_mask": tf.intaa, "token_type_ids": tf.intaa}, tf.intaa) ,( { "input_ids": tf.TensorShape([None] ), "attention_mask": tf.TensorShape([None] ), "token_type_ids": tf.TensorShape([None] ), }, tf.TensorShape([None] ), ) ,) def UpperCamelCase_ ( self : int ): __A = self.dataset.apply(tf.data.experimental.assert_cardinality(len(self.features ) ) ) return self.dataset def __len__( self : Any ): return len(self.features ) def __getitem__( self : List[Any] ,A : Optional[Any] ): return self.features[i]
15
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): SCREAMING_SNAKE_CASE :Any = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: SCREAMING_SNAKE_CASE :int = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" __A = (images / 2 + 0.5).clamp(0 , 1 ) __A = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __A = numpy_to_pil(a_ ) return images def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if images.ndim == 3: __A = images[None, ...] __A = (images * 2_5_5).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __A = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __A = [Image.fromarray(a_ ) for image in images] return pil_images
15
1
from __future__ import annotations from collections import namedtuple def _a ( a :float , a :float , a :float ) -> tuple: a = namedtuple('''result''' , '''name value''' ) if (voltage, current, power).count(0 ) != 1: raise ValueError('''Only one argument must be 0''' ) elif power < 0: raise ValueError( '''Power cannot be negative in any electrical/electronics system''' ) elif voltage == 0: return result('''voltage''' , power / current ) elif current == 0: return result('''current''' , power / voltage ) elif power == 0: return result('''power''' , float(round(abs(voltage * current ) , 2 ) ) ) else: raise ValueError('''Exactly one argument must be 0''' ) if __name__ == "__main__": import doctest doctest.testmod()
0
from collections import OrderedDict from typing import Mapping from packaging import version from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging SCREAMING_SNAKE_CASE :Optional[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 UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "yolos" def __init__( self : Any ,A : Optional[Any]=7_68 ,A : Dict=12 ,A : Any=12 ,A : str=30_72 ,A : Any="gelu" ,A : str=0.0 ,A : List[str]=0.0 ,A : Dict=0.02 ,A : int=1E-12 ,A : Tuple=[5_12, 8_64] ,A : List[Any]=16 ,A : str=3 ,A : str=True ,A : Any=1_00 ,A : Dict=True ,A : Dict=False ,A : Tuple=1 ,A : Union[str, Any]=5 ,A : Optional[Any]=2 ,A : Union[str, Any]=5 ,A : int=2 ,A : int=0.1 ,**A : List[str] ,): super().__init__(**A ) __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = initializer_range __A = layer_norm_eps __A = image_size __A = patch_size __A = num_channels __A = qkv_bias __A = num_detection_tokens __A = use_mid_position_embeddings __A = auxiliary_loss # Hungarian matcher __A = class_cost __A = bbox_cost __A = giou_cost # Loss coefficients __A = bbox_loss_coefficient __A = giou_loss_coefficient __A = eos_coefficient class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = version.parse("1.11" ) @property def UpperCamelCase_ ( self : str ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCamelCase_ ( self : List[Any] ): return 1E-4 @property def UpperCamelCase_ ( self : Optional[Any] ): return 12
15
0
'''simple docstring''' import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, PNDMScheduler, StableDiffusionLDMaDPipeline, UNetaDConditionModel, ) from diffusers.utils import nightly, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS enable_full_determinism() class __A ( unittest.TestCase ): a__ : Union[str, Any] = StableDiffusionLDMaDPipeline a__ : str = TEXT_TO_IMAGE_PARAMS a__ : Dict = TEXT_TO_IMAGE_BATCH_PARAMS a__ : str = TEXT_TO_IMAGE_IMAGE_PARAMS def _lowercase (self : int ): torch.manual_seed(0 ) UpperCAmelCase_ = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("DownBlock2D", "CrossAttnDownBlock2D") , up_block_types=("CrossAttnUpBlock2D", "UpBlock2D") , cross_attention_dim=32 , ) 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=6 , out_channels=6 , down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"] , up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"] , latent_channels=4 , ) 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 , ) 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, "safety_checker": None, "feature_extractor": None, } return components def _lowercase (self : Any , __a : str , __a : Any=0 ): 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", "generator": generator, "num_inference_steps": 2, "guidance_scale": 6.0, "output_type": "numpy", } return inputs def _lowercase (self : List[str] ): UpperCAmelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = StableDiffusionLDMaDPipeline(**__a ) UpperCAmelCase_ = ldmad_pipe.to(__a ) ldmad_pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_dummy_inputs(__a ) UpperCAmelCase_ = ldmad_pipe(**__a ) UpperCAmelCase_ , UpperCAmelCase_ = output.rgb, output.depth UpperCAmelCase_ = rgb[0, -3:, -3:, -1] UpperCAmelCase_ = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) UpperCAmelCase_ = np.array( [0.37_33_81_76, 0.7_02_47, 0.74_20_31_93, 0.51_64_36_04, 0.58_25_67_93, 0.60_93_21_36, 0.4_18_10_95, 0.48_35_58_77, 0.46_53_52_62] ) UpperCAmelCase_ = np.array([1_03.4_67_27, 85.81_20_04, 87.84_92_36] ) assert np.abs(image_slice_rgb.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(image_slice_depth.flatten() - expected_slice_depth ).max() < 1E-2 def _lowercase (self : Optional[int] ): UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = StableDiffusionLDMaDPipeline(**__a ) UpperCAmelCase_ = ldmad_pipe.to(__a ) ldmad_pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_dummy_inputs(__a ) UpperCAmelCase_ = 3 * [inputs["prompt"]] # forward UpperCAmelCase_ = ldmad_pipe(**__a ) UpperCAmelCase_ , UpperCAmelCase_ = output.rgb, output.depth UpperCAmelCase_ = rgb_slice_a[0, -3:, -3:, -1] UpperCAmelCase_ = depth_slice_a[0, -3:, -1] UpperCAmelCase_ = self.get_dummy_inputs(__a ) UpperCAmelCase_ = 3 * [inputs.pop("prompt" )] UpperCAmelCase_ = ldmad_pipe.tokenizer( __a , padding="max_length" , max_length=ldmad_pipe.tokenizer.model_max_length , truncation=__a , return_tensors="pt" , ) UpperCAmelCase_ = text_inputs["input_ids"].to(__a ) UpperCAmelCase_ = ldmad_pipe.text_encoder(__a )[0] UpperCAmelCase_ = prompt_embeds # forward UpperCAmelCase_ = ldmad_pipe(**__a ) UpperCAmelCase_ , UpperCAmelCase_ = output.rgb, output.depth UpperCAmelCase_ = rgb_slice_a[0, -3:, -3:, -1] UpperCAmelCase_ = depth_slice_a[0, -3:, -1] assert np.abs(rgb_slice_a.flatten() - rgb_slice_a.flatten() ).max() < 1E-4 assert np.abs(depth_slice_a.flatten() - depth_slice_a.flatten() ).max() < 1E-4 def _lowercase (self : Optional[Any] ): UpperCAmelCase_ = "cpu" # ensure determinism for the device-dependent torch.Generator UpperCAmelCase_ = self.get_dummy_components() UpperCAmelCase_ = PNDMScheduler(skip_prk_steps=__a ) UpperCAmelCase_ = StableDiffusionLDMaDPipeline(**__a ) UpperCAmelCase_ = ldmad_pipe.to(__a ) ldmad_pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_dummy_inputs(__a ) UpperCAmelCase_ = "french fries" UpperCAmelCase_ = ldmad_pipe(**__a , negative_prompt=__a ) UpperCAmelCase_ , UpperCAmelCase_ = output.rgb, output.depth UpperCAmelCase_ = rgb[0, -3:, -3:, -1] UpperCAmelCase_ = depth[0, -3:, -1] assert rgb.shape == (1, 64, 64, 3) assert depth.shape == (1, 64, 64) UpperCAmelCase_ = np.array( [0.3_70_44, 0.71_81_15_03, 0.7_22_32_51, 0.48_60_36_75, 0.5_63_83_91, 0.6_36_49_48, 0.42_83_37_04, 0.4_90_13_15, 0.47_92_62_17] ) UpperCAmelCase_ = np.array([1_07.8_47_38, 84.6_28_02, 89.96_21_35] ) assert np.abs(rgb_slice.flatten() - expected_slice_rgb ).max() < 1E-2 assert np.abs(depth_slice.flatten() - expected_slice_depth ).max() < 1E-2 @slow @require_torch_gpu class __A ( unittest.TestCase ): def _lowercase (self : str ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : Union[str, Any] , __a : List[Any] , __a : int="cpu" , __a : Dict=torch.floataa , __a : Dict=0 ): UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(__a ) UpperCAmelCase_ = np.random.RandomState(__a ).standard_normal((1, 4, 64, 64) ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a , dtype=__a ) UpperCAmelCase_ = { "prompt": "a photograph of an astronaut riding a horse", "latents": latents, "generator": generator, "num_inference_steps": 3, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def _lowercase (self : Tuple ): UpperCAmelCase_ = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" ) UpperCAmelCase_ = ldmad_pipe.to(__a ) ldmad_pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_inputs(__a ) UpperCAmelCase_ = ldmad_pipe(**__a ) UpperCAmelCase_ , UpperCAmelCase_ = output.rgb, output.depth UpperCAmelCase_ = rgb[0, -3:, -3:, -1].flatten() UpperCAmelCase_ = rgb[0, -3:, -1].flatten() assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512) UpperCAmelCase_ = np.array( [0.53_80_54_65, 0.56_70_73_05, 0.5_48_65_15, 0.57_01_22_36, 0.5_81_45_11, 0.56_25_34_87, 0.54_84_30_14, 0.55_09_22_63, 0.6_45_97_06] ) UpperCAmelCase_ = np.array( [0.9_26_37_81, 0.6_67_86_72, 0.5_48_65_15, 0.92_20_21_45, 0.67_83_11_35, 0.56_25_34_87, 0.9_24_16_94, 0.7_55_14_78, 0.6_45_97_06] ) assert np.abs(rgb_slice - expected_slice_rgb ).max() < 3E-3 assert np.abs(depth_slice - expected_slice_depth ).max() < 3E-3 @nightly @require_torch_gpu class __A ( unittest.TestCase ): def _lowercase (self : List[Any] ): super().tearDown() gc.collect() torch.cuda.empty_cache() def _lowercase (self : int , __a : Union[str, Any] , __a : List[str]="cpu" , __a : List[str]=torch.floataa , __a : Tuple=0 ): UpperCAmelCase_ = torch.Generator(device=__a ).manual_seed(__a ) UpperCAmelCase_ = np.random.RandomState(__a ).standard_normal((1, 4, 64, 64) ) UpperCAmelCase_ = torch.from_numpy(__a ).to(device=__a , dtype=__a ) UpperCAmelCase_ = { "prompt": "a photograph of an astronaut riding a horse", "latents": latents, "generator": generator, "num_inference_steps": 50, "guidance_scale": 7.5, "output_type": "numpy", } return inputs def _lowercase (self : Optional[int] ): UpperCAmelCase_ = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d" ).to(__a ) ldmad_pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_inputs(__a ) UpperCAmelCase_ = ldmad_pipe(**__a ) UpperCAmelCase_ , UpperCAmelCase_ = output.rgb, output.depth UpperCAmelCase_ = 0.49_55_86 UpperCAmelCase_ = 0.33_79_55_15 UpperCAmelCase_ = 1_12.4_85_18 UpperCAmelCase_ = 98.48_97_46 assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3 def _lowercase (self : Any ): UpperCAmelCase_ = StableDiffusionLDMaDPipeline.from_pretrained("Intel/ldm3d-4c" ).to(__a ) ldmad_pipe.set_progress_bar_config(disable=__a ) UpperCAmelCase_ = self.get_inputs(__a ) UpperCAmelCase_ = ldmad_pipe(**__a ) UpperCAmelCase_ , UpperCAmelCase_ = output.rgb, output.depth UpperCAmelCase_ = 0.4_19_41_27 UpperCAmelCase_ = 0.35_37_55_86 UpperCAmelCase_ = 0.5_63_85_02 UpperCAmelCase_ = 0.34_68_61_03 assert rgb.shape == (1, 512, 512, 3) assert depth.shape == (1, 512, 512, 1) assert np.abs(expected_rgb_mean - rgb.mean() ) < 1E-3 assert np.abs(expected_rgb_std - rgb.std() ) < 1E-3 assert np.abs(expected_depth_mean - depth.mean() ) < 1E-3 assert np.abs(expected_depth_std - depth.std() ) < 1E-3
1
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) SCREAMING_SNAKE_CASE :List[str] = 'pytorch_model.bin' SCREAMING_SNAKE_CASE :str = 'pytorch_model.bin.index.json' SCREAMING_SNAKE_CASE :Optional[int] = 'adapter_config.json' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.bin' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.safetensors' SCREAMING_SNAKE_CASE :str = 'tf_model.h5' SCREAMING_SNAKE_CASE :List[Any] = 'tf_model.h5.index.json' SCREAMING_SNAKE_CASE :str = 'model.ckpt' SCREAMING_SNAKE_CASE :List[Any] = 'flax_model.msgpack' SCREAMING_SNAKE_CASE :Optional[int] = 'flax_model.msgpack.index.json' SCREAMING_SNAKE_CASE :Tuple = 'model.safetensors' SCREAMING_SNAKE_CASE :List[Any] = 'model.safetensors.index.json' SCREAMING_SNAKE_CASE :str = 'config.json' SCREAMING_SNAKE_CASE :int = 'preprocessor_config.json' SCREAMING_SNAKE_CASE :Optional[Any] = FEATURE_EXTRACTOR_NAME SCREAMING_SNAKE_CASE :Optional[int] = 'generation_config.json' SCREAMING_SNAKE_CASE :List[str] = 'modelcard.json' SCREAMING_SNAKE_CASE :Optional[int] = '▁' SCREAMING_SNAKE_CASE :Optional[Any] = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility SCREAMING_SNAKE_CASE :str = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. SCREAMING_SNAKE_CASE :Optional[Any] = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] SCREAMING_SNAKE_CASE :List[Any] = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" if version.parse(a_ ) < version.parse(a_ ): if "dev" in min_version: __A = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: __A = F'''This example requires a minimum version of {min_version},''' error_message += F''' but the version found is {__version__}.\n''' raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers." )
15
0
'''simple docstring''' import json import os from pathlib import Path import pytest from datasets.download.download_config import DownloadConfig from datasets.download.download_manager import DownloadManager from datasets.utils.file_utils import hash_url_to_filename lowerCamelCase : Tuple = 'http://www.mocksite.com/file1.txt' lowerCamelCase : Union[str, Any] = '"text": ["foo", "foo"]' lowerCamelCase : Dict = '6d8ce9aa78a471c7477201efbeabd3bb01ac2e7d100a6dc024ba1608361f90a8' class __lowerCAmelCase : '''simple docstring''' lowerCAmelCase__ : Union[str, Any] = 200 lowerCAmelCase__ : str = {"""Content-Length""": """100"""} lowerCAmelCase__ : Optional[Any] = {} def UpperCamelCase__ (self : Tuple , **UpperCamelCase : int ): '''simple docstring''' return [bytes(UpperCamelCase , '''utf-8''' )] def _SCREAMING_SNAKE_CASE (*A , **A ) -> str: """simple docstring""" return MockResponse() @pytest.mark.parametrize('''urls_type''' , [str, list, dict] ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> List[str]: """simple docstring""" import requests monkeypatch.setattr(A , '''request''' , A ) lowercase__ = URL if issubclass(A , A ): lowercase__ = url elif issubclass(A , A ): lowercase__ = [url] elif issubclass(A , A ): lowercase__ = {'''train''': url} lowercase__ = '''dummy''' lowercase__ = '''downloads''' lowercase__ = tmp_path lowercase__ = DownloadConfig( cache_dir=os.path.join(A , A ) , use_etag=A , ) lowercase__ = DownloadManager(dataset_name=A , download_config=A ) lowercase__ = dl_manager.download(A ) lowercase__ = urls for downloaded_paths in [downloaded_paths]: if isinstance(A , A ): lowercase__ = [downloaded_paths] lowercase__ = [urls] elif isinstance(A , A ): assert "train" in downloaded_paths.keys() lowercase__ = downloaded_paths.values() lowercase__ = urls.values() assert downloaded_paths for downloaded_path, input_url in zip(A , A ): assert downloaded_path == dl_manager.downloaded_paths[input_url] lowercase__ = Path(A ) lowercase__ = downloaded_path.parts assert parts[-1] == HASH assert parts[-2] == cache_subdir assert downloaded_path.exists() lowercase__ = downloaded_path.read_text() assert content == CONTENT lowercase__ = downloaded_path.with_suffix('''.json''' ) assert metadata_downloaded_path.exists() lowercase__ = json.loads(metadata_downloaded_path.read_text() ) assert metadata_content == {"url": URL, "etag": None} @pytest.mark.parametrize('''paths_type''' , [str, list, dict] ) def _SCREAMING_SNAKE_CASE (A , A , A ) -> List[str]: """simple docstring""" lowercase__ = str(A ) if issubclass(A , A ): lowercase__ = filename elif issubclass(A , A ): lowercase__ = [filename] elif issubclass(A , A ): lowercase__ = {'''train''': filename} lowercase__ = '''dummy''' lowercase__ = xz_file.parent lowercase__ = '''extracted''' lowercase__ = DownloadConfig( cache_dir=A , use_etag=A , ) lowercase__ = DownloadManager(dataset_name=A , download_config=A ) lowercase__ = dl_manager.extract(A ) lowercase__ = paths for extracted_paths in [extracted_paths]: if isinstance(A , A ): lowercase__ = [extracted_paths] lowercase__ = [paths] elif isinstance(A , A ): assert "train" in extracted_paths.keys() lowercase__ = extracted_paths.values() lowercase__ = paths.values() assert extracted_paths for extracted_path, input_path in zip(A , A ): assert extracted_path == dl_manager.extracted_paths[input_path] lowercase__ = Path(A ) lowercase__ = extracted_path.parts assert parts[-1] == hash_url_to_filename(A , etag=A ) assert parts[-2] == extracted_subdir assert extracted_path.exists() lowercase__ = extracted_path.read_text() lowercase__ = text_file.read_text() assert extracted_file_content == expected_file_content def _SCREAMING_SNAKE_CASE (A , A ) -> Any: """simple docstring""" assert path.endswith('''.jsonl''' ) for num_items, line in enumerate(A , start=1 ): lowercase__ = json.loads(line.decode('''utf-8''' ) ) assert item.keys() == {"col_1", "col_2", "col_3"} assert num_items == 4 @pytest.mark.parametrize('''archive_jsonl''' , ['''tar_jsonl_path''', '''zip_jsonl_path'''] ) def _SCREAMING_SNAKE_CASE (A , A ) -> Any: """simple docstring""" lowercase__ = request.getfixturevalue(A ) lowercase__ = DownloadManager() for num_jsonl, (path, file) in enumerate(dl_manager.iter_archive(A ) , start=1 ): _test_jsonl(A , A ) assert num_jsonl == 2 @pytest.mark.parametrize('''archive_nested_jsonl''' , ['''tar_nested_jsonl_path''', '''zip_nested_jsonl_path'''] ) def _SCREAMING_SNAKE_CASE (A , A ) -> int: """simple docstring""" lowercase__ = request.getfixturevalue(A ) lowercase__ = DownloadManager() for num_tar, (path, file) in enumerate(dl_manager.iter_archive(A ) , start=1 ): for num_jsonl, (subpath, subfile) in enumerate(dl_manager.iter_archive(A ) , start=1 ): _test_jsonl(A , A ) assert num_tar == 1 assert num_jsonl == 2 def _SCREAMING_SNAKE_CASE (A ) -> Tuple: """simple docstring""" lowercase__ = DownloadManager() for num_file, file in enumerate(dl_manager.iter_files(A ) , start=1 ): assert os.path.basename(A ) == ("test.txt" if num_file == 1 else "train.txt") assert num_file == 2
2
def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = [0] * len(a_ ) __A = [] __A = [1] * len(a_ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(a_ ) ): if indegree[i] == 0: queue.append(a_ ) while queue: __A = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __A = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(a_ ) print(max(a_ ) ) # Adjacency list of Graph SCREAMING_SNAKE_CASE :List[Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
15
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowercase : Any = logging.get_logger(__name__) lowercase : int = { 'tiiuae/falcon-40b': 'https://huggingface.co/tiiuae/falcon-40b/resolve/main/config.json', 'tiiuae/falcon-7b': 'https://huggingface.co/tiiuae/falcon-7b/resolve/main/config.json', } class A ( __snake_case ): __magic_name__ = '''falcon''' __magic_name__ = ['''past_key_values'''] def __init__( self , SCREAMING_SNAKE_CASE=65024 , SCREAMING_SNAKE_CASE=4544 , SCREAMING_SNAKE_CASE=32 , SCREAMING_SNAKE_CASE=71 , SCREAMING_SNAKE_CASE=1e-5 , SCREAMING_SNAKE_CASE=0.02 , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=0.0 , SCREAMING_SNAKE_CASE=None , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=True , SCREAMING_SNAKE_CASE=False , SCREAMING_SNAKE_CASE=11 , SCREAMING_SNAKE_CASE=11 , **SCREAMING_SNAKE_CASE , ) -> Tuple: """simple docstring""" A : Tuple = vocab_size # Backward compatibility with n_embed kwarg A : Dict = kwargs.pop('''n_embed''' , SCREAMING_SNAKE_CASE ) A : int = hidden_size if n_embed is None else n_embed A : Dict = num_hidden_layers A : List[Any] = num_attention_heads A : Optional[Any] = layer_norm_epsilon A : List[Any] = initializer_range A : str = use_cache A : Optional[int] = hidden_dropout A : Union[str, Any] = attention_dropout A : Dict = bos_token_id A : List[Any] = eos_token_id A : List[str] = num_attention_heads if num_kv_heads is None else num_kv_heads A : int = alibi A : List[str] = new_decoder_architecture A : Union[str, Any] = multi_query # Ignored when new_decoder_architecture is True A : int = parallel_attn A : Union[str, Any] = bias super().__init__(bos_token_id=SCREAMING_SNAKE_CASE , eos_token_id=SCREAMING_SNAKE_CASE , **SCREAMING_SNAKE_CASE ) @property def __lowerCAmelCase ( self ) -> List[Any]: """simple docstring""" return self.hidden_size // self.num_attention_heads @property def __lowerCAmelCase ( self ) -> Tuple: """simple docstring""" return not self.alibi
3
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __A = key.replace("heads.cmd.mim_head.cls.predictions" , "mmm_image_head" ) __A = key.replace("heads.cmd.mlm_head.cls.predictions" , "mmm_text_head" ) __A = key.replace("heads.cmd.itm_head.cls" , "itm_head" ) __A = key.replace("heads.cmd.itm_head.pooler" , "itm_head.pooler" ) __A = key.replace("heads.cmd.clip_head.logit_scale" , "flava.logit_scale" ) __A = key.replace("heads.fairseq_mlm.cls.predictions" , "mlm_head" ) __A = key.replace("heads.imagenet.mim_head.cls.predictions" , "mim_head" ) __A = key.replace("mm_text_projection" , "flava.text_to_mm_projection" ) __A = key.replace("mm_image_projection" , "flava.image_to_mm_projection" ) __A = key.replace("image_encoder.module" , "flava.image_model" ) __A = key.replace("text_encoder.module" , "flava.text_model" ) __A = key.replace("mm_encoder.module.encoder.cls_token" , "flava.multimodal_model.cls_token" ) __A = key.replace("mm_encoder.module" , "flava.multimodal_model" ) __A = key.replace("text_projection" , "flava.text_projection" ) __A = key.replace("image_projection" , "flava.image_projection" ) __A = value.float() for key, value in codebook_state_dict.items(): __A = value return upgrade @torch.no_grad() def UpperCAmelCase ( a_ , a_ , a_ , a_=None ) -> Tuple: """simple docstring""" if config_path is not None: __A = FlavaConfig.from_pretrained(a_ ) else: __A = FlavaConfig() __A = FlavaForPreTraining(a_ ).eval() __A = convert_dalle_checkpoint(a_ , a_ , save_checkpoint=a_ ) if os.path.exists(a_ ): __A = torch.load(a_ , map_location="cpu" ) else: __A = torch.hub.load_state_dict_from_url(a_ , map_location="cpu" ) __A = upgrade_state_dict(a_ , a_ ) hf_model.load_state_dict(a_ ) __A = hf_model.state_dict() __A = count_parameters(a_ ) __A = count_parameters(a_ ) + count_parameters(a_ ) assert torch.allclose(a_ , a_ , atol=1E-3 ) hf_model.save_pretrained(a_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
15
0
'''simple docstring''' # Lint as: python3 import sys from collections.abc import Mapping from typing import TYPE_CHECKING, Dict, Optional import numpy as np import pyarrow as pa from .. import config from ..utils.logging import get_logger from ..utils.py_utils import map_nested from .formatting import TensorFormatter if TYPE_CHECKING: import jax import jaxlib __snake_case =get_logger() __snake_case =None class UpperCAmelCase_ ( TensorFormatter[Mapping, '''jax.Array''', Mapping] ): def __init__( self : Optional[int] , UpperCAmelCase__ : Union[str, Any]=None , UpperCAmelCase__ : List[Any]=None , **UpperCAmelCase__ : Dict ) -> int: super().__init__(features=UpperCAmelCase__ ) import jax from jaxlib.xla_client import Device if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ): raise ValueError( F'''Expected {device} to be a `str` not {type(UpperCAmelCase__ )}, as `jaxlib.xla_extension.Device` ''' 'is not serializable neither with `pickle` nor with `dill`. Instead you can surround ' 'the device with `str()` to get its string identifier that will be internally mapped ' 'to the actual `jaxlib.xla_extension.Device`.' ) lowerCAmelCase = device if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) else str(jax.devices()[0] ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: lowerCAmelCase = self._map_devices_to_str() if self.device not in list(DEVICE_MAPPING.keys() ): logger.warning( F'''Device with string identifier {self.device} not listed among the available ''' F'''devices: {list(DEVICE_MAPPING.keys() )}, so falling back to the default ''' F'''device: {str(jax.devices()[0] )}.''' ) lowerCAmelCase = str(jax.devices()[0] ) lowerCAmelCase = jnp_array_kwargs @staticmethod def __UpperCAmelCase ( ) -> Dict[str, "jaxlib.xla_extension.Device"]: import jax return {str(UpperCAmelCase__ ): device for device in jax.devices()} def __UpperCAmelCase ( self : Tuple , UpperCAmelCase__ : Optional[Any] ) -> List[Any]: import jax import jax.numpy as jnp if isinstance(UpperCAmelCase__ , UpperCAmelCase__ ) and column: if all( isinstance(UpperCAmelCase__ , jax.Array ) and x.shape == column[0].shape and x.dtype == column[0].dtype for x in column ): return jnp.stack(UpperCAmelCase__ , axis=0 ) return column def __UpperCAmelCase ( self : Any , UpperCAmelCase__ : Union[str, Any] ) -> List[Any]: import jax import jax.numpy as jnp if isinstance(UpperCAmelCase__ , (str, bytes, type(UpperCAmelCase__ )) ): return value elif isinstance(UpperCAmelCase__ , (np.character, np.ndarray) ) and np.issubdtype(value.dtype , np.character ): return value.tolist() lowerCAmelCase = {} if isinstance(UpperCAmelCase__ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.integer ): # the default int precision depends on the jax config # see https://jax.readthedocs.io/en/latest/notebooks/Common_Gotchas_in_JAX.html#double-64bit-precision if jax.config.jax_enable_xaa: lowerCAmelCase = {'dtype': jnp.intaa} else: lowerCAmelCase = {'dtype': jnp.intaa} elif isinstance(UpperCAmelCase__ , (np.number, np.ndarray) ) and np.issubdtype(value.dtype , np.floating ): lowerCAmelCase = {'dtype': jnp.floataa} elif config.PIL_AVAILABLE and "PIL" in sys.modules: import PIL.Image if isinstance(UpperCAmelCase__ , PIL.Image.Image ): lowerCAmelCase = np.asarray(UpperCAmelCase__ ) # using global variable since `jaxlib.xla_extension.Device` is not serializable neither # with `pickle` nor with `dill`, so we need to use a global variable instead global DEVICE_MAPPING if DEVICE_MAPPING is None: lowerCAmelCase = self._map_devices_to_str() with jax.default_device(DEVICE_MAPPING[self.device] ): # calling jnp.array on a np.ndarray does copy the data # see https://github.com/google/jax/issues/4486 return jnp.array(UpperCAmelCase__ , **{**default_dtype, **self.jnp_array_kwargs} ) def __UpperCAmelCase ( self : Union[str, Any] , UpperCAmelCase__ : Optional[int] ) -> str: import jax # support for torch, tf, jax etc. if config.TORCH_AVAILABLE and "torch" in sys.modules: import torch if isinstance(UpperCAmelCase__ , torch.Tensor ): return self._tensorize(data_struct.detach().cpu().numpy()[()] ) if hasattr(UpperCAmelCase__ , '__array__' ) and not isinstance(UpperCAmelCase__ , jax.Array ): lowerCAmelCase = data_struct.__array__() # support for nested types like struct of list of struct if isinstance(UpperCAmelCase__ , np.ndarray ): if data_struct.dtype == object: # jax arrays cannot be instantied from an array of objects return self._consolidate([self.recursive_tensorize(UpperCAmelCase__ ) for substruct in data_struct] ) elif isinstance(UpperCAmelCase__ , (list, tuple) ): return self._consolidate([self.recursive_tensorize(UpperCAmelCase__ ) for substruct in data_struct] ) return self._tensorize(UpperCAmelCase__ ) def __UpperCAmelCase ( self : List[str] , UpperCAmelCase__ : dict ) -> str: return map_nested(self._recursive_tensorize , UpperCAmelCase__ , map_list=UpperCAmelCase__ ) def __UpperCAmelCase ( self : Any , UpperCAmelCase__ : pa.Table ) -> Mapping: lowerCAmelCase = self.numpy_arrow_extractor().extract_row(UpperCAmelCase__ ) lowerCAmelCase = self.python_features_decoder.decode_row(UpperCAmelCase__ ) return self.recursive_tensorize(UpperCAmelCase__ ) def __UpperCAmelCase ( self : str , UpperCAmelCase__ : pa.Table ) -> "jax.Array": lowerCAmelCase = self.numpy_arrow_extractor().extract_column(UpperCAmelCase__ ) lowerCAmelCase = self.python_features_decoder.decode_column(UpperCAmelCase__ , pa_table.column_names[0] ) lowerCAmelCase = self.recursive_tensorize(UpperCAmelCase__ ) lowerCAmelCase = self._consolidate(UpperCAmelCase__ ) return column def __UpperCAmelCase ( self : Optional[int] , UpperCAmelCase__ : pa.Table ) -> Mapping: lowerCAmelCase = self.numpy_arrow_extractor().extract_batch(UpperCAmelCase__ ) lowerCAmelCase = self.python_features_decoder.decode_batch(UpperCAmelCase__ ) lowerCAmelCase = self.recursive_tensorize(UpperCAmelCase__ ) for column_name in batch: lowerCAmelCase = self._consolidate(batch[column_name] ) return batch
4
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Optional[int] = {'vocab_file': 'sentencepiece.bpe.model'} SCREAMING_SNAKE_CASE :Tuple = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', } } SCREAMING_SNAKE_CASE :List[Any] = { 'camembert-base': 512, } SCREAMING_SNAKE_CASE :List[str] = '▁' class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[Any] ,A : List[str] ,A : List[Any]="<s>" ,A : Tuple="</s>" ,A : Any="</s>" ,A : Optional[Any]="<s>" ,A : Tuple="<unk>" ,A : str="<pad>" ,A : int="<mask>" ,A : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] ,A : Optional[Dict[str, Any]] = None ,**A : Optional[Any] ,): # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,sep_token=A ,cls_token=A ,pad_token=A ,mask_token=A ,additional_special_tokens=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A ) ) __A = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> __A = {"<s>NOTUSED": 0, "<pad>": 1, "</s>NOTUSED": 2, "<unk>": 3} __A = len(self.fairseq_tokens_to_ids ) __A = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) __A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self : int ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : Dict ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Union[str, Any] ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self : Dict ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def UpperCamelCase_ ( self : int ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Dict ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(A ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : Tuple ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase_ ( self : Optional[Any] ,A : Dict ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def __getstate__( self : Dict ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Union[str, Any] ,A : Any ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,)
15
0
import json import os import shutil import sys import tempfile import unittest import unittest.mock as mock from pathlib import Path from huggingface_hub import HfFolder, delete_repo from requests.exceptions import HTTPError from transformers import AutoConfig, BertConfig, GPTaConfig from transformers.configuration_utils import PretrainedConfig from transformers.testing_utils import TOKEN, USER, is_staging_test sys.path.append(str(Path(__file__).parent.parent / '''utils''')) from test_module.custom_configuration import CustomConfig # noqa E402 UpperCAmelCase__ = { '''return_dict''': False, '''output_hidden_states''': True, '''output_attentions''': True, '''torchscript''': True, '''torch_dtype''': '''float16''', '''use_bfloat16''': True, '''tf_legacy_loss''': True, '''pruned_heads''': {'''a''': 1}, '''tie_word_embeddings''': False, '''is_decoder''': True, '''cross_attention_hidden_size''': 128, '''add_cross_attention''': True, '''tie_encoder_decoder''': True, '''max_length''': 50, '''min_length''': 3, '''do_sample''': True, '''early_stopping''': True, '''num_beams''': 3, '''num_beam_groups''': 3, '''diversity_penalty''': 0.5, '''temperature''': 2.0, '''top_k''': 10, '''top_p''': 0.7, '''typical_p''': 0.2, '''repetition_penalty''': 0.8, '''length_penalty''': 0.8, '''no_repeat_ngram_size''': 5, '''encoder_no_repeat_ngram_size''': 5, '''bad_words_ids''': [1, 2, 3], '''num_return_sequences''': 3, '''chunk_size_feed_forward''': 5, '''output_scores''': True, '''return_dict_in_generate''': True, '''forced_bos_token_id''': 2, '''forced_eos_token_id''': 3, '''remove_invalid_values''': True, '''architectures''': ['''BertModel'''], '''finetuning_task''': '''translation''', '''id2label''': {0: '''label'''}, '''label2id''': {'''label''': '''0'''}, '''tokenizer_class''': '''BertTokenizerFast''', '''prefix''': '''prefix''', '''bos_token_id''': 6, '''pad_token_id''': 7, '''eos_token_id''': 8, '''sep_token_id''': 9, '''decoder_start_token_id''': 10, '''exponential_decay_length_penalty''': (5, 1.01), '''suppress_tokens''': [0, 1], '''begin_suppress_tokens''': 2, '''task_specific_params''': {'''translation''': '''some_params'''}, '''problem_type''': '''regression''', } @is_staging_test class lowerCamelCase__ ( unittest.TestCase): @classmethod def __A (cls ) -> List[str]: _lowercase =TOKEN HfFolder.save_token(UpperCAmelCase ) @classmethod def __A (cls ) -> Dict: try: delete_repo(token=cls._token , repo_id='''test-config''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''valid_org/test-config-org''' ) except HTTPError: pass try: delete_repo(token=cls._token , repo_id='''test-dynamic-config''' ) except HTTPError: pass def __A (self ) -> Dict: _lowercase =BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) config.push_to_hub('''test-config''' , use_auth_token=self._token ) _lowercase =BertConfig.from_pretrained(f"{USER}/test-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='''test-config''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained(UpperCAmelCase , repo_id='''test-config''' , push_to_hub=UpperCAmelCase , use_auth_token=self._token ) _lowercase =BertConfig.from_pretrained(f"{USER}/test-config" ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) def __A (self ) -> Optional[Any]: _lowercase =BertConfig( vocab_size=9_9 , hidden_size=3_2 , num_hidden_layers=5 , num_attention_heads=4 , intermediate_size=3_7 ) config.push_to_hub('''valid_org/test-config-org''' , use_auth_token=self._token ) _lowercase =BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) # Reset repo delete_repo(token=self._token , repo_id='''valid_org/test-config-org''' ) # Push to hub via save_pretrained with tempfile.TemporaryDirectory() as tmp_dir: config.save_pretrained( UpperCAmelCase , repo_id='''valid_org/test-config-org''' , push_to_hub=UpperCAmelCase , use_auth_token=self._token ) _lowercase =BertConfig.from_pretrained('''valid_org/test-config-org''' ) for k, v in config.to_dict().items(): if k != "transformers_version": self.assertEqual(UpperCAmelCase , getattr(UpperCAmelCase , UpperCAmelCase ) ) def __A (self ) -> str: CustomConfig.register_for_auto_class() _lowercase =CustomConfig(attribute=4_2 ) config.push_to_hub('''test-dynamic-config''' , use_auth_token=self._token ) # This has added the proper auto_map field to the config self.assertDictEqual(config.auto_map , {'''AutoConfig''': '''custom_configuration.CustomConfig'''} ) _lowercase =AutoConfig.from_pretrained(f"{USER}/test-dynamic-config" , trust_remote_code=UpperCAmelCase ) # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module self.assertEqual(new_config.__class__.__name__ , '''CustomConfig''' ) self.assertEqual(new_config.attribute , 4_2 ) class lowerCamelCase__ ( unittest.TestCase): def __A (self ) -> Any: _lowercase =GPTaConfig() # attempt to modify each of int/float/bool/str config records and verify they were updated _lowercase =c.n_embd + 1 # int _lowercase =c.resid_pdrop + 1.0 # float _lowercase =not c.scale_attn_weights # bool _lowercase =c.summary_type + '''foo''' # str c.update_from_string( f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}" ) self.assertEqual(UpperCAmelCase , c.n_embd , '''mismatch for key: n_embd''' ) self.assertEqual(UpperCAmelCase , c.resid_pdrop , '''mismatch for key: resid_pdrop''' ) self.assertEqual(UpperCAmelCase , c.scale_attn_weights , '''mismatch for key: scale_attn_weights''' ) self.assertEqual(UpperCAmelCase , c.summary_type , '''mismatch for key: summary_type''' ) def __A (self ) -> Union[str, Any]: _lowercase =PretrainedConfig() _lowercase =[key for key in base_config.__dict__ if key not in config_common_kwargs] # If this part of the test fails, you have arguments to addin config_common_kwargs above. self.assertListEqual( UpperCAmelCase , ['''is_encoder_decoder''', '''_name_or_path''', '''_commit_hash''', '''transformers_version'''] ) _lowercase =[key for key, value in config_common_kwargs.items() if value == getattr(UpperCAmelCase , UpperCAmelCase )] if len(UpperCAmelCase ) > 0: raise ValueError( '''The following keys are set with the default values in''' ''' `test_configuration_common.config_common_kwargs` pick another value for them:''' f" {', '.join(UpperCAmelCase )}." ) def __A (self ) -> Optional[int]: with self.assertRaises(UpperCAmelCase ): # config is in subfolder, the following should not work without specifying the subfolder _lowercase =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' ) _lowercase =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert-subfolder''' , subfolder='''bert''' ) self.assertIsNotNone(UpperCAmelCase ) def __A (self ) -> List[str]: # A mock response for an HTTP head request to emulate server down _lowercase =mock.Mock() _lowercase =5_0_0 _lowercase ={} _lowercase =HTTPError _lowercase ={} # Download this model to make sure it's in the cache. _lowercase =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # Under the mock environment we get a 500 error when trying to reach the model. with mock.patch('''requests.Session.request''' , return_value=UpperCAmelCase ) as mock_head: _lowercase =BertConfig.from_pretrained('''hf-internal-testing/tiny-random-bert''' ) # This check we did call the fake head request mock_head.assert_called() def __A (self ) -> Union[str, Any]: # This test is for deprecated behavior and can be removed in v5 _lowercase =BertConfig.from_pretrained( '''https://huggingface.co/hf-internal-testing/tiny-random-bert/resolve/main/config.json''' ) def __A (self ) -> Any: _lowercase =AutoConfig.from_pretrained('''bert-base-cased''' ) _lowercase =['''config.4.0.0.json'''] with tempfile.TemporaryDirectory() as tmp_dir: configuration.save_pretrained(UpperCAmelCase ) _lowercase =2 json.dump(configuration.to_dict() , open(os.path.join(UpperCAmelCase , '''config.4.0.0.json''' ) , '''w''' ) ) # This should pick the new configuration file as the version of Transformers is > 4.0.0 _lowercase =AutoConfig.from_pretrained(UpperCAmelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # Will need to be adjusted if we reach v42 and this test is still here. # Should pick the old configuration file as the version of Transformers is < 4.42.0 _lowercase =['''config.42.0.0.json'''] _lowercase =7_6_8 configuration.save_pretrained(UpperCAmelCase ) shutil.move(os.path.join(UpperCAmelCase , '''config.4.0.0.json''' ) , os.path.join(UpperCAmelCase , '''config.42.0.0.json''' ) ) _lowercase =AutoConfig.from_pretrained(UpperCAmelCase ) self.assertEqual(new_configuration.hidden_size , 7_6_8 ) def __A (self ) -> List[Any]: # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. _lowercase ='''hf-internal-testing/test-two-configs''' import transformers as new_transformers _lowercase ='''v4.0.0''' _lowercase , _lowercase =new_transformers.models.auto.AutoConfig.from_pretrained( UpperCAmelCase , return_unused_kwargs=UpperCAmelCase ) self.assertEqual(new_configuration.hidden_size , 2 ) # This checks `_configuration_file` ia not kept in the kwargs by mistake. self.assertDictEqual(UpperCAmelCase , {} ) # Testing an older version by monkey-patching the version in the module it's used. import transformers as old_transformers _lowercase ='''v3.0.0''' _lowercase =old_transformers.models.auto.AutoConfig.from_pretrained(UpperCAmelCase ) self.assertEqual(old_configuration.hidden_size , 7_6_8 )
5
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return [tuple(a_ )] __A = [] def generate(a_ , a_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , a_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even __A , __A = arr[k - 1], arr[i] else: # k is odd __A , __A = arr[k - 1], arr[0] generate(k - 1 , a_ ) generate(len(a_ ) , a_ ) return res if __name__ == "__main__": SCREAMING_SNAKE_CASE :int = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :Dict = [int(item) for item in user_input.split(',')] print(heaps(arr))
15
0
import torch from diffusers import CMStochasticIterativeScheduler from .test_schedulers import SchedulerCommonTest class __A( a ): snake_case_ = (CMStochasticIterativeScheduler,) snake_case_ = 1_0 def SCREAMING_SNAKE_CASE_ ( self , **_snake_case ) -> List[str]: '''simple docstring''' __a = { '''num_train_timesteps''': 201, '''sigma_min''': 0.002, '''sigma_max''': 80.0, } config.update(**_snake_case ) return config def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = 10 __a = self.get_scheduler_config() __a = self.scheduler_classes[0](**_snake_case ) scheduler.set_timesteps(_snake_case ) __a = scheduler.timesteps[0] __a = scheduler.timesteps[1] __a = self.dummy_sample __a = 0.1 * sample __a = scheduler.step(_snake_case , _snake_case , _snake_case ).prev_sample __a = scheduler.step(_snake_case , _snake_case , _snake_case ).prev_sample self.assertEqual(output_a.shape , sample.shape ) self.assertEqual(output_a.shape , output_a.shape ) def SCREAMING_SNAKE_CASE_ ( self ) -> Union[str, Any]: '''simple docstring''' for timesteps in [10, 50, 100, 1_000]: self.check_over_configs(num_train_timesteps=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Tuple: '''simple docstring''' for clip_denoised in [True, False]: self.check_over_configs(clip_denoised=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Optional[Any]: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = 1 scheduler.set_timesteps(_snake_case ) __a = scheduler.timesteps __a = torch.manual_seed(0 ) __a = self.dummy_model() __a = self.dummy_sample_deter * scheduler.init_noise_sigma for i, t in enumerate(_snake_case ): # 1. scale model input __a = scheduler.scale_model_input(_snake_case , _snake_case ) # 2. predict noise residual __a = model(_snake_case , _snake_case ) # 3. predict previous sample x_t-1 __a = scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_snake_case ) ) __a = torch.mean(torch.abs(_snake_case ) ) assert abs(result_sum.item() - 192.7614 ) < 1E-2 assert abs(result_mean.item() - 0.2510 ) < 1E-3 def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = [106, 0] scheduler.set_timesteps(timesteps=_snake_case ) __a = scheduler.timesteps __a = torch.manual_seed(0 ) __a = self.dummy_model() __a = self.dummy_sample_deter * scheduler.init_noise_sigma for t in timesteps: # 1. scale model input __a = scheduler.scale_model_input(_snake_case , _snake_case ) # 2. predict noise residual __a = model(_snake_case , _snake_case ) # 3. predict previous sample x_t-1 __a = scheduler.step(_snake_case , _snake_case , _snake_case , generator=_snake_case ).prev_sample __a = pred_prev_sample __a = torch.sum(torch.abs(_snake_case ) ) __a = torch.mean(torch.abs(_snake_case ) ) assert abs(result_sum.item() - 347.6357 ) < 1E-2 assert abs(result_mean.item() - 0.4527 ) < 1E-3 def SCREAMING_SNAKE_CASE_ ( self ) -> str: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = [39, 30, 12, 15, 0] with self.assertRaises(_snake_case , msg='''`timesteps` must be in descending order.''' ): scheduler.set_timesteps(timesteps=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> Any: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = [39, 30, 12, 1, 0] __a = len(_snake_case ) with self.assertRaises(_snake_case , msg='''Can only pass one of `num_inference_steps` or `timesteps`.''' ): scheduler.set_timesteps(num_inference_steps=_snake_case , timesteps=_snake_case ) def SCREAMING_SNAKE_CASE_ ( self ) -> List[str]: '''simple docstring''' __a = self.scheduler_classes[0] __a = self.get_scheduler_config() __a = scheduler_class(**_snake_case ) __a = [scheduler.config.num_train_timesteps] with self.assertRaises( _snake_case , msg='''`timesteps` must start before `self.config.train_timesteps`: {scheduler.config.num_train_timesteps}}''' , ): scheduler.set_timesteps(timesteps=_snake_case )
6
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return lst __A = 1 while i < len(a_ ): if lst[i - 1] <= lst[i]: i += 1 else: __A , __A = lst[i], lst[i - 1] i -= 1 if i == 0: __A = 1 return lst if __name__ == "__main__": SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :List[Any] = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
15
0
import json import os import shutil import tempfile from unittest import TestCase from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast from transformers.models.bart.configuration_bart import BartConfig from transformers.models.bert.tokenization_bert import VOCAB_FILES_NAMES as DPR_VOCAB_FILES_NAMES from transformers.models.dpr.configuration_dpr import DPRConfig from transformers.models.roberta.tokenization_roberta import VOCAB_FILES_NAMES as BART_VOCAB_FILES_NAMES from transformers.testing_utils import require_faiss, require_tokenizers, require_torch, slow from transformers.utils import is_datasets_available, is_faiss_available, is_torch_available if is_torch_available() and is_datasets_available() and is_faiss_available(): from transformers.models.rag.configuration_rag import RagConfig from transformers.models.rag.tokenization_rag import RagTokenizer @require_faiss @require_torch class A ( _UpperCAmelCase ): """simple docstring""" def snake_case__ ( self : List[Any] )-> int: '''simple docstring''' A__ = tempfile.mkdtemp() A__ = 8 # DPR tok A__ = [ '[UNK]', '[CLS]', '[SEP]', '[PAD]', '[MASK]', 'want', '##want', '##ed', 'wa', 'un', 'runn', '##ing', ',', 'low', 'lowest', ] A__ = os.path.join(self.tmpdirname,'dpr_tokenizer' ) os.makedirs(lowercase_,exist_ok=lowercase_ ) A__ = os.path.join(lowercase_,DPR_VOCAB_FILES_NAMES['vocab_file'] ) with open(self.vocab_file,'w',encoding='utf-8' ) as vocab_writer: vocab_writer.write(''.join([x + '\n' for x in vocab_tokens] ) ) # BART tok A__ = [ 'l', 'o', 'w', 'e', 'r', 's', 't', 'i', 'd', 'n', '\u0120', '\u0120l', '\u0120n', '\u0120lo', '\u0120low', 'er', '\u0120lowest', '\u0120newer', '\u0120wider', '<unk>', ] A__ = dict(zip(lowercase_,range(len(lowercase_ ) ) ) ) A__ = ['#version: 0.2', '\u0120 l', '\u0120l o', '\u0120lo w', 'e r', ''] A__ = {'unk_token': '<unk>'} A__ = os.path.join(self.tmpdirname,'bart_tokenizer' ) os.makedirs(lowercase_,exist_ok=lowercase_ ) A__ = os.path.join(lowercase_,BART_VOCAB_FILES_NAMES['vocab_file'] ) A__ = os.path.join(lowercase_,BART_VOCAB_FILES_NAMES['merges_file'] ) with open(self.vocab_file,'w',encoding='utf-8' ) as fp: fp.write(json.dumps(lowercase_ ) + '\n' ) with open(self.merges_file,'w',encoding='utf-8' ) as fp: fp.write('\n'.join(lowercase_ ) ) def snake_case__ ( self : List[str] )-> DPRQuestionEncoderTokenizer: '''simple docstring''' return DPRQuestionEncoderTokenizer.from_pretrained(os.path.join(self.tmpdirname,'dpr_tokenizer' ) ) def snake_case__ ( self : List[Any] )-> BartTokenizer: '''simple docstring''' return BartTokenizer.from_pretrained(os.path.join(self.tmpdirname,'bart_tokenizer' ) ) def snake_case__ ( self : List[str] )-> List[str]: '''simple docstring''' shutil.rmtree(self.tmpdirname ) @require_tokenizers def snake_case__ ( self : str )-> Any: '''simple docstring''' A__ = os.path.join(self.tmpdirname,'rag_tokenizer' ) A__ = RagConfig(question_encoder=DPRConfig().to_dict(),generator=BartConfig().to_dict() ) A__ = RagTokenizer(question_encoder=self.get_dpr_tokenizer(),generator=self.get_bart_tokenizer() ) rag_config.save_pretrained(lowercase_ ) rag_tokenizer.save_pretrained(lowercase_ ) A__ = RagTokenizer.from_pretrained(lowercase_,config=lowercase_ ) self.assertIsInstance(new_rag_tokenizer.question_encoder,lowercase_ ) self.assertEqual(new_rag_tokenizer.question_encoder.get_vocab(),rag_tokenizer.question_encoder.get_vocab() ) self.assertIsInstance(new_rag_tokenizer.generator,lowercase_ ) self.assertEqual(new_rag_tokenizer.generator.get_vocab(),rag_tokenizer.generator.get_vocab() ) @slow def snake_case__ ( self : Optional[int] )-> Union[str, Any]: '''simple docstring''' A__ = RagTokenizer.from_pretrained('facebook/rag-token-nq' ) A__ = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] A__ = tokenizer(lowercase_ ) self.assertIsNotNone(lowercase_ ) @slow def snake_case__ ( self : Optional[Any] )-> Dict: '''simple docstring''' A__ = RagTokenizer.from_pretrained('facebook/rag-sequence-nq' ) A__ = [ 'who got the first nobel prize in physics', 'when is the next deadpool movie being released', 'which mode is used for short wave broadcast service', 'who is the owner of reading football club', 'when is the next scandal episode coming out', 'when is the last time the philadelphia won the superbowl', 'what is the most current adobe flash player version', 'how many episodes are there in dragon ball z', 'what is the first step in the evolution of the eye', 'where is gall bladder situated in human body', 'what is the main mineral in lithium batteries', 'who is the president of usa right now', 'where do the greasers live in the outsiders', 'panda is a national animal of which country', 'what is the name of manchester united stadium', ] A__ = tokenizer(lowercase_ ) self.assertIsNotNone(lowercase_ )
7
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 snake_case_ = 42 snake_case_ = None class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 2 @register_to_config def __init__( self : str ,A : float = 0.02 ,A : float = 1_00 ,A : float = 1.0_07 ,A : float = 80 ,A : float = 0.05 ,A : float = 50 ,): # standard deviation of the initial noise distribution __A = sigma_max # setable values __A = None __A = None __A = None # sigma(t_i) def UpperCamelCase_ ( self : str ,A : torch.FloatTensor ,A : Optional[int] = None ): return sample def UpperCamelCase_ ( self : Dict ,A : int ,A : Union[str, torch.device] = None ): __A = num_inference_steps __A = np.arange(0 ,self.num_inference_steps )[::-1].copy() __A = torch.from_numpy(A ).to(A ) __A = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __A = torch.tensor(A ,dtype=torch.floataa ,device=A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : torch.FloatTensor ,A : float ,A : Optional[torch.Generator] = None ): if self.config.s_min <= sigma <= self.config.s_max: __A = min(self.config.s_churn / self.num_inference_steps ,2**0.5 - 1 ) else: __A = 0 # sample eps ~ N(0, S_noise^2 * I) __A = self.config.s_noise * randn_tensor(sample.shape ,generator=A ).to(sample.device ) __A = sigma + gamma * sigma __A = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase_ ( self : Dict ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_hat + sigma_hat * model_output __A = (sample_hat - pred_original_sample) / sigma_hat __A = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : Optional[int] ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_prev + sigma_prev * model_output __A = (sample_prev - pred_original_sample) / sigma_prev __A = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : List[Any] ,A : Dict ,A : List[str] ,A : str ): raise NotImplementedError()
15
0
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 lowerCAmelCase_ = get_tests_dir('''fixtures/test_sentencepiece.model''') @require_sentencepiece @require_tokenizers class snake_case_ ( __A , unittest.TestCase ): '''simple docstring''' SCREAMING_SNAKE_CASE : Optional[int] = ReformerTokenizer SCREAMING_SNAKE_CASE : int = ReformerTokenizerFast SCREAMING_SNAKE_CASE : int = True SCREAMING_SNAKE_CASE : Optional[Any] = False SCREAMING_SNAKE_CASE : str = True def snake_case__( self : Dict ) ->List[str]: super().setUp() snake_case_ = ReformerTokenizer(_UpperCamelCase , keep_accents=_UpperCamelCase ) tokenizer.save_pretrained(self.tmpdirname ) def snake_case__( self : Optional[Any] ) ->int: snake_case_ = '''<s>''' snake_case_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(_UpperCamelCase ) , _UpperCamelCase ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(_UpperCamelCase ) , _UpperCamelCase ) def snake_case__( self : Optional[Any] ) ->Dict: snake_case_ = 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(_UpperCamelCase ) , 1_0_0_0 ) def snake_case__( self : Union[str, Any] ) ->Dict: self.assertEqual(self.get_tokenizer().vocab_size , 1_0_0_0 ) def snake_case__( self : List[Any] ) ->str: if not self.test_rust_tokenizer: return snake_case_ = self.get_tokenizer() snake_case_ = self.get_rust_tokenizer() snake_case_ = '''I was born in 92000, and this is falsé.''' snake_case_ = tokenizer.tokenize(_UpperCamelCase ) snake_case_ = rust_tokenizer.tokenize(_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) snake_case_ = tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase ) snake_case_ = rust_tokenizer.encode(_UpperCamelCase , add_special_tokens=_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) snake_case_ = self.get_rust_tokenizer() snake_case_ = tokenizer.encode(_UpperCamelCase ) snake_case_ = rust_tokenizer.encode(_UpperCamelCase ) self.assertListEqual(_UpperCamelCase , _UpperCamelCase ) def snake_case__( self : Optional[int] , _UpperCamelCase : Tuple=1_5 ) ->Tuple: for tokenizer, pretrained_name, kwargs in self.tokenizers_list: with self.subTest(f'''{tokenizer.__class__.__name__} ({pretrained_name})''' ): snake_case_ = self.rust_tokenizer_class.from_pretrained(_UpperCamelCase , **_UpperCamelCase ) # Simple input snake_case_ = '''This is a simple input''' snake_case_ = ['''This is a simple input 1''', '''This is a simple input 2'''] snake_case_ = ('''This is a simple input''', '''This is a pair''') snake_case_ = [ ('''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(_UpperCamelCase , tokenizer_r.encode , _UpperCamelCase , max_length=_UpperCamelCase , padding='''max_length''' ) # Simple input self.assertRaises(_UpperCamelCase , tokenizer_r.encode_plus , _UpperCamelCase , max_length=_UpperCamelCase , padding='''max_length''' ) # Simple input self.assertRaises( _UpperCamelCase , tokenizer_r.batch_encode_plus , _UpperCamelCase , max_length=_UpperCamelCase , padding='''max_length''' , ) # Pair input self.assertRaises(_UpperCamelCase , tokenizer_r.encode , _UpperCamelCase , max_length=_UpperCamelCase , padding='''max_length''' ) # Pair input self.assertRaises(_UpperCamelCase , tokenizer_r.encode_plus , _UpperCamelCase , max_length=_UpperCamelCase , padding='''max_length''' ) # Pair input self.assertRaises( _UpperCamelCase , tokenizer_r.batch_encode_plus , _UpperCamelCase , max_length=_UpperCamelCase , padding='''max_length''' , ) def snake_case__( self : Dict ) ->int: pass def snake_case__( self : Dict ) ->str: snake_case_ = ReformerTokenizer(_UpperCamelCase , keep_accents=_UpperCamelCase ) snake_case_ = tokenizer.tokenize('''This is a test''' ) self.assertListEqual(_UpperCamelCase , ['''▁This''', '''▁is''', '''▁a''', '''▁t''', '''est'''] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(_UpperCamelCase ) , [2_8_5, 4_6, 1_0, 1_7_0, 3_8_2] , ) snake_case_ = tokenizer.tokenize('''I was born in 92000, and this is falsé.''' ) self.assertListEqual( _UpperCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''9''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''é''', '''.''', ] , ) snake_case_ = tokenizer.convert_tokens_to_ids(_UpperCamelCase ) self.assertListEqual( _UpperCamelCase , [8, 2_1, 8_4, 5_5, 2_4, 1_9, 7, 0, 6_0_2, 3_4_7, 3_4_7, 3_4_7, 3, 1_2, 6_6, 4_6, 7_2, 8_0, 6, 0, 4] , ) snake_case_ = tokenizer.convert_ids_to_tokens(_UpperCamelCase ) self.assertListEqual( _UpperCamelCase , [ SPIECE_UNDERLINE + '''I''', SPIECE_UNDERLINE + '''was''', SPIECE_UNDERLINE + '''b''', '''or''', '''n''', SPIECE_UNDERLINE + '''in''', SPIECE_UNDERLINE + '''''', '''<unk>''', '''2''', '''0''', '''0''', '''0''', ''',''', SPIECE_UNDERLINE + '''and''', SPIECE_UNDERLINE + '''this''', SPIECE_UNDERLINE + '''is''', SPIECE_UNDERLINE + '''f''', '''al''', '''s''', '''<unk>''', '''.''', ] , ) @cached_property def snake_case__( self : Optional[int] ) ->Tuple: return ReformerTokenizer.from_pretrained('''google/reformer-crime-and-punishment''' ) @slow def snake_case__( self : Optional[Any] ) ->int: snake_case_ = '''Hello World!''' snake_case_ = [1_2_6, 3_2, 2_6_2, 1_5_2, 3_8, 7_2, 2_8_7] self.assertListEqual(_UpperCamelCase , self.big_tokenizer.encode(_UpperCamelCase ) ) @slow def snake_case__( self : str ) ->str: snake_case_ = ( '''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''' ) snake_case_ = [ 1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 3_5, 2_8, 2_7_5, 3, 2_5_9, 2_9_7, 2_6_0, 8_4, 4, 3_5, 1_1_0, 4_4, 8, 2_5_9, 9_1, 2_6_8, 2_1, 1_1, 2_0_9, 2_7_4, 1_0_9, 2_6_6, 2_7_7, 1_1_7, 8_6, 9_3, 3_1_5, 2_5_8, 2_7_8, 2_5_8, 2_7_7, 2_5_8, 0, 2_5_8, 2_8_8, 2_5_8, 3_1_9, 2_5_8, 0, 2_5_8, 0, 2_5_8, 0, 2_5_8, 0, 2_5_8, 2_8_7, 2_5_8, 3_1_5, 2_5_8, 2_8_9, 2_5_8, 2_7_8, 9_9, 2_6_9, 2_6_6, 2_6_2, 8, 2_5_9, 2_4_1, 4, 2_1_7, 2_3_0, 2_6_8, 2_6_6, 5_5, 1_6_8, 1_0_6, 7_5, 1_9_3, 2_6_6, 2_2_3, 2_7, 4_9, 2_6, 2_8_2, 2_5, 2_6_4, 2_9_9, 1_9, 2_6, 0, 2_5_8, 2_7_7, 1_1_7, 8_6, 9_3, 1_7_6, 1_8_3, 2_7_0, 1_1, 2_6_2, 4_2, 6_1, 2_6_5, ] self.assertListEqual(_UpperCamelCase , self.big_tokenizer.encode(_UpperCamelCase ) ) @require_torch @slow def snake_case__( self : List[str] ) ->List[str]: import torch from transformers import ReformerConfig, ReformerModel # Build sequence snake_case_ = list(self.big_tokenizer.get_vocab().keys() )[:1_0] snake_case_ = ''' '''.join(_UpperCamelCase ) snake_case_ = self.big_tokenizer.encode_plus(_UpperCamelCase , return_tensors='''pt''' ) snake_case_ = self.big_tokenizer.batch_encode_plus([sequence, sequence] , return_tensors='''pt''' ) snake_case_ = ReformerConfig() # The input gets padded during training so adjust the axial position encodings from the pretrained model value of (512, 1024) snake_case_ = encoded_sequence['''input_ids'''].shape snake_case_ = ReformerModel(_UpperCamelCase ) # 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(**_UpperCamelCase ) model(**_UpperCamelCase ) @slow def snake_case__( self : List[Any] ) ->Dict: # fmt: off snake_case_ = {'''input_ids''': [[1_0_8, 2_6_5, 2_4, 1_1_1, 4, 2_5_8, 1_5_6, 7, 5_1, 2_7_9, 5_8, 7, 7_6, 2_5, 6_9, 2_7_8], [1_4_0, 2_4_3, 2_6_4, 1_3_4, 1_7, 2_6_7, 7_7, 2_6_3, 2_2, 2_6_2, 2_9_7, 2_5_8, 3_0_4, 1_7_7, 2_7_9, 2_6_6, 1_4, 8_9, 1_3, 3_5, 2_6_1, 2_9_9, 2_7_2, 1_3_7, 2_7_5, 2_7_8]], '''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 snake_case_ = [ '''This is a very simple sentence.''', '''The quick brown fox jumps over the lazy dog.''', ] self.tokenizer_integration_test_util( expected_encoding=_UpperCamelCase , model_name='''google/reformer-crime-and-punishment''' , revision='''0e6c3decb8211d49bf881013425dc8b0448b3f5a''' , padding=_UpperCamelCase , sequences=_UpperCamelCase , )
8
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version SCREAMING_SNAKE_CASE :Union[str, Any] = get_logger(__name__) class UpperCAmelCase : '''simple docstring''' snake_case_ = "dummy_data" snake_case_ = "datasets" snake_case_ = False def __init__( self : Optional[int] ,A : str ,A : str ,A : Union[Version, str] ,A : Optional[str] = None ,A : bool = False ,A : bool = True ,A : Optional[List[Callable]] = None ,): __A = 0 __A = dataset_name __A = cache_dir __A = use_local_dummy_data __A = config # download_callbacks take a single url as input __A = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __A = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __A = str(A ) # to be downloaded __A = None __A = None @property def UpperCamelCase_ ( self : Union[str, Any] ): if self._dummy_file is None: __A = self.download_dummy_data() return self._dummy_file @property def UpperCamelCase_ ( self : Optional[Any] ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" ,self.config.name ,self.version_name ) # structure is dummy / version_name return os.path.join("dummy" ,self.version_name ) @property def UpperCamelCase_ ( self : List[Any] ): return os.path.join(self.dummy_data_folder ,"dummy_data.zip" ) def UpperCamelCase_ ( self : Tuple ): __A = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __A = cached_path( A ,cache_dir=self.cache_dir ,extract_compressed_file=A ,force_extract=A ) return os.path.join(A ,self.dummy_file_name ) @property def UpperCamelCase_ ( self : str ): return os.path.join(self.datasets_scripts_dir ,self.dataset_name ,self.dummy_zip_file ) @property def UpperCamelCase_ ( self : Any ): if self._bucket_url is None: __A = hf_github_url(self.dataset_name ,self.dummy_zip_file.replace(os.sep ,"/" ) ) return self._bucket_url @property def UpperCamelCase_ ( self : Tuple ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep ,"/" ).split("/" )[:-1] ) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,*A : Dict ): if self.load_existing_dummy_data: # dummy data is downloaded and tested __A = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __A = self.dummy_file_name # special case when data_url is a dict if isinstance(A ,A ): return self.create_dummy_data_dict(A ,A ) elif isinstance(A ,(list, tuple) ): return self.create_dummy_data_list(A ,A ) else: return self.create_dummy_data_single(A ,A ) def UpperCamelCase_ ( self : str ,A : List[Any] ,*A : List[Any] ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : List[str] ,A : List[str] ,A : Tuple ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : Any ,A : Any ,*A : Optional[Any] ,**A : List[str] ): return path def UpperCamelCase_ ( self : str ): return {} def UpperCamelCase_ ( self : int ,A : int ,A : Tuple ): __A = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A ,A ): for single_url in single_urls: download_callback(A ) else: __A = single_urls download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A ,A ): __A = [os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) for x in single_urls] else: __A = single_urls __A = os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) __A = value # make sure that values are unique if all(isinstance(A ,A ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __A = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,A : str ): __A = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __A = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" ,A ) ) for url in data_url ) __A = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __A = [data_url[0]] * len(A ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(A ) return dummy_data_list def UpperCamelCase_ ( self : str ,A : List[Any] ,A : Optional[Any] ): for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(A ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : Dict ): pass def UpperCamelCase_ ( self : Optional[Any] ,A : List[Any] ): def _iter_archive_members(A : Optional[Any] ): # this preserves the order of the members inside the ZIP archive __A = Path(self.dummy_file ).parent __A = path.relative_to(A ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __A = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A ) __A = Path(A ) __A = _iter_archive_members(A ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(A ).as_posix(), file_path.open("rb" ) def UpperCamelCase_ ( self : List[Any] ,A : Any ): if not isinstance(A ,A ): __A = [paths] for path in paths: if os.path.isfile(A ): if os.path.basename(A ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(A ): if os.path.basename(A ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(A ): if filename.startswith((".", "__") ): continue yield os.path.join(A ,A )
15
0
def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : Union[str, Any] = set() # edges = list of graph's edges __SCREAMING_SNAKE_CASE : List[str] = get_edges(lowercase__ ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE : int = edges.pop() chosen_vertices.add(lowercase__ ) chosen_vertices.add(lowercase__ ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(lowercase__ ) return chosen_vertices def _UpperCamelCase ( lowercase__ ): __SCREAMING_SNAKE_CASE : Optional[int] = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
9
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE :List[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :List[str] = ['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 :Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
15
0
import copy from typing import Dict, Optional from ...configuration_utils import PretrainedConfig from ...utils import logging from ..auto import CONFIG_MAPPING from ..detr import DetrConfig from ..swin import SwinConfig __A = { "facebook/maskformer-swin-base-ade": ( "https://huggingface.co/facebook/maskformer-swin-base-ade/blob/main/config.json" ) # See all MaskFormer models at https://huggingface.co/models?filter=maskformer } __A = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' lowercase_ = "maskformer" lowercase_ = {"hidden_size": "mask_feature_size"} lowercase_ = ["resnet", "swin"] lowercase_ = ["detr"] def __init__(self : Optional[int] , UpperCAmelCase_ : int = 256 , UpperCAmelCase_ : int = 256 , UpperCAmelCase_ : float = 0.1 , UpperCAmelCase_ : bool = False , UpperCAmelCase_ : Optional[Dict] = None , UpperCAmelCase_ : Optional[Dict] = None , UpperCAmelCase_ : float = 0.02 , UpperCAmelCase_ : float = 1.0 , UpperCAmelCase_ : float = 1.0 , UpperCAmelCase_ : float = 1.0 , UpperCAmelCase_ : float = 20.0 , UpperCAmelCase_ : Optional[bool] = None , **UpperCAmelCase_ : Optional[Any] , ) ->str: '''simple docstring''' if backbone_config is None: # fall back to https://huggingface.co/microsoft/swin-base-patch4-window12-384-in22k lowerCamelCase__: Any =SwinConfig( image_size=384 , in_channels=3 , patch_size=4 , embed_dim=128 , depths=[2, 2, 18, 2] , num_heads=[4, 8, 16, 32] , window_size=12 , drop_path_rate=0.3 , out_features=["stage1", "stage2", "stage3", "stage4"] , ) if isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: List[str] =backbone_config.pop("model_type") lowerCamelCase__: int =CONFIG_MAPPING[backbone_model_type] lowerCamelCase__: List[Any] =config_class.from_dict(UpperCAmelCase_) # verify that the backbone is supported if backbone_config.model_type not in self.backbones_supported: logger.warning_once( F"""Backbone {backbone_config.model_type} is not a supported model and may not be compatible with MaskFormer. """ F"""Supported model types: {",".join(self.backbones_supported)}""") if decoder_config is None: # fall back to https://huggingface.co/facebook/detr-resnet-50 lowerCamelCase__: Tuple =DetrConfig() else: # verify that the decoder is supported lowerCamelCase__: Any =( decoder_config.pop("model_type") if isinstance(UpperCAmelCase_ , UpperCAmelCase_) else decoder_config.model_type ) if decoder_type not in self.decoders_supported: raise ValueError( F"""Transformer Decoder {decoder_type} not supported, please use one of""" F""" {",".join(self.decoders_supported)}""") if isinstance(UpperCAmelCase_ , UpperCAmelCase_): lowerCamelCase__: Union[str, Any] =CONFIG_MAPPING[decoder_type] lowerCamelCase__: List[Any] =config_class.from_dict(UpperCAmelCase_) lowerCamelCase__: List[str] =backbone_config lowerCamelCase__: Dict =decoder_config # main feature dimension for the model lowerCamelCase__: Any =fpn_feature_size lowerCamelCase__: Optional[int] =mask_feature_size # initializer lowerCamelCase__: Union[str, Any] =init_std lowerCamelCase__: str =init_xavier_std # Hungarian matcher && loss lowerCamelCase__: Tuple =cross_entropy_weight lowerCamelCase__: Union[str, Any] =dice_weight lowerCamelCase__: List[str] =mask_weight lowerCamelCase__: List[str] =use_auxiliary_loss lowerCamelCase__: List[str] =no_object_weight lowerCamelCase__: Dict =output_auxiliary_logits lowerCamelCase__: Any =self.decoder_config.encoder_attention_heads lowerCamelCase__: List[Any] =self.decoder_config.num_hidden_layers super().__init__(**UpperCAmelCase_) @classmethod def SCREAMING_SNAKE_CASE_ (cls : List[str] , UpperCAmelCase_ : PretrainedConfig , UpperCAmelCase_ : PretrainedConfig , **UpperCAmelCase_ : List[str]) ->int: '''simple docstring''' return cls( backbone_config=UpperCAmelCase_ , decoder_config=UpperCAmelCase_ , **UpperCAmelCase_ , ) def SCREAMING_SNAKE_CASE_ (self : List[str]) ->Dict[str, any]: '''simple docstring''' lowerCamelCase__: Union[str, Any] =copy.deepcopy(self.__dict__) lowerCamelCase__: Any =self.backbone_config.to_dict() lowerCamelCase__: Any =self.decoder_config.to_dict() lowerCamelCase__: List[str] =self.__class__.model_type return output
10
from typing import Dict, Optional import numpy as np import datasets SCREAMING_SNAKE_CASE :List[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' SCREAMING_SNAKE_CASE :List[str] = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' SCREAMING_SNAKE_CASE :str = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Tuple: """simple docstring""" if label_map is not None: for old_id, new_id in label_map.items(): __A = new_id # turn into Numpy arrays __A = np.array(a_ ) __A = np.array(a_ ) if reduce_labels: __A = 2_5_5 __A = label - 1 __A = 2_5_5 __A = label != ignore_index __A = np.not_equal(a_ , a_ ) __A = pred_label[mask] __A = np.array(a_ )[mask] __A = pred_label[pred_label == label] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Union[str, Any]: """simple docstring""" __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(a_ , a_ ): __A , __A , __A , __A = intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = None , a_ = False , ) -> str: """simple docstring""" __A , __A , __A , __A = total_intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) # compute metrics __A = {} __A = total_area_intersect.sum() / total_area_label.sum() __A = total_area_intersect / total_area_union __A = total_area_intersect / total_area_label __A = np.nanmean(a_ ) __A = np.nanmean(a_ ) __A = all_acc __A = iou __A = acc if nan_to_num is not None: __A = {metric: np.nan_to_num(a_ , nan=a_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), } ) ,reference_urls=[ "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py" ] ,) def UpperCamelCase_ ( self : int ,A : Optional[Any] ,A : Optional[Any] ,A : int ,A : bool ,A : Optional[int] = None ,A : Optional[Dict[int, int]] = None ,A : bool = False ,): __A = mean_iou( results=A ,gt_seg_maps=A ,num_labels=A ,ignore_index=A ,nan_to_num=A ,label_map=A ,reduce_labels=A ,) return iou_result
15
0
import argparse import torch from torch import nn from transformers import MaMaaaConfig, MaMaaaForConditionalGeneration def _UpperCAmelCase (UpperCamelCase__ : Optional[int] ): _A : List[Any] = [ "encoder.version", "decoder.version", "model.encoder.version", "model.decoder.version", "decoder.output_projection.weight", "_float_tensor", "encoder.embed_positions._float_tensor", "decoder.embed_positions._float_tensor", ] for k in ignore_keys: state_dict.pop(UpperCamelCase__ , UpperCamelCase__ ) def _UpperCAmelCase (UpperCamelCase__ : Union[str, Any] ): _A , _A : List[str] = emb.weight.shape _A : Union[str, Any] = nn.Linear(UpperCamelCase__ , UpperCamelCase__ , bias=UpperCamelCase__ ) _A : Dict = emb.weight.data return lin_layer def _UpperCAmelCase (UpperCamelCase__ : int ): _A : Tuple = torch.load(UpperCamelCase__ , map_location="cpu" ) _A : int = mam_aaa["args"] or mam_aaa["cfg"]["model"] _A : int = mam_aaa["model"] remove_ignore_keys_(UpperCamelCase__ ) _A : Union[str, Any] = state_dict["encoder.embed_tokens.weight"].shape[0] _A : List[str] = MaMaaaConfig( vocab_size=UpperCamelCase__ , max_position_embeddings=1024 , encoder_layers=args.encoder_layers , decoder_layers=args.decoder_layers , encoder_attention_heads=args.encoder_attention_heads , decoder_attention_heads=args.decoder_attention_heads , encoder_ffn_dim=args.encoder_ffn_embed_dim , decoder_ffn_dim=args.decoder_ffn_embed_dim , d_model=args.encoder_embed_dim , encoder_layerdrop=args.encoder_layerdrop , decoder_layerdrop=args.decoder_layerdrop , dropout=args.dropout , attention_dropout=args.attention_dropout , activation_dropout=args.activation_dropout , activation_function="relu" , ) _A : Optional[Any] = state_dict["decoder.embed_tokens.weight"] _A : int = MaMaaaForConditionalGeneration(UpperCamelCase__ ) model.model.load_state_dict(UpperCamelCase__ , strict=UpperCamelCase__ ) _A : Any = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": lowerCAmelCase__ = argparse.ArgumentParser() # Required parameters parser.add_argument('fairseq_path', type=str, help='path to a model.pt on local filesystem.') parser.add_argument('pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') lowerCAmelCase__ = parser.parse_args() lowerCAmelCase__ = convert_fairseq_mamaaa_checkpoint_from_disk(args.fairseq_pathß) model.save_pretrained(args.pytorch_dump_folder_path)
11
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE :List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :List[str] = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Dict = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE :Optional[Any] = { 'AI-Sweden/gpt-sw3-126m': 2048, 'AI-Sweden/gpt-sw3-350m': 2048, 'AI-Sweden/gpt-sw3-1.6b': 2048, 'AI-Sweden/gpt-sw3-6.7b': 2048, 'AI-Sweden/gpt-sw3-20b': 2048, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[int] ,A : Optional[Any] ,A : Optional[int]=False ,A : int=False ,A : Union[str, Any]=False ,A : int=None ,A : Optional[Any]=None ,A : Union[str, Any]=None ,A : Optional[Any]=None ,A : Optional[Dict[str, Any]] = None ,**A : Tuple ,): __A = {} if sp_model_kwargs is None else sp_model_kwargs __A = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) __A = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __A = "<|endoftext|>" if eos_token is None else eos_token __A = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __A = unk_token if pad_token is None else pad_token __A = eos_token if bos_token is None else bos_token else: __A = "<pad>" if pad_token is None else pad_token __A = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=A ,remove_space=A ,keep_accents=A ,bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = do_lower_case __A = remove_space __A = keep_accents __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) # Used for whitespace normalization in input texts # fmt : off __A = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __A = re.compile( f'''[{''.join(map(A ,list(range(0 ,9 ) ) + list(range(11 ,32 ) ) + list(range(1_27 ,1_60 ) ) + [1_60, 1_73, 82_03] ) )}]''' ) def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Optional[Any] ,A : Union[str, Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCamelCase_ ( self : List[str] ): return len(self.sp_model ) def UpperCamelCase_ ( self : int ,A : str ): __A = self.non_printing_characters_re.sub("" ,A ) # Normalize whitespaces __A = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization __A = unicodedata.normalize("NFC" ,A ) return text def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,**A : Optional[int] ): __A = self.preprocess_text(A ) return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : int ): return self.sp_model.IdToPiece(A ) @staticmethod def UpperCamelCase_ ( A : str ): return out_string def UpperCamelCase_ ( self : str ,A : List[str] ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string def UpperCamelCase_ ( self : str ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : List[str] ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Union[str, Any] ,A : Union[str, List[str]] ,A : Union[str, bool] = False ): if isinstance(A ,A ): __A = self.preprocess_text(A ) __A = self.sp_model.encode(A ) else: __A = [self.preprocess_text(A ) for t in text] __A = self.sp_model.encode(A ) if return_tensors is True or return_tensors == "pt": __A = torch.tensor(A ) return token_ids def UpperCamelCase_ ( self : List[Any] ,A : Union[int, List[int]] ): return self.sp_model.decode(A ) def UpperCamelCase_ ( self : List[str] ,A : "Conversation" ): __A = [f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __A = ( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(A ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=A )
15
0
import inspect import logging import os import random import shutil import tempfile import unittest import pytest import torch from torch import nn from torch.utils.data import DataLoader, TensorDataset from accelerate import Accelerator from accelerate.test_utils import execute_subprocess_async, require_cuda from accelerate.utils import ProjectConfiguration, set_seed UpperCAmelCase_ = logging.getLogger(__name__) def lowerCamelCase__ ( A__ : Union[str, Any]=2 , A__ : List[Any]=3 , A__ : Optional[int]=16 , A__ : int = 10 , A__ : int = 2 ): '''simple docstring''' def get_dataset(A__ : Union[str, Any] ): __lowerCamelCase = torch.randn(batch_size * n_batches , 1 ) return TensorDataset(A__ , a * x + b + 0.1 * torch.randn(batch_size * n_batches , 1 ) ) __lowerCamelCase = get_dataset(A__ ) __lowerCamelCase = get_dataset(A__ ) __lowerCamelCase = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 ) __lowerCamelCase = DataLoader(A__ , shuffle=A__ , batch_size=A__ , num_workers=4 ) return (train_dataloader, valid_dataloader) def lowerCamelCase__ ( A__ : List[str] , A__ : List[str] , A__ : Optional[Any] , A__ : Tuple , A__ : Dict , A__ : Union[str, Any]=None ): '''simple docstring''' __lowerCamelCase = [] for epoch in range(A__ ): # Train quickly model.train() for batch in dataloader: __lowerCamelCase, __lowerCamelCase = batch __lowerCamelCase = model(A__ ) __lowerCamelCase = torch.nn.functional.mse_loss(A__ , A__ ) accelerator.backward(A__ ) optimizer.step() optimizer.zero_grad() rands.append(random.random() ) # Introduce some randomness if scheduler is not None: scheduler.step() return rands class lowerCamelCase__( nn.Module): def __init__( self: Dict ): super().__init__() __lowerCamelCase = nn.Parameter(torch.randn(1 ) ) __lowerCamelCase = nn.Parameter(torch.randn(1 ) ) def lowerCAmelCase__ ( self: List[Any] , UpperCamelCase_: Union[str, Any] ): return x * self.a + self.b class lowerCamelCase__( unittest.TestCase): def lowerCAmelCase__ ( self: int ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = ProjectConfiguration(total_limit=1 , project_dir=UpperCamelCase_ , automatic_checkpoint_naming=UpperCamelCase_ ) # Train baseline __lowerCamelCase = Accelerator(project_config=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save initial accelerator.save_state() # Save second state accelerator.save_state() self.assertEqual(len(os.listdir(accelerator.project_dir ) ) , 1 ) def lowerCAmelCase__ ( self: Optional[int] ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() # Train baseline __lowerCamelCase = Accelerator() __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save initial __lowerCamelCase = os.path.join(UpperCamelCase_ , """initial""" ) accelerator.save_state(UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() __lowerCamelCase = train(3 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() # Train partially set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = Accelerator() __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) accelerator.load_state(UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = train(2 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save everything __lowerCamelCase = os.path.join(UpperCamelCase_ , """checkpoint""" ) accelerator.save_state(UpperCamelCase_ ) # Load everything back in and make sure all states work accelerator.load_state(UpperCamelCase_ ) test_rands += train(1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( self: List[str] ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_ ) # Train baseline __lowerCamelCase = Accelerator(project_dir=UpperCamelCase_ , project_config=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save initial accelerator.save_state() ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() __lowerCamelCase = train(3 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() # Train partially set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = ProjectConfiguration(iteration=1 , automatic_checkpoint_naming=UpperCamelCase_ ) __lowerCamelCase = Accelerator(project_dir=UpperCamelCase_ , project_config=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) accelerator.load_state(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_0""" ) ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = train(2 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save everything accelerator.save_state() # Load everything back in and make sure all states work accelerator.load_state(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_1""" ) ) test_rands += train(1 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) ((__lowerCamelCase), (__lowerCamelCase)) = model.a.item(), model.b.item() __lowerCamelCase = optimizer.state_dict() self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) self.assertEqual(UpperCamelCase_ , UpperCamelCase_ ) def lowerCAmelCase__ ( self: Optional[Any] ): __lowerCamelCase = torch.tensor([1, 2, 3] ) __lowerCamelCase = torch.tensor([2, 3, 4] ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(net.parameters() ) __lowerCamelCase = Accelerator() with self.assertRaises(UpperCamelCase_ ) as ve: accelerator.register_for_checkpointing(UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) __lowerCamelCase = str(ve.exception ) self.assertTrue("""Item at index 0""" in message ) self.assertTrue("""Item at index 1""" in message ) self.assertFalse("""Item at index 2""" in message ) self.assertFalse("""Item at index 3""" in message ) def lowerCAmelCase__ ( self: Optional[int] ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = torch.optim.Adam(params=model.parameters() , lr=1E-3 ) __lowerCamelCase = torch.optim.lr_scheduler.StepLR(UpperCamelCase_ , step_size=1 , gamma=0.99 ) __lowerCamelCase, __lowerCamelCase = dummy_dataloaders() __lowerCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_ ) # Train baseline __lowerCamelCase = Accelerator(project_dir=UpperCamelCase_ , project_config=UpperCamelCase_ ) __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase, __lowerCamelCase = accelerator.prepare( UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) # Save initial accelerator.save_state() __lowerCamelCase = scheduler.state_dict() train(3 , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ , UpperCamelCase_ ) self.assertNotEqual(UpperCamelCase_ , scheduler.state_dict() ) # Load everything back in and make sure all states work accelerator.load_state(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_0""" ) ) self.assertEqual(UpperCamelCase_ , scheduler.state_dict() ) def lowerCAmelCase__ ( self: Dict ): with tempfile.TemporaryDirectory() as tmpdir: set_seed(42 ) __lowerCamelCase = DummyModel() __lowerCamelCase = ProjectConfiguration(automatic_checkpoint_naming=UpperCamelCase_ , total_limit=2 ) # Train baseline __lowerCamelCase = Accelerator(project_dir=UpperCamelCase_ , project_config=UpperCamelCase_ ) __lowerCamelCase = accelerator.prepare(UpperCamelCase_ ) # Save 3 states: for _ in range(11 ): accelerator.save_state() self.assertTrue(not os.path.exists(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_0""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_9""" ) ) ) self.assertTrue(os.path.exists(os.path.join(UpperCamelCase_ , """checkpoints""" , """checkpoint_10""" ) ) ) @require_cuda def lowerCAmelCase__ ( self: Optional[Any] ): __lowerCamelCase = ["""torchrun""", F'--nproc_per_node={torch.cuda.device_count()}', inspect.getfile(self.__class__ )] execute_subprocess_async(UpperCamelCase_ , env=os.environ.copy() ) if __name__ == "__main__": UpperCAmelCase_ = '/tmp/accelerate/state_checkpointing' UpperCAmelCase_ = DummyModel() UpperCAmelCase_ = torch.optim.Adam(params=model.parameters(), lr=1E-3) UpperCAmelCase_ = torch.optim.lr_scheduler.StepLR(optimizer, step_size=1, gamma=0.99) UpperCAmelCase_ , UpperCAmelCase_ = dummy_dataloaders() UpperCAmelCase_ = ProjectConfiguration(automatic_checkpoint_naming=True) # Train baseline UpperCAmelCase_ = Accelerator(project_dir=savedir, project_config=project_config, mixed_precision='no') if accelerator.process_index == 0: if os.path.exists(savedir): shutil.rmtree(savedir) os.makedirs(savedir) UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare( model, optimizer, train_dataloader, valid_dataloader, scheduler ) UpperCAmelCase_ , UpperCAmelCase_ = accelerator.prepare(model, optimizer) train(3, model, train_dataloader, optimizer, accelerator, scheduler) # Check that the intial optimizer is loaded on the GPU for group in optimizer.param_groups: UpperCAmelCase_ = group['params'][0].device break assert param_device.type == accelerator.device.type UpperCAmelCase_ = model.cpu() accelerator.wait_for_everyone() accelerator.save_state() accelerator.wait_for_everyone() # Check CPU state accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='cpu') for group in optimizer.param_groups: UpperCAmelCase_ = group['params'][0].device break assert ( param_device.type == torch.device('cpu').type ), f"Loaded optimizer states did not match, expected to be loaded on the CPU but got {param_device}" # Check device state model.to(accelerator.device) accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='on_device') for group in optimizer.param_groups: UpperCAmelCase_ = group['params'][0].device break assert ( param_device.type == accelerator.device.type ), f"Loaded optimizer states did not match, expected to be loaded on {accelerator.device} but got {param_device}" # Check error with pytest.raises(TypeError, match='Unsupported optimizer map location passed'): accelerator.load_state(os.path.join(savedir, 'checkpoints', 'checkpoint_0'), map_location='invalid') accelerator.wait_for_everyone() if accelerator.process_index == 0: shutil.rmtree(savedir) accelerator.wait_for_everyone()
12
import numpy as np def UpperCAmelCase ( a_ , a_ , a_ = 1E-12 , a_ = 1_0_0 , ) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(a_ )[0] == np.shape(a_ )[1] # Ensure proper dimensionality. assert np.shape(a_ )[0] == np.shape(a_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a_ ) == np.iscomplexobj(a_ ) __A = np.iscomplexobj(a_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __A = False __A = 0 __A = 0 __A = 1E12 while not convergence: # Multiple matrix by the vector. __A = np.dot(a_ , a_ ) # Normalize the resulting output vector. __A = w / np.linalg.norm(a_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __A = vector.conj().T if is_complex else vector.T __A = np.dot(a_ , np.dot(a_ , a_ ) ) # Check convergence. __A = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __A = True __A = lambda_ if is_complex: __A = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase ( ) -> None: """simple docstring""" __A = np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]] ) __A = np.array([4_1, 4, 2_0] ) __A = real_input_matrix.astype(np.complexaaa ) __A = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __A = np.array([4_1, 4, 2_0] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __A = real_input_matrix __A = real_vector elif problem_type == "complex": __A = complex_input_matrix __A = complex_vector # Our implementation. __A , __A = power_iteration(a_ , a_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __A , __A = np.linalg.eigh(a_ ) # Last eigenvalue is the maximum one. __A = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __A = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a_ ) - np.abs(a_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
0
from dataclasses import dataclass, field from typing import TYPE_CHECKING, Any, ClassVar, Dict, List, Optional, Union import pyarrow as pa if TYPE_CHECKING: from .features import FeatureType @dataclass class __lowercase : """simple docstring""" _UpperCAmelCase : List[str] _UpperCAmelCase : Optional[str] = None # Automatically constructed _UpperCAmelCase : ClassVar[str] = "dict" _UpperCAmelCase : ClassVar[Any] = None _UpperCAmelCase : str = field(default='''Translation''' , init=UpperCAmelCase_ , repr=UpperCAmelCase_ ) def __call__( self : str): return pa.struct({lang: pa.string() for lang in sorted(self.languages)}) def _SCREAMING_SNAKE_CASE ( self : Tuple): from .features import Value return {k: Value("string") for k in sorted(self.languages)} @dataclass class __lowercase : """simple docstring""" _UpperCAmelCase : Optional[List] = None _UpperCAmelCase : Optional[int] = None _UpperCAmelCase : Optional[str] = None # Automatically constructed _UpperCAmelCase : ClassVar[str] = "dict" _UpperCAmelCase : ClassVar[Any] = None _UpperCAmelCase : str = field(default='''TranslationVariableLanguages''' , init=UpperCAmelCase_ , repr=UpperCAmelCase_ ) def _SCREAMING_SNAKE_CASE ( self : Tuple): SCREAMING_SNAKE_CASE_: List[str] = sorted(set(self.languages)) if self.languages else None SCREAMING_SNAKE_CASE_: Tuple = len(self.languages) if self.languages else None def __call__( self : Any): return pa.struct({"language": pa.list_(pa.string()), "translation": pa.list_(pa.string())}) def _SCREAMING_SNAKE_CASE ( self : int , lowerCAmelCase__ : Any): SCREAMING_SNAKE_CASE_: Optional[Any] = set(self.languages) if self.languages and set(lowerCAmelCase__) - lang_set: raise ValueError( F"Some languages in example ({', '.join(sorted(set(lowerCAmelCase__) - lang_set))}) are not in valid set ({', '.join(lowerCAmelCase__)}).") # Convert dictionary into tuples, splitting out cases where there are # multiple translations for a single language. SCREAMING_SNAKE_CASE_: Tuple = [] for lang, text in translation_dict.items(): if isinstance(lowerCAmelCase__ , lowerCAmelCase__): translation_tuples.append((lang, text)) else: translation_tuples.extend([(lang, el) for el in text]) # Ensure translations are in ascending order by language code. SCREAMING_SNAKE_CASE_ , SCREAMING_SNAKE_CASE_: List[Any] = zip(*sorted(lowerCAmelCase__)) return {"language": languages, "translation": translations} def _SCREAMING_SNAKE_CASE ( self : List[str]): from .features import Sequence, Value return { "language": Sequence(Value("string")), "translation": Sequence(Value("string")), }
13
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig SCREAMING_SNAKE_CASE :str = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE :str = 'RegNetConfig' # Base docstring SCREAMING_SNAKE_CASE :List[str] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Union[str, Any] = [1, 1088, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE :Optional[int] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Any = 'tabby, tabby cat' SCREAMING_SNAKE_CASE :Optional[int] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : int ,A : int = 3 ,A : int = 1 ,A : int = 1 ,A : Optional[str] = "relu" ,**A : Dict ,): super().__init__(**A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __A = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=A ,strides=A ,padding="VALID" ,groups=A ,use_bias=A ,name="convolution" ,) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) __A = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : List[Any] ,A : Any ): __A = self.convolution(self.padding(A ) ) __A = self.normalization(A ) __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : RegNetConfig ,**A : str ): super().__init__(**A ) __A = config.num_channels __A = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name="embedder" ,) def UpperCamelCase_ ( self : Tuple ,A : Optional[Any] ): __A = shape_list(A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __A = tf.transpose(A ,perm=(0, 2, 3, 1) ) __A = self.embedder(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Optional[int] ,A : int ,A : int = 2 ,**A : Tuple ): super().__init__(**A ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=1 ,strides=A ,use_bias=A ,name="convolution" ) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) def UpperCamelCase_ ( self : Union[str, Any] ,A : tf.Tensor ,A : bool = False ): return self.normalization(self.convolution(A ) ,training=A ) class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Dict ,A : int ,A : int ,**A : str ): super().__init__(**A ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) __A = [ tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="relu" ,name="attention.0" ), tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="sigmoid" ,name="attention.2" ), ] def UpperCamelCase_ ( self : Dict ,A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __A = self.pooler(A ) for layer_module in self.attention: __A = layer_module(A ) __A = hidden_state * pooled return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : Optional[int] ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.2" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : int ,A : Optional[int] ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : str ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetSELayer(A ,reduced_channels=int(round(in_channels / 4 ) ) ,name="layer.2" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.3" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict ,A : Any ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 2 ,A : int = 2 ,**A : Optional[int] ): super().__init__(**A ) __A = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __A = [ # downsampling is done in the first layer with stride of 2 layer(A ,A ,A ,stride=A ,name="layers.0" ), *[layer(A ,A ,A ,name=f'''layers.{i+1}''' ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Any ,A : List[str] ): for layer_module in self.layers: __A = layer_module(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any ,A : RegNetConfig ,**A : List[str] ): super().__init__(**A ) __A = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( A ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name="stages.0" ,) ) __A = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(A ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(A ,A ,A ,depth=A ,name=f'''stages.{i+1}''' ) ) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor ,A : bool = False ,A : bool = True ): __A = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __A = hidden_states + (hidden_state,) __A = stage_module(A ) if output_hidden_states: __A = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=A ,hidden_states=A ) @keras_serializable class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' snake_case_ = RegNetConfig def __init__( self : int ,A : Optional[int] ,**A : Dict ): super().__init__(**A ) __A = config __A = TFRegNetEmbeddings(A ,name="embedder" ) __A = TFRegNetEncoder(A ,name="encoder" ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) @unpack_inputs def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : bool = False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.embedder(A ,training=A ) __A = self.encoder( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = encoder_outputs[0] __A = self.pooler(A ) # Change to NCHW output format have uniformity in the modules __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __A = tuple([tf.transpose(A ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A ,pooler_output=A ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = RegNetConfig snake_case_ = "regnet" snake_case_ = "pixel_values" @property def UpperCamelCase_ ( self : Optional[Any] ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} SCREAMING_SNAKE_CASE :Dict = R'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' SCREAMING_SNAKE_CASE :Dict = R'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,*A : List[Any] ,**A : str ): super().__init__(A ,*A ,**A ) __A = TFRegNetMainLayer(A ,name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=A ,config_class=_CONFIG_FOR_DOC ,modality="vision" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : int=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( pixel_values=A ,output_hidden_states=A ,return_dict=A ,training=A ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Optional[int] ,A : RegNetConfig ,*A : str ,**A : Tuple ): super().__init__(A ,*A ,**A ) __A = config.num_labels __A = TFRegNetMainLayer(A ,name="regnet" ) # classification head __A = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=A ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor = None ,A : tf.Tensor = None ,A : bool = None ,A : bool = None ,A : Union[str, Any]=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = outputs.pooler_output if return_dict else outputs[1] __A = self.classifier[0](A ) __A = self.classifier[1](A ) __A = None if labels is None else self.hf_compute_loss(labels=A ,logits=A ) if not return_dict: __A = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=A ,logits=A ,hidden_states=outputs.hidden_states )
15
0
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def SCREAMING_SNAKE_CASE ( lowercase_ ) -> Dict: """simple docstring""" A__ = args.pruning_method A__ = args.threshold A__ = args.model_name_or_path.rstrip('''/''' ) A__ = args.target_model_path print(f"""Load fine-pruned model from {model_name_or_path}""" ) A__ = torch.load(os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) A__ = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: A__ = tensor print(f"""Copied layer {name}""" ) elif "classifier" in name or "qa_output" in name: A__ = tensor print(f"""Copied layer {name}""" ) elif "bias" in name: A__ = tensor print(f"""Copied layer {name}""" ) else: if pruning_method == "magnitude": A__ = MagnitudeBinarizer.apply(inputs=lowercase_ , threshold=lowercase_ ) A__ = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "topK": if "mask_scores" in name: continue A__ = name[:-6] A__ = model[f"""{prefix_}mask_scores"""] A__ = TopKBinarizer.apply(lowercase_ , lowercase_ ) A__ = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue A__ = name[:-6] A__ = model[f"""{prefix_}mask_scores"""] A__ = ThresholdBinarizer.apply(lowercase_ , lowercase_ , lowercase_ ) A__ = tensor * mask print(f"""Pruned layer {name}""" ) elif pruning_method == "l0": if "mask_scores" in name: continue A__ = name[:-6] A__ = model[f"""{prefix_}mask_scores"""] A__ , A__ = -0.1, 1.1 A__ = torch.sigmoid(lowercase_ ) A__ = s * (r - l) + l A__ = s_bar.clamp(min=0.0 , max=1.0 ) A__ = tensor * mask print(f"""Pruned layer {name}""" ) else: raise ValueError('''Unknown pruning method''' ) if target_model_path is None: A__ = os.path.join( os.path.dirname(lowercase_ ) , f"""bertarized_{os.path.basename(lowercase_ )}""" ) if not os.path.isdir(lowercase_ ): shutil.copytree(lowercase_ , lowercase_ ) print(f"""\nCreated folder {target_model_path}""" ) torch.save(lowercase_ , os.path.join(lowercase_ , '''pytorch_model.bin''' ) ) print('''\nPruned model saved! See you later!''' ) if __name__ == "__main__": _lowerCamelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument( """--pruning_method""", choices=["""l0""", """magnitude""", """topK""", """sigmoied_threshold"""], type=str, required=True, help=( """Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,""" """ sigmoied_threshold = Soft movement pruning)""" ), ) parser.add_argument( """--threshold""", type=float, required=False, help=( """For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.""" """For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.""" """Not needed for `l0`""" ), ) parser.add_argument( """--model_name_or_path""", type=str, required=True, help="""Folder containing the model that was previously fine-pruned""", ) parser.add_argument( """--target_model_path""", default=None, type=str, required=False, help="""Folder containing the model that was previously fine-pruned""", ) _lowerCamelCase : int = parser.parse_args() main(args)
14
import math def UpperCAmelCase ( a_ , a_ = 0 , a_ = 0 ) -> list: """simple docstring""" __A = end or len(a_ ) for i in range(a_ , a_ ): __A = i __A = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: __A = array[temp_index - 1] temp_index -= 1 __A = temp_index_value return array def UpperCAmelCase ( a_ , a_ , a_ ) -> None: # Max Heap """simple docstring""" __A = index __A = 2 * index + 1 # Left Node __A = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: __A = left_index if right_index < heap_size and array[largest] < array[right_index]: __A = right_index if largest != index: __A , __A = array[largest], array[index] heapify(a_ , a_ , a_ ) def UpperCAmelCase ( a_ ) -> list: """simple docstring""" __A = len(a_ ) for i in range(n // 2 , -1 , -1 ): heapify(a_ , a_ , a_ ) for i in range(n - 1 , 0 , -1 ): __A , __A = array[0], array[i] heapify(a_ , 0 , a_ ) return array def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" __A = low __A = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i __A , __A = array[j], array[i] i += 1 def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) == 0: return array __A = 2 * math.ceil(math.loga(len(a_ ) ) ) __A = 1_6 return intro_sort(a_ , 0 , len(a_ ) , a_ , a_ ) def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ ) -> list: """simple docstring""" while end - start > size_threshold: if max_depth == 0: return heap_sort(a_ ) max_depth -= 1 __A = median_of_a(a_ , a_ , start + ((end - start) // 2) + 1 , end - 1 ) __A = partition(a_ , a_ , a_ , a_ ) intro_sort(a_ , a_ , a_ , a_ , a_ ) __A = p return insertion_sort(a_ , a_ , a_ ) if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma : ').strip() SCREAMING_SNAKE_CASE :str = [float(item) for item in user_input.split(',')] print(sort(unsorted))
15
0
"""simple docstring""" import itertools import random import unittest import numpy as np from transformers import is_speech_available from transformers.testing_utils import require_torch, require_torchaudio from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin if is_speech_available(): from transformers import SpeechaTextFeatureExtractor lowerCAmelCase_ = random.Random() def __UpperCAmelCase ( __lowerCamelCase , __lowerCamelCase=1.0 , __lowerCamelCase=None , __lowerCamelCase=None ) -> int: if rng is None: lowercase__ : List[Any] = global_rng lowercase__ : Union[str, Any] = [] for batch_idx in range(shape[0] ): values.append([] ) for _ in range(shape[1] ): values[-1].append(rng.random() * scale ) return values @require_torch @require_torchaudio class __A ( unittest.TestCase ): '''simple docstring''' def __init__( self : Tuple ,_snake_case : Dict ,_snake_case : Optional[Any]=7 ,_snake_case : int=400 ,_snake_case : Dict=2_000 ,_snake_case : Dict=24 ,_snake_case : Any=24 ,_snake_case : str=0.0 ,_snake_case : Optional[Any]=16_000 ,_snake_case : List[str]=True ,_snake_case : Dict=True ,) -> Dict: """simple docstring""" lowercase__ : str = parent lowercase__ : Union[str, Any] = batch_size lowercase__ : Optional[Any] = min_seq_length lowercase__ : int = max_seq_length lowercase__ : Union[str, Any] = (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1) lowercase__ : Tuple = feature_size lowercase__ : str = num_mel_bins lowercase__ : List[Any] = padding_value lowercase__ : Tuple = sampling_rate lowercase__ : List[Any] = return_attention_mask lowercase__ : Dict = do_normalize def UpperCAmelCase ( self : Optional[Any] ) -> str: """simple docstring""" return { "feature_size": self.feature_size, "num_mel_bins": self.num_mel_bins, "padding_value": self.padding_value, "sampling_rate": self.sampling_rate, "return_attention_mask": self.return_attention_mask, "do_normalize": self.do_normalize, } def UpperCAmelCase ( self : Any ,_snake_case : Any=False ,_snake_case : int=False ) -> Tuple: """simple docstring""" def _flatten(_snake_case : Optional[Any] ): return list(itertools.chain(*_snake_case ) ) if equal_length: lowercase__ : Union[str, Any] = [floats_list((self.max_seq_length, self.feature_size) ) for _ in range(self.batch_size )] else: # make sure that inputs increase in size lowercase__ : Dict = [ floats_list((x, self.feature_size) ) for x in range(self.min_seq_length ,self.max_seq_length ,self.seq_length_diff ) ] if numpify: lowercase__ : Optional[Any] = [np.asarray(_snake_case ) for x in speech_inputs] return speech_inputs @require_torch @require_torchaudio class __A ( A_ ,unittest.TestCase ): '''simple docstring''' lowerCAmelCase : Tuple = SpeechaTextFeatureExtractor if is_speech_available() else None def UpperCAmelCase ( self : int ) -> List[str]: """simple docstring""" lowercase__ : Any = SpeechaTextFeatureExtractionTester(self ) def UpperCAmelCase ( self : Union[str, Any] ,_snake_case : List[str] ) -> List[str]: """simple docstring""" self.assertTrue(np.all(np.mean(_snake_case ,axis=0 ) < 1e-3 ) ) self.assertTrue(np.all(np.abs(np.var(_snake_case ,axis=0 ) - 1 ) < 1e-3 ) ) def UpperCAmelCase ( self : Tuple ) -> Any: """simple docstring""" lowercase__ : List[str] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) # create three inputs of length 800, 1000, and 1200 lowercase__ : Union[str, Any] = [floats_list((1, x) )[0] for x in range(800 ,1_400 ,200 )] lowercase__ : Any = [np.asarray(_snake_case ) for speech_input in speech_inputs] # Test feature size lowercase__ : List[str] = feature_extractor(_snake_case ,padding=_snake_case ,return_tensors='''np''' ).input_features self.assertTrue(input_features.ndim == 3 ) self.assertTrue(input_features.shape[-1] == feature_extractor.feature_size ) # Test not batched input lowercase__ : Dict = feature_extractor(speech_inputs[0] ,return_tensors='''np''' ).input_features lowercase__ : str = feature_extractor(np_speech_inputs[0] ,return_tensors='''np''' ).input_features self.assertTrue(np.allclose(_snake_case ,_snake_case ,atol=1e-3 ) ) # Test batched lowercase__ : Optional[int] = feature_extractor(_snake_case ,return_tensors='''np''' ).input_features lowercase__ : Union[str, Any] = feature_extractor(_snake_case ,return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(_snake_case ,_snake_case ): self.assertTrue(np.allclose(_snake_case ,_snake_case ,atol=1e-3 ) ) # Test 2-D numpy arrays are batched. lowercase__ : Any = [floats_list((1, x) )[0] for x in (800, 800, 800)] lowercase__ : Dict = np.asarray(_snake_case ) lowercase__ : str = feature_extractor(_snake_case ,return_tensors='''np''' ).input_features lowercase__ : Tuple = feature_extractor(_snake_case ,return_tensors='''np''' ).input_features for enc_seq_a, enc_seq_a in zip(_snake_case ,_snake_case ): self.assertTrue(np.allclose(_snake_case ,_snake_case ,atol=1e-3 ) ) def UpperCAmelCase ( self : Tuple ) -> str: """simple docstring""" lowercase__ : Optional[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowercase__ : str = [floats_list((1, x) )[0] for x in range(800 ,1_400 ,200 )] lowercase__ : str = ['''longest''', '''max_length''', '''do_not_pad'''] lowercase__ : Union[str, Any] = [None, 16, None] for max_length, padding in zip(_snake_case ,_snake_case ): lowercase__ : Union[str, Any] = feature_extractor( _snake_case ,padding=_snake_case ,max_length=_snake_case ,return_attention_mask=_snake_case ) lowercase__ : Any = inputs.input_features lowercase__ : Any = inputs.attention_mask lowercase__ : Optional[Any] = [np.sum(_snake_case ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def UpperCAmelCase ( self : Union[str, Any] ) -> int: """simple docstring""" lowercase__ : str = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowercase__ : List[Any] = [floats_list((1, x) )[0] for x in range(800 ,1_400 ,200 )] lowercase__ : List[Any] = ['''longest''', '''max_length''', '''do_not_pad'''] lowercase__ : Optional[int] = [None, 16, None] for max_length, padding in zip(_snake_case ,_snake_case ): lowercase__ : Optional[int] = feature_extractor( _snake_case ,max_length=_snake_case ,padding=_snake_case ,return_tensors='''np''' ,return_attention_mask=_snake_case ) lowercase__ : Any = inputs.input_features lowercase__ : Any = inputs.attention_mask lowercase__ : Tuple = [np.sum(_snake_case ) for x in attention_mask] self._check_zero_mean_unit_variance(input_features[0][: fbank_feat_lengths[0]] ) self.assertTrue(input_features[0][fbank_feat_lengths[0] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[1][: fbank_feat_lengths[1]] ) self.assertTrue(input_features[0][fbank_feat_lengths[1] :].sum() < 1e-6 ) self._check_zero_mean_unit_variance(input_features[2][: fbank_feat_lengths[2]] ) def UpperCAmelCase ( self : Any ) -> str: """simple docstring""" lowercase__ : Dict = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowercase__ : Any = [floats_list((1, x) )[0] for x in range(800 ,1_400 ,200 )] lowercase__ : List[Any] = feature_extractor( _snake_case ,padding='''max_length''' ,max_length=4 ,truncation=_snake_case ,return_tensors='''np''' ,return_attention_mask=_snake_case ,) lowercase__ : Optional[int] = inputs.input_features lowercase__ : Optional[Any] = inputs.attention_mask lowercase__ : str = np.sum(attention_mask == 1 ,axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1] ) self._check_zero_mean_unit_variance(input_features[2] ) def UpperCAmelCase ( self : Tuple ) -> Any: """simple docstring""" lowercase__ : Optional[int] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowercase__ : int = [floats_list((1, x) )[0] for x in range(800 ,1_400 ,200 )] lowercase__ : str = feature_extractor( _snake_case ,padding='''longest''' ,max_length=4 ,truncation=_snake_case ,return_tensors='''np''' ,return_attention_mask=_snake_case ,) lowercase__ : Optional[Any] = inputs.input_features lowercase__ : List[str] = inputs.attention_mask lowercase__ : int = np.sum(attention_mask == 1 ,axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape ,(3, 4, 24) ) lowercase__ : Dict = [floats_list((1, x) )[0] for x in range(800 ,1_400 ,200 )] lowercase__ : List[Any] = feature_extractor( _snake_case ,padding='''longest''' ,max_length=16 ,truncation=_snake_case ,return_tensors='''np''' ,return_attention_mask=_snake_case ,) lowercase__ : List[str] = inputs.input_features lowercase__ : List[Any] = inputs.attention_mask lowercase__ : Dict = np.sum(attention_mask == 1 ,axis=1 ) self._check_zero_mean_unit_variance(input_features[0, : fbank_feat_lengths[0]] ) self._check_zero_mean_unit_variance(input_features[1, : fbank_feat_lengths[1]] ) self._check_zero_mean_unit_variance(input_features[2] ) # make sure that if max_length < longest -> then pad to max_length self.assertEqual(input_features.shape ,(3, 6, 24) ) def UpperCAmelCase ( self : str ) -> List[str]: """simple docstring""" import torch lowercase__ : List[Any] = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowercase__ : int = np.random.rand(100 ,32 ).astype(np.floataa ) lowercase__ : Tuple = np_speech_inputs.tolist() for inputs in [py_speech_inputs, np_speech_inputs]: lowercase__ : Tuple = feature_extractor.pad([{'''input_features''': inputs}] ,return_tensors='''np''' ) self.assertTrue(np_processed.input_features.dtype == np.floataa ) lowercase__ : Union[str, Any] = feature_extractor.pad([{'''input_features''': inputs}] ,return_tensors='''pt''' ) self.assertTrue(pt_processed.input_features.dtype == torch.floataa ) def UpperCAmelCase ( self : Any ,_snake_case : str ) -> Optional[Any]: """simple docstring""" from datasets import load_dataset lowercase__ : List[str] = load_dataset('''hf-internal-testing/librispeech_asr_dummy''' ,'''clean''' ,split='''validation''' ) # automatic decoding with librispeech lowercase__ : int = ds.sort('''id''' ).select(range(_snake_case ) )[:num_samples]['''audio'''] return [x["array"] for x in speech_samples] def UpperCAmelCase ( self : Union[str, Any] ) -> List[Any]: """simple docstring""" lowercase__ : str = np.array([ -1.5745, -1.7713, -1.7020, -1.6069, -1.2250, -1.1105, -0.9072, -0.8241, -1.2310, -0.8098, -0.3320, -0.4101, -0.7985, -0.4996, -0.8213, -0.9128, -1.0420, -1.1286, -1.0440, -0.7999, -0.8405, -1.2275, -1.5443, -1.4625, ] ) # fmt: on lowercase__ : List[Any] = self._load_datasamples(1 ) lowercase__ : Tuple = self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() ) lowercase__ : Optional[Any] = feature_extractor(_snake_case ,return_tensors='''pt''' ).input_features self.assertEquals(input_features.shape ,(1, 584, 24) ) self.assertTrue(np.allclose(input_features[0, 0, :30] ,_snake_case ,atol=1e-4 ) )
16
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml SCREAMING_SNAKE_CASE :Optional[int] = NewType('DataClass', Any) SCREAMING_SNAKE_CASE :int = NewType('DataClassType', Any) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" if isinstance(a_ , a_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def UpperCAmelCase ( a_ ) -> Callable[[str], Any]: """simple docstring""" __A = {str(a_ ): choice for choice in choices} return lambda a_ : str_to_choice.get(a_ , a_ ) def UpperCAmelCase ( *, a_ = None , a_ = None , a_ = dataclasses.MISSING , a_ = dataclasses.MISSING , a_ = None , **a_ , ) -> dataclasses.Field: """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls __A = {} if aliases is not None: __A = aliases if help is not None: __A = help return dataclasses.field(metadata=a_ , default=a_ , default_factory=a_ , **a_ ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 def __init__( self : Union[str, Any] ,A : Union[DataClassType, Iterable[DataClassType]] ,**A : List[Any] ): # To make the default appear when using --help if "formatter_class" not in kwargs: __A = ArgumentDefaultsHelpFormatter super().__init__(**A ) if dataclasses.is_dataclass(A ): __A = [dataclass_types] __A = list(A ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A ) @staticmethod def UpperCamelCase_ ( A : ArgumentParser ,A : dataclasses.Field ): __A = f'''--{field.name}''' __A = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type ,A ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) __A = kwargs.pop("aliases" ,[] ) if isinstance(A ,A ): __A = [aliases] __A = getattr(field.type ,"__origin__" ,field.type ) if origin_type is Union or (hasattr(A ,"UnionType" ) and isinstance(A ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." f''' Problem encountered in field \'{field.name}\'.''' ) if type(A ) not in field.type.__args__: # filter `str` in Union __A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] __A = getattr(field.type ,"__origin__" ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) __A = ( field.type.__args__[0] if isinstance(A ,field.type.__args__[1] ) else field.type.__args__[1] ) __A = getattr(field.type ,"__origin__" ,field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) __A = {} if origin_type is Literal or (isinstance(field.type ,A ) and issubclass(field.type ,A )): if origin_type is Literal: __A = field.type.__args__ else: __A = [x.value for x in field.type] __A = make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: __A = field.default else: __A = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument __A = copy(A ) # Hack because type=bool in argparse does not behave as we want. __A = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. __A = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way __A = default # This tells argparse we accept 0 or 1 value after --field_name __A = "?" # This is the value that will get picked if we do --field_name (without value) __A = True elif isclass(A ) and issubclass(A ,A ): __A = field.type.__args__[0] __A = "+" if field.default_factory is not dataclasses.MISSING: __A = field.default_factory() elif field.default is dataclasses.MISSING: __A = True else: __A = field.type if field.default is not dataclasses.MISSING: __A = field.default elif field.default_factory is not dataclasses.MISSING: __A = field.default_factory() else: __A = True parser.add_argument(A ,*A ,**A ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): __A = False parser.add_argument(f'''--no_{field.name}''' ,action="store_false" ,dest=field.name ,**A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : DataClassType ): if hasattr(A ,"_argument_group_name" ): __A = self.add_argument_group(dtype._argument_group_name ) else: __A = self try: __A = get_type_hints(A ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(A ): __A = ".".join(map(A ,sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(A ): if not field.init: continue __A = type_hints[field.name] self._parse_dataclass_field(A ,A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : List[Any]=None ,A : List[Any]=False ,A : Optional[Any]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=None ,): if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): __A = [] if args_filename: args_files.append(Path(A ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values __A = ArgumentParser() args_file_parser.add_argument(A ,type=A ,action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) __A , __A = args_file_parser.parse_known_args(args=A ) __A = vars(A ).get(args_file_flag.lstrip("-" ) ,A ) if cmd_args_file_paths: args_files.extend([Path(A ) for p in cmd_args_file_paths] ) __A = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last __A = file_args + args if args is not None else file_args + sys.argv[1:] __A , __A = self.parse_known_args(args=A ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in vars(A ).items() if k in keys} for k in keys: delattr(A ,A ) __A = dtype(**A ) outputs.append(A ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def UpperCamelCase_ ( self : Dict ,A : Dict[str, Any] ,A : bool = False ): __A = set(args.keys() ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) __A = dtype(**A ) outputs.append(A ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(A )}''' ) return tuple(A ) def UpperCamelCase_ ( self : List[str] ,A : str ,A : bool = False ): with open(Path(A ) ,encoding="utf-8" ) as open_json_file: __A = json.loads(open_json_file.read() ) __A = self.parse_dict(A ,allow_extra_keys=A ) return tuple(A ) def UpperCamelCase_ ( self : int ,A : str ,A : bool = False ): __A = self.parse_dict(yaml.safe_load(Path(A ).read_text() ) ,allow_extra_keys=A ) return tuple(A )
15
0
"""simple docstring""" import unicodedata from dataclasses import dataclass from typing import Optional, Union import numpy as np from transformers.data.data_collator import DataCollatorMixin from transformers.file_utils import PaddingStrategy from transformers.tokenization_utils_base import PreTrainedTokenizerBase def _A ( UpperCamelCase_ : int, UpperCamelCase_ : List[Any], UpperCamelCase_ : Any, UpperCamelCase_ : List[str]) -> Optional[int]: '''simple docstring''' if isinstance(UpperCamelCase_, UpperCamelCase_): __lowercase = np.full((len(UpperCamelCase_), sequence_length, 2), UpperCamelCase_) else: __lowercase = np.full((len(UpperCamelCase_), sequence_length), UpperCamelCase_) for i, tensor in enumerate(UpperCamelCase_): if padding_side == "right": if isinstance(UpperCamelCase_, UpperCamelCase_): __lowercase = tensor[:sequence_length] else: __lowercase = tensor[:sequence_length] else: if isinstance(UpperCamelCase_, UpperCamelCase_): __lowercase = tensor[:sequence_length] else: __lowercase = tensor[:sequence_length] return out_tensor.tolist() def _A ( UpperCamelCase_ : Dict) -> str: '''simple docstring''' __lowercase = ord(UpperCamelCase_) if (cp >= 33 and cp <= 47) or (cp >= 58 and cp <= 64) or (cp >= 91 and cp <= 96) or (cp >= 123 and cp <= 126): return True __lowercase = unicodedata.category(UpperCamelCase_) if cat.startswith("P"): return True return False @dataclass class _lowerCAmelCase ( lowercase ): """simple docstring""" __UpperCAmelCase : PreTrainedTokenizerBase __UpperCAmelCase : Union[bool, str, PaddingStrategy] = True __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : Optional[int] = None __UpperCAmelCase : int = -1_0_0 __UpperCAmelCase : str = "pt" def _lowercase ( self : str, UpperCAmelCase__ : List[str] ): import torch __lowercase = "label" if "label" in features[0].keys() else "labels" __lowercase = [feature[label_name] for feature in features] if label_name in features[0].keys() else None __lowercase = self.tokenizer.pad( UpperCAmelCase__, padding=self.padding, max_length=self.max_length, pad_to_multiple_of=self.pad_to_multiple_of, return_tensors="pt" if labels is None else None, ) if labels is None: return batch __lowercase = torch.tensor(batch["entity_ids"] ).shape[1] __lowercase = self.tokenizer.padding_side if padding_side == "right": __lowercase = [ list(UpperCAmelCase__ ) + [self.label_pad_token_id] * (sequence_length - len(UpperCAmelCase__ )) for label in labels ] else: __lowercase = [ [self.label_pad_token_id] * (sequence_length - len(UpperCAmelCase__ )) + list(UpperCAmelCase__ ) for label in labels ] __lowercase = [feature["ner_tags"] for feature in features] __lowercase = padding_tensor(UpperCAmelCase__, -1, UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = [feature["original_entity_spans"] for feature in features] __lowercase = padding_tensor(UpperCAmelCase__, (-1, -1), UpperCAmelCase__, UpperCAmelCase__ ) __lowercase = {k: torch.tensor(UpperCAmelCase__, dtype=torch.intaa ) for k, v in batch.items()} return batch
17
SCREAMING_SNAKE_CASE :Any = 256 # Modulus to hash a string SCREAMING_SNAKE_CASE :Union[str, Any] = 100_0003 def UpperCAmelCase ( a_ , a_ ) -> bool: """simple docstring""" __A = len(a_ ) __A = len(a_ ) if p_len > t_len: return False __A = 0 __A = 0 __A = 1 # Calculating the hash of pattern and substring of text for i in range(a_ ): __A = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus __A = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue __A = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash __A = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def UpperCAmelCase ( ) -> None: """simple docstring""" __A = "abc1abc12" __A = "alskfjaldsabc1abc1abc12k23adsfabcabc" __A = "alskfjaldsk23adsfabcabc" assert rabin_karp(a_ , a_ ) and not rabin_karp(a_ , a_ ) # Test 2) __A = "ABABX" __A = "ABABZABABYABABX" assert rabin_karp(a_ , a_ ) # Test 3) __A = "AAAB" __A = "ABAAAAAB" assert rabin_karp(a_ , a_ ) # Test 4) __A = "abcdabcy" __A = "abcxabcdabxabcdabcdabcy" assert rabin_karp(a_ , a_ ) # Test 5) __A = "Lü" __A = "Lüsai" assert rabin_karp(a_ , a_ ) __A = "Lue" assert not rabin_karp(a_ , a_ ) print("Success." ) if __name__ == "__main__": test_rabin_karp()
15
0
import argparse import os import re __lowerCamelCase : int = '''src/diffusers''' # Pattern that looks at the indentation in a line. __lowerCamelCase : Union[str, Any] = re.compile(R'''^(\s*)\S''') # Pattern that matches `"key":" and puts `key` in group 0. __lowerCamelCase : List[Any] = re.compile(R'''^\s*"([^"]+)":''') # Pattern that matches `_import_structure["key"]` and puts `key` in group 0. __lowerCamelCase : Optional[Any] = re.compile(R'''^\s*_import_structure\["([^"]+)"\]''') # Pattern that matches `"key",` and puts `key` in group 0. __lowerCamelCase : List[str] = re.compile(R'''^\s*"([^"]+)",\s*$''') # Pattern that matches any `[stuff]` and puts `stuff` in group 0. __lowerCamelCase : List[str] = re.compile(R'''\[([^\]]+)\]''') def _snake_case ( lowerCAmelCase : int ): """simple docstring""" SCREAMING_SNAKE_CASE_ : List[str] = _re_indent.search(lowerCAmelCase ) return "" if search is None else search.groups()[0] def _snake_case ( lowerCAmelCase : List[str] , lowerCAmelCase : List[Any]="" , lowerCAmelCase : Dict=None , lowerCAmelCase : Any=None ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Optional[int] = 0 SCREAMING_SNAKE_CASE_ : Optional[Any] = code.split("\n" ) if start_prompt is not None: while not lines[index].startswith(lowerCAmelCase ): index += 1 SCREAMING_SNAKE_CASE_ : List[Any] = ["\n".join(lines[:index] )] else: SCREAMING_SNAKE_CASE_ : List[str] = [] # We split into blocks until we get to the `end_prompt` (or the end of the block). SCREAMING_SNAKE_CASE_ : List[Any] = [lines[index]] index += 1 while index < len(lowerCAmelCase ) and (end_prompt is None or not lines[index].startswith(lowerCAmelCase )): if len(lines[index] ) > 0 and get_indent(lines[index] ) == indent_level: if len(lowerCAmelCase ) > 0 and get_indent(current_block[-1] ).startswith(indent_level + " " ): current_block.append(lines[index] ) blocks.append("\n".join(lowerCAmelCase ) ) if index < len(lowerCAmelCase ) - 1: SCREAMING_SNAKE_CASE_ : Any = [lines[index + 1]] index += 1 else: SCREAMING_SNAKE_CASE_ : Tuple = [] else: blocks.append("\n".join(lowerCAmelCase ) ) SCREAMING_SNAKE_CASE_ : Dict = [lines[index]] else: current_block.append(lines[index] ) index += 1 # Adds current block if it's nonempty. if len(lowerCAmelCase ) > 0: blocks.append("\n".join(lowerCAmelCase ) ) # Add final block after end_prompt if provided. if end_prompt is not None and index < len(lowerCAmelCase ): blocks.append("\n".join(lines[index:] ) ) return blocks def _snake_case ( lowerCAmelCase : Tuple ): """simple docstring""" def _inner(lowerCAmelCase : List[str] ): return key(lowerCAmelCase ).lower().replace("_" , "" ) return _inner def _snake_case ( lowerCAmelCase : int , lowerCAmelCase : Dict=None ): """simple docstring""" def noop(lowerCAmelCase : Optional[Any] ): return x if key is None: SCREAMING_SNAKE_CASE_ : Dict = noop # Constants are all uppercase, they go first. SCREAMING_SNAKE_CASE_ : List[Any] = [obj for obj in objects if key(lowerCAmelCase ).isupper()] # Classes are not all uppercase but start with a capital, they go second. SCREAMING_SNAKE_CASE_ : Optional[Any] = [obj for obj in objects if key(lowerCAmelCase )[0].isupper() and not key(lowerCAmelCase ).isupper()] # Functions begin with a lowercase, they go last. SCREAMING_SNAKE_CASE_ : str = [obj for obj in objects if not key(lowerCAmelCase )[0].isupper()] SCREAMING_SNAKE_CASE_ : Union[str, Any] = ignore_underscore(lowerCAmelCase ) return sorted(lowerCAmelCase , key=lowerCAmelCase ) + sorted(lowerCAmelCase , key=lowerCAmelCase ) + sorted(lowerCAmelCase , key=lowerCAmelCase ) def _snake_case ( lowerCAmelCase : Tuple ): """simple docstring""" def _replace(lowerCAmelCase : Any ): SCREAMING_SNAKE_CASE_ : Optional[int] = match.groups()[0] if "," not in imports: return f'[{imports}]' SCREAMING_SNAKE_CASE_ : List[Any] = [part.strip().replace("\"" , "" ) for part in imports.split("," )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: SCREAMING_SNAKE_CASE_ : Union[str, Any] = keys[:-1] return "[" + ", ".join([f'"{k}"' for k in sort_objects(lowerCAmelCase )] ) + "]" SCREAMING_SNAKE_CASE_ : str = import_statement.split("\n" ) if len(lowerCAmelCase ) > 3: # Here we have to sort internal imports that are on several lines (one per name): # key: [ # "object1", # "object2", # ... # ] # We may have to ignore one or two lines on each side. SCREAMING_SNAKE_CASE_ : str = 2 if lines[1].strip() == "[" else 1 SCREAMING_SNAKE_CASE_ : Tuple = [(i, _re_strip_line.search(lowerCAmelCase ).groups()[0]) for i, line in enumerate(lines[idx:-idx] )] SCREAMING_SNAKE_CASE_ : Tuple = sort_objects(lowerCAmelCase , key=lambda lowerCAmelCase : x[1] ) SCREAMING_SNAKE_CASE_ : Optional[int] = [lines[x[0] + idx] for x in sorted_indices] return "\n".join(lines[:idx] + sorted_lines + lines[-idx:] ) elif len(lowerCAmelCase ) == 3: # Here we have to sort internal imports that are on one separate line: # key: [ # "object1", "object2", ... # ] if _re_bracket_content.search(lines[1] ) is not None: SCREAMING_SNAKE_CASE_ : Any = _re_bracket_content.sub(_replace , lines[1] ) else: SCREAMING_SNAKE_CASE_ : int = [part.strip().replace("\"" , "" ) for part in lines[1].split("," )] # We will have a final empty element if the line finished with a comma. if len(keys[-1] ) == 0: SCREAMING_SNAKE_CASE_ : Tuple = keys[:-1] SCREAMING_SNAKE_CASE_ : Optional[int] = get_indent(lines[1] ) + ", ".join([f'"{k}"' for k in sort_objects(lowerCAmelCase )] ) return "\n".join(lowerCAmelCase ) else: # Finally we have to deal with imports fitting on one line SCREAMING_SNAKE_CASE_ : Dict = _re_bracket_content.sub(_replace , lowerCAmelCase ) return import_statement def _snake_case ( lowerCAmelCase : Optional[Any] , lowerCAmelCase : List[Any]=True ): """simple docstring""" with open(lowerCAmelCase , "r" ) as f: SCREAMING_SNAKE_CASE_ : List[str] = f.read() if "_import_structure" not in code: return # Blocks of indent level 0 SCREAMING_SNAKE_CASE_ : Tuple = split_code_in_indented_blocks( lowerCAmelCase , start_prompt="_import_structure = {" , end_prompt="if TYPE_CHECKING:" ) # We ignore block 0 (everything until start_prompt) and the last block (everything after end_prompt). for block_idx in range(1 , len(lowerCAmelCase ) - 1 ): # Check if the block contains some `_import_structure`s thingy to sort. SCREAMING_SNAKE_CASE_ : int = main_blocks[block_idx] SCREAMING_SNAKE_CASE_ : Any = block.split("\n" ) # Get to the start of the imports. SCREAMING_SNAKE_CASE_ : str = 0 while line_idx < len(lowerCAmelCase ) and "_import_structure" not in block_lines[line_idx]: # Skip dummy import blocks if "import dummy" in block_lines[line_idx]: SCREAMING_SNAKE_CASE_ : Optional[int] = len(lowerCAmelCase ) else: line_idx += 1 if line_idx >= len(lowerCAmelCase ): continue # Ignore beginning and last line: they don't contain anything. SCREAMING_SNAKE_CASE_ : Any = "\n".join(block_lines[line_idx:-1] ) SCREAMING_SNAKE_CASE_ : Any = get_indent(block_lines[1] ) # Slit the internal block into blocks of indent level 1. SCREAMING_SNAKE_CASE_ : int = split_code_in_indented_blocks(lowerCAmelCase , indent_level=lowerCAmelCase ) # We have two categories of import key: list or _import_structure[key].append/extend SCREAMING_SNAKE_CASE_ : Any = _re_direct_key if "_import_structure" in block_lines[0] else _re_indirect_key # Grab the keys, but there is a trap: some lines are empty or just comments. SCREAMING_SNAKE_CASE_ : List[Any] = [(pattern.search(lowerCAmelCase ).groups()[0] if pattern.search(lowerCAmelCase ) is not None else None) for b in internal_blocks] # We only sort the lines with a key. SCREAMING_SNAKE_CASE_ : Any = [(i, key) for i, key in enumerate(lowerCAmelCase ) if key is not None] SCREAMING_SNAKE_CASE_ : int = [x[0] for x in sorted(lowerCAmelCase , key=lambda lowerCAmelCase : x[1] )] # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. SCREAMING_SNAKE_CASE_ : List[str] = 0 SCREAMING_SNAKE_CASE_ : Any = [] for i in range(len(lowerCAmelCase ) ): if keys[i] is None: reordered_blocks.append(internal_blocks[i] ) else: SCREAMING_SNAKE_CASE_ : Dict = sort_objects_in_import(internal_blocks[sorted_indices[count]] ) reordered_blocks.append(lowerCAmelCase ) count += 1 # And we put our main block back together with its first and last line. SCREAMING_SNAKE_CASE_ : Dict = "\n".join(block_lines[:line_idx] + reordered_blocks + [block_lines[-1]] ) if code != "\n".join(lowerCAmelCase ): if check_only: return True else: print(f'Overwriting {file}.' ) with open(lowerCAmelCase , "w" ) as f: f.write("\n".join(lowerCAmelCase ) ) def _snake_case ( lowerCAmelCase : Union[str, Any]=True ): """simple docstring""" SCREAMING_SNAKE_CASE_ : Any = [] for root, _, files in os.walk(lowerCAmelCase ): if "__init__.py" in files: SCREAMING_SNAKE_CASE_ : int = sort_imports(os.path.join(lowerCAmelCase , "__init__.py" ) , check_only=lowerCAmelCase ) if result: SCREAMING_SNAKE_CASE_ : Optional[int] = [os.path.join(lowerCAmelCase , "__init__.py" )] if len(lowerCAmelCase ) > 0: raise ValueError(f'Would overwrite {len(lowerCAmelCase )} files, run `make style`.' ) if __name__ == "__main__": __lowerCamelCase : Any = argparse.ArgumentParser() parser.add_argument('''--check_only''', action='''store_true''', help='''Whether to only check or fix style.''') __lowerCamelCase : Any = parser.parse_args() sort_imports_in_all_inits(check_only=args.check_only)
18
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel SCREAMING_SNAKE_CASE :Union[str, Any] = False SCREAMING_SNAKE_CASE :Any = True SCREAMING_SNAKE_CASE :Tuple = False if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE :Union[str, Any] = parser.parse_args() SCREAMING_SNAKE_CASE :Dict = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } SCREAMING_SNAKE_CASE :Optional[int] = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } SCREAMING_SNAKE_CASE :int = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: SCREAMING_SNAKE_CASE :Dict = reader.read() SCREAMING_SNAKE_CASE :List[str] = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): SCREAMING_SNAKE_CASE :Optional[int] = UNetaDModel(**config) else: SCREAMING_SNAKE_CASE :Optional[Any] = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel SCREAMING_SNAKE_CASE :List[str] = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) SCREAMING_SNAKE_CASE :List[str] = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: SCREAMING_SNAKE_CASE :Optional[Any] = config[key] del config[key] SCREAMING_SNAKE_CASE :Optional[Any] = [k.replace('UNetRes', '') for k in config['down_block_types']] SCREAMING_SNAKE_CASE :List[Any] = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: SCREAMING_SNAKE_CASE :Tuple = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) SCREAMING_SNAKE_CASE :Any = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue SCREAMING_SNAKE_CASE :List[str] = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: SCREAMING_SNAKE_CASE :List[Any] = param_value SCREAMING_SNAKE_CASE :str = True if not has_changed: SCREAMING_SNAKE_CASE :List[str] = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
15
0
import argparse import torch from transformers import BlenderbotConfig, BlenderbotForConditionalGeneration from transformers.utils import logging logging.set_verbosity_info() __A =logging.get_logger(__name__) __A =[ ['''attention''', '''attn'''], ['''encoder_attention''', '''encoder_attn'''], ['''q_lin''', '''q_proj'''], ['''k_lin''', '''k_proj'''], ['''v_lin''', '''v_proj'''], ['''out_lin''', '''out_proj'''], ['''norm_embeddings''', '''layernorm_embedding'''], ['''position_embeddings''', '''embed_positions'''], ['''embeddings''', '''embed_tokens'''], ['''ffn.lin''', '''fc'''], ] def lowerCamelCase_ ( lowerCamelCase__ ): if k == "embeddings.weight": return "shared.weight" for parlai_name, hf_name in PATTERNS: lowerCamelCase_ = k.replace(lowerCamelCase__ , lowerCamelCase__ ) if k.startswith("encoder" ): lowerCamelCase_ = k.replace(".attn" , ".self_attn" ) lowerCamelCase_ = k.replace("norm1" , "self_attn_layer_norm" ) lowerCamelCase_ = k.replace("norm2" , "final_layer_norm" ) elif k.startswith("decoder" ): lowerCamelCase_ = k.replace("norm1" , "self_attn_layer_norm" ) lowerCamelCase_ = k.replace("norm2" , "encoder_attn_layer_norm" ) lowerCamelCase_ = k.replace("norm3" , "final_layer_norm" ) return k def lowerCamelCase_ ( lowerCamelCase__ ): lowerCamelCase_ = [ "model.encoder.layernorm_embedding.weight", "model.encoder.layernorm_embedding.bias", "model.decoder.layernorm_embedding.weight", "model.decoder.layernorm_embedding.bias", ] for k in keys: lowerCamelCase_ = sd.pop(lowerCamelCase__ ) lowerCamelCase_ = k.replace("layernorm_embedding" , "layer_norm" ) assert new_k not in sd lowerCamelCase_ = v __A =['''START'''] @torch.no_grad() def lowerCamelCase_ ( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ ): lowerCamelCase_ = torch.load(lowerCamelCase__ , map_location="cpu" ) lowerCamelCase_ = model["model"] lowerCamelCase_ = BlenderbotConfig.from_json_file(lowerCamelCase__ ) lowerCamelCase_ = BlenderbotForConditionalGeneration(lowerCamelCase__ ) lowerCamelCase_ = m.model.state_dict().keys() lowerCamelCase_ = [] lowerCamelCase_ = {} for k, v in sd.items(): if k in IGNORE_KEYS: continue lowerCamelCase_ = rename_state_dict_key(lowerCamelCase__ ) if new_k not in valid_keys: failures.append([k, new_k] ) else: lowerCamelCase_ = v if cfg.normalize_before: # Blenderbot-3B checkpoints. Rename layernorm_embedding -> layer_norm rename_layernorm_keys(lowerCamelCase__ ) m.model.load_state_dict(lowerCamelCase__ , strict=lowerCamelCase__ ) m.half() m.save_pretrained(lowerCamelCase__ ) if __name__ == "__main__": __A =argparse.ArgumentParser() # Required parameters parser.add_argument('''--src_path''', type=str, help='''like blenderbot-model.bin''') parser.add_argument('''--save_dir''', default='''hf_blenderbot''', type=str, help='''Where to save converted model.''') parser.add_argument( '''--hf_config_json''', default='''blenderbot-3b-config.json''', type=str, help='''Path to config to use''' ) __A =parser.parse_args() convert_parlai_checkpoint(args.src_path, args.save_dir, args.hf_config_json)
19
import argparse import math import traceback import dateutil.parser as date_parser import requests def UpperCAmelCase ( a_ ) -> str: """simple docstring""" __A = {} __A = job["started_at"] __A = job["completed_at"] __A = date_parser.parse(a_ ) __A = date_parser.parse(a_ ) __A = round((end_datetime - start_datetime).total_seconds() / 60.0 ) __A = start __A = end __A = duration_in_min return job_info def UpperCAmelCase ( a_ , a_=None ) -> str: """simple docstring""" __A = None if token is not None: __A = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} __A = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' __A = requests.get(a_ , headers=a_ ).json() __A = {} try: job_time.update({job["name"]: extract_time_from_single_job(a_ ) for job in result["jobs"]} ) __A = math.ceil((result["total_count"] - 1_0_0) / 1_0_0 ) for i in range(a_ ): __A = requests.get(url + F'''&page={i + 2}''' , headers=a_ ).json() job_time.update({job["name"]: extract_time_from_single_job(a_ ) for job in result["jobs"]} ) return job_time except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} if __name__ == "__main__": SCREAMING_SNAKE_CASE :Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() SCREAMING_SNAKE_CASE :Union[str, Any] = get_job_time(args.workflow_run_id) SCREAMING_SNAKE_CASE :Optional[int] = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'''{k}: {v["duration"]}''')
15
0
import random import unittest import numpy as np import torch from diffusers import ( DPMSolverMultistepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, LMSDiscreteScheduler, OnnxStableDiffusionUpscalePipeline, PNDMScheduler, ) from diffusers.utils import floats_tensor from diffusers.utils.testing_utils import ( is_onnx_available, load_image, nightly, require_onnxruntime, require_torch_gpu, ) from ..test_pipelines_onnx_common import OnnxPipelineTesterMixin if is_onnx_available(): import onnxruntime as ort class __snake_case ( lowerCAmelCase , unittest.TestCase ): # TODO: is there an appropriate internal test set? _a : List[str]= "ssube/stable-diffusion-x4-upscaler-onnx" def _SCREAMING_SNAKE_CASE ( self ,snake_case=0 ): '''simple docstring''' lowercase : List[Any] = floats_tensor((1, 3, 128, 128) ,rng=random.Random(snake_case ) ) lowercase : str = torch.manual_seed(snake_case ) lowercase : Dict = { """prompt""": """A painting of a squirrel eating a burger""", """image""": image, """generator""": generator, """num_inference_steps""": 3, """guidance_scale""": 7.5, """output_type""": """numpy""", } return inputs def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Union[str, Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,provider="""CPUExecutionProvider""" ) pipe.set_progress_bar_config(disable=snake_case ) lowercase : Tuple = self.get_dummy_inputs() lowercase : List[str] = pipe(**snake_case ).images lowercase : List[str] = image[0, -3:, -3:, -1].flatten() # started as 128, should now be 512 assert image.shape == (1, 512, 512, 3) lowercase : List[Any] = np.array( [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223] ) assert np.abs(image_slice - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,provider="""CPUExecutionProvider""" ) lowercase : Optional[int] = PNDMScheduler.from_config(pipe.scheduler.config ,skip_prk_steps=snake_case ) pipe.set_progress_bar_config(disable=snake_case ) lowercase : Union[str, Any] = self.get_dummy_inputs() lowercase : Tuple = pipe(**snake_case ).images lowercase : List[Any] = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowercase : List[str] = np.array( [0.6_898_892, 0.59_240_556, 0.52_499_527, 0.58_866_215, 0.52_258_235, 0.52_572_715, 0.62_414_473, 0.6_174_387, 0.6_214_964] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : int = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,provider="""CPUExecutionProvider""" ) lowercase : Dict = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=snake_case ) lowercase : int = self.get_dummy_inputs() lowercase : str = pipe(**snake_case ).images lowercase : int = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowercase : Any = np.array( [0.7_659_278, 0.76_437_664, 0.75_579_107, 0.7_691_116, 0.77_666_986, 0.7_727_672, 0.7_758_664, 0.7_812_226, 0.76_942_515] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,provider="""CPUExecutionProvider""" ) lowercase : str = EulerDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=snake_case ) lowercase : List[Any] = self.get_dummy_inputs() lowercase : Dict = pipe(**snake_case ).images lowercase : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowercase : Optional[int] = np.array( [0.6_974_782, 0.68_902_093, 0.70_135_885, 0.7_583_618, 0.7_804_545, 0.7_854_912, 0.78_667_426, 0.78_743_863, 0.78_070_223] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : str = OnnxStableDiffusionUpscalePipeline.from_pretrained(self.hub_checkpoint ,provider="""CPUExecutionProvider""" ) lowercase : List[Any] = EulerAncestralDiscreteScheduler.from_config(pipe.scheduler.config ) pipe.set_progress_bar_config(disable=snake_case ) lowercase : Tuple = self.get_dummy_inputs() lowercase : Optional[int] = pipe(**snake_case ).images lowercase : Dict = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowercase : str = np.array( [0.77_424_496, 0.773_601, 0.7_645_288, 0.7_769_598, 0.7_772_739, 0.7_738_688, 0.78_187_233, 0.77_879_584, 0.767_043] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-1 @nightly @require_onnxruntime @require_torch_gpu class __snake_case ( unittest.TestCase ): @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' return ( "CUDAExecutionProvider", { "gpu_mem_limit": "15000000000", # 15GB "arena_extend_strategy": "kSameAsRequested", }, ) @property def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Dict = ort.SessionOptions() lowercase : Tuple = False return options def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : Optional[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) lowercase : Dict = init_image.resize((128, 128) ) # using the PNDM scheduler by default lowercase : List[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=snake_case ) lowercase : List[str] = """A fantasy landscape, trending on artstation""" lowercase : str = torch.manual_seed(0 ) lowercase : Any = pipe( prompt=snake_case ,image=snake_case ,guidance_scale=7.5 ,num_inference_steps=10 ,generator=snake_case ,output_type="""np""" ,) lowercase : Optional[Any] = output.images lowercase : str = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) lowercase : Optional[int] = np.array([0.4_883, 0.4_947, 0.4_980, 0.4_975, 0.4_982, 0.4_980, 0.5_000, 0.5_006, 0.4_972] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2 def _SCREAMING_SNAKE_CASE ( self ): '''simple docstring''' lowercase : List[Any] = load_image( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" """/img2img/sketch-mountains-input.jpg""" ) lowercase : Dict = init_image.resize((128, 128) ) lowercase : Union[str, Any] = LMSDiscreteScheduler.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" ,subfolder="""scheduler""" ) lowercase : List[Any] = OnnxStableDiffusionUpscalePipeline.from_pretrained( """ssube/stable-diffusion-x4-upscaler-onnx""" ,scheduler=snake_case ,provider=self.gpu_provider ,sess_options=self.gpu_options ,) pipe.set_progress_bar_config(disable=snake_case ) lowercase : int = """A fantasy landscape, trending on artstation""" lowercase : Tuple = torch.manual_seed(0 ) lowercase : Any = pipe( prompt=snake_case ,image=snake_case ,guidance_scale=7.5 ,num_inference_steps=20 ,generator=snake_case ,output_type="""np""" ,) lowercase : str = output.images lowercase : int = images[0, 255:258, 383:386, -1] assert images.shape == (1, 512, 512, 3) lowercase : Tuple = np.array( [0.50_173_753, 0.50_223_356, 0.502_039, 0.50_233_036, 0.5_023_725, 0.5_022_601, 0.5_018_758, 0.50_234_085, 0.50_241_566] ) # TODO: lower the tolerance after finding the cause of onnxruntime reproducibility issues assert np.abs(image_slice.flatten() - expected_slice ).max() < 2e-2
20
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" __A = args.pruning_method __A = args.threshold __A = args.model_name_or_path.rstrip("/" ) __A = args.target_model_path print(F'''Load fine-pruned model from {model_name_or_path}''' ) __A = torch.load(os.path.join(a_ , "pytorch_model.bin" ) ) __A = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __A = tensor print(F'''Copied layer {name}''' ) elif "classifier" in name or "qa_output" in name: __A = tensor print(F'''Copied layer {name}''' ) elif "bias" in name: __A = tensor print(F'''Copied layer {name}''' ) else: if pruning_method == "magnitude": __A = MagnitudeBinarizer.apply(inputs=a_ , threshold=a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "topK": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A = TopKBinarizer.apply(a_ , a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A = ThresholdBinarizer.apply(a_ , a_ , a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "l0": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A , __A = -0.1, 1.1 __A = torch.sigmoid(a_ ) __A = s * (r - l) + l __A = s_bar.clamp(min=0.0 , max=1.0 ) __A = tensor * mask print(F'''Pruned layer {name}''' ) else: raise ValueError("Unknown pruning method" ) if target_model_path is None: __A = os.path.join( os.path.dirname(a_ ) , F'''bertarized_{os.path.basename(a_ )}''' ) if not os.path.isdir(a_ ): shutil.copytree(a_ , a_ ) print(F'''\nCreated folder {target_model_path}''' ) torch.save(a_ , os.path.join(a_ , "pytorch_model.bin" ) ) print("\nPruned model saved! See you later!" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--pruning_method', choices=['l0', 'magnitude', 'topK', 'sigmoied_threshold'], type=str, required=True, help=( 'Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,' ' sigmoied_threshold = Soft movement pruning)' ), ) parser.add_argument( '--threshold', type=float, required=False, help=( 'For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.' 'For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.' 'Not needed for `l0`' ), ) parser.add_argument( '--model_name_or_path', type=str, required=True, help='Folder containing the model that was previously fine-pruned', ) parser.add_argument( '--target_model_path', default=None, type=str, required=False, help='Folder containing the model that was previously fine-pruned', ) SCREAMING_SNAKE_CASE :str = parser.parse_args() main(args)
15
0
from sklearn.metrics import fa_score import datasets SCREAMING_SNAKE_CASE : Any = "\nThe F1 score is the harmonic mean of the precision and recall. It can be computed with the equation:\nF1 = 2 * (precision * recall) / (precision + recall)\n" SCREAMING_SNAKE_CASE : List[Any] = "\nArgs:\n predictions (`list` of `int`): Predicted labels.\n references (`list` of `int`): Ground truth labels.\n labels (`list` of `int`): The set of labels to include when `average` is not set to `'binary'`, and the order of the labels if `average` is `None`. Labels present in the data can be excluded, for example to calculate a multiclass average ignoring a majority negative class. Labels not present in the data will result in 0 components in a macro average. For multilabel targets, labels are column indices. By default, all labels in `predictions` and `references` are used in sorted order. Defaults to None.\n pos_label (`int`): The class to be considered the positive class, in the case where `average` is set to `binary`. Defaults to 1.\n average (`string`): This parameter is required for multiclass/multilabel targets. If set to `None`, the scores for each class are returned. Otherwise, this determines the type of averaging performed on the data. Defaults to `'binary'`.\n\n - 'binary': Only report results for the class specified by `pos_label`. This is applicable only if the classes found in `predictions` and `references` are binary.\n - 'micro': Calculate metrics globally by counting the total true positives, false negatives and false positives.\n - 'macro': Calculate metrics for each label, and find their unweighted mean. This does not take label imbalance into account.\n - 'weighted': Calculate metrics for each label, and find their average weighted by support (the number of true instances for each label). This alters `'macro'` to account for label imbalance. This option can result in an F-score that is not between precision and recall.\n - 'samples': Calculate metrics for each instance, and find their average (only meaningful for multilabel classification).\n sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n f1 (`float` or `array` of `float`): F1 score or list of f1 scores, depending on the value passed to `average`. Minimum possible value is 0. Maximum possible value is 1. Higher f1 scores are better.\n\nExamples:\n\n Example 1-A simple binary example\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0])\n >>> print(results)\n {'f1': 0.5}\n\n Example 2-The same simple binary example as in Example 1, but with `pos_label` set to `0`.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], pos_label=0)\n >>> print(round(results['f1'], 2))\n 0.67\n\n Example 3-The same simple binary example as in Example 1, but with `sample_weight` included.\n >>> f1_metric = datasets.load_metric(\"f1\")\n >>> results = f1_metric.compute(references=[0, 1, 0, 1, 0], predictions=[0, 0, 1, 1, 0], sample_weight=[0.9, 0.5, 3.9, 1.2, 0.3])\n >>> print(round(results['f1'], 2))\n 0.35\n\n Example 4-A multiclass example, with different values for the `average` input.\n >>> predictions = [0, 2, 1, 0, 0, 1]\n >>> references = [0, 1, 2, 0, 1, 2]\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"macro\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"micro\")\n >>> print(round(results['f1'], 2))\n 0.33\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=\"weighted\")\n >>> print(round(results['f1'], 2))\n 0.27\n >>> results = f1_metric.compute(predictions=predictions, references=references, average=None)\n >>> print(results)\n {'f1': array([0.8, 0. , 0. ])}\n" SCREAMING_SNAKE_CASE : List[Any] = "\n@article{scikit-learn,\n title={Scikit-learn: Machine Learning in {P}ython},\n author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.\n and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.\n and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and\n Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},\n journal={Journal of Machine Learning Research},\n volume={12},\n pages={2825--2830},\n year={2011}\n}\n" @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION, _KWARGS_DESCRIPTION ) class _lowerCamelCase( datasets.Metric ): def UpperCamelCase ( self) -> Dict: """simple docstring""" return datasets.MetricInfo( description=_DESCRIPTION, citation=_CITATION, inputs_description=_KWARGS_DESCRIPTION, features=datasets.Features( { 'predictions': datasets.Sequence(datasets.Value('int32')), 'references': datasets.Sequence(datasets.Value('int32')), } if self.config_name == 'multilabel' else { 'predictions': datasets.Value('int32'), 'references': datasets.Value('int32'), }), reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.f1_score.html'], ) def UpperCamelCase ( self, lowerCamelCase, lowerCamelCase, lowerCamelCase=None, lowerCamelCase=1, lowerCamelCase="binary", lowerCamelCase=None) -> Union[str, Any]: """simple docstring""" _lowercase : int = fa_score( lowerCamelCase, lowerCamelCase, labels=lowerCamelCase, pos_label=lowerCamelCase, average=lowerCamelCase, sample_weight=lowerCamelCase) return {"f1": float(lowerCamelCase) if score.size == 1 else score}
21
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :int = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Union[str, Any] = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } SCREAMING_SNAKE_CASE :int = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] snake_case_ = [] def __init__( self : Any ,A : List[str] ,A : str="<unk>" ,A : int="<s>" ,A : Union[str, Any]="</s>" ,A : List[str]="<pad>" ,A : int="[SEP]" ,A : Optional[Any]="[MASK]" ,A : Tuple="[CLS]" ,A : Optional[Dict[str, Any]] = None ,**A : Any ,): __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else bos_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else eos_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else unk_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else pad_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else cls_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else sep_token # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sep_token=A ,mask_token=A ,cls_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) @property def UpperCamelCase_ ( self : List[str] ): return self.sp_model.get_piece_size() def UpperCamelCase_ ( self : Optional[Any] ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : str ,A : Optional[Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Tuple ): return self.sp_model.piece_to_id(A ) def UpperCamelCase_ ( self : List[Any] ,A : Tuple ): __A = self.sp_model.IdToPiece(A ) return token def UpperCamelCase_ ( self : List[Any] ,A : int ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def UpperCamelCase_ ( self : Tuple ,A : List[int] ,A : bool = False ,A : bool = None ,A : bool = True ,**A : Union[str, Any] ,): __A = kwargs.pop("use_source_tokenizer" ,A ) __A = self.convert_ids_to_tokens(A ,skip_special_tokens=A ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __A = [] __A = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(A ) ) __A = [] sub_texts.append(A ) else: current_sub_text.append(A ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(A ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: __A = re.sub(R" (\[(MASK|SEP)\])" ,R"\1" ," ".join(A ) ) else: __A = "".join(A ) __A = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __A = self.clean_up_tokenization(A ) return clean_text else: return text def UpperCamelCase_ ( self : str ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Dict ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : Optional[int] ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Any ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [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]
15
0
'''simple docstring''' def UpperCAmelCase_ ( __lowercase : int ) -> str: '''simple docstring''' if isinstance(__lowercase , __lowercase ): raise TypeError("'float' object cannot be interpreted as an integer" ) if isinstance(__lowercase , __lowercase ): raise TypeError("'str' object cannot be interpreted as an integer" ) if num == 0: return "0b0" _UpperCAmelCase = False if num < 0: _UpperCAmelCase = True _UpperCAmelCase = -num _UpperCAmelCase = [] while num > 0: binary.insert(0 , num % 2 ) num >>= 1 if negative: return "-0b" + "".join(str(__lowercase ) for e in binary ) return "0b" + "".join(str(__lowercase ) for e in binary ) if __name__ == "__main__": import doctest doctest.testmod()
22
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): SCREAMING_SNAKE_CASE :Any = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: SCREAMING_SNAKE_CASE :int = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" __A = (images / 2 + 0.5).clamp(0 , 1 ) __A = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __A = numpy_to_pil(a_ ) return images def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if images.ndim == 3: __A = images[None, ...] __A = (images * 2_5_5).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __A = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __A = [Image.fromarray(a_ ) for image in images] return pil_images
15
0
'''simple docstring''' class SCREAMING_SNAKE_CASE: """simple docstring""" def __init__( self : Optional[Any] ) -> None: UpperCAmelCase : dict[str, TrieNode] = {} # Mapping from char to TrieNode UpperCAmelCase : str = False def A ( self : Tuple , __snake_case : list[str] ) -> None: for word in words: self.insert(__snake_case ) def A ( self : Union[str, Any] , __snake_case : str ) -> None: UpperCAmelCase : Any = self for char in word: if char not in curr.nodes: UpperCAmelCase : str = TrieNode() UpperCAmelCase : str = curr.nodes[char] UpperCAmelCase : Optional[Any] = True def A ( self : Optional[Any] , __snake_case : str ) -> bool: UpperCAmelCase : str = self for char in word: if char not in curr.nodes: return False UpperCAmelCase : List[str] = curr.nodes[char] return curr.is_leaf def A ( self : List[str] , __snake_case : str ) -> None: def _delete(__snake_case : TrieNode , __snake_case : str , __snake_case : int ) -> bool: if index == len(__snake_case ): # If word does not exist if not curr.is_leaf: return False UpperCAmelCase : Union[str, Any] = False return len(curr.nodes ) == 0 UpperCAmelCase : Optional[Any] = word[index] UpperCAmelCase : str = curr.nodes.get(__snake_case ) # If char not in current trie node if not char_node: return False # Flag to check if node can be deleted UpperCAmelCase : Union[str, Any] = _delete(__snake_case , __snake_case , index + 1 ) if delete_curr: del curr.nodes[char] return len(curr.nodes ) == 0 return delete_curr _delete(self , __snake_case , 0 ) def snake_case_ ( _lowerCAmelCase : TrieNode , _lowerCAmelCase : str ) -> None: if node.is_leaf: print(_lowerCAmelCase , end=''' ''' ) for key, value in node.nodes.items(): print_words(_lowerCAmelCase , word + key ) def snake_case_ ( ) -> bool: UpperCAmelCase : List[str] = '''banana bananas bandana band apple all beast'''.split() UpperCAmelCase : int = TrieNode() root.insert_many(_lowerCAmelCase ) # print_words(root, "") assert all(root.find(_lowerCAmelCase ) for word in words ) assert root.find('''banana''' ) assert not root.find('''bandanas''' ) assert not root.find('''apps''' ) assert root.find('''apple''' ) assert root.find('''all''' ) root.delete('''all''' ) assert not root.find('''all''' ) root.delete('''banana''' ) assert not root.find('''banana''' ) assert root.find('''bananas''' ) return True def snake_case_ ( _lowerCAmelCase : str , _lowerCAmelCase : bool ) -> None: print(str(_lowerCAmelCase ) , '''works!''' if passes else '''doesn\'t work :(''' ) def snake_case_ ( ) -> None: assert test_trie() def snake_case_ ( ) -> None: print_results('''Testing trie functionality''' , test_trie() ) if __name__ == "__main__": main()
23
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 :Optional[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 UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "yolos" def __init__( self : Any ,A : Optional[Any]=7_68 ,A : Dict=12 ,A : Any=12 ,A : str=30_72 ,A : Any="gelu" ,A : str=0.0 ,A : List[str]=0.0 ,A : Dict=0.02 ,A : int=1E-12 ,A : Tuple=[5_12, 8_64] ,A : List[Any]=16 ,A : str=3 ,A : str=True ,A : Any=1_00 ,A : Dict=True ,A : Dict=False ,A : Tuple=1 ,A : Union[str, Any]=5 ,A : Optional[Any]=2 ,A : Union[str, Any]=5 ,A : int=2 ,A : int=0.1 ,**A : List[str] ,): super().__init__(**A ) __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = initializer_range __A = layer_norm_eps __A = image_size __A = patch_size __A = num_channels __A = qkv_bias __A = num_detection_tokens __A = use_mid_position_embeddings __A = auxiliary_loss # Hungarian matcher __A = class_cost __A = bbox_cost __A = giou_cost # Loss coefficients __A = bbox_loss_coefficient __A = giou_loss_coefficient __A = eos_coefficient class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = version.parse("1.11" ) @property def UpperCamelCase_ ( self : str ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCamelCase_ ( self : List[Any] ): return 1E-4 @property def UpperCamelCase_ ( self : Optional[Any] ): return 12
15
0
import re def lowerCamelCase__ ( snake_case_ : str ) -> list: return [char.split() for char in re.split(R'''[^ a-z A-Z 0-9 \s]''' , str_ )] def lowerCamelCase__ ( snake_case_ : str ) -> str: __snake_case = split_input(str_ ) return "".join( [''''''.join([char.capitalize() for char in sub_str] ) for sub_str in string_split] ) def lowerCamelCase__ ( snake_case_ : str , snake_case_ : bool , snake_case_ : str ) -> str: try: __snake_case = split_input(snake_case_ ) if upper: __snake_case = ''''''.join( [ separator.join([char.upper() for char in sub_str] ) for sub_str in string_split ] ) else: __snake_case = ''''''.join( [ separator.join([char.lower() for char in sub_str] ) for sub_str in string_split ] ) return res_str except IndexError: return "not valid string" def lowerCamelCase__ ( snake_case_ : str ) -> str: return to_simple_case(snake_case_ ) def lowerCamelCase__ ( snake_case_ : str ) -> str: try: __snake_case = to_simple_case(snake_case_ ) return res_str[0].lower() + res_str[1:] except IndexError: return "not valid string" def lowerCamelCase__ ( snake_case_ : str , snake_case_ : bool ) -> str: return to_complex_case(snake_case_ , snake_case_ , '''_''' ) def lowerCamelCase__ ( snake_case_ : str , snake_case_ : bool ) -> str: return to_complex_case(snake_case_ , snake_case_ , '''-''' ) if __name__ == "__main__": __import__('doctest').testmod()
24
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) SCREAMING_SNAKE_CASE :List[str] = 'pytorch_model.bin' SCREAMING_SNAKE_CASE :str = 'pytorch_model.bin.index.json' SCREAMING_SNAKE_CASE :Optional[int] = 'adapter_config.json' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.bin' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.safetensors' SCREAMING_SNAKE_CASE :str = 'tf_model.h5' SCREAMING_SNAKE_CASE :List[Any] = 'tf_model.h5.index.json' SCREAMING_SNAKE_CASE :str = 'model.ckpt' SCREAMING_SNAKE_CASE :List[Any] = 'flax_model.msgpack' SCREAMING_SNAKE_CASE :Optional[int] = 'flax_model.msgpack.index.json' SCREAMING_SNAKE_CASE :Tuple = 'model.safetensors' SCREAMING_SNAKE_CASE :List[Any] = 'model.safetensors.index.json' SCREAMING_SNAKE_CASE :str = 'config.json' SCREAMING_SNAKE_CASE :int = 'preprocessor_config.json' SCREAMING_SNAKE_CASE :Optional[Any] = FEATURE_EXTRACTOR_NAME SCREAMING_SNAKE_CASE :Optional[int] = 'generation_config.json' SCREAMING_SNAKE_CASE :List[str] = 'modelcard.json' SCREAMING_SNAKE_CASE :Optional[int] = '▁' SCREAMING_SNAKE_CASE :Optional[Any] = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility SCREAMING_SNAKE_CASE :str = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. SCREAMING_SNAKE_CASE :Optional[Any] = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] SCREAMING_SNAKE_CASE :List[Any] = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" if version.parse(a_ ) < version.parse(a_ ): if "dev" in min_version: __A = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: __A = F'''This example requires a minimum version of {min_version},''' error_message += F''' but the version found is {__version__}.\n''' raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers." )
15
0
"""simple docstring""" from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCAmelCase__ : Tuple = logging.get_logger(__name__) UpperCAmelCase__ : Union[str, Any] = { 'facebook/vit-mae-base': 'https://huggingface.co/facebook/vit-mae-base/resolve/main/config.json', # See all ViT MAE models at https://huggingface.co/models?filter=vit-mae } class lowerCAmelCase_ (a__ ): """simple docstring""" __UpperCamelCase : List[Any] = '''vit_mae''' def __init__(self , SCREAMING_SNAKE_CASE__=7_68 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=12 , SCREAMING_SNAKE_CASE__=30_72 , SCREAMING_SNAKE_CASE__="gelu" , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.0 , SCREAMING_SNAKE_CASE__=0.02 , SCREAMING_SNAKE_CASE__=1E-12 , SCREAMING_SNAKE_CASE__=2_24 , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=3 , SCREAMING_SNAKE_CASE__=True , SCREAMING_SNAKE_CASE__=16 , SCREAMING_SNAKE_CASE__=5_12 , SCREAMING_SNAKE_CASE__=8 , SCREAMING_SNAKE_CASE__=20_48 , SCREAMING_SNAKE_CASE__=0.75 , SCREAMING_SNAKE_CASE__=False , **SCREAMING_SNAKE_CASE__ , ) -> Tuple: """simple docstring""" super().__init__(**SCREAMING_SNAKE_CASE__ ) SCREAMING_SNAKE_CASE__ : int = hidden_size SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_hidden_layers SCREAMING_SNAKE_CASE__ : Union[str, Any] = num_attention_heads SCREAMING_SNAKE_CASE__ : Any = intermediate_size SCREAMING_SNAKE_CASE__ : Optional[Any] = hidden_act SCREAMING_SNAKE_CASE__ : Tuple = hidden_dropout_prob SCREAMING_SNAKE_CASE__ : Optional[Any] = attention_probs_dropout_prob SCREAMING_SNAKE_CASE__ : Dict = initializer_range SCREAMING_SNAKE_CASE__ : Any = layer_norm_eps SCREAMING_SNAKE_CASE__ : int = image_size SCREAMING_SNAKE_CASE__ : str = patch_size SCREAMING_SNAKE_CASE__ : List[Any] = num_channels SCREAMING_SNAKE_CASE__ : Union[str, Any] = qkv_bias SCREAMING_SNAKE_CASE__ : Any = decoder_num_attention_heads SCREAMING_SNAKE_CASE__ : Optional[Any] = decoder_hidden_size SCREAMING_SNAKE_CASE__ : List[str] = decoder_num_hidden_layers SCREAMING_SNAKE_CASE__ : Optional[int] = decoder_intermediate_size SCREAMING_SNAKE_CASE__ : str = mask_ratio SCREAMING_SNAKE_CASE__ : List[Any] = norm_pix_loss
25
def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = [0] * len(a_ ) __A = [] __A = [1] * len(a_ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(a_ ) ): if indegree[i] == 0: queue.append(a_ ) while queue: __A = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __A = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(a_ ) print(max(a_ ) ) # Adjacency list of Graph SCREAMING_SNAKE_CASE :List[Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
15
0
import numpy as np from numpy import ndarray from scipy.optimize import Bounds, LinearConstraint, minimize def lowerCAmelCase_ ( snake_case_ ): return np.dot(snake_case_,snake_case_ ) class lowercase : def __init__( self , *, _a = np.inf , _a = "linear" , _a = 0.0 , ) -> None: _A : List[Any] = regularization _A : Optional[int] = gamma if kernel == "linear": _A : List[str] = 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""" ) _A : Optional[int] = 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: _A : Dict = F'''Unknown kernel: {kernel}''' raise ValueError(_a ) def a__ ( self , _a , _a ) -> float: return np.dot(_a , _a ) def a__ ( self , _a , _a ) -> float: return np.exp(-(self.gamma * norm_squared(vectora - vectora )) ) def a__ ( self , _a , _a ) -> None: _A : List[Any] = observations _A : Optional[int] = 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 ((_A) , ) : Union[str, Any] = np.shape(_a ) def to_minimize(_a ) -> float: _A : str = 0 ((_A) , ) : Optional[int] = 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 ) _A : Optional[int] = LinearConstraint(_a , 0 , 0 ) _A : List[str] = Bounds(0 , self.regularization ) _A : Dict = minimize( _a , np.ones(_a ) , bounds=_a , constraints=[ly_contraint] ).x _A : Union[str, Any] = l_star # calculating mean offset of separation plane to points _A : Optional[int] = 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] ) _A : str = s / n def a__ ( self , _a ) -> int: _A : Union[str, Any] = 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()
26
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __A = key.replace("heads.cmd.mim_head.cls.predictions" , "mmm_image_head" ) __A = key.replace("heads.cmd.mlm_head.cls.predictions" , "mmm_text_head" ) __A = key.replace("heads.cmd.itm_head.cls" , "itm_head" ) __A = key.replace("heads.cmd.itm_head.pooler" , "itm_head.pooler" ) __A = key.replace("heads.cmd.clip_head.logit_scale" , "flava.logit_scale" ) __A = key.replace("heads.fairseq_mlm.cls.predictions" , "mlm_head" ) __A = key.replace("heads.imagenet.mim_head.cls.predictions" , "mim_head" ) __A = key.replace("mm_text_projection" , "flava.text_to_mm_projection" ) __A = key.replace("mm_image_projection" , "flava.image_to_mm_projection" ) __A = key.replace("image_encoder.module" , "flava.image_model" ) __A = key.replace("text_encoder.module" , "flava.text_model" ) __A = key.replace("mm_encoder.module.encoder.cls_token" , "flava.multimodal_model.cls_token" ) __A = key.replace("mm_encoder.module" , "flava.multimodal_model" ) __A = key.replace("text_projection" , "flava.text_projection" ) __A = key.replace("image_projection" , "flava.image_projection" ) __A = value.float() for key, value in codebook_state_dict.items(): __A = value return upgrade @torch.no_grad() def UpperCAmelCase ( a_ , a_ , a_ , a_=None ) -> Tuple: """simple docstring""" if config_path is not None: __A = FlavaConfig.from_pretrained(a_ ) else: __A = FlavaConfig() __A = FlavaForPreTraining(a_ ).eval() __A = convert_dalle_checkpoint(a_ , a_ , save_checkpoint=a_ ) if os.path.exists(a_ ): __A = torch.load(a_ , map_location="cpu" ) else: __A = torch.hub.load_state_dict_from_url(a_ , map_location="cpu" ) __A = upgrade_state_dict(a_ , a_ ) hf_model.load_state_dict(a_ ) __A = hf_model.state_dict() __A = count_parameters(a_ ) __A = count_parameters(a_ ) + count_parameters(a_ ) assert torch.allclose(a_ , a_ , atol=1E-3 ) hf_model.save_pretrained(a_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
15
0
'''simple docstring''' import fire from torch.utils.data import DataLoader from tqdm import tqdm from transformers import AutoTokenizer from utils import SeqaSeqDataset, pickle_save def lowerCamelCase (_SCREAMING_SNAKE_CASE : int , _SCREAMING_SNAKE_CASE : Optional[int] , _SCREAMING_SNAKE_CASE : Union[str, Any]=1_024 , _SCREAMING_SNAKE_CASE : Optional[int]=1_024 , _SCREAMING_SNAKE_CASE : Tuple=False , **_SCREAMING_SNAKE_CASE : Union[str, Any] ): __a : Dict = AutoTokenizer.from_pretrained(_SCREAMING_SNAKE_CASE ) __a : Tuple = SeqaSeqDataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , type_path='train' , **_SCREAMING_SNAKE_CASE ) __a : int = tok.pad_token_id def get_lens(_SCREAMING_SNAKE_CASE : str ): __a : List[Any] = tqdm( DataLoader(_SCREAMING_SNAKE_CASE , batch_size=512 , num_workers=8 , shuffle=_SCREAMING_SNAKE_CASE , collate_fn=ds.collate_fn ) , desc=str(ds.len_file ) , ) __a : Dict = [] for batch in dl: __a : Optional[int] = batch['input_ids'].ne(_SCREAMING_SNAKE_CASE ).sum(1 ).tolist() __a : Any = batch['labels'].ne(_SCREAMING_SNAKE_CASE ).sum(1 ).tolist() if consider_target: for src, tgt in zip(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ): max_lens.append(max(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE ) ) else: max_lens.extend(_SCREAMING_SNAKE_CASE ) return max_lens __a : Optional[int] = get_lens(_SCREAMING_SNAKE_CASE ) __a : Optional[int] = SeqaSeqDataset(_SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , _SCREAMING_SNAKE_CASE , type_path='val' , **_SCREAMING_SNAKE_CASE ) __a : int = get_lens(_SCREAMING_SNAKE_CASE ) pickle_save(_SCREAMING_SNAKE_CASE , train_ds.len_file ) pickle_save(_SCREAMING_SNAKE_CASE , val_ds.len_file ) if __name__ == "__main__": fire.Fire(save_len_file)
27
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Optional[int] = {'vocab_file': 'sentencepiece.bpe.model'} SCREAMING_SNAKE_CASE :Tuple = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', } } SCREAMING_SNAKE_CASE :List[Any] = { 'camembert-base': 512, } SCREAMING_SNAKE_CASE :List[str] = '▁' class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[Any] ,A : List[str] ,A : List[Any]="<s>" ,A : Tuple="</s>" ,A : Any="</s>" ,A : Optional[Any]="<s>" ,A : Tuple="<unk>" ,A : str="<pad>" ,A : int="<mask>" ,A : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] ,A : Optional[Dict[str, Any]] = None ,**A : Optional[Any] ,): # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,sep_token=A ,cls_token=A ,pad_token=A ,mask_token=A ,additional_special_tokens=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A ) ) __A = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> __A = {"<s>NOTUSED": 0, "<pad>": 1, "</s>NOTUSED": 2, "<unk>": 3} __A = len(self.fairseq_tokens_to_ids ) __A = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) __A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self : int ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : Dict ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Union[str, Any] ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self : Dict ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def UpperCamelCase_ ( self : int ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Dict ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(A ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : Tuple ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase_ ( self : Optional[Any] ,A : Dict ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def __getstate__( self : Dict ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Union[str, Any] ,A : Any ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,)
15
0
'''simple docstring''' import argparse import os import re import packaging.version _lowerCamelCase : int = "examples/" _lowerCamelCase : Dict = { "examples": (re.compile(R"^check_min_version\(\"[^\"]+\"\)\s*$", re.MULTILINE), "check_min_version(\"VERSION\")\n"), "init": (re.compile(R"^__version__\s+=\s+\"([^\"]+)\"\s*$", re.MULTILINE), "__version__ = \"VERSION\"\n"), "setup": (re.compile(R"^(\s*)version\s*=\s*\"[^\"]+\",", re.MULTILINE), R"\1version=\"VERSION\","), "doc": (re.compile(R"^(\s*)release\s*=\s*\"[^\"]+\"$", re.MULTILINE), "release = \"VERSION\"\n"), } _lowerCamelCase : List[str] = { "init": "src/transformers/__init__.py", "setup": "setup.py", } _lowerCamelCase : Union[str, Any] = "README.md" def __lowerCamelCase ( A__ , A__ , A__ ) -> Optional[Any]: """simple docstring""" with open(A__ , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase = f.read() UpperCamelCase , UpperCamelCase = REPLACE_PATTERNS[pattern] UpperCamelCase = replace.replace('VERSION' , A__ ) UpperCamelCase = re_pattern.sub(A__ , A__ ) with open(A__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.write(A__ ) def __lowerCamelCase ( A__ ) -> Optional[int]: """simple docstring""" for folder, directories, fnames in os.walk(A__ ): # Removing some of the folders with non-actively maintained examples from the walk if "research_projects" in directories: directories.remove('research_projects' ) if "legacy" in directories: directories.remove('legacy' ) for fname in fnames: if fname.endswith('.py' ): update_version_in_file(os.path.join(A__ , A__ ) , A__ , pattern='examples' ) def __lowerCamelCase ( A__ , A__=False ) -> List[str]: """simple docstring""" for pattern, fname in REPLACE_FILES.items(): update_version_in_file(A__ , A__ , A__ ) if not patch: update_version_in_examples(A__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" UpperCamelCase = '🤗 Transformers currently provides the following architectures' UpperCamelCase = '1. Want to contribute a new model?' with open(A__ , 'r' , encoding='utf-8' , newline='\n' ) as f: UpperCamelCase = f.readlines() # Find the start of the list. UpperCamelCase = 0 while not lines[start_index].startswith(_start_prompt ): start_index += 1 start_index += 1 UpperCamelCase = start_index # Update the lines in the model list. while not lines[index].startswith(_end_prompt ): if lines[index].startswith('1.' ): UpperCamelCase = lines[index].replace( 'https://huggingface.co/docs/transformers/main/model_doc' , 'https://huggingface.co/docs/transformers/model_doc' , ) index += 1 with open(A__ , 'w' , encoding='utf-8' , newline='\n' ) as f: f.writelines(A__ ) def __lowerCamelCase ( ) -> Optional[Any]: """simple docstring""" with open(REPLACE_FILES['init'] , 'r' ) as f: UpperCamelCase = f.read() UpperCamelCase = REPLACE_PATTERNS['init'][0].search(A__ ).groups()[0] return packaging.version.parse(A__ ) def __lowerCamelCase ( A__=False ) -> Union[str, Any]: """simple docstring""" UpperCamelCase = get_version() if patch and default_version.is_devrelease: raise ValueError('Can\'t create a patch version from the dev branch, checkout a released version!' ) if default_version.is_devrelease: UpperCamelCase = default_version.base_version elif patch: UpperCamelCase = F"""{default_version.major}.{default_version.minor}.{default_version.micro + 1}""" else: UpperCamelCase = F"""{default_version.major}.{default_version.minor + 1}.0""" # Now let's ask nicely if that's the right one. UpperCamelCase = input(F"""Which version are you releasing? [{default_version}]""" ) if len(A__ ) == 0: UpperCamelCase = default_version print(F"""Updating version to {version}.""" ) global_version_update(A__ , patch=A__ ) if not patch: print('Cleaning main README, don\'t forget to run `make fix-copies`.' ) clean_main_ref_in_model_list() def __lowerCamelCase ( ) -> int: """simple docstring""" UpperCamelCase = get_version() UpperCamelCase = F"""{current_version.major}.{current_version.minor + 1}.0.dev0""" UpperCamelCase = current_version.base_version # Check with the user we got that right. UpperCamelCase = input(F"""Which version are we developing now? [{dev_version}]""" ) if len(A__ ) == 0: UpperCamelCase = dev_version print(F"""Updating version to {version}.""" ) global_version_update(A__ ) print('Cleaning main README, don\'t forget to run `make fix-copies`.' ) clean_main_ref_in_model_list() if __name__ == "__main__": _lowerCamelCase : Optional[Any] = argparse.ArgumentParser() parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") _lowerCamelCase : Dict = parser.parse_args() if not args.post_release: pre_release_work(patch=args.patch) elif args.patch: print("Nothing to do after a patch :-)") else: post_release_work()
28
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return [tuple(a_ )] __A = [] def generate(a_ , a_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , a_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even __A , __A = arr[k - 1], arr[i] else: # k is odd __A , __A = arr[k - 1], arr[0] generate(k - 1 , a_ ) generate(len(a_ ) , a_ ) return res if __name__ == "__main__": SCREAMING_SNAKE_CASE :int = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :Dict = [int(item) for item in user_input.split(',')] print(heaps(arr))
15
0
__UpperCAmelCase = { 0: '0', 1: '1', 2: '2', 3: '3', 4: '4', 5: '5', 6: '6', 7: '7', 8: '8', 9: '9', 10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f', } def lowercase__ ( __snake_case : float ): '''simple docstring''' assert type(__snake_case ) in (int, float) and decimal == int(__snake_case ) UpperCAmelCase_ : Tuple = int(__snake_case ) UpperCAmelCase_ : int = '' UpperCAmelCase_ : Dict = False if decimal < 0: UpperCAmelCase_ : Any = True decimal *= -1 while decimal > 0: UpperCAmelCase_ , UpperCAmelCase_ : Dict = divmod(__snake_case , 16 ) UpperCAmelCase_ : Optional[int] = values[remainder] + hexadecimal UpperCAmelCase_ : str = '0x' + hexadecimal if negative: UpperCAmelCase_ : Optional[int] = '-' + hexadecimal return hexadecimal if __name__ == "__main__": import doctest doctest.testmod()
29
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return lst __A = 1 while i < len(a_ ): if lst[i - 1] <= lst[i]: i += 1 else: __A , __A = lst[i], lst[i - 1] i -= 1 if i == 0: __A = 1 return lst if __name__ == "__main__": SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :List[Any] = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
15
0
from typing import TYPE_CHECKING # rely on isort to merge the imports from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __a = { 'configuration_autoformer': [ 'AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP', 'AutoformerConfig', ], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __a = [ 'AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST', 'AutoformerForPrediction', 'AutoformerModel', 'AutoformerPreTrainedModel', ] if TYPE_CHECKING: from .configuration_autoformer import ( AUTOFORMER_PRETRAINED_CONFIG_ARCHIVE_MAP, AutoformerConfig, ) try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_autoformer import ( AUTOFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, AutoformerForPrediction, AutoformerModel, AutoformerPreTrainedModel, ) else: import sys __a = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
30
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 snake_case_ = 42 snake_case_ = None class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 2 @register_to_config def __init__( self : str ,A : float = 0.02 ,A : float = 1_00 ,A : float = 1.0_07 ,A : float = 80 ,A : float = 0.05 ,A : float = 50 ,): # standard deviation of the initial noise distribution __A = sigma_max # setable values __A = None __A = None __A = None # sigma(t_i) def UpperCamelCase_ ( self : str ,A : torch.FloatTensor ,A : Optional[int] = None ): return sample def UpperCamelCase_ ( self : Dict ,A : int ,A : Union[str, torch.device] = None ): __A = num_inference_steps __A = np.arange(0 ,self.num_inference_steps )[::-1].copy() __A = torch.from_numpy(A ).to(A ) __A = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __A = torch.tensor(A ,dtype=torch.floataa ,device=A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : torch.FloatTensor ,A : float ,A : Optional[torch.Generator] = None ): if self.config.s_min <= sigma <= self.config.s_max: __A = min(self.config.s_churn / self.num_inference_steps ,2**0.5 - 1 ) else: __A = 0 # sample eps ~ N(0, S_noise^2 * I) __A = self.config.s_noise * randn_tensor(sample.shape ,generator=A ).to(sample.device ) __A = sigma + gamma * sigma __A = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase_ ( self : Dict ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_hat + sigma_hat * model_output __A = (sample_hat - pred_original_sample) / sigma_hat __A = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : Optional[int] ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_prev + sigma_prev * model_output __A = (sample_prev - pred_original_sample) / sigma_prev __A = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : List[Any] ,A : Dict ,A : List[str] ,A : str ): raise NotImplementedError()
15
0
'''simple docstring''' import logging import numpy as np import pytest from scipy.linalg import eigh logging.basicConfig(level=logging.INFO, format="""%(message)s""") def UpperCamelCase_ ( _UpperCAmelCase : np.ndarray ) -> np.ndarray: """simple docstring""" return input_array.reshape((input_array.size, 1) ) def UpperCamelCase_ ( _UpperCAmelCase : np.ndarray , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : int ) -> np.ndarray: """simple docstring""" _UpperCAmelCase : Dict = np.nan for i in range(_UpperCAmelCase ): _UpperCAmelCase : Union[str, Any] = features[:, labels == i] _UpperCAmelCase : Dict = data.mean(1 ) # Centralize the data of class i _UpperCAmelCase : Any = data - column_reshape(_UpperCAmelCase ) if i > 0: # If covariance_sum is not None covariance_sum += np.dot(_UpperCAmelCase , centered_data.T ) else: # If covariance_sum is np.nan (i.e. first loop) _UpperCAmelCase : Tuple = np.dot(_UpperCAmelCase , centered_data.T ) return covariance_sum / features.shape[1] def UpperCamelCase_ ( _UpperCAmelCase : np.ndarray , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : int ) -> np.ndarray: """simple docstring""" _UpperCAmelCase : Any = features.mean(1 ) _UpperCAmelCase : Tuple = np.nan for i in range(_UpperCAmelCase ): _UpperCAmelCase : int = features[:, labels == i] _UpperCAmelCase : Dict = data.shape[1] _UpperCAmelCase : Dict = data.mean(1 ) if i > 0: # If covariance_sum is not None covariance_sum += device_data * np.dot( column_reshape(_UpperCAmelCase ) - column_reshape(_UpperCAmelCase ) , (column_reshape(_UpperCAmelCase ) - column_reshape(_UpperCAmelCase )).T , ) else: # If covariance_sum is np.nan (i.e. first loop) _UpperCAmelCase : int = device_data * np.dot( column_reshape(_UpperCAmelCase ) - column_reshape(_UpperCAmelCase ) , (column_reshape(_UpperCAmelCase ) - column_reshape(_UpperCAmelCase )).T , ) return covariance_sum / features.shape[1] def UpperCamelCase_ ( _UpperCAmelCase : np.ndarray , _UpperCAmelCase : int ) -> np.ndarray: """simple docstring""" if features.any(): _UpperCAmelCase : Any = features.mean(1 ) # Center the dataset _UpperCAmelCase : Tuple = features - np.reshape(_UpperCAmelCase , (data_mean.size, 1) ) _UpperCAmelCase : List[str] = np.dot(_UpperCAmelCase , centered_data.T ) / features.shape[1] _UpperCAmelCase , _UpperCAmelCase : Union[str, Any] = np.linalg.eigh(_UpperCAmelCase ) # Take all the columns in the reverse order (-1), and then takes only the first _UpperCAmelCase : Tuple = eigenvectors[:, ::-1][:, 0:dimensions] # Project the database on the new space _UpperCAmelCase : List[Any] = np.dot(filtered_eigenvectors.T , _UpperCAmelCase ) logging.info("Principal Component Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=_UpperCAmelCase ) logging.error("Dataset empty" ) raise AssertionError def UpperCamelCase_ ( _UpperCAmelCase : np.ndarray , _UpperCAmelCase : np.ndarray , _UpperCAmelCase : int , _UpperCAmelCase : int ) -> np.ndarray: """simple docstring""" assert classes > dimensions # Check if features have been already loaded if features.any: _UpperCAmelCase , _UpperCAmelCase : str = eigh( covariance_between_classes(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) , covariance_within_classes(_UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) , ) _UpperCAmelCase : Any = eigenvectors[:, ::-1][:, :dimensions] _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase : List[Any] = np.linalg.svd(_UpperCAmelCase ) _UpperCAmelCase : Union[str, Any] = svd_matrix[:, 0:dimensions] _UpperCAmelCase : List[str] = np.dot(filtered_svd_matrix.T , _UpperCAmelCase ) logging.info("Linear Discriminant Analysis computed" ) return projected_data else: logging.basicConfig(level=logging.ERROR , format="%(message)s" , force=_UpperCAmelCase ) logging.error("Dataset empty" ) raise AssertionError def UpperCamelCase_ ( ) -> None: """simple docstring""" _UpperCAmelCase : Dict = np.array([[1, 2, 3, 4, 5], [2, 3, 4, 5, 6], [3, 4, 5, 6, 7]] ) _UpperCAmelCase : Dict = np.array([0, 0, 0, 1, 1] ) _UpperCAmelCase : Tuple = 2 _UpperCAmelCase : int = 2 # Assert that the function raises an AssertionError if dimensions > classes with pytest.raises(_UpperCAmelCase ) as error_info: _UpperCAmelCase : Any = linear_discriminant_analysis( _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase ) if isinstance(_UpperCAmelCase , np.ndarray ): raise AssertionError( "Did not raise AssertionError for dimensions > classes" ) assert error_info.type is AssertionError def UpperCamelCase_ ( ) -> None: """simple docstring""" _UpperCAmelCase : Optional[int] = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]] ) _UpperCAmelCase : Optional[int] = 2 _UpperCAmelCase : List[Any] = np.array([[6.9_2_8_2_0_3_2_3, 8.6_6_0_2_5_4_0_4, 1_0.3_9_2_3_0_4_8_5], [3.0, 3.0, 3.0]] ) with pytest.raises(_UpperCAmelCase ) as error_info: _UpperCAmelCase : Optional[Any] = principal_component_analysis(_UpperCAmelCase , _UpperCAmelCase ) if not np.allclose(_UpperCAmelCase , _UpperCAmelCase ): raise AssertionError assert error_info.type is AssertionError if __name__ == "__main__": import doctest doctest.testmod()
31
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version SCREAMING_SNAKE_CASE :Union[str, Any] = get_logger(__name__) class UpperCAmelCase : '''simple docstring''' snake_case_ = "dummy_data" snake_case_ = "datasets" snake_case_ = False def __init__( self : Optional[int] ,A : str ,A : str ,A : Union[Version, str] ,A : Optional[str] = None ,A : bool = False ,A : bool = True ,A : Optional[List[Callable]] = None ,): __A = 0 __A = dataset_name __A = cache_dir __A = use_local_dummy_data __A = config # download_callbacks take a single url as input __A = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __A = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __A = str(A ) # to be downloaded __A = None __A = None @property def UpperCamelCase_ ( self : Union[str, Any] ): if self._dummy_file is None: __A = self.download_dummy_data() return self._dummy_file @property def UpperCamelCase_ ( self : Optional[Any] ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" ,self.config.name ,self.version_name ) # structure is dummy / version_name return os.path.join("dummy" ,self.version_name ) @property def UpperCamelCase_ ( self : List[Any] ): return os.path.join(self.dummy_data_folder ,"dummy_data.zip" ) def UpperCamelCase_ ( self : Tuple ): __A = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __A = cached_path( A ,cache_dir=self.cache_dir ,extract_compressed_file=A ,force_extract=A ) return os.path.join(A ,self.dummy_file_name ) @property def UpperCamelCase_ ( self : str ): return os.path.join(self.datasets_scripts_dir ,self.dataset_name ,self.dummy_zip_file ) @property def UpperCamelCase_ ( self : Any ): if self._bucket_url is None: __A = hf_github_url(self.dataset_name ,self.dummy_zip_file.replace(os.sep ,"/" ) ) return self._bucket_url @property def UpperCamelCase_ ( self : Tuple ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep ,"/" ).split("/" )[:-1] ) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,*A : Dict ): if self.load_existing_dummy_data: # dummy data is downloaded and tested __A = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __A = self.dummy_file_name # special case when data_url is a dict if isinstance(A ,A ): return self.create_dummy_data_dict(A ,A ) elif isinstance(A ,(list, tuple) ): return self.create_dummy_data_list(A ,A ) else: return self.create_dummy_data_single(A ,A ) def UpperCamelCase_ ( self : str ,A : List[Any] ,*A : List[Any] ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : List[str] ,A : List[str] ,A : Tuple ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : Any ,A : Any ,*A : Optional[Any] ,**A : List[str] ): return path def UpperCamelCase_ ( self : str ): return {} def UpperCamelCase_ ( self : int ,A : int ,A : Tuple ): __A = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A ,A ): for single_url in single_urls: download_callback(A ) else: __A = single_urls download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A ,A ): __A = [os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) for x in single_urls] else: __A = single_urls __A = os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) __A = value # make sure that values are unique if all(isinstance(A ,A ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __A = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,A : str ): __A = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __A = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" ,A ) ) for url in data_url ) __A = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __A = [data_url[0]] * len(A ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(A ) return dummy_data_list def UpperCamelCase_ ( self : str ,A : List[Any] ,A : Optional[Any] ): for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(A ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : Dict ): pass def UpperCamelCase_ ( self : Optional[Any] ,A : List[Any] ): def _iter_archive_members(A : Optional[Any] ): # this preserves the order of the members inside the ZIP archive __A = Path(self.dummy_file ).parent __A = path.relative_to(A ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __A = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A ) __A = Path(A ) __A = _iter_archive_members(A ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(A ).as_posix(), file_path.open("rb" ) def UpperCamelCase_ ( self : List[Any] ,A : Any ): if not isinstance(A ,A ): __A = [paths] for path in paths: if os.path.isfile(A ): if os.path.basename(A ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(A ): if os.path.basename(A ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(A ): if filename.startswith((".", "__") ): continue yield os.path.join(A ,A )
15
0
import os from tempfile import TemporaryDirectory from unittest import TestCase import pytest from absl.testing import parameterized from datasets import config from datasets.arrow_reader import HF_GCP_BASE_URL from datasets.builder import DatasetBuilder from datasets.dataset_dict import IterableDatasetDict from datasets.iterable_dataset import IterableDataset from datasets.load import dataset_module_factory, import_main_class from datasets.utils.file_utils import cached_path UpperCAmelCase_ : Optional[int] = [ {'dataset': 'wikipedia', 'config_name': '20220301.de'}, {'dataset': 'wikipedia', 'config_name': '20220301.en'}, {'dataset': 'wikipedia', 'config_name': '20220301.fr'}, {'dataset': 'wikipedia', 'config_name': '20220301.frr'}, {'dataset': 'wikipedia', 'config_name': '20220301.it'}, {'dataset': 'wikipedia', 'config_name': '20220301.simple'}, {'dataset': 'snli', 'config_name': 'plain_text'}, {'dataset': 'eli5', 'config_name': 'LFQA_reddit'}, {'dataset': 'wiki40b', 'config_name': 'en'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.compressed'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.nq.no_index'}, {'dataset': 'wiki_dpr', 'config_name': 'psgs_w100.multiset.no_index'}, {'dataset': 'natural_questions', 'config_name': 'default'}, ] def SCREAMING_SNAKE_CASE_ ( __A : Tuple=True ) -> Union[str, Any]: """simple docstring""" if with_config: return [ { "testcase_name": d["dataset"] + "/" + d["config_name"], "dataset": d["dataset"], "config_name": d["config_name"], } for d in DATASETS_ON_HF_GCP ] else: return [ {"testcase_name": dataset, "dataset": dataset} for dataset in {d["dataset"] for d in DATASETS_ON_HF_GCP} ] @parameterized.named_parameters(list_datasets_on_hf_gcp_parameters(with_config=lowercase__ ) ) class SCREAMING_SNAKE_CASE__ ( lowercase__ ): snake_case__ : List[Any] = None snake_case__ : List[str] = None def SCREAMING_SNAKE_CASE ( self : Optional[Any] , SCREAMING_SNAKE_CASE__ : Union[str, Any] , SCREAMING_SNAKE_CASE__ : Tuple ) -> List[str]: with TemporaryDirectory() as tmp_dir: a_ : Optional[Any] = dataset_module_factory(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ) a_ : Optional[int] = import_main_class(dataset_module.module_path , dataset=SCREAMING_SNAKE_CASE__ ) a_ : DatasetBuilder = builder_cls( cache_dir=SCREAMING_SNAKE_CASE__ , config_name=SCREAMING_SNAKE_CASE__ , hash=dataset_module.hash , ) a_ : Any = '/'.join( [ HF_GCP_BASE_URL, builder_instance._relative_data_dir(with_hash=SCREAMING_SNAKE_CASE__ ).replace(os.sep , '/' ), config.DATASET_INFO_FILENAME, ] ) a_ : Dict = cached_path(SCREAMING_SNAKE_CASE__ , cache_dir=SCREAMING_SNAKE_CASE__ ) self.assertTrue(os.path.exists(SCREAMING_SNAKE_CASE__ ) ) @pytest.mark.integration def SCREAMING_SNAKE_CASE_ ( __A : List[str] ) -> int: """simple docstring""" a_ : List[str] = tmp_path_factory.mktemp('test_hf_gcp' ) / 'test_wikipedia_simple' a_ : Union[str, Any] = dataset_module_factory('wikipedia' , cache_dir=__A ) a_ : Dict = import_main_class(dataset_module.module_path ) a_ : DatasetBuilder = builder_cls( cache_dir=__A , config_name='20220301.frr' , hash=dataset_module.hash , ) # use the HF cloud storage, not the original download_and_prepare that uses apache-beam a_ : Optional[Any] = None builder_instance.download_and_prepare() a_ : List[Any] = builder_instance.as_dataset() assert ds @pytest.mark.integration def SCREAMING_SNAKE_CASE_ ( __A : Tuple ) -> List[Any]: """simple docstring""" a_ : Optional[int] = dataset_module_factory('wikipedia' , cache_dir=__A ) a_ : Any = import_main_class(dataset_module.module_path , dataset=__A ) a_ : DatasetBuilder = builder_cls( cache_dir=__A , config_name='20220301.frr' , hash=dataset_module.hash , ) a_ : Tuple = builder_instance.as_streaming_dataset() assert ds assert isinstance(__A , __A ) assert "train" in ds assert isinstance(ds['train'] , __A ) assert next(iter(ds['train'] ) )
32
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE :List[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :List[str] = ['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 :Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
15
0
"""simple docstring""" from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import ( center_crop, get_resize_output_image_size, normalize, rescale, resize, to_channel_dimension_format, ) from ...image_utils import ( IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, ChannelDimension, ImageInput, PILImageResampling, is_batched, to_numpy_array, valid_images, ) from ...utils import TensorType, logging __A : Union[str, Any] = logging.get_logger(__name__) class _UpperCAmelCase ( _A ): SCREAMING_SNAKE_CASE_ : str = ["pixel_values"] def __init__( self : str , A : bool = True , A : Optional[Dict[str, int]] = None , A : PILImageResampling = PILImageResampling.BICUBIC , A : bool = True , A : bool = True , A : Union[int, float] = 1 / 2_55 , A : Dict[str, int] = None , A : bool = True , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , **A : Dict , ) -> None: super().__init__(**A ) lowercase_ : Tuple = size if size is not None else {'''height''': 2_24, '''width''': 2_24} lowercase_ : Dict = get_size_dict(A ) lowercase_ : Union[str, Any] = crop_size if crop_size is not None else {'''height''': 2_24, '''width''': 2_24} lowercase_ : List[Any] = get_size_dict(A , default_to_square=A , param_name='''crop_size''' ) lowercase_ : Optional[Any] = do_resize lowercase_ : List[str] = do_rescale lowercase_ : Optional[int] = do_normalize lowercase_ : List[str] = do_center_crop lowercase_ : Union[str, Any] = crop_size lowercase_ : Optional[Any] = size lowercase_ : Optional[Any] = resample lowercase_ : Optional[Any] = rescale_factor lowercase_ : Tuple = image_mean if image_mean is not None else IMAGENET_DEFAULT_MEAN lowercase_ : Tuple = image_std if image_std is not None else IMAGENET_DEFAULT_STD def A ( self : str , A : np.ndarray , A : Dict[str, int] , A : PILImageResampling = PILImageResampling.BILINEAR , A : Optional[Union[str, ChannelDimension]] = None , **A : List[str] , ) -> np.ndarray: lowercase_ : str = get_size_dict(A ) if "shortest_edge" in size: lowercase_ : Dict = get_resize_output_image_size(A , size=size['''shortest_edge'''] , default_to_square=A ) # size = get_resize_output_image_size(image, size["shortest_edge"], size["longest_edge"]) elif "height" in size and "width" in size: lowercase_ : List[Any] = (size['''height'''], size['''width''']) else: raise ValueError(F'''Size must contain \'height\' and \'width\' keys or \'shortest_edge\' key. Got {size.keys()}''' ) return resize(A , size=A , resample=A , data_format=A , **A ) def A ( self : str , A : np.ndarray , A : Dict[str, int] , A : Optional[Union[str, ChannelDimension]] = None , **A : Dict , ) -> np.ndarray: lowercase_ : List[Any] = get_size_dict(A ) if "height" not in size or "width" not in size: raise ValueError(F'''The `size` parameter must contain the keys (height, width). Got {size.keys()}''' ) return center_crop(A , size=(size['''height'''], size['''width''']) , data_format=A , **A ) def A ( self : Tuple , A : np.ndarray , A : float , A : Optional[Union[str, ChannelDimension]] = None , **A : Any ) -> np.ndarray: return rescale(A , scale=A , data_format=A , **A ) def A ( self : Optional[int] , A : np.ndarray , A : Union[float, List[float]] , A : Union[float, List[float]] , A : Optional[Union[str, ChannelDimension]] = None , **A : Tuple , ) -> np.ndarray: return normalize(A , mean=A , std=A , data_format=A , **A ) def A ( self : Dict , A : ImageInput , A : Optional[bool] = None , A : Dict[str, int] = None , A : PILImageResampling = None , A : bool = None , A : int = None , A : Optional[bool] = None , A : Optional[float] = None , A : Optional[bool] = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[float, List[float]]] = None , A : Optional[Union[str, TensorType]] = None , A : Union[str, ChannelDimension] = ChannelDimension.FIRST , **A : List[str] , ) -> BatchFeature: lowercase_ : str = do_resize if do_resize is not None else self.do_resize lowercase_ : int = do_rescale if do_rescale is not None else self.do_rescale lowercase_ : str = do_normalize if do_normalize is not None else self.do_normalize lowercase_ : Any = do_center_crop if do_center_crop is not None else self.do_center_crop lowercase_ : str = crop_size if crop_size is not None else self.crop_size lowercase_ : int = get_size_dict(A , param_name='''crop_size''' , default_to_square=A ) lowercase_ : Union[str, Any] = resample if resample is not None else self.resample lowercase_ : Any = rescale_factor if rescale_factor is not None else self.rescale_factor lowercase_ : Tuple = image_mean if image_mean is not None else self.image_mean lowercase_ : Tuple = image_std if image_std is not None else self.image_std lowercase_ : Union[str, Any] = size if size is not None else self.size lowercase_ : str = get_size_dict(A ) if not is_batched(A ): lowercase_ : List[Any] = [images] if not valid_images(A ): raise ValueError( '''Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ''' '''torch.Tensor, tf.Tensor or jax.ndarray.''' ) if do_resize and size is None: raise ValueError('''Size must be specified if do_resize is True.''' ) if do_center_crop and crop_size is None: raise ValueError('''Crop size must be specified if do_center_crop is True.''' ) if do_rescale and rescale_factor is None: raise ValueError('''Rescale factor must be specified if do_rescale is True.''' ) # All transformations expect numpy arrays. lowercase_ : Tuple = [to_numpy_array(A ) for image in images] if do_resize: lowercase_ : List[str] = [self.resize(image=A , size=A , resample=A ) for image in images] if do_center_crop: lowercase_ : List[Any] = [self.center_crop(image=A , size=A ) for image in images] if do_rescale: lowercase_ : List[Any] = [self.rescale(image=A , scale=A ) for image in images] if do_normalize: lowercase_ : Dict = [self.normalize(image=A , mean=A , std=A ) for image in images] lowercase_ : List[str] = [to_channel_dimension_format(A , A ) for image in images] lowercase_ : Optional[Any] = {'''pixel_values''': images} return BatchFeature(data=A , tensor_type=A )
33
from typing import Dict, Optional import numpy as np import datasets SCREAMING_SNAKE_CASE :List[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' SCREAMING_SNAKE_CASE :List[str] = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' SCREAMING_SNAKE_CASE :str = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Tuple: """simple docstring""" if label_map is not None: for old_id, new_id in label_map.items(): __A = new_id # turn into Numpy arrays __A = np.array(a_ ) __A = np.array(a_ ) if reduce_labels: __A = 2_5_5 __A = label - 1 __A = 2_5_5 __A = label != ignore_index __A = np.not_equal(a_ , a_ ) __A = pred_label[mask] __A = np.array(a_ )[mask] __A = pred_label[pred_label == label] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Union[str, Any]: """simple docstring""" __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(a_ , a_ ): __A , __A , __A , __A = intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = None , a_ = False , ) -> str: """simple docstring""" __A , __A , __A , __A = total_intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) # compute metrics __A = {} __A = total_area_intersect.sum() / total_area_label.sum() __A = total_area_intersect / total_area_union __A = total_area_intersect / total_area_label __A = np.nanmean(a_ ) __A = np.nanmean(a_ ) __A = all_acc __A = iou __A = acc if nan_to_num is not None: __A = {metric: np.nan_to_num(a_ , nan=a_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), } ) ,reference_urls=[ "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py" ] ,) def UpperCamelCase_ ( self : int ,A : Optional[Any] ,A : Optional[Any] ,A : int ,A : bool ,A : Optional[int] = None ,A : Optional[Dict[int, int]] = None ,A : bool = False ,): __A = mean_iou( results=A ,gt_seg_maps=A ,num_labels=A ,ignore_index=A ,nan_to_num=A ,label_map=A ,reduce_labels=A ,) return iou_result
15
0
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging A =logging.get_logger(__name__) A ={ 'xlm-roberta-base': 'https://huggingface.co/xlm-roberta-base/resolve/main/config.json', 'xlm-roberta-large': 'https://huggingface.co/xlm-roberta-large/resolve/main/config.json', 'xlm-roberta-large-finetuned-conll02-dutch': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-dutch/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll02-spanish': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll02-spanish/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-english': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-english/resolve/main/config.json' ), 'xlm-roberta-large-finetuned-conll03-german': ( 'https://huggingface.co/xlm-roberta-large-finetuned-conll03-german/resolve/main/config.json' ), } class _a ( __a ): __a : Union[str, Any] = """xlm-roberta""" def __init__( self : List[str] , lowercase : Any=30_522 , lowercase : Optional[Any]=768 , lowercase : Optional[int]=12 , lowercase : List[str]=12 , lowercase : Optional[Any]=3_072 , lowercase : Any="gelu" , lowercase : Union[str, Any]=0.1 , lowercase : List[str]=0.1 , lowercase : Union[str, Any]=512 , lowercase : List[str]=2 , lowercase : Dict=0.02 , lowercase : Union[str, Any]=1E-12 , lowercase : Tuple=1 , lowercase : int=0 , lowercase : Dict=2 , lowercase : List[Any]="absolute" , lowercase : List[str]=True , lowercase : Dict=None , **lowercase : str , ): '''simple docstring''' super().__init__(pad_token_id=lowercase , bos_token_id=lowercase , eos_token_id=lowercase , **lowercase ) UpperCAmelCase = vocab_size UpperCAmelCase = hidden_size UpperCAmelCase = num_hidden_layers UpperCAmelCase = num_attention_heads UpperCAmelCase = hidden_act UpperCAmelCase = intermediate_size UpperCAmelCase = hidden_dropout_prob UpperCAmelCase = attention_probs_dropout_prob UpperCAmelCase = max_position_embeddings UpperCAmelCase = type_vocab_size UpperCAmelCase = initializer_range UpperCAmelCase = layer_norm_eps UpperCAmelCase = position_embedding_type UpperCAmelCase = use_cache UpperCAmelCase = classifier_dropout class _a ( __a ): @property def A ( self : Optional[Any] ): '''simple docstring''' if self.task == "multiple-choice": UpperCAmelCase = {0: '''batch''', 1: '''choice''', 2: '''sequence'''} else: UpperCAmelCase = {0: '''batch''', 1: '''sequence'''} return OrderedDict( [ ('''input_ids''', dynamic_axis), ('''attention_mask''', dynamic_axis), ] )
34
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE :List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :List[str] = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Dict = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE :Optional[Any] = { 'AI-Sweden/gpt-sw3-126m': 2048, 'AI-Sweden/gpt-sw3-350m': 2048, 'AI-Sweden/gpt-sw3-1.6b': 2048, 'AI-Sweden/gpt-sw3-6.7b': 2048, 'AI-Sweden/gpt-sw3-20b': 2048, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[int] ,A : Optional[Any] ,A : Optional[int]=False ,A : int=False ,A : Union[str, Any]=False ,A : int=None ,A : Optional[Any]=None ,A : Union[str, Any]=None ,A : Optional[Any]=None ,A : Optional[Dict[str, Any]] = None ,**A : Tuple ,): __A = {} if sp_model_kwargs is None else sp_model_kwargs __A = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) __A = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __A = "<|endoftext|>" if eos_token is None else eos_token __A = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __A = unk_token if pad_token is None else pad_token __A = eos_token if bos_token is None else bos_token else: __A = "<pad>" if pad_token is None else pad_token __A = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=A ,remove_space=A ,keep_accents=A ,bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = do_lower_case __A = remove_space __A = keep_accents __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) # Used for whitespace normalization in input texts # fmt : off __A = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __A = re.compile( f'''[{''.join(map(A ,list(range(0 ,9 ) ) + list(range(11 ,32 ) ) + list(range(1_27 ,1_60 ) ) + [1_60, 1_73, 82_03] ) )}]''' ) def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Optional[Any] ,A : Union[str, Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCamelCase_ ( self : List[str] ): return len(self.sp_model ) def UpperCamelCase_ ( self : int ,A : str ): __A = self.non_printing_characters_re.sub("" ,A ) # Normalize whitespaces __A = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization __A = unicodedata.normalize("NFC" ,A ) return text def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,**A : Optional[int] ): __A = self.preprocess_text(A ) return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : int ): return self.sp_model.IdToPiece(A ) @staticmethod def UpperCamelCase_ ( A : str ): return out_string def UpperCamelCase_ ( self : str ,A : List[str] ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string def UpperCamelCase_ ( self : str ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : List[str] ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Union[str, Any] ,A : Union[str, List[str]] ,A : Union[str, bool] = False ): if isinstance(A ,A ): __A = self.preprocess_text(A ) __A = self.sp_model.encode(A ) else: __A = [self.preprocess_text(A ) for t in text] __A = self.sp_model.encode(A ) if return_tensors is True or return_tensors == "pt": __A = torch.tensor(A ) return token_ids def UpperCamelCase_ ( self : List[Any] ,A : Union[int, List[int]] ): return self.sp_model.decode(A ) def UpperCamelCase_ ( self : List[str] ,A : "Conversation" ): __A = [f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __A = ( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(A ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=A )
15
0
'''simple docstring''' import inspect import os import re from transformers.configuration_utils import PretrainedConfig from transformers.utils import direct_transformers_import # All paths are set with the intent you should run this script from the root of the repo with the command # python utils/check_config_docstrings.py __a = "src/transformers" # This is to make sure the transformers module imported is the one in the repo. __a = direct_transformers_import(PATH_TO_TRANSFORMERS) __a = transformers.models.auto.configuration_auto.CONFIG_MAPPING __a = { # used to compute the property `self.chunk_length` "EncodecConfig": ["overlap"], # used as `self.bert_model = BertModel(config, ...)` "DPRConfig": True, # not used in modeling files, but it's an important information "FSMTConfig": ["langs"], # used internally in the configuration class file "GPTNeoConfig": ["attention_types"], # used internally in the configuration class file "EsmConfig": ["is_folding_model"], # used during training (despite we don't have training script for these models yet) "Mask2FormerConfig": ["ignore_value"], # `ignore_value` used during training (despite we don't have training script for these models yet) # `norm` used in conversion script (despite not using in the modeling file) "OneFormerConfig": ["ignore_value", "norm"], # used during preprocessing and collation, see `collating_graphormer.py` "GraphormerConfig": ["spatial_pos_max"], # used internally in the configuration class file "T5Config": ["feed_forward_proj"], # used internally in the configuration class file # `tokenizer_class` get default value `T5Tokenizer` intentionally "MT5Config": ["feed_forward_proj", "tokenizer_class"], "UMT5Config": ["feed_forward_proj", "tokenizer_class"], # used internally in the configuration class file "LongT5Config": ["feed_forward_proj"], # used internally in the configuration class file "SwitchTransformersConfig": ["feed_forward_proj"], # having default values other than `1e-5` - we can't fix them without breaking "BioGptConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "GLPNConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "SegformerConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "CvtConfig": ["layer_norm_eps"], # having default values other than `1e-5` - we can't fix them without breaking "PerceiverConfig": ["layer_norm_eps"], # used internally to calculate the feature size "InformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "TimeSeriesTransformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate the feature size "AutoformerConfig": ["num_static_real_features", "num_time_features"], # used internally to calculate `mlp_dim` "SamVisionConfig": ["mlp_ratio"], # For (head) training, but so far not implemented "ClapAudioConfig": ["num_classes"], # Not used, but providing useful information to users "SpeechT5HifiGanConfig": ["sampling_rate"], } # TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure SPECIAL_CASES_TO_ALLOW.update( { "CLIPSegConfig": True, "DeformableDetrConfig": True, "DetaConfig": True, "DinatConfig": True, "DonutSwinConfig": True, "EfficientFormerConfig": True, "FSMTConfig": True, "JukeboxConfig": True, "LayoutLMv2Config": True, "MaskFormerSwinConfig": True, "MT5Config": True, "NatConfig": True, "OneFormerConfig": True, "PerceiverConfig": True, "RagConfig": True, "SpeechT5Config": True, "SwinConfig": True, "Swin2SRConfig": True, "Swinv2Config": True, "SwitchTransformersConfig": True, "TableTransformerConfig": True, "TapasConfig": True, "TransfoXLConfig": True, "UniSpeechConfig": True, "UniSpeechSatConfig": True, "WavLMConfig": True, "WhisperConfig": True, # TODO: @Arthur (for `alignment_head` and `alignment_layer`) "JukeboxPriorConfig": True, # TODO: @Younes (for `is_decoder`) "Pix2StructTextConfig": True, } ) def __snake_case( _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) -> List[str]: snake_case__ : List[str] = False for attribute in attributes: for modeling_source in source_strings: # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` if ( f"config.{attribute}" in modeling_source or f"getattr(config, \"{attribute}\"" in modeling_source or f"getattr(self.config, \"{attribute}\"" in modeling_source ): snake_case__ : str = True # Deal with multi-line cases elif ( re.search( rf"getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*\"{attribute}\"" , _lowerCAmelCase , ) is not None ): snake_case__ : Optional[Any] = True # `SequenceSummary` is called with `SequenceSummary(config)` elif attribute in [ "summary_type", "summary_use_proj", "summary_activation", "summary_last_dropout", "summary_proj_to_labels", "summary_first_dropout", ]: if "SequenceSummary" in modeling_source: snake_case__ : Union[str, Any] = True if attribute_used: break if attribute_used: break # common and important attributes, even if they do not always appear in the modeling files snake_case__ : List[Any] = [ """bos_index""", """eos_index""", """pad_index""", """unk_index""", """mask_index""", """image_size""", """use_cache""", """out_features""", """out_indices""", ] snake_case__ : Union[str, Any] = ["""encoder_no_repeat_ngram_size"""] # Special cases to be allowed snake_case__ : Union[str, Any] = True if not attribute_used: snake_case__ : Any = False for attribute in attributes: # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` if attribute in ["is_encoder_decoder"] and default_value is True: snake_case__ : Dict = True elif attribute in ["tie_word_embeddings"] and default_value is False: snake_case__ : Any = True # Allow cases without checking the default value in the configuration class elif attribute in attributes_to_allow + attributes_used_in_generation: snake_case__ : Union[str, Any] = True elif attribute.endswith("""_token_id""" ): snake_case__ : Union[str, Any] = True # configuration class specific cases if not case_allowed: snake_case__ : str = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__ , [] ) snake_case__ : Tuple = allowed_cases is True or attribute in allowed_cases return attribute_used or case_allowed def __snake_case( _lowerCAmelCase ) -> str: snake_case__ : List[str] = dict(inspect.signature(config_class.__init__ ).parameters ) snake_case__ : Tuple = [x for x in list(signature.keys() ) if x not in ["""self""", """kwargs"""]] snake_case__ : List[str] = [signature[param].default for param in parameter_names] # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long # as one variant is used, the test should pass snake_case__ : str = {} if len(config_class.attribute_map ) > 0: snake_case__ : Dict = {v: k for k, v in config_class.attribute_map.items()} # Get the path to modeling source files snake_case__ : int = inspect.getsourcefile(_lowerCAmelCase ) snake_case__ : int = os.path.dirname(_lowerCAmelCase ) # Let's check against all frameworks: as long as one framework uses an attribute, we are good. snake_case__ : List[str] = [os.path.join(_lowerCAmelCase , _lowerCAmelCase ) for fn in os.listdir(_lowerCAmelCase ) if fn.startswith("""modeling_""" )] # Get the source code strings snake_case__ : Dict = [] for path in modeling_paths: if os.path.isfile(_lowerCAmelCase ): with open(_lowerCAmelCase ) as fp: modeling_sources.append(fp.read() ) snake_case__ : List[str] = [] for config_param, default_value in zip(_lowerCAmelCase , _lowerCAmelCase ): # `attributes` here is all the variant names for `config_param` snake_case__ : Tuple = [config_param] # some configuration classes have non-empty `attribute_map`, and both names could be used in the # corresponding modeling files. As long as one of them appears, it is fine. if config_param in reversed_attribute_map: attributes.append(reversed_attribute_map[config_param] ) if not check_attribute_being_used(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ): unused_attributes.append(attributes[0] ) return sorted(_lowerCAmelCase ) def __snake_case( ) -> List[str]: snake_case__ : str = {} for _config_class in list(CONFIG_MAPPING.values() ): # Skip deprecated models if "models.deprecated" in _config_class.__module__: continue # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) snake_case__ : List[Any] = [ cls for name, cls in inspect.getmembers( inspect.getmodule(_config_class ) , lambda _lowerCAmelCase : inspect.isclass(_lowerCAmelCase ) and issubclass(_lowerCAmelCase , _lowerCAmelCase ) and inspect.getmodule(_lowerCAmelCase ) == inspect.getmodule(_config_class ) , ) ] for config_class in config_classes_in_module: snake_case__ : Union[str, Any] = check_config_attributes_being_used(_lowerCAmelCase ) if len(_lowerCAmelCase ) > 0: snake_case__ : Union[str, Any] = unused_attributes if len(_lowerCAmelCase ) > 0: snake_case__ : str = """The following configuration classes contain unused attributes in the corresponding modeling files:\n""" for name, attributes in configs_with_unused_attributes.items(): error += f"{name}: {attributes}\n" raise ValueError(_lowerCAmelCase ) if __name__ == "__main__": check_config_attributes()
35
import numpy as np def UpperCAmelCase ( a_ , a_ , a_ = 1E-12 , a_ = 1_0_0 , ) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(a_ )[0] == np.shape(a_ )[1] # Ensure proper dimensionality. assert np.shape(a_ )[0] == np.shape(a_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a_ ) == np.iscomplexobj(a_ ) __A = np.iscomplexobj(a_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __A = False __A = 0 __A = 0 __A = 1E12 while not convergence: # Multiple matrix by the vector. __A = np.dot(a_ , a_ ) # Normalize the resulting output vector. __A = w / np.linalg.norm(a_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __A = vector.conj().T if is_complex else vector.T __A = np.dot(a_ , np.dot(a_ , a_ ) ) # Check convergence. __A = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __A = True __A = lambda_ if is_complex: __A = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase ( ) -> None: """simple docstring""" __A = np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]] ) __A = np.array([4_1, 4, 2_0] ) __A = real_input_matrix.astype(np.complexaaa ) __A = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __A = np.array([4_1, 4, 2_0] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __A = real_input_matrix __A = real_vector elif problem_type == "complex": __A = complex_input_matrix __A = complex_vector # Our implementation. __A , __A = power_iteration(a_ , a_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __A , __A = np.linalg.eigh(a_ ) # Last eigenvalue is the maximum one. __A = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __A = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a_ ) - np.abs(a_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
0
def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Optional[int] = set() # edges = list of graph's edges _lowerCAmelCase : Dict = get_edges(_lowerCamelCase ) # While there are still elements in edges list, take an arbitrary edge # (from_node, to_node) and add his extremity to chosen_vertices and then # remove all arcs adjacent to the from_node and to_node while edges: _lowerCAmelCase , _lowerCAmelCase : List[Any] = edges.pop() chosen_vertices.add(_lowerCamelCase ) chosen_vertices.add(_lowerCamelCase ) for edge in edges.copy(): if from_node in edge or to_node in edge: edges.discard(_lowerCamelCase ) return chosen_vertices def A ( _lowerCamelCase ): '''simple docstring''' _lowerCAmelCase : Union[str, Any] = set() for from_node, to_nodes in graph.items(): for to_node in to_nodes: edges.add((from_node, to_node) ) return edges if __name__ == "__main__": import doctest doctest.testmod() # graph = {0: [1, 3], 1: [0, 3], 2: [0, 3, 4], 3: [0, 1, 2], 4: [2, 3]} # print(f"Matching vertex cover:\n{matching_min_vertex_cover(graph)}")
36
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig SCREAMING_SNAKE_CASE :str = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE :str = 'RegNetConfig' # Base docstring SCREAMING_SNAKE_CASE :List[str] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Union[str, Any] = [1, 1088, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE :Optional[int] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Any = 'tabby, tabby cat' SCREAMING_SNAKE_CASE :Optional[int] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : int ,A : int = 3 ,A : int = 1 ,A : int = 1 ,A : Optional[str] = "relu" ,**A : Dict ,): super().__init__(**A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __A = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=A ,strides=A ,padding="VALID" ,groups=A ,use_bias=A ,name="convolution" ,) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) __A = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : List[Any] ,A : Any ): __A = self.convolution(self.padding(A ) ) __A = self.normalization(A ) __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : RegNetConfig ,**A : str ): super().__init__(**A ) __A = config.num_channels __A = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name="embedder" ,) def UpperCamelCase_ ( self : Tuple ,A : Optional[Any] ): __A = shape_list(A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __A = tf.transpose(A ,perm=(0, 2, 3, 1) ) __A = self.embedder(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Optional[int] ,A : int ,A : int = 2 ,**A : Tuple ): super().__init__(**A ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=1 ,strides=A ,use_bias=A ,name="convolution" ) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) def UpperCamelCase_ ( self : Union[str, Any] ,A : tf.Tensor ,A : bool = False ): return self.normalization(self.convolution(A ) ,training=A ) class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Dict ,A : int ,A : int ,**A : str ): super().__init__(**A ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) __A = [ tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="relu" ,name="attention.0" ), tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="sigmoid" ,name="attention.2" ), ] def UpperCamelCase_ ( self : Dict ,A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __A = self.pooler(A ) for layer_module in self.attention: __A = layer_module(A ) __A = hidden_state * pooled return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : Optional[int] ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.2" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : int ,A : Optional[int] ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : str ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetSELayer(A ,reduced_channels=int(round(in_channels / 4 ) ) ,name="layer.2" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.3" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict ,A : Any ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 2 ,A : int = 2 ,**A : Optional[int] ): super().__init__(**A ) __A = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __A = [ # downsampling is done in the first layer with stride of 2 layer(A ,A ,A ,stride=A ,name="layers.0" ), *[layer(A ,A ,A ,name=f'''layers.{i+1}''' ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Any ,A : List[str] ): for layer_module in self.layers: __A = layer_module(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any ,A : RegNetConfig ,**A : List[str] ): super().__init__(**A ) __A = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( A ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name="stages.0" ,) ) __A = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(A ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(A ,A ,A ,depth=A ,name=f'''stages.{i+1}''' ) ) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor ,A : bool = False ,A : bool = True ): __A = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __A = hidden_states + (hidden_state,) __A = stage_module(A ) if output_hidden_states: __A = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=A ,hidden_states=A ) @keras_serializable class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' snake_case_ = RegNetConfig def __init__( self : int ,A : Optional[int] ,**A : Dict ): super().__init__(**A ) __A = config __A = TFRegNetEmbeddings(A ,name="embedder" ) __A = TFRegNetEncoder(A ,name="encoder" ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) @unpack_inputs def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : bool = False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.embedder(A ,training=A ) __A = self.encoder( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = encoder_outputs[0] __A = self.pooler(A ) # Change to NCHW output format have uniformity in the modules __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __A = tuple([tf.transpose(A ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A ,pooler_output=A ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = RegNetConfig snake_case_ = "regnet" snake_case_ = "pixel_values" @property def UpperCamelCase_ ( self : Optional[Any] ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} SCREAMING_SNAKE_CASE :Dict = R'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' SCREAMING_SNAKE_CASE :Dict = R'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,*A : List[Any] ,**A : str ): super().__init__(A ,*A ,**A ) __A = TFRegNetMainLayer(A ,name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=A ,config_class=_CONFIG_FOR_DOC ,modality="vision" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : int=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( pixel_values=A ,output_hidden_states=A ,return_dict=A ,training=A ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Optional[int] ,A : RegNetConfig ,*A : str ,**A : Tuple ): super().__init__(A ,*A ,**A ) __A = config.num_labels __A = TFRegNetMainLayer(A ,name="regnet" ) # classification head __A = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=A ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor = None ,A : tf.Tensor = None ,A : bool = None ,A : bool = None ,A : Union[str, Any]=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = outputs.pooler_output if return_dict else outputs[1] __A = self.classifier[0](A ) __A = self.classifier[1](A ) __A = None if labels is None else self.hf_compute_loss(labels=A ,logits=A ) if not return_dict: __A = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=A ,logits=A ,hidden_states=outputs.hidden_states )
15
0
'''simple docstring''' import warnings from ...utils import logging from .image_processing_deit import DeiTImageProcessor _lowerCAmelCase = logging.get_logger(__name__) class lowerCAmelCase_( SCREAMING_SNAKE_CASE_ ): '''simple docstring''' def __init__( self ,*__UpperCAmelCase ,**__UpperCAmelCase ) -> None: warnings.warn( """The class DeiTFeatureExtractor is deprecated and will be removed in version 5 of Transformers. Please""" """ use DeiTImageProcessor instead.""" ,__UpperCAmelCase ,) super().__init__(*__UpperCAmelCase ,**__UpperCAmelCase )
37
import math def UpperCAmelCase ( a_ , a_ = 0 , a_ = 0 ) -> list: """simple docstring""" __A = end or len(a_ ) for i in range(a_ , a_ ): __A = i __A = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: __A = array[temp_index - 1] temp_index -= 1 __A = temp_index_value return array def UpperCAmelCase ( a_ , a_ , a_ ) -> None: # Max Heap """simple docstring""" __A = index __A = 2 * index + 1 # Left Node __A = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: __A = left_index if right_index < heap_size and array[largest] < array[right_index]: __A = right_index if largest != index: __A , __A = array[largest], array[index] heapify(a_ , a_ , a_ ) def UpperCAmelCase ( a_ ) -> list: """simple docstring""" __A = len(a_ ) for i in range(n // 2 , -1 , -1 ): heapify(a_ , a_ , a_ ) for i in range(n - 1 , 0 , -1 ): __A , __A = array[0], array[i] heapify(a_ , 0 , a_ ) return array def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" __A = low __A = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i __A , __A = array[j], array[i] i += 1 def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) == 0: return array __A = 2 * math.ceil(math.loga(len(a_ ) ) ) __A = 1_6 return intro_sort(a_ , 0 , len(a_ ) , a_ , a_ ) def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ ) -> list: """simple docstring""" while end - start > size_threshold: if max_depth == 0: return heap_sort(a_ ) max_depth -= 1 __A = median_of_a(a_ , a_ , start + ((end - start) // 2) + 1 , end - 1 ) __A = partition(a_ , a_ , a_ , a_ ) intro_sort(a_ , a_ , a_ , a_ , a_ ) __A = p return insertion_sort(a_ , a_ , a_ ) if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma : ').strip() SCREAMING_SNAKE_CASE :str = [float(item) for item in user_input.split(',')] print(sort(unsorted))
15
0
import html from ...feature_extraction_utils import BatchFeature, FeatureExtractionMixin from ...utils import is_bsa_available, logging, requires_backends if is_bsa_available(): import bsa from bsa import BeautifulSoup UpperCAmelCase_ : Any = logging.get_logger(__name__) class _SCREAMING_SNAKE_CASE ( _a ): def __init__( self : Optional[int] , **__lowerCamelCase : Optional[int] ): requires_backends(self , ["""bs4"""] ) super().__init__(**__lowerCamelCase ) def _A ( self : List[str] , __lowerCamelCase : Any ): UpperCamelCase :Optional[int] = [] UpperCamelCase :List[str] = [] UpperCamelCase :Union[str, Any] = element if element.name else element.parent for parent in child.parents: # type: bs4.element.Tag UpperCamelCase :Optional[Any] = parent.find_all(child.name , recursive=__lowerCamelCase ) xpath_tags.append(child.name ) xpath_subscripts.append( 0 if 1 == len(__lowerCamelCase ) else next(i for i, s in enumerate(__lowerCamelCase , 1 ) if s is child ) ) UpperCamelCase :Any = parent xpath_tags.reverse() xpath_subscripts.reverse() return xpath_tags, xpath_subscripts def _A ( self : Any , __lowerCamelCase : Tuple ): UpperCamelCase :Any = BeautifulSoup(__lowerCamelCase , """html.parser""" ) UpperCamelCase :Union[str, Any] = [] UpperCamelCase :Tuple = [] UpperCamelCase :Tuple = [] for element in html_code.descendants: if type(__lowerCamelCase ) == bsa.element.NavigableString: if type(element.parent ) != bsa.element.Tag: continue UpperCamelCase :Any = html.unescape(__lowerCamelCase ).strip() if not text_in_this_tag: continue all_doc_strings.append(__lowerCamelCase ) UpperCamelCase , UpperCamelCase :Optional[Any] = self.xpath_soup(__lowerCamelCase ) stringaxtag_seq.append(__lowerCamelCase ) stringaxsubs_seq.append(__lowerCamelCase ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xtags does not correspond""" ) if len(__lowerCamelCase ) != len(__lowerCamelCase ): raise ValueError("""Number of doc strings and xsubs does not correspond""" ) return all_doc_strings, stringaxtag_seq, stringaxsubs_seq def _A ( self : int , __lowerCamelCase : List[Any] , __lowerCamelCase : List[str] ): UpperCamelCase :Tuple = """""" for tagname, subs in zip(__lowerCamelCase , __lowerCamelCase ): xpath += F"""/{tagname}""" if subs != 0: xpath += F"""[{subs}]""" return xpath def __call__( self : Any , __lowerCamelCase : Dict ): UpperCamelCase :Any = False # Check that strings has a valid type if isinstance(__lowerCamelCase , __lowerCamelCase ): UpperCamelCase :List[Any] = True elif isinstance(__lowerCamelCase , (list, tuple) ): if len(__lowerCamelCase ) == 0 or isinstance(html_strings[0] , __lowerCamelCase ): UpperCamelCase :Any = True if not valid_strings: raise ValueError( """HTML strings must of type `str`, `List[str]` (batch of examples), """ F"""but is of type {type(__lowerCamelCase )}.""" ) UpperCamelCase :str = bool(isinstance(__lowerCamelCase , (list, tuple) ) and (isinstance(html_strings[0] , __lowerCamelCase )) ) if not is_batched: UpperCamelCase :Any = [html_strings] # Get nodes + xpaths UpperCamelCase :Union[str, Any] = [] UpperCamelCase :str = [] for html_string in html_strings: UpperCamelCase , UpperCamelCase , UpperCamelCase :int = self.get_three_from_single(__lowerCamelCase ) nodes.append(__lowerCamelCase ) UpperCamelCase :int = [] for node, tag_list, sub_list in zip(__lowerCamelCase , __lowerCamelCase , __lowerCamelCase ): UpperCamelCase :str = self.construct_xpath(__lowerCamelCase , __lowerCamelCase ) xpath_strings.append(__lowerCamelCase ) xpaths.append(__lowerCamelCase ) # return as Dict UpperCamelCase :Optional[int] = {"""nodes""": nodes, """xpaths""": xpaths} UpperCamelCase :Any = BatchFeature(data=__lowerCamelCase , tensor_type=__lowerCamelCase ) return encoded_inputs
38
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml SCREAMING_SNAKE_CASE :Optional[int] = NewType('DataClass', Any) SCREAMING_SNAKE_CASE :int = NewType('DataClassType', Any) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" if isinstance(a_ , a_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def UpperCAmelCase ( a_ ) -> Callable[[str], Any]: """simple docstring""" __A = {str(a_ ): choice for choice in choices} return lambda a_ : str_to_choice.get(a_ , a_ ) def UpperCAmelCase ( *, a_ = None , a_ = None , a_ = dataclasses.MISSING , a_ = dataclasses.MISSING , a_ = None , **a_ , ) -> dataclasses.Field: """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls __A = {} if aliases is not None: __A = aliases if help is not None: __A = help return dataclasses.field(metadata=a_ , default=a_ , default_factory=a_ , **a_ ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 def __init__( self : Union[str, Any] ,A : Union[DataClassType, Iterable[DataClassType]] ,**A : List[Any] ): # To make the default appear when using --help if "formatter_class" not in kwargs: __A = ArgumentDefaultsHelpFormatter super().__init__(**A ) if dataclasses.is_dataclass(A ): __A = [dataclass_types] __A = list(A ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A ) @staticmethod def UpperCamelCase_ ( A : ArgumentParser ,A : dataclasses.Field ): __A = f'''--{field.name}''' __A = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type ,A ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) __A = kwargs.pop("aliases" ,[] ) if isinstance(A ,A ): __A = [aliases] __A = getattr(field.type ,"__origin__" ,field.type ) if origin_type is Union or (hasattr(A ,"UnionType" ) and isinstance(A ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." f''' Problem encountered in field \'{field.name}\'.''' ) if type(A ) not in field.type.__args__: # filter `str` in Union __A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] __A = getattr(field.type ,"__origin__" ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) __A = ( field.type.__args__[0] if isinstance(A ,field.type.__args__[1] ) else field.type.__args__[1] ) __A = getattr(field.type ,"__origin__" ,field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) __A = {} if origin_type is Literal or (isinstance(field.type ,A ) and issubclass(field.type ,A )): if origin_type is Literal: __A = field.type.__args__ else: __A = [x.value for x in field.type] __A = make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: __A = field.default else: __A = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument __A = copy(A ) # Hack because type=bool in argparse does not behave as we want. __A = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. __A = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way __A = default # This tells argparse we accept 0 or 1 value after --field_name __A = "?" # This is the value that will get picked if we do --field_name (without value) __A = True elif isclass(A ) and issubclass(A ,A ): __A = field.type.__args__[0] __A = "+" if field.default_factory is not dataclasses.MISSING: __A = field.default_factory() elif field.default is dataclasses.MISSING: __A = True else: __A = field.type if field.default is not dataclasses.MISSING: __A = field.default elif field.default_factory is not dataclasses.MISSING: __A = field.default_factory() else: __A = True parser.add_argument(A ,*A ,**A ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): __A = False parser.add_argument(f'''--no_{field.name}''' ,action="store_false" ,dest=field.name ,**A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : DataClassType ): if hasattr(A ,"_argument_group_name" ): __A = self.add_argument_group(dtype._argument_group_name ) else: __A = self try: __A = get_type_hints(A ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(A ): __A = ".".join(map(A ,sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(A ): if not field.init: continue __A = type_hints[field.name] self._parse_dataclass_field(A ,A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : List[Any]=None ,A : List[Any]=False ,A : Optional[Any]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=None ,): if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): __A = [] if args_filename: args_files.append(Path(A ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values __A = ArgumentParser() args_file_parser.add_argument(A ,type=A ,action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) __A , __A = args_file_parser.parse_known_args(args=A ) __A = vars(A ).get(args_file_flag.lstrip("-" ) ,A ) if cmd_args_file_paths: args_files.extend([Path(A ) for p in cmd_args_file_paths] ) __A = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last __A = file_args + args if args is not None else file_args + sys.argv[1:] __A , __A = self.parse_known_args(args=A ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in vars(A ).items() if k in keys} for k in keys: delattr(A ,A ) __A = dtype(**A ) outputs.append(A ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def UpperCamelCase_ ( self : Dict ,A : Dict[str, Any] ,A : bool = False ): __A = set(args.keys() ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) __A = dtype(**A ) outputs.append(A ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(A )}''' ) return tuple(A ) def UpperCamelCase_ ( self : List[str] ,A : str ,A : bool = False ): with open(Path(A ) ,encoding="utf-8" ) as open_json_file: __A = json.loads(open_json_file.read() ) __A = self.parse_dict(A ,allow_extra_keys=A ) return tuple(A ) def UpperCamelCase_ ( self : int ,A : str ,A : bool = False ): __A = self.parse_dict(yaml.safe_load(Path(A ).read_text() ) ,allow_extra_keys=A ) return tuple(A )
15
0
import logging import torch from torch import nn from torch.nn import CrossEntropyLoss, MSELoss from transformers.file_utils import add_start_docstrings, add_start_docstrings_to_model_forward from transformers.models.bert.modeling_bert import ( BERT_INPUTS_DOCSTRING, BERT_START_DOCSTRING, BertEncoder, BertModel, BertPreTrainedModel, ) _a = logging.getLogger(__name__) class __lowerCamelCase ( snake_case__): """simple docstring""" def UpperCamelCase ( self , UpperCAmelCase , UpperCAmelCase , UpperCAmelCase=None , UpperCAmelCase=None ): """simple docstring""" _UpperCAmelCase = self.layer[current_layer](UpperCAmelCase , UpperCAmelCase , head_mask[current_layer] ) _UpperCAmelCase = layer_outputs[0] return hidden_states @add_start_docstrings( "The bare Bert Model transformer with PABEE outputting raw hidden-states without any specific head on top." , snake_case__ , ) class __lowerCamelCase ( snake_case__): """simple docstring""" def __init__( self , UpperCAmelCase ): """simple docstring""" super().__init__(UpperCAmelCase ) _UpperCAmelCase = BertEncoderWithPabee(UpperCAmelCase ) self.init_weights() _UpperCAmelCase = 0 _UpperCAmelCase = 0 _UpperCAmelCase = 0 _UpperCAmelCase = 0 def UpperCamelCase ( self , UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = threshold def UpperCamelCase ( self , UpperCAmelCase ): """simple docstring""" _UpperCAmelCase = patience def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = 0 _UpperCAmelCase = 0 def UpperCamelCase ( self ): """simple docstring""" _UpperCAmelCase = self.inference_layers_num / self.inference_instances_num _UpperCAmelCase = ( F"""*** Patience = {self.patience} Avg. Inference Layers = {avg_inf_layers:.2f} Speed Up =""" F""" {1 - avg_inf_layers / self.config.num_hidden_layers:.2f} ***""" ) print(UpperCAmelCase ) @add_start_docstrings_to_model_forward(UpperCAmelCase ) def UpperCamelCase ( self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=False , ): """simple docstring""" if input_ids is not None and inputs_embeds is not None: raise ValueError('You cannot specify both input_ids and inputs_embeds at the same time' ) elif input_ids is not None: _UpperCAmelCase = input_ids.size() elif inputs_embeds is not None: _UpperCAmelCase = inputs_embeds.size()[:-1] else: raise ValueError('You have to specify either input_ids or inputs_embeds' ) _UpperCAmelCase = input_ids.device if input_ids is not None else inputs_embeds.device if attention_mask is None: _UpperCAmelCase = torch.ones(UpperCAmelCase , device=UpperCAmelCase ) if token_type_ids is None: _UpperCAmelCase = torch.zeros(UpperCAmelCase , dtype=torch.long , device=UpperCAmelCase ) # We can provide a self-attention mask of dimensions [batch_size, from_seq_length, to_seq_length] # ourselves in which case we just need to make it broadcastable to all heads. _UpperCAmelCase = self.get_extended_attention_mask(UpperCAmelCase , UpperCAmelCase , UpperCAmelCase ) # If a 2D ou 3D attention mask is provided for the cross-attention # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length] if self.config.is_decoder and encoder_hidden_states is not None: _UpperCAmelCase , _UpperCAmelCase , _UpperCAmelCase = encoder_hidden_states.size() _UpperCAmelCase = (encoder_batch_size, encoder_sequence_length) if encoder_attention_mask is None: _UpperCAmelCase = torch.ones(UpperCAmelCase , device=UpperCAmelCase ) _UpperCAmelCase = self.invert_attention_mask(UpperCAmelCase ) else: _UpperCAmelCase = None # Prepare head mask if needed # 1.0 in head_mask indicate we keep the head # attention_probs has shape bsz x n_heads x N x N # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads] # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length] _UpperCAmelCase = self.get_head_mask(UpperCAmelCase , self.config.num_hidden_layers ) _UpperCAmelCase = self.embeddings( input_ids=UpperCAmelCase , position_ids=UpperCAmelCase , token_type_ids=UpperCAmelCase , inputs_embeds=UpperCAmelCase ) _UpperCAmelCase = embedding_output if self.training: _UpperCAmelCase = [] for i in range(self.config.num_hidden_layers ): _UpperCAmelCase = self.encoder.adaptive_forward( UpperCAmelCase , current_layer=UpperCAmelCase , attention_mask=UpperCAmelCase , head_mask=UpperCAmelCase ) _UpperCAmelCase = self.pooler(UpperCAmelCase ) _UpperCAmelCase = output_layers[i](output_dropout(UpperCAmelCase ) ) res.append(UpperCAmelCase ) elif self.patience == 0: # Use all layers for inference _UpperCAmelCase = self.encoder( UpperCAmelCase , attention_mask=UpperCAmelCase , head_mask=UpperCAmelCase , encoder_hidden_states=UpperCAmelCase , encoder_attention_mask=UpperCAmelCase , ) _UpperCAmelCase = self.pooler(encoder_outputs[0] ) _UpperCAmelCase = [output_layers[self.config.num_hidden_layers - 1](UpperCAmelCase )] else: _UpperCAmelCase = 0 _UpperCAmelCase = None _UpperCAmelCase = 0 for i in range(self.config.num_hidden_layers ): calculated_layer_num += 1 _UpperCAmelCase = self.encoder.adaptive_forward( UpperCAmelCase , current_layer=UpperCAmelCase , attention_mask=UpperCAmelCase , head_mask=UpperCAmelCase ) _UpperCAmelCase = self.pooler(UpperCAmelCase ) _UpperCAmelCase = output_layers[i](UpperCAmelCase ) if regression: _UpperCAmelCase = logits.detach() if patient_result is not None: _UpperCAmelCase = patient_result.detach() if (patient_result is not None) and torch.abs(patient_result - labels ) < self.regression_threshold: patient_counter += 1 else: _UpperCAmelCase = 0 else: _UpperCAmelCase = logits.detach().argmax(dim=1 ) if patient_result is not None: _UpperCAmelCase = patient_result.detach().argmax(dim=1 ) if (patient_result is not None) and torch.all(labels.eq(UpperCAmelCase ) ): patient_counter += 1 else: _UpperCAmelCase = 0 _UpperCAmelCase = logits if patient_counter == self.patience: break _UpperCAmelCase = [patient_result] self.inference_layers_num += calculated_layer_num self.inference_instances_num += 1 return res @add_start_docstrings( "Bert Model transformer with PABEE and a sequence classification/regression head on top (a linear layer on top of\n the pooled output) e.g. for GLUE tasks. " , snake_case__ , ) class __lowerCamelCase ( snake_case__): """simple docstring""" def __init__( self , UpperCAmelCase ): """simple docstring""" super().__init__(UpperCAmelCase ) _UpperCAmelCase = config.num_labels _UpperCAmelCase = BertModelWithPabee(UpperCAmelCase ) _UpperCAmelCase = nn.Dropout(config.hidden_dropout_prob ) _UpperCAmelCase = nn.ModuleList( [nn.Linear(config.hidden_size , self.config.num_labels ) for _ in range(config.num_hidden_layers )] ) self.init_weights() @add_start_docstrings_to_model_forward(UpperCAmelCase ) def UpperCamelCase ( self , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , UpperCAmelCase=None , ): """simple docstring""" _UpperCAmelCase = self.bert( input_ids=UpperCAmelCase , attention_mask=UpperCAmelCase , token_type_ids=UpperCAmelCase , position_ids=UpperCAmelCase , head_mask=UpperCAmelCase , inputs_embeds=UpperCAmelCase , output_dropout=self.dropout , output_layers=self.classifiers , regression=self.num_labels == 1 , ) _UpperCAmelCase = (logits[-1],) if labels is not None: _UpperCAmelCase = None _UpperCAmelCase = 0 for ix, logits_item in enumerate(UpperCAmelCase ): if self.num_labels == 1: # We are doing regression _UpperCAmelCase = MSELoss() _UpperCAmelCase = loss_fct(logits_item.view(-1 ) , labels.view(-1 ) ) else: _UpperCAmelCase = CrossEntropyLoss() _UpperCAmelCase = loss_fct(logits_item.view(-1 , self.num_labels ) , labels.view(-1 ) ) if total_loss is None: _UpperCAmelCase = loss else: total_loss += loss * (ix + 1) total_weights += ix + 1 _UpperCAmelCase = (total_loss / total_weights,) + outputs return outputs
39
SCREAMING_SNAKE_CASE :Any = 256 # Modulus to hash a string SCREAMING_SNAKE_CASE :Union[str, Any] = 100_0003 def UpperCAmelCase ( a_ , a_ ) -> bool: """simple docstring""" __A = len(a_ ) __A = len(a_ ) if p_len > t_len: return False __A = 0 __A = 0 __A = 1 # Calculating the hash of pattern and substring of text for i in range(a_ ): __A = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus __A = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue __A = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash __A = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def UpperCAmelCase ( ) -> None: """simple docstring""" __A = "abc1abc12" __A = "alskfjaldsabc1abc1abc12k23adsfabcabc" __A = "alskfjaldsk23adsfabcabc" assert rabin_karp(a_ , a_ ) and not rabin_karp(a_ , a_ ) # Test 2) __A = "ABABX" __A = "ABABZABABYABABX" assert rabin_karp(a_ , a_ ) # Test 3) __A = "AAAB" __A = "ABAAAAAB" assert rabin_karp(a_ , a_ ) # Test 4) __A = "abcdabcy" __A = "abcxabcdabxabcdabcdabcy" assert rabin_karp(a_ , a_ ) # Test 5) __A = "Lü" __A = "Lüsai" assert rabin_karp(a_ , a_ ) __A = "Lue" assert not rabin_karp(a_ , a_ ) print("Success." ) if __name__ == "__main__": test_rabin_karp()
15
0
"""simple docstring""" from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_tokenizers_available, is_torch_available, is_vision_available, ) __lowercase = { """configuration_clip""": [ """CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP""", """CLIPConfig""", """CLIPOnnxConfig""", """CLIPTextConfig""", """CLIPVisionConfig""", ], """processing_clip""": ["""CLIPProcessor"""], """tokenization_clip""": ["""CLIPTokenizer"""], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ["""CLIPTokenizerFast"""] try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = ["""CLIPFeatureExtractor"""] __lowercase = ["""CLIPImageProcessor"""] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ """CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """CLIPModel""", """CLIPPreTrainedModel""", """CLIPTextModel""", """CLIPTextModelWithProjection""", """CLIPVisionModel""", """CLIPVisionModelWithProjection""", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ """TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST""", """TFCLIPModel""", """TFCLIPPreTrainedModel""", """TFCLIPTextModel""", """TFCLIPVisionModel""", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowercase = [ """FlaxCLIPModel""", """FlaxCLIPPreTrainedModel""", """FlaxCLIPTextModel""", """FlaxCLIPTextPreTrainedModel""", """FlaxCLIPVisionModel""", """FlaxCLIPVisionPreTrainedModel""", ] if TYPE_CHECKING: from .configuration_clip import ( CLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, CLIPConfig, CLIPOnnxConfig, CLIPTextConfig, CLIPVisionConfig, ) from .processing_clip import CLIPProcessor from .tokenization_clip import CLIPTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_clip_fast import CLIPTokenizerFast try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .feature_extraction_clip import CLIPFeatureExtractor from .image_processing_clip import CLIPImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_clip import ( CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, CLIPModel, CLIPPreTrainedModel, CLIPTextModel, CLIPTextModelWithProjection, CLIPVisionModel, CLIPVisionModelWithProjection, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_clip import ( TF_CLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFCLIPModel, TFCLIPPreTrainedModel, TFCLIPTextModel, TFCLIPVisionModel, ) try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_clip import ( FlaxCLIPModel, FlaxCLIPPreTrainedModel, FlaxCLIPTextModel, FlaxCLIPTextPreTrainedModel, FlaxCLIPVisionModel, FlaxCLIPVisionPreTrainedModel, ) else: import sys __lowercase = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
40
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel SCREAMING_SNAKE_CASE :Union[str, Any] = False SCREAMING_SNAKE_CASE :Any = True SCREAMING_SNAKE_CASE :Tuple = False if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE :Union[str, Any] = parser.parse_args() SCREAMING_SNAKE_CASE :Dict = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } SCREAMING_SNAKE_CASE :Optional[int] = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } SCREAMING_SNAKE_CASE :int = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: SCREAMING_SNAKE_CASE :Dict = reader.read() SCREAMING_SNAKE_CASE :List[str] = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): SCREAMING_SNAKE_CASE :Optional[int] = UNetaDModel(**config) else: SCREAMING_SNAKE_CASE :Optional[Any] = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel SCREAMING_SNAKE_CASE :List[str] = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) SCREAMING_SNAKE_CASE :List[str] = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: SCREAMING_SNAKE_CASE :Optional[Any] = config[key] del config[key] SCREAMING_SNAKE_CASE :Optional[Any] = [k.replace('UNetRes', '') for k in config['down_block_types']] SCREAMING_SNAKE_CASE :List[Any] = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: SCREAMING_SNAKE_CASE :Tuple = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) SCREAMING_SNAKE_CASE :Any = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue SCREAMING_SNAKE_CASE :List[str] = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: SCREAMING_SNAKE_CASE :List[Any] = param_value SCREAMING_SNAKE_CASE :str = True if not has_changed: SCREAMING_SNAKE_CASE :List[str] = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
15
0
'''simple docstring''' _A : Any ={'''a''': ['''c''', '''b'''], '''b''': ['''d''', '''e'''], '''c''': [], '''d''': [], '''e''': []} _A : Optional[Any] =['''a''', '''b''', '''c''', '''d''', '''e'''] def SCREAMING_SNAKE_CASE_ (UpperCamelCase , UpperCamelCase , UpperCamelCase ) -> Union[str, Any]: lowerCamelCase__ : str = start # add current to visited visited.append(UpperCamelCase ) lowerCamelCase__ : Optional[Any] = edges[current] for neighbor in neighbors: # if neighbor not in visited, visit if neighbor not in visited: lowerCamelCase__ : str = topological_sort(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # if all neighbors visited add current to sort sort.append(UpperCamelCase ) # if all vertices haven't been visited select a new one to visit if len(UpperCamelCase ) != len(UpperCamelCase ): for vertice in vertices: if vertice not in visited: lowerCamelCase__ : Union[str, Any] = topological_sort(UpperCamelCase , UpperCamelCase , UpperCamelCase ) # return sort return sort if __name__ == "__main__": _A : Optional[Any] =topological_sort('''a''', [], []) print(sort)
41
import argparse import math import traceback import dateutil.parser as date_parser import requests def UpperCAmelCase ( a_ ) -> str: """simple docstring""" __A = {} __A = job["started_at"] __A = job["completed_at"] __A = date_parser.parse(a_ ) __A = date_parser.parse(a_ ) __A = round((end_datetime - start_datetime).total_seconds() / 60.0 ) __A = start __A = end __A = duration_in_min return job_info def UpperCAmelCase ( a_ , a_=None ) -> str: """simple docstring""" __A = None if token is not None: __A = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} __A = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' __A = requests.get(a_ , headers=a_ ).json() __A = {} try: job_time.update({job["name"]: extract_time_from_single_job(a_ ) for job in result["jobs"]} ) __A = math.ceil((result["total_count"] - 1_0_0) / 1_0_0 ) for i in range(a_ ): __A = requests.get(url + F'''&page={i + 2}''' , headers=a_ ).json() job_time.update({job["name"]: extract_time_from_single_job(a_ ) for job in result["jobs"]} ) return job_time except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} if __name__ == "__main__": SCREAMING_SNAKE_CASE :Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() SCREAMING_SNAKE_CASE :Union[str, Any] = get_job_time(args.workflow_run_id) SCREAMING_SNAKE_CASE :Optional[int] = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'''{k}: {v["duration"]}''')
15
0
'''simple docstring''' import random import unittest from torch.utils.data import BatchSampler, DataLoader, IterableDataset from accelerate import Accelerator from accelerate.data_loader import ( BatchSamplerShard, DataLoaderDispatcher, DataLoaderShard, IterableDatasetShard, SkipBatchSampler, SkipDataLoader, skip_first_batches, ) class __UpperCAmelCase ( _lowerCamelCase ): def __init__( self , lowerCAmelCase_=0.01 , lowerCAmelCase_=10_00 ): """simple docstring""" _snake_case = p_stop _snake_case = max_length def __iter__( self ): """simple docstring""" _snake_case = 0 _snake_case = False while not stop and count < self.max_length: yield count count += 1 _snake_case = random.random() < self.p_stop class __UpperCAmelCase ( unittest.TestCase ): def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=True ): """simple docstring""" _snake_case = [ BatchSamplerShard(lowerCAmelCase_ , 2 , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) for i in range(2 ) ] _snake_case = [list(lowerCAmelCase_ ) for batch_sampler_shard in batch_sampler_shards] if not split_batches: self.assertListEqual([len(lowerCAmelCase_ ) for shard in batch_sampler_shards] , [len(lowerCAmelCase_ ) for e in expected] ) self.assertListEqual(lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = BatchSampler(range(24 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = BatchSampler(range(24 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. _snake_case = BatchSampler(range(21 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [0, 1, 2]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = BatchSampler(range(21 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. _snake_case = BatchSampler(range(22 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 0, 1]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = BatchSampler(range(22 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. _snake_case = BatchSampler(range(20 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 0]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [1, 2, 3]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = BatchSampler(range(20 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) # Check the shards when the dataset is very small. _snake_case = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [[[0, 1, 0]], [[1, 0, 1]]] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) _snake_case = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [[], []] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = BatchSampler(range(24 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(24 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size. _snake_case = BatchSampler(range(22 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [0, 1]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(22 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. _snake_case = BatchSampler(range(21 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 0]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [1, 2]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(21 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) # Check the shards when the dataset is very small. _snake_case = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [[[0, 1]], [[0, 1]]] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [[], []] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = BatchSampler(range(24 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21, 22, 23]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(24 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) # Check the shards when the dataset is a round multiple of batch size but not total batch size. _snake_case = BatchSampler(range(21 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(21 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but has a multiple of # num_processes batch. _snake_case = BatchSampler(range(22 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19, 20]], [[3, 4, 5], [9, 10, 11], [15, 16, 17], [21]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(22 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size but and has not a multiple of # num_processes batch. _snake_case = BatchSampler(range(20 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14], [18, 19]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(20 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1, 2], [6, 7, 8], [12, 13, 14]], [[3, 4, 5], [9, 10, 11], [15, 16, 17]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) # Check the shards when the dataset is very small. _snake_case = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [[[0, 1]], []] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(2 ) , batch_size=3 , drop_last=lowerCAmelCase_ ) _snake_case = [[], []] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = BatchSampler(range(24 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19], [22, 23]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(24 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) # Expected shouldn't change self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size. _snake_case = BatchSampler(range(22 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20, 21]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(22 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) # Check the shards when the dataset is not a round multiple of batch size or num_processes. _snake_case = BatchSampler(range(21 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17], [20]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(21 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [ [[0, 1], [4, 5], [8, 9], [12, 13], [16, 17]], [[2, 3], [6, 7], [10, 11], [14, 15], [18, 19]], ] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) # Check the shards when the dataset is very small. _snake_case = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [[[0, 1]], []] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) _snake_case = BatchSampler(range(2 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = [[], []] self.check_batch_sampler_shards(lowerCAmelCase_ , lowerCAmelCase_ , split_batches=lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = [[0, 1, 2], [3, 4], [5, 6, 7, 8], [9, 10, 11], [12, 13]] _snake_case = [BatchSamplerShard(lowerCAmelCase_ , 2 , lowerCAmelCase_ , even_batches=lowerCAmelCase_ ) for i in range(2 )] self.assertEqual(len(batch_sampler_shards[0] ) , 3 ) self.assertEqual(len(batch_sampler_shards[1] ) , 2 ) self.assertListEqual(list(batch_sampler_shards[0] ) , [[0, 1, 2], [5, 6, 7, 8], [12, 13]] ) self.assertListEqual(list(batch_sampler_shards[1] ) , [[3, 4], [9, 10, 11]] ) def lowerCamelCase ( self , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_ , lowerCAmelCase_=False , lowerCAmelCase_=2 , lowerCAmelCase_=False ): """simple docstring""" random.seed(lowerCAmelCase_ ) _snake_case = list(lowerCAmelCase_ ) _snake_case = [ IterableDatasetShard( lowerCAmelCase_ , batch_size=lowerCAmelCase_ , drop_last=lowerCAmelCase_ , num_processes=lowerCAmelCase_ , process_index=lowerCAmelCase_ , split_batches=lowerCAmelCase_ , ) for i in range(lowerCAmelCase_ ) ] _snake_case = [] for iterable_dataset_shard in iterable_dataset_shards: # Since our random iterable dataset will be... random... we need to use a seed to get reproducible results. random.seed(lowerCAmelCase_ ) iterable_dataset_lists.append(list(lowerCAmelCase_ ) ) _snake_case = batch_size // num_processes if split_batches else batch_size # All iterable dataset shard should have the same length, a round multiple of shard_batch_size _snake_case = iterable_dataset_lists[0] for l in iterable_dataset_lists[1:]: self.assertEqual(len(lowerCAmelCase_ ) , len(lowerCAmelCase_ ) ) self.assertTrue(len(lowerCAmelCase_ ) % shard_batch_size == 0 ) _snake_case = [] for idx in range(0 , len(lowerCAmelCase_ ) , lowerCAmelCase_ ): for l in iterable_dataset_lists: observed += l[idx : idx + shard_batch_size] if not drop_last: while len(lowerCAmelCase_ ) < len(lowerCAmelCase_ ): reference += reference self.assertListEqual(lowerCAmelCase_ , reference[: len(lowerCAmelCase_ )] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = 42 _snake_case = RandomIterableDataset() self.check_iterable_dataset_shards(lowerCAmelCase_ , lowerCAmelCase_ , batch_size=4 , drop_last=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) self.check_iterable_dataset_shards(lowerCAmelCase_ , lowerCAmelCase_ , batch_size=4 , drop_last=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) self.check_iterable_dataset_shards(lowerCAmelCase_ , lowerCAmelCase_ , batch_size=4 , drop_last=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) self.check_iterable_dataset_shards(lowerCAmelCase_ , lowerCAmelCase_ , batch_size=4 , drop_last=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) # Edge case with a very small dataset _snake_case = RandomIterableDataset(max_length=2 ) self.check_iterable_dataset_shards(lowerCAmelCase_ , lowerCAmelCase_ , batch_size=4 , drop_last=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) self.check_iterable_dataset_shards(lowerCAmelCase_ , lowerCAmelCase_ , batch_size=4 , drop_last=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) self.check_iterable_dataset_shards(lowerCAmelCase_ , lowerCAmelCase_ , batch_size=4 , drop_last=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) self.check_iterable_dataset_shards(lowerCAmelCase_ , lowerCAmelCase_ , batch_size=4 , drop_last=lowerCAmelCase_ , split_batches=lowerCAmelCase_ ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = BatchSampler(range(16 ) , batch_size=4 , drop_last=lowerCAmelCase_ ) _snake_case = SkipBatchSampler(lowerCAmelCase_ , 2 ) self.assertListEqual(list(lowerCAmelCase_ ) , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = SkipDataLoader(list(range(16 ) ) , batch_size=4 , skip_batches=2 ) self.assertListEqual([t.tolist() for t in dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = DataLoader(list(range(16 ) ) , batch_size=4 ) _snake_case = skip_first_batches(lowerCAmelCase_ , num_batches=2 ) self.assertListEqual([t.tolist() for t in new_dataloader] , [[8, 9, 10, 11], [12, 13, 14, 15]] ) def lowerCamelCase ( self ): """simple docstring""" _snake_case = DataLoaderShard(list(range(16 ) ) , batch_size=4 ) for idx, _ in enumerate(lowerCAmelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(lowerCAmelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) def lowerCamelCase ( self ): """simple docstring""" Accelerator() _snake_case = DataLoaderDispatcher(range(16 ) , batch_size=4 ) for idx, _ in enumerate(lowerCAmelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 ) # Test it also works on the second iteration for idx, _ in enumerate(lowerCAmelCase_ ): self.assertEqual(dataloader.end_of_dataloader , idx == 3 )
42
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" __A = args.pruning_method __A = args.threshold __A = args.model_name_or_path.rstrip("/" ) __A = args.target_model_path print(F'''Load fine-pruned model from {model_name_or_path}''' ) __A = torch.load(os.path.join(a_ , "pytorch_model.bin" ) ) __A = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __A = tensor print(F'''Copied layer {name}''' ) elif "classifier" in name or "qa_output" in name: __A = tensor print(F'''Copied layer {name}''' ) elif "bias" in name: __A = tensor print(F'''Copied layer {name}''' ) else: if pruning_method == "magnitude": __A = MagnitudeBinarizer.apply(inputs=a_ , threshold=a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "topK": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A = TopKBinarizer.apply(a_ , a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A = ThresholdBinarizer.apply(a_ , a_ , a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "l0": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A , __A = -0.1, 1.1 __A = torch.sigmoid(a_ ) __A = s * (r - l) + l __A = s_bar.clamp(min=0.0 , max=1.0 ) __A = tensor * mask print(F'''Pruned layer {name}''' ) else: raise ValueError("Unknown pruning method" ) if target_model_path is None: __A = os.path.join( os.path.dirname(a_ ) , F'''bertarized_{os.path.basename(a_ )}''' ) if not os.path.isdir(a_ ): shutil.copytree(a_ , a_ ) print(F'''\nCreated folder {target_model_path}''' ) torch.save(a_ , os.path.join(a_ , "pytorch_model.bin" ) ) print("\nPruned model saved! See you later!" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--pruning_method', choices=['l0', 'magnitude', 'topK', 'sigmoied_threshold'], type=str, required=True, help=( 'Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,' ' sigmoied_threshold = Soft movement pruning)' ), ) parser.add_argument( '--threshold', type=float, required=False, help=( 'For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.' 'For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.' 'Not needed for `l0`' ), ) parser.add_argument( '--model_name_or_path', type=str, required=True, help='Folder containing the model that was previously fine-pruned', ) parser.add_argument( '--target_model_path', default=None, type=str, required=False, help='Folder containing the model that was previously fine-pruned', ) SCREAMING_SNAKE_CASE :str = parser.parse_args() main(args)
15
0
from timeit import timeit def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if number < 0: raise ValueError('''the value of input must not be negative''' ) __UpperCamelCase :str = 0 while number: number &= number - 1 result += 1 return result def lowerCamelCase ( SCREAMING_SNAKE_CASE ): '''simple docstring''' if number < 0: raise ValueError('''the value of input must not be negative''' ) __UpperCamelCase :Optional[Any] = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def lowerCamelCase ( ): '''simple docstring''' def do_benchmark(SCREAMING_SNAKE_CASE ) -> None: __UpperCamelCase :List[str] = '''import __main__ as z''' print(f"""Benchmark when {number = }:""" ) print(f"""{get_set_bits_count_using_modulo_operator(SCREAMING_SNAKE_CASE ) = }""" ) __UpperCamelCase :Optional[int] = timeit('''z.get_set_bits_count_using_modulo_operator(25)''' , setup=SCREAMING_SNAKE_CASE ) print(f"""timeit() runs in {timing} seconds""" ) print(f"""{get_set_bits_count_using_brian_kernighans_algorithm(SCREAMING_SNAKE_CASE ) = }""" ) __UpperCamelCase :Union[str, Any] = timeit( '''z.get_set_bits_count_using_brian_kernighans_algorithm(25)''' , setup=SCREAMING_SNAKE_CASE , ) print(f"""timeit() runs in {timing} seconds""" ) for number in (25, 37, 58, 0): do_benchmark(SCREAMING_SNAKE_CASE ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
43
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :int = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Union[str, Any] = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } SCREAMING_SNAKE_CASE :int = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] snake_case_ = [] def __init__( self : Any ,A : List[str] ,A : str="<unk>" ,A : int="<s>" ,A : Union[str, Any]="</s>" ,A : List[str]="<pad>" ,A : int="[SEP]" ,A : Optional[Any]="[MASK]" ,A : Tuple="[CLS]" ,A : Optional[Dict[str, Any]] = None ,**A : Any ,): __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else bos_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else eos_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else unk_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else pad_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else cls_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else sep_token # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sep_token=A ,mask_token=A ,cls_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) @property def UpperCamelCase_ ( self : List[str] ): return self.sp_model.get_piece_size() def UpperCamelCase_ ( self : Optional[Any] ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : str ,A : Optional[Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Tuple ): return self.sp_model.piece_to_id(A ) def UpperCamelCase_ ( self : List[Any] ,A : Tuple ): __A = self.sp_model.IdToPiece(A ) return token def UpperCamelCase_ ( self : List[Any] ,A : int ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def UpperCamelCase_ ( self : Tuple ,A : List[int] ,A : bool = False ,A : bool = None ,A : bool = True ,**A : Union[str, Any] ,): __A = kwargs.pop("use_source_tokenizer" ,A ) __A = self.convert_ids_to_tokens(A ,skip_special_tokens=A ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __A = [] __A = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(A ) ) __A = [] sub_texts.append(A ) else: current_sub_text.append(A ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(A ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: __A = re.sub(R" (\[(MASK|SEP)\])" ,R"\1" ," ".join(A ) ) else: __A = "".join(A ) __A = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __A = self.clean_up_tokenization(A ) return clean_text else: return text def UpperCamelCase_ ( self : str ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Dict ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : Optional[int] ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Any ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [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]
15
0
"""simple docstring""" # Copyright (c) 2021-, NVIDIA CORPORATION. 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. #################################################################################################### # # Note: If when running this conversion script you're getting an exception: # ModuleNotFoundError: No module named 'megatron.model.enums' # you need to tell python where to find the clone of Megatron-LM, e.g.: # # cd /tmp # git clone https://github.com/NVIDIA/Megatron-LM # PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py ... # # if you already have it cloned elsewhere, simply adjust the path to the existing path # # If the training was done using a Megatron-LM fork, e.g., # https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one # in your path, i.e., /path/to/Megatron-DeepSpeed/ # import argparse import os import re import zipfile import torch from transformers import AutoTokenizer, GPTaConfig def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : Union[str, Any] ,_lowerCamelCase : Optional[int]=0 ) -> Dict: # Format the message. if name is None: _lowerCAmelCase : int = None else: _lowerCAmelCase : int = """.""" * max(0 ,spaces - 2 ) + """# {:""" + str(50 - spaces ) + """s}""" _lowerCAmelCase : Optional[int] = fmt.format(_lowerCamelCase ) # Print and recurse (if needed). if isinstance(_lowerCamelCase ,_lowerCamelCase ): if msg is not None: print(_lowerCamelCase ) for k in val.keys(): recursive_print(_lowerCamelCase ,val[k] ,spaces + 2 ) elif isinstance(_lowerCamelCase ,torch.Tensor ): print(_lowerCamelCase ,""":""" ,val.size() ) else: print(_lowerCamelCase ,""":""" ,_lowerCamelCase ) def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : Optional[int] ,_lowerCamelCase : int ,_lowerCamelCase : Dict ,_lowerCamelCase : Dict ) -> Tuple: # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :] # for compatibility with later versions of NVIDIA Megatron-LM. # The inverse operation is performed inside Megatron-LM to read checkpoints: # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209 # If param is the weight tensor of the self-attention block, the returned tensor # will have to be transposed one more time to be read by HuggingFace GPT2. _lowerCAmelCase : int = param.size() if checkpoint_version == 1.0: # version 1.0 stores [num_heads * hidden_size * num_splits, :] _lowerCAmelCase : Union[str, Any] = (num_heads, hidden_size, num_splits) + input_shape[1:] _lowerCAmelCase : List[str] = param.view(*_lowerCamelCase ) _lowerCAmelCase : Tuple = param.transpose(0 ,2 ) _lowerCAmelCase : List[Any] = param.transpose(1 ,2 ).contiguous() elif checkpoint_version >= 2.0: # other versions store [num_heads * num_splits * hidden_size, :] _lowerCAmelCase : List[Any] = (num_heads, num_splits, hidden_size) + input_shape[1:] _lowerCAmelCase : str = param.view(*_lowerCamelCase ) _lowerCAmelCase : int = param.transpose(0 ,1 ).contiguous() _lowerCAmelCase : List[Any] = param.view(*_lowerCamelCase ) return param def SCREAMING_SNAKE_CASE ( _lowerCamelCase : Optional[Any] ,_lowerCamelCase : List[Any] ,_lowerCamelCase : Dict ) -> Optional[int]: # The converted output model. _lowerCAmelCase : Tuple = {} # old versions did not store training args _lowerCAmelCase : List[Any] = input_state_dict.get("""args""" ,_lowerCamelCase ) if ds_args is not None: # do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint # from pprint import pprint # pprint(vars(ds_args)) _lowerCAmelCase : Any = ds_args.padded_vocab_size _lowerCAmelCase : Tuple = ds_args.max_position_embeddings _lowerCAmelCase : Dict = ds_args.hidden_size _lowerCAmelCase : Dict = ds_args.num_layers _lowerCAmelCase : str = ds_args.num_attention_heads _lowerCAmelCase : List[Any] = ds_args.ffn_hidden_size # pprint(config) # The number of heads. _lowerCAmelCase : Tuple = config.n_head # The hidden_size per head. _lowerCAmelCase : int = config.n_embd // config.n_head # Megatron-LM checkpoint version if "checkpoint_version" in input_state_dict.keys(): _lowerCAmelCase : List[Any] = input_state_dict["""checkpoint_version"""] else: _lowerCAmelCase : Union[str, Any] = 0.0 # The model. _lowerCAmelCase : Tuple = input_state_dict["""model"""] # The language model. _lowerCAmelCase : List[Any] = model["""language_model"""] # The embeddings. _lowerCAmelCase : List[str] = lm["""embedding"""] # The word embeddings. _lowerCAmelCase : Union[str, Any] = embeddings["""word_embeddings"""]["""weight"""] # Truncate the embedding table to vocab_size rows. _lowerCAmelCase : Tuple = word_embeddings[: config.vocab_size, :] _lowerCAmelCase : Tuple = word_embeddings # The position embeddings. _lowerCAmelCase : List[str] = embeddings["""position_embeddings"""]["""weight"""] # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size] _lowerCAmelCase : int = pos_embeddings.size(0 ) if n_positions != config.n_positions: raise ValueError( f"pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match" ) # Store the position embeddings. _lowerCAmelCase : Tuple = pos_embeddings # The transformer. _lowerCAmelCase : List[Any] = lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""] # The regex to extract layer names. _lowerCAmelCase : Optional[Any] = re.compile(r"""layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)""" ) # The simple map of names for "automated" rules. _lowerCAmelCase : Any = { """attention.dense""": """.attn.c_proj.""", """self_attention.dense""": """.attn.c_proj.""", """mlp.dense_h_to_4h""": """.mlp.c_fc.""", """mlp.dense_4h_to_h""": """.mlp.c_proj.""", } # Extract the layers. for key, val in transformer.items(): # Match the name. _lowerCAmelCase : Optional[Any] = layer_re.match(_lowerCamelCase ) # Stop if that's not a layer if m is None: break # The index of the layer. _lowerCAmelCase : Any = int(m.group(1 ) ) # The name of the operation. _lowerCAmelCase : Any = m.group(2 ) # Is it a weight or a bias? _lowerCAmelCase : Optional[Any] = m.group(3 ) # The name of the layer. _lowerCAmelCase : Union[str, Any] = f"transformer.h.{layer_idx}" # For layernorm(s), simply store the layer norm. if op_name.endswith("""layernorm""" ): _lowerCAmelCase : Optional[int] = """ln_1""" if op_name.startswith("""input""" ) else """ln_2""" _lowerCAmelCase : Union[str, Any] = val # Transpose the QKV matrix. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "weight": # Insert a tensor of 1x1xDxD bias. _lowerCAmelCase : Any = torch.tril(torch.ones((n_positions, n_positions) ,dtype=torch.floataa ) ).view( 1 ,1 ,_lowerCamelCase ,_lowerCamelCase ) _lowerCAmelCase : str = causal_mask # Insert a "dummy" tensor for masked_bias. _lowerCAmelCase : str = torch.tensor(-1e4 ,dtype=torch.floataa ) _lowerCAmelCase : Union[str, Any] = masked_bias _lowerCAmelCase : Tuple = fix_query_key_value_ordering(_lowerCamelCase ,_lowerCamelCase ,3 ,_lowerCamelCase ,_lowerCamelCase ) # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D. _lowerCAmelCase : Dict = out_val.transpose(0 ,1 ).contiguous() # Store. _lowerCAmelCase : List[Any] = out_val # Transpose the bias. elif ( op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value" ) and weight_or_bias == "bias": _lowerCAmelCase : Dict = fix_query_key_value_ordering(_lowerCamelCase ,_lowerCamelCase ,3 ,_lowerCamelCase ,_lowerCamelCase ) # Store. No change of shape. _lowerCAmelCase : List[Any] = out_val # Transpose the weights. elif weight_or_bias == "weight": _lowerCAmelCase : Dict = megatron_to_transformers[op_name] _lowerCAmelCase : Dict = val.transpose(0 ,1 ) # Copy the bias. elif weight_or_bias == "bias": _lowerCAmelCase : Union[str, Any] = megatron_to_transformers[op_name] _lowerCAmelCase : List[str] = val # DEBUG. assert config.n_layer == layer_idx + 1 # The final layernorm. _lowerCAmelCase : Union[str, Any] = transformer["""final_layernorm.weight"""] _lowerCAmelCase : Union[str, Any] = transformer["""final_layernorm.bias"""] # For LM head, transformers' wants the matrix to weight embeddings. _lowerCAmelCase : Dict = word_embeddings # It should be done! return output_state_dict def SCREAMING_SNAKE_CASE ( ) -> int: # Create the argument parser. _lowerCAmelCase : Tuple = argparse.ArgumentParser() parser.add_argument("""--print-checkpoint-structure""" ,action="""store_true""" ) parser.add_argument( """path_to_checkpoint""" ,type=_lowerCamelCase ,help="""Path to the checkpoint file (.zip archive or direct .pt file)""" ,) parser.add_argument( """--config_file""" ,default="""""" ,type=_lowerCamelCase ,help="""An optional config json file describing the pre-trained model.""" ,) _lowerCAmelCase : Dict = parser.parse_args() # Extract the basename. _lowerCAmelCase : Optional[int] = os.path.dirname(args.path_to_checkpoint ) # Load the model. # the .zip is very optional, let's keep it for backward compatibility print(f"Extracting PyTorch state dictionary from {args.path_to_checkpoint}" ) if args.path_to_checkpoint.endswith(""".zip""" ): with zipfile.ZipFile(args.path_to_checkpoint ,"""r""" ) as checkpoint: with checkpoint.open("""release/mp_rank_00/model_optim_rng.pt""" ) as pytorch_dict: _lowerCAmelCase : int = torch.load(_lowerCamelCase ,map_location="""cpu""" ) else: _lowerCAmelCase : List[Any] = torch.load(args.path_to_checkpoint ,map_location="""cpu""" ) _lowerCAmelCase : Union[str, Any] = input_state_dict.get("""args""" ,_lowerCamelCase ) # Read the config, or default to the model released by NVIDIA. if args.config_file == "": if ds_args is not None: if ds_args.bias_gelu_fusion: _lowerCAmelCase : Optional[Any] = """gelu_fast""" elif ds_args.openai_gelu: _lowerCAmelCase : Any = """gelu_new""" else: _lowerCAmelCase : int = """gelu""" else: # in the very early days this used to be "gelu_new" _lowerCAmelCase : Tuple = """gelu_new""" # Spell out all parameters in case the defaults change. _lowerCAmelCase : Dict = GPTaConfig( vocab_size=50257 ,n_positions=1024 ,n_embd=1024 ,n_layer=24 ,n_head=16 ,n_inner=4096 ,activation_function=_lowerCamelCase ,resid_pdrop=0.1 ,embd_pdrop=0.1 ,attn_pdrop=0.1 ,layer_norm_epsilon=1e-5 ,initializer_range=0.02 ,summary_type="""cls_index""" ,summary_use_proj=_lowerCamelCase ,summary_activation=_lowerCamelCase ,summary_proj_to_labels=_lowerCamelCase ,summary_first_dropout=0.1 ,scale_attn_weights=_lowerCamelCase ,use_cache=_lowerCamelCase ,bos_token_id=50256 ,eos_token_id=50256 ,) else: _lowerCAmelCase : int = GPTaConfig.from_json_file(args.config_file ) _lowerCAmelCase : Tuple = ["""GPT2LMHeadModel"""] # Convert. print("""Converting""" ) _lowerCAmelCase : int = convert_megatron_checkpoint(_lowerCamelCase ,_lowerCamelCase ,_lowerCamelCase ) # Print the structure of converted state dict. if args.print_checkpoint_structure: recursive_print(_lowerCamelCase ,_lowerCamelCase ) # Add tokenizer class info to config # see https://github.com/huggingface/transformers/issues/13906) if ds_args is not None: _lowerCAmelCase : str = ds_args.tokenizer_type if tokenizer_type == "GPT2BPETokenizer": _lowerCAmelCase : List[Any] = """gpt2""" elif tokenizer_type == "PretrainedFromHF": _lowerCAmelCase : str = ds_args.tokenizer_name_or_path else: raise ValueError(f"Unrecognized tokenizer_type {tokenizer_type}" ) else: _lowerCAmelCase : Optional[Any] = """gpt2""" _lowerCAmelCase : Union[str, Any] = AutoTokenizer.from_pretrained(_lowerCamelCase ) _lowerCAmelCase : int = type(_lowerCamelCase ).__name__ _lowerCAmelCase : str = tokenizer_class # Store the config to file. print("""Saving config""" ) config.save_pretrained(_lowerCamelCase ) # Save tokenizer based on args print(f"Adding {tokenizer_class} tokenizer files" ) tokenizer.save_pretrained(_lowerCamelCase ) # Store the state_dict to file. _lowerCAmelCase : int = os.path.join(_lowerCamelCase ,"""pytorch_model.bin""" ) print(f"Saving checkpoint to \"{output_checkpoint_file}\"" ) torch.save(_lowerCamelCase ,_lowerCamelCase ) #################################################################################################### if __name__ == "__main__": main() ####################################################################################################
44
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): SCREAMING_SNAKE_CASE :Any = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: SCREAMING_SNAKE_CASE :int = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" __A = (images / 2 + 0.5).clamp(0 , 1 ) __A = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __A = numpy_to_pil(a_ ) return images def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if images.ndim == 3: __A = images[None, ...] __A = (images * 2_5_5).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __A = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __A = [Image.fromarray(a_ ) for image in images] return pil_images
15
0
"""simple docstring""" import logging import os from .state import PartialState class __lowerCAmelCase ( logging.LoggerAdapter ): '''simple docstring''' @staticmethod def __UpperCAmelCase ( _a ): __a = PartialState() return not main_process_only or (main_process_only and state.is_main_process) def __UpperCAmelCase ( self , _a , _a , *_a , **_a ): if PartialState._shared_state == {}: raise RuntimeError( '''You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility.''' ) __a = kwargs.pop('''main_process_only''' , _a ) __a = kwargs.pop('''in_order''' , _a ) if self.isEnabledFor(_a ): if self._should_log(_a ): __a , __a = self.process(_a , _a ) self.logger.log(_a , _a , *_a , **_a ) elif in_order: __a = PartialState() for i in range(state.num_processes ): if i == state.process_index: __a , __a = self.process(_a , _a ) self.logger.log(_a , _a , *_a , **_a ) state.wait_for_everyone() def lowercase ( lowerCAmelCase__ : str , lowerCAmelCase__ : str = None ) -> Any: if log_level is None: __a = os.environ.get('''ACCELERATE_LOG_LEVEL''' , lowerCAmelCase__ ) __a = logging.getLogger(lowerCAmelCase__ ) if log_level is not None: logger.setLevel(log_level.upper() ) logger.root.setLevel(log_level.upper() ) return MultiProcessAdapter(lowerCAmelCase__ , {} )
45
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 :Optional[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 UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "yolos" def __init__( self : Any ,A : Optional[Any]=7_68 ,A : Dict=12 ,A : Any=12 ,A : str=30_72 ,A : Any="gelu" ,A : str=0.0 ,A : List[str]=0.0 ,A : Dict=0.02 ,A : int=1E-12 ,A : Tuple=[5_12, 8_64] ,A : List[Any]=16 ,A : str=3 ,A : str=True ,A : Any=1_00 ,A : Dict=True ,A : Dict=False ,A : Tuple=1 ,A : Union[str, Any]=5 ,A : Optional[Any]=2 ,A : Union[str, Any]=5 ,A : int=2 ,A : int=0.1 ,**A : List[str] ,): super().__init__(**A ) __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = initializer_range __A = layer_norm_eps __A = image_size __A = patch_size __A = num_channels __A = qkv_bias __A = num_detection_tokens __A = use_mid_position_embeddings __A = auxiliary_loss # Hungarian matcher __A = class_cost __A = bbox_cost __A = giou_cost # Loss coefficients __A = bbox_loss_coefficient __A = giou_loss_coefficient __A = eos_coefficient class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = version.parse("1.11" ) @property def UpperCamelCase_ ( self : str ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCamelCase_ ( self : List[Any] ): return 1E-4 @property def UpperCamelCase_ ( self : Optional[Any] ): return 12
15
0
"""simple docstring""" import gc import unittest import numpy as np import torch from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, StableDiffusionSAGPipeline, UNetaDConditionModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin enable_full_determinism() class lowercase ( _UpperCAmelCase , _UpperCAmelCase , unittest.TestCase ): _SCREAMING_SNAKE_CASE = StableDiffusionSAGPipeline _SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_PARAMS _SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_BATCH_PARAMS _SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_IMAGE_PARAMS _SCREAMING_SNAKE_CASE = TEXT_TO_IMAGE_IMAGE_PARAMS _SCREAMING_SNAKE_CASE = False def _snake_case ( self ) -> Union[str, Any]: torch.manual_seed(0 ) lowerCAmelCase = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") , up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") , cross_attention_dim=32 , ) lowerCAmelCase = DDIMScheduler( beta_start=0.00_085 , beta_end=0.012 , beta_schedule="""scaled_linear""" , clip_sample=lowercase , set_alpha_to_one=lowercase , ) torch.manual_seed(0 ) lowerCAmelCase = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] , up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] , latent_channels=4 , ) torch.manual_seed(0 ) lowerCAmelCase = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-05 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=1_000 , ) lowerCAmelCase = CLIPTextModel(lowercase ) lowerCAmelCase = CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ) lowerCAmelCase = { """unet""": unet, """scheduler""": scheduler, """vae""": vae, """text_encoder""": text_encoder, """tokenizer""": tokenizer, """safety_checker""": None, """feature_extractor""": None, } return components def _snake_case ( self , lowercase , lowercase=0 ) -> Union[str, Any]: if str(lowercase ).startswith("""mps""" ): lowerCAmelCase = torch.manual_seed(lowercase ) else: lowerCAmelCase = torch.Generator(device=lowercase ).manual_seed(lowercase ) lowerCAmelCase = { """prompt""": """.""", """generator""": generator, """num_inference_steps""": 2, """guidance_scale""": 1.0, """sag_scale""": 1.0, """output_type""": """numpy""", } return inputs def _snake_case ( self ) -> str: super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class lowercase ( unittest.TestCase ): def _snake_case ( self ) -> Tuple: # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def _snake_case ( self ) -> Optional[Any]: lowerCAmelCase = StableDiffusionSAGPipeline.from_pretrained("""CompVis/stable-diffusion-v1-4""" ) lowerCAmelCase = sag_pipe.to(lowercase ) sag_pipe.set_progress_bar_config(disable=lowercase ) lowerCAmelCase = """.""" lowerCAmelCase = torch.manual_seed(0 ) lowerCAmelCase = sag_pipe( [prompt] , generator=lowercase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" ) lowerCAmelCase = output.images lowerCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase = np.array([0.1_568, 0.1_738, 0.1_695, 0.1_693, 0.1_507, 0.1_705, 0.1_547, 0.1_751, 0.1_949] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def _snake_case ( self ) -> str: lowerCAmelCase = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) lowerCAmelCase = sag_pipe.to(lowercase ) sag_pipe.set_progress_bar_config(disable=lowercase ) lowerCAmelCase = """.""" lowerCAmelCase = torch.manual_seed(0 ) lowerCAmelCase = sag_pipe( [prompt] , generator=lowercase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" ) lowerCAmelCase = output.images lowerCAmelCase = image[0, -3:, -3:, -1] assert image.shape == (1, 512, 512, 3) lowerCAmelCase = np.array([0.3_459, 0.2_876, 0.2_537, 0.3_002, 0.2_671, 0.2_160, 0.3_026, 0.2_262, 0.2_371] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def _snake_case ( self ) -> Tuple: lowerCAmelCase = StableDiffusionSAGPipeline.from_pretrained("""stabilityai/stable-diffusion-2-1-base""" ) lowerCAmelCase = sag_pipe.to(lowercase ) sag_pipe.set_progress_bar_config(disable=lowercase ) lowerCAmelCase = """.""" lowerCAmelCase = torch.manual_seed(0 ) lowerCAmelCase = sag_pipe( [prompt] , width=768 , height=512 , generator=lowercase , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type="""np""" , ) lowerCAmelCase = output.images assert image.shape == (1, 512, 768, 3)
46
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) SCREAMING_SNAKE_CASE :List[str] = 'pytorch_model.bin' SCREAMING_SNAKE_CASE :str = 'pytorch_model.bin.index.json' SCREAMING_SNAKE_CASE :Optional[int] = 'adapter_config.json' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.bin' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.safetensors' SCREAMING_SNAKE_CASE :str = 'tf_model.h5' SCREAMING_SNAKE_CASE :List[Any] = 'tf_model.h5.index.json' SCREAMING_SNAKE_CASE :str = 'model.ckpt' SCREAMING_SNAKE_CASE :List[Any] = 'flax_model.msgpack' SCREAMING_SNAKE_CASE :Optional[int] = 'flax_model.msgpack.index.json' SCREAMING_SNAKE_CASE :Tuple = 'model.safetensors' SCREAMING_SNAKE_CASE :List[Any] = 'model.safetensors.index.json' SCREAMING_SNAKE_CASE :str = 'config.json' SCREAMING_SNAKE_CASE :int = 'preprocessor_config.json' SCREAMING_SNAKE_CASE :Optional[Any] = FEATURE_EXTRACTOR_NAME SCREAMING_SNAKE_CASE :Optional[int] = 'generation_config.json' SCREAMING_SNAKE_CASE :List[str] = 'modelcard.json' SCREAMING_SNAKE_CASE :Optional[int] = '▁' SCREAMING_SNAKE_CASE :Optional[Any] = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility SCREAMING_SNAKE_CASE :str = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. SCREAMING_SNAKE_CASE :Optional[Any] = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] SCREAMING_SNAKE_CASE :List[Any] = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" if version.parse(a_ ) < version.parse(a_ ): if "dev" in min_version: __A = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: __A = F'''This example requires a minimum version of {min_version},''' error_message += F''' but the version found is {__version__}.\n''' raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers." )
15
0
'''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 ( _UpperCamelCase : List[str] , _UpperCamelCase : Any ) -> str: """simple docstring""" _SCREAMING_SNAKE_CASE ='https://storage.googleapis.com/sfr-vision-language-research/BLIP/demo.jpg' _SCREAMING_SNAKE_CASE =Image.open(requests.get(_UpperCamelCase , stream=_UpperCamelCase ).raw ).convert('RGB' ) _SCREAMING_SNAKE_CASE =transforms.Compose( [ transforms.Resize((image_size, image_size) , interpolation=InterpolationMode.BICUBIC ), transforms.ToTensor(), transforms.Normalize((0.48_14_54_66, 0.4_57_82_75, 0.40_82_10_73) , (0.26_86_29_54, 0.26_13_02_58, 0.27_57_77_11) ), ] ) _SCREAMING_SNAKE_CASE =transform(_UpperCamelCase ).unsqueeze(0 ).to(_UpperCamelCase ) return image def _lowerCAmelCase ( _UpperCamelCase : Dict ) -> str: """simple docstring""" if "visual_encoder" in key: _SCREAMING_SNAKE_CASE =re.sub('visual_encoder*' , 'vision_model.encoder' , _UpperCamelCase ) if "blocks" in key: _SCREAMING_SNAKE_CASE =re.sub(r'blocks' , 'layers' , _UpperCamelCase ) if "attn" in key: _SCREAMING_SNAKE_CASE =re.sub(r'attn' , 'self_attn' , _UpperCamelCase ) if "norm1" in key: _SCREAMING_SNAKE_CASE =re.sub(r'norm1' , 'layer_norm1' , _UpperCamelCase ) if "norm2" in key: _SCREAMING_SNAKE_CASE =re.sub(r'norm2' , 'layer_norm2' , _UpperCamelCase ) if "encoder.norm" in key: _SCREAMING_SNAKE_CASE =re.sub(r'encoder.norm' , 'post_layernorm' , _UpperCamelCase ) if "encoder.patch_embed.proj" in key: _SCREAMING_SNAKE_CASE =re.sub(r'encoder.patch_embed.proj' , 'embeddings.patch_embedding' , _UpperCamelCase ) if "encoder.pos_embed" in key: _SCREAMING_SNAKE_CASE =re.sub(r'encoder.pos_embed' , 'embeddings.position_embedding' , _UpperCamelCase ) if "encoder.cls_token" in key: _SCREAMING_SNAKE_CASE =re.sub(r'encoder.cls_token' , 'embeddings.class_embedding' , _UpperCamelCase ) if "self_attn" in key: _SCREAMING_SNAKE_CASE =re.sub(r'self_attn.proj' , 'self_attn.projection' , _UpperCamelCase ) return key @torch.no_grad() def _lowerCAmelCase ( _UpperCamelCase : Union[str, Any] , _UpperCamelCase : int=None ) -> Tuple: """simple docstring""" if config_path is not None: _SCREAMING_SNAKE_CASE =BlipConfig.from_pretrained(_UpperCamelCase ) else: _SCREAMING_SNAKE_CASE =BlipConfig(projection_dim=5_12 , text_config={} , vision_config={} ) _SCREAMING_SNAKE_CASE =BlipForConditionalGeneration(_UpperCamelCase ).eval() _SCREAMING_SNAKE_CASE ='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_capfilt_large.pth' _SCREAMING_SNAKE_CASE =blip_decoder(pretrained=_UpperCamelCase , image_size=3_84 , vit='base' ) _SCREAMING_SNAKE_CASE =pt_model.eval() _SCREAMING_SNAKE_CASE =pt_model.state_dict() for key in modified_state_dict.copy(): _SCREAMING_SNAKE_CASE =modified_state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =rename_key(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =value hf_model.load_state_dict(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =3_84 _SCREAMING_SNAKE_CASE =load_demo_image(image_size=_UpperCamelCase , device='cpu' ) _SCREAMING_SNAKE_CASE =BertTokenizer.from_pretrained('bert-base-uncased' ) _SCREAMING_SNAKE_CASE =tokenizer(['a picture of'] ).input_ids _SCREAMING_SNAKE_CASE =hf_model.generate(_UpperCamelCase , _UpperCamelCase ) 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] _SCREAMING_SNAKE_CASE =hf_model.generate(_UpperCamelCase ) 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(_UpperCamelCase ) # model_url = 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_vqa.pth' _SCREAMING_SNAKE_CASE =( 'https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_vqa_capfilt_large.pth' ) _SCREAMING_SNAKE_CASE =blip_vqa(pretrained=_UpperCamelCase , image_size=_UpperCamelCase , vit='base' ) vqa_model.eval() _SCREAMING_SNAKE_CASE =vqa_model.state_dict() for key in modified_state_dict.copy(): _SCREAMING_SNAKE_CASE =modified_state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =rename_key(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =BlipForQuestionAnswering(_UpperCamelCase ) hf_vqa_model.load_state_dict(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =['How many dogs are in this image?'] _SCREAMING_SNAKE_CASE =tokenizer(_UpperCamelCase , return_tensors='pt' ).input_ids _SCREAMING_SNAKE_CASE =hf_vqa_model.generate(_UpperCamelCase , _UpperCamelCase ) 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' ) _SCREAMING_SNAKE_CASE ='https://storage.googleapis.com/sfr-vision-language-research/BLIP/models/model_base_retrieval_coco.pth' _SCREAMING_SNAKE_CASE =blip_itm(pretrained=_UpperCamelCase , image_size=_UpperCamelCase , vit='base' ) itm_model.eval() _SCREAMING_SNAKE_CASE =itm_model.state_dict() for key in modified_state_dict.copy(): _SCREAMING_SNAKE_CASE =modified_state_dict.pop(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =rename_key(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =value _SCREAMING_SNAKE_CASE =BlipForImageTextRetrieval(_UpperCamelCase ) _SCREAMING_SNAKE_CASE =['A picture of a woman with a dog sitting in a beach'] _SCREAMING_SNAKE_CASE =tokenizer( _UpperCamelCase , return_tensors='pt' , padding='max_length' , truncation=_UpperCamelCase , max_length=35 , ).input_ids hf_itm_model.load_state_dict(_UpperCamelCase ) hf_itm_model.eval() _SCREAMING_SNAKE_CASE =hf_itm_model(_UpperCamelCase , _UpperCamelCase , use_itm_head=_UpperCamelCase ) _SCREAMING_SNAKE_CASE =hf_itm_model(_UpperCamelCase , _UpperCamelCase , use_itm_head=_UpperCamelCase ) assert out[0].item() == 0.21_10_68_74_94_27_79_54 assert torch.nn.functional.softmax(out_itm[0] , dim=1 )[:, 1].item() == 0.4_56_98_84_53_86_50_51_27 if pytorch_dump_folder_path is not None: hf_itm_model.save_pretrained(pytorch_dump_folder_path + '_itm' ) if __name__ == "__main__": lowerCamelCase : Dict = 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") lowerCamelCase : int = parser.parse_args() convert_blip_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path)
47
def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = [0] * len(a_ ) __A = [] __A = [1] * len(a_ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(a_ ) ): if indegree[i] == 0: queue.append(a_ ) while queue: __A = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __A = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(a_ ) print(max(a_ ) ) # Adjacency list of Graph SCREAMING_SNAKE_CASE :List[Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
15
0
SCREAMING_SNAKE_CASE__ : Optional[Any] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' def A ( _SCREAMING_SNAKE_CASE ) -> bytes: # Make sure the supplied data is a bytes-like object if not isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): lowerCamelCase : int = f'''a bytes-like object is required, not \'{data.__class__.__name__}\'''' raise TypeError(_SCREAMING_SNAKE_CASE ) lowerCamelCase : Optional[int] = "".join(bin(_SCREAMING_SNAKE_CASE )[2:].zfill(8 ) for byte in data ) lowerCamelCase : List[str] = len(_SCREAMING_SNAKE_CASE ) % 6 != 0 if padding_needed: # The padding that will be added later lowerCamelCase : Optional[int] = B"=" * ((6 - len(_SCREAMING_SNAKE_CASE ) % 6) // 2) # Append binary_stream with arbitrary binary digits (0's by default) to make its # length a multiple of 6. binary_stream += "0" * (6 - len(_SCREAMING_SNAKE_CASE ) % 6) else: lowerCamelCase : List[Any] = B"" # Encode every 6 binary digits to their corresponding Base64 character return ( "".join( B64_CHARSET[int(binary_stream[index : index + 6] ,2 )] for index in range(0 ,len(_SCREAMING_SNAKE_CASE ) ,6 ) ).encode() + padding ) def A ( _SCREAMING_SNAKE_CASE ) -> bytes: # Make sure encoded_data is either a string or a bytes-like object if not isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ) and not isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): lowerCamelCase : List[Any] = ( "argument should be a bytes-like object or ASCII string, " f'''not \'{encoded_data.__class__.__name__}\'''' ) raise TypeError(_SCREAMING_SNAKE_CASE ) # In case encoded_data is a bytes-like object, make sure it contains only # ASCII characters so we convert it to a string object if isinstance(_SCREAMING_SNAKE_CASE ,_SCREAMING_SNAKE_CASE ): try: lowerCamelCase : Optional[Any] = encoded_data.decode("utf-8" ) except UnicodeDecodeError: raise ValueError("base64 encoded data should only contain ASCII characters" ) lowerCamelCase : Optional[Any] = encoded_data.count("=" ) # Check if the encoded string contains non base64 characters if padding: assert all( char in B64_CHARSET for char in encoded_data[:-padding] ), "Invalid base64 character(s) found." else: assert all( char in B64_CHARSET for char in encoded_data ), "Invalid base64 character(s) found." # Check the padding assert len(_SCREAMING_SNAKE_CASE ) % 4 == 0 and padding < 3, "Incorrect padding" if padding: # Remove padding if there is one lowerCamelCase : Optional[Any] = encoded_data[:-padding] lowerCamelCase : Tuple = "".join( bin(B64_CHARSET.index(_SCREAMING_SNAKE_CASE ) )[2:].zfill(6 ) for char in encoded_data )[: -padding * 2] else: lowerCamelCase : Dict = "".join( bin(B64_CHARSET.index(_SCREAMING_SNAKE_CASE ) )[2:].zfill(6 ) for char in encoded_data ) lowerCamelCase : int = [ int(binary_stream[index : index + 8] ,2 ) for index in range(0 ,len(_SCREAMING_SNAKE_CASE ) ,8 ) ] return bytes(_SCREAMING_SNAKE_CASE ) if __name__ == "__main__": import doctest doctest.testmod()
48
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __A = key.replace("heads.cmd.mim_head.cls.predictions" , "mmm_image_head" ) __A = key.replace("heads.cmd.mlm_head.cls.predictions" , "mmm_text_head" ) __A = key.replace("heads.cmd.itm_head.cls" , "itm_head" ) __A = key.replace("heads.cmd.itm_head.pooler" , "itm_head.pooler" ) __A = key.replace("heads.cmd.clip_head.logit_scale" , "flava.logit_scale" ) __A = key.replace("heads.fairseq_mlm.cls.predictions" , "mlm_head" ) __A = key.replace("heads.imagenet.mim_head.cls.predictions" , "mim_head" ) __A = key.replace("mm_text_projection" , "flava.text_to_mm_projection" ) __A = key.replace("mm_image_projection" , "flava.image_to_mm_projection" ) __A = key.replace("image_encoder.module" , "flava.image_model" ) __A = key.replace("text_encoder.module" , "flava.text_model" ) __A = key.replace("mm_encoder.module.encoder.cls_token" , "flava.multimodal_model.cls_token" ) __A = key.replace("mm_encoder.module" , "flava.multimodal_model" ) __A = key.replace("text_projection" , "flava.text_projection" ) __A = key.replace("image_projection" , "flava.image_projection" ) __A = value.float() for key, value in codebook_state_dict.items(): __A = value return upgrade @torch.no_grad() def UpperCAmelCase ( a_ , a_ , a_ , a_=None ) -> Tuple: """simple docstring""" if config_path is not None: __A = FlavaConfig.from_pretrained(a_ ) else: __A = FlavaConfig() __A = FlavaForPreTraining(a_ ).eval() __A = convert_dalle_checkpoint(a_ , a_ , save_checkpoint=a_ ) if os.path.exists(a_ ): __A = torch.load(a_ , map_location="cpu" ) else: __A = torch.hub.load_state_dict_from_url(a_ , map_location="cpu" ) __A = upgrade_state_dict(a_ , a_ ) hf_model.load_state_dict(a_ ) __A = hf_model.state_dict() __A = count_parameters(a_ ) __A = count_parameters(a_ ) + count_parameters(a_ ) assert torch.allclose(a_ , a_ , atol=1E-3 ) hf_model.save_pretrained(a_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
15
0
from timeit import timeit def __snake_case ( _UpperCAmelCase ): if number < 0: raise ValueError('''the value of input must not be negative''' ) __a = 0 while number: number &= number - 1 result += 1 return result def __snake_case ( _UpperCAmelCase ): if number < 0: raise ValueError('''the value of input must not be negative''' ) __a = 0 while number: if number % 2 == 1: result += 1 number >>= 1 return result def __snake_case ( ): def do_benchmark(_UpperCAmelCase ) -> None: __a = '''import __main__ as z''' print(f'Benchmark when {number = }:' ) print(f'{get_set_bits_count_using_modulo_operator(_UpperCAmelCase ) = }' ) __a = timeit('''z.get_set_bits_count_using_modulo_operator(25)''' , setup=_UpperCAmelCase ) print(f'timeit() runs in {timing} seconds' ) print(f'{get_set_bits_count_using_brian_kernighans_algorithm(_UpperCAmelCase ) = }' ) __a = timeit( '''z.get_set_bits_count_using_brian_kernighans_algorithm(25)''' , setup=_UpperCAmelCase , ) print(f'timeit() runs in {timing} seconds' ) for number in (25, 37, 58, 0): do_benchmark(_UpperCAmelCase ) print() if __name__ == "__main__": import doctest doctest.testmod() benchmark()
49
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Optional[int] = {'vocab_file': 'sentencepiece.bpe.model'} SCREAMING_SNAKE_CASE :Tuple = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', } } SCREAMING_SNAKE_CASE :List[Any] = { 'camembert-base': 512, } SCREAMING_SNAKE_CASE :List[str] = '▁' class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[Any] ,A : List[str] ,A : List[Any]="<s>" ,A : Tuple="</s>" ,A : Any="</s>" ,A : Optional[Any]="<s>" ,A : Tuple="<unk>" ,A : str="<pad>" ,A : int="<mask>" ,A : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] ,A : Optional[Dict[str, Any]] = None ,**A : Optional[Any] ,): # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,sep_token=A ,cls_token=A ,pad_token=A ,mask_token=A ,additional_special_tokens=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A ) ) __A = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> __A = {"<s>NOTUSED": 0, "<pad>": 1, "</s>NOTUSED": 2, "<unk>": 3} __A = len(self.fairseq_tokens_to_ids ) __A = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) __A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self : int ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : Dict ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Union[str, Any] ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self : Dict ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def UpperCamelCase_ ( self : int ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Dict ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(A ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : Tuple ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase_ ( self : Optional[Any] ,A : Dict ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def __getstate__( self : Dict ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Union[str, Any] ,A : Any ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,)
15
0
_UpperCAmelCase : Dict = """ # Transformers 설치 방법 ! pip install transformers datasets # 마지막 릴리스 대신 소스에서 설치하려면, 위 명령을 주석으로 바꾸고 아래 명령을 해제하세요. # ! pip install git+https://github.com/huggingface/transformers.git """ _UpperCAmelCase : Optional[int] = [{"""type""": """code""", """content""": INSTALL_CONTENT}] _UpperCAmelCase : List[Any] = { """{processor_class}""": """FakeProcessorClass""", """{model_class}""": """FakeModelClass""", """{object_class}""": """FakeObjectClass""", }
50
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return [tuple(a_ )] __A = [] def generate(a_ , a_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , a_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even __A , __A = arr[k - 1], arr[i] else: # k is odd __A , __A = arr[k - 1], arr[0] generate(k - 1 , a_ ) generate(len(a_ ) , a_ ) return res if __name__ == "__main__": SCREAMING_SNAKE_CASE :int = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :Dict = [int(item) for item in user_input.split(',')] print(heaps(arr))
15
0
from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_sentencepiece_available, is_tf_available, is_tokenizers_available, is_torch_available, ) snake_case_ : Dict = {"configuration_mbart": ["MBART_PRETRAINED_CONFIG_ARCHIVE_MAP", "MBartConfig", "MBartOnnxConfig"]} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Tuple = ["MBartTokenizer"] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : str = ["MBartTokenizerFast"] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : List[Any] = [ "MBART_PRETRAINED_MODEL_ARCHIVE_LIST", "MBartForCausalLM", "MBartForConditionalGeneration", "MBartForQuestionAnswering", "MBartForSequenceClassification", "MBartModel", "MBartPreTrainedModel", ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : Any = [ "TFMBartForConditionalGeneration", "TFMBartModel", "TFMBartPreTrainedModel", ] try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: snake_case_ : List[str] = [ "FlaxMBartForConditionalGeneration", "FlaxMBartForQuestionAnswering", "FlaxMBartForSequenceClassification", "FlaxMBartModel", "FlaxMBartPreTrainedModel", ] if TYPE_CHECKING: from .configuration_mbart import MBART_PRETRAINED_CONFIG_ARCHIVE_MAP, MBartConfig, MBartOnnxConfig try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart import MBartTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_mbart_fast import MBartTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mbart import ( MBART_PRETRAINED_MODEL_ARCHIVE_LIST, MBartForCausalLM, MBartForConditionalGeneration, MBartForQuestionAnswering, MBartForSequenceClassification, MBartModel, MBartPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_mbart import TFMBartForConditionalGeneration, TFMBartModel, TFMBartPreTrainedModel try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_flax_mbart import ( FlaxMBartForConditionalGeneration, FlaxMBartForQuestionAnswering, FlaxMBartForSequenceClassification, FlaxMBartModel, FlaxMBartPreTrainedModel, ) else: import sys snake_case_ : Any = _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
51
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return lst __A = 1 while i < len(a_ ): if lst[i - 1] <= lst[i]: i += 1 else: __A , __A = lst[i], lst[i - 1] i -= 1 if i == 0: __A = 1 return lst if __name__ == "__main__": SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :List[Any] = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
15
0
from typing import TYPE_CHECKING from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available __lowerCamelCase : Optional[int] = {"""configuration_mmbt""": ["""MMBTConfig"""]} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: __lowerCamelCase : List[Any] = ["""MMBTForClassification""", """MMBTModel""", """ModalEmbeddings"""] if TYPE_CHECKING: from .configuration_mmbt import MMBTConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings else: import sys __lowerCamelCase : int = _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
52
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 snake_case_ = 42 snake_case_ = None class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 2 @register_to_config def __init__( self : str ,A : float = 0.02 ,A : float = 1_00 ,A : float = 1.0_07 ,A : float = 80 ,A : float = 0.05 ,A : float = 50 ,): # standard deviation of the initial noise distribution __A = sigma_max # setable values __A = None __A = None __A = None # sigma(t_i) def UpperCamelCase_ ( self : str ,A : torch.FloatTensor ,A : Optional[int] = None ): return sample def UpperCamelCase_ ( self : Dict ,A : int ,A : Union[str, torch.device] = None ): __A = num_inference_steps __A = np.arange(0 ,self.num_inference_steps )[::-1].copy() __A = torch.from_numpy(A ).to(A ) __A = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __A = torch.tensor(A ,dtype=torch.floataa ,device=A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : torch.FloatTensor ,A : float ,A : Optional[torch.Generator] = None ): if self.config.s_min <= sigma <= self.config.s_max: __A = min(self.config.s_churn / self.num_inference_steps ,2**0.5 - 1 ) else: __A = 0 # sample eps ~ N(0, S_noise^2 * I) __A = self.config.s_noise * randn_tensor(sample.shape ,generator=A ).to(sample.device ) __A = sigma + gamma * sigma __A = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase_ ( self : Dict ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_hat + sigma_hat * model_output __A = (sample_hat - pred_original_sample) / sigma_hat __A = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : Optional[int] ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_prev + sigma_prev * model_output __A = (sample_prev - pred_original_sample) / sigma_prev __A = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : List[Any] ,A : Dict ,A : List[str] ,A : str ): raise NotImplementedError()
15
0
'''simple docstring''' import argparse import torch from torch import nn from transformers import MBartConfig, MBartForConditionalGeneration def lowercase__ ( __lowercase : Any ) -> Union[str, Any]: """simple docstring""" __UpperCamelCase = [ 'encoder.version', 'decoder.version', 'model.encoder.version', 'model.decoder.version', '_float_tensor', 'decoder.output_projection.weight', ] for k in ignore_keys: state_dict.pop(__lowercase , __lowercase ) def lowercase__ ( __lowercase : Tuple ) -> int: """simple docstring""" __UpperCamelCase , __UpperCamelCase = emb.weight.shape __UpperCamelCase = nn.Linear(__lowercase , __lowercase , bias=__lowercase ) __UpperCamelCase = emb.weight.data return lin_layer def lowercase__ ( __lowercase : int , __lowercase : List[str]="facebook/mbart-large-en-ro" , __lowercase : str=False , __lowercase : List[Any]=False ) -> int: """simple docstring""" __UpperCamelCase = torch.load(__lowercase , map_location='cpu' )['model'] remove_ignore_keys_(__lowercase ) __UpperCamelCase = state_dict['encoder.embed_tokens.weight'].shape[0] __UpperCamelCase = MBartConfig.from_pretrained(__lowercase , vocab_size=__lowercase ) if mbart_aa and finetuned: __UpperCamelCase = 'relu' __UpperCamelCase = state_dict['decoder.embed_tokens.weight'] __UpperCamelCase = MBartForConditionalGeneration(__lowercase ) model.model.load_state_dict(__lowercase ) if finetuned: __UpperCamelCase = make_linear_from_emb(model.model.shared ) return model if __name__ == "__main__": a__ : Dict =argparse.ArgumentParser() # Required parameters parser.add_argument( '''fairseq_path''', type=str, help='''bart.large, bart.large.cnn or a path to a model.pt on local filesystem.''' ) parser.add_argument('''pytorch_dump_folder_path''', default=None, type=str, help='''Path to the output PyTorch model.''') parser.add_argument( '''--hf_config''', default='''facebook/mbart-large-cc25''', type=str, help='''Which huggingface architecture to use: mbart-large''', ) parser.add_argument('''--mbart_50''', action='''store_true''', help='''whether the model is mMART-50 checkpoint''') parser.add_argument('''--finetuned''', action='''store_true''', help='''whether the model is a fine-tuned checkpoint''') a__ : Union[str, Any] =parser.parse_args() a__ : str =convert_fairseq_mbart_checkpoint_from_disk( args.fairseq_path, hf_config_path=args.hf_config, finetuned=args.finetuned, mbart_aa=args.mbart_aa ) model.save_pretrained(args.pytorch_dump_folder_path)
53
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version SCREAMING_SNAKE_CASE :Union[str, Any] = get_logger(__name__) class UpperCAmelCase : '''simple docstring''' snake_case_ = "dummy_data" snake_case_ = "datasets" snake_case_ = False def __init__( self : Optional[int] ,A : str ,A : str ,A : Union[Version, str] ,A : Optional[str] = None ,A : bool = False ,A : bool = True ,A : Optional[List[Callable]] = None ,): __A = 0 __A = dataset_name __A = cache_dir __A = use_local_dummy_data __A = config # download_callbacks take a single url as input __A = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __A = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __A = str(A ) # to be downloaded __A = None __A = None @property def UpperCamelCase_ ( self : Union[str, Any] ): if self._dummy_file is None: __A = self.download_dummy_data() return self._dummy_file @property def UpperCamelCase_ ( self : Optional[Any] ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" ,self.config.name ,self.version_name ) # structure is dummy / version_name return os.path.join("dummy" ,self.version_name ) @property def UpperCamelCase_ ( self : List[Any] ): return os.path.join(self.dummy_data_folder ,"dummy_data.zip" ) def UpperCamelCase_ ( self : Tuple ): __A = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __A = cached_path( A ,cache_dir=self.cache_dir ,extract_compressed_file=A ,force_extract=A ) return os.path.join(A ,self.dummy_file_name ) @property def UpperCamelCase_ ( self : str ): return os.path.join(self.datasets_scripts_dir ,self.dataset_name ,self.dummy_zip_file ) @property def UpperCamelCase_ ( self : Any ): if self._bucket_url is None: __A = hf_github_url(self.dataset_name ,self.dummy_zip_file.replace(os.sep ,"/" ) ) return self._bucket_url @property def UpperCamelCase_ ( self : Tuple ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep ,"/" ).split("/" )[:-1] ) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,*A : Dict ): if self.load_existing_dummy_data: # dummy data is downloaded and tested __A = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __A = self.dummy_file_name # special case when data_url is a dict if isinstance(A ,A ): return self.create_dummy_data_dict(A ,A ) elif isinstance(A ,(list, tuple) ): return self.create_dummy_data_list(A ,A ) else: return self.create_dummy_data_single(A ,A ) def UpperCamelCase_ ( self : str ,A : List[Any] ,*A : List[Any] ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : List[str] ,A : List[str] ,A : Tuple ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : Any ,A : Any ,*A : Optional[Any] ,**A : List[str] ): return path def UpperCamelCase_ ( self : str ): return {} def UpperCamelCase_ ( self : int ,A : int ,A : Tuple ): __A = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A ,A ): for single_url in single_urls: download_callback(A ) else: __A = single_urls download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A ,A ): __A = [os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) for x in single_urls] else: __A = single_urls __A = os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) __A = value # make sure that values are unique if all(isinstance(A ,A ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __A = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,A : str ): __A = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __A = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" ,A ) ) for url in data_url ) __A = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __A = [data_url[0]] * len(A ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(A ) return dummy_data_list def UpperCamelCase_ ( self : str ,A : List[Any] ,A : Optional[Any] ): for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(A ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : Dict ): pass def UpperCamelCase_ ( self : Optional[Any] ,A : List[Any] ): def _iter_archive_members(A : Optional[Any] ): # this preserves the order of the members inside the ZIP archive __A = Path(self.dummy_file ).parent __A = path.relative_to(A ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __A = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A ) __A = Path(A ) __A = _iter_archive_members(A ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(A ).as_posix(), file_path.open("rb" ) def UpperCamelCase_ ( self : List[Any] ,A : Any ): if not isinstance(A ,A ): __A = [paths] for path in paths: if os.path.isfile(A ): if os.path.basename(A ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(A ): if os.path.basename(A ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(A ): if filename.startswith((".", "__") ): continue yield os.path.join(A ,A )
15
0
"""simple docstring""" def UpperCAmelCase__ (lowerCAmelCase_ = 10 ): '''simple docstring''' if not isinstance(lowerCAmelCase_ , lowerCAmelCase_ ) or n < 0: raise ValueError("Invalid input" ) __SCREAMING_SNAKE_CASE = 10**n __SCREAMING_SNAKE_CASE = 2_8433 * (pow(2 , 783_0457 , lowerCAmelCase_ )) + 1 return str(number % modulus ) if __name__ == "__main__": from doctest import testmod testmod() print(F"{solution(1_0) = }")
54
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE :List[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :List[str] = ['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 :Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
15
0
'''simple docstring''' import argparse import json import os import fairseq import torch from fairseq.data import Dictionary # Register SEW's fairseq modules from sew_asapp import tasks # noqa: F401 from transformers import ( SEWConfig, SEWForCTC, SEWModel, WavaVecaCTCTokenizer, WavaVecaFeatureExtractor, WavaVecaProcessor, logging, ) logging.set_verbosity_info() a_ : Dict = logging.get_logger(__name__) a_ : Tuple = { """post_extract_proj""": """feature_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.upsample.0""": """encoder.upsample.projection""", """encoder.layer_norm""": """encoder.layer_norm""", """w2v_model.layer_norm""": """layer_norm""", """w2v_encoder.proj""": """lm_head""", """mask_emb""": """masked_spec_embed""", } def __snake_case ( UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : Optional[Any] , UpperCAmelCase_ : Optional[Any] ): for attribute in key.split("." ): lowerCamelCase_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ) if weight_type is not None: lowerCamelCase_ = getattr(UpperCAmelCase_ , UpperCAmelCase_ ).shape else: lowerCamelCase_ = 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": lowerCamelCase_ = value elif weight_type == "weight_g": lowerCamelCase_ = value elif weight_type == "weight_v": lowerCamelCase_ = value elif weight_type == "bias": lowerCamelCase_ = value else: lowerCamelCase_ = value logger.info(F'''{key + "." + weight_type if weight_type is not None else ""} was initialized from {full_name}.''' ) def __snake_case ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : Tuple , UpperCAmelCase_ : str ): lowerCamelCase_ = [] lowerCamelCase_ = fairseq_model.state_dict() lowerCamelCase_ = hf_model.sew.feature_extractor if is_finetuned else hf_model.feature_extractor for name, value in fairseq_dict.items(): lowerCamelCase_ = False if "conv_layers" in name: load_conv_layer( UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , hf_model.config.feat_extract_norm == "group" , ) lowerCamelCase_ = True else: for key, mapped_key in MAPPING.items(): lowerCamelCase_ = "sew." + mapped_key if (is_finetuned and mapped_key != "lm_head") else mapped_key if key in name or key.split("w2v_model." )[-1] == name.split("." )[0]: lowerCamelCase_ = True if "*" in mapped_key: lowerCamelCase_ = name.split(UpperCAmelCase_ )[0].split("." )[-2] lowerCamelCase_ = mapped_key.replace("*" , UpperCAmelCase_ ) if "weight_g" in name: lowerCamelCase_ = "weight_g" elif "weight_v" in name: lowerCamelCase_ = "weight_v" elif "weight" in name: lowerCamelCase_ = "weight" elif "bias" in name: lowerCamelCase_ = "bias" else: lowerCamelCase_ = None set_recursively(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) continue if not is_used: unused_weights.append(UpperCAmelCase_ ) logger.warning(F'''Unused weights: {unused_weights}''' ) def __snake_case ( UpperCAmelCase_ : List[str] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : List[Any] , UpperCAmelCase_ : Any , UpperCAmelCase_ : List[Any] ): lowerCamelCase_ = full_name.split("conv_layers." )[-1] lowerCamelCase_ = name.split("." ) lowerCamelCase_ = int(items[0] ) lowerCamelCase_ = 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.''' ) lowerCamelCase_ = 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.''' ) lowerCamelCase_ = 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." ) lowerCamelCase_ = 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.''' ) lowerCamelCase_ = value logger.info(F'''Feat extract layer norm weight of layer {layer_id} was initialized from {full_name}.''' ) else: unused_weights.append(UpperCAmelCase_ ) def __snake_case ( UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : Any ): lowerCamelCase_ = SEWConfig() if is_finetuned: lowerCamelCase_ = model.wav_encoder.wav_model.cfg else: lowerCamelCase_ = model.cfg lowerCamelCase_ = fs_config.conv_bias lowerCamelCase_ = eval(fs_config.conv_feature_layers ) lowerCamelCase_ = [x[0] for x in conv_layers] lowerCamelCase_ = [x[1] for x in conv_layers] lowerCamelCase_ = [x[2] for x in conv_layers] lowerCamelCase_ = "gelu" lowerCamelCase_ = "layer" if fs_config.extractor_mode == "layer_norm" else "group" lowerCamelCase_ = 0.0 lowerCamelCase_ = fs_config.activation_fn.name lowerCamelCase_ = fs_config.encoder_embed_dim lowerCamelCase_ = 0.02 lowerCamelCase_ = fs_config.encoder_ffn_embed_dim lowerCamelCase_ = 1E-5 lowerCamelCase_ = fs_config.encoder_layerdrop lowerCamelCase_ = fs_config.encoder_attention_heads lowerCamelCase_ = fs_config.conv_pos_groups lowerCamelCase_ = fs_config.conv_pos lowerCamelCase_ = len(UpperCAmelCase_ ) lowerCamelCase_ = fs_config.encoder_layers lowerCamelCase_ = fs_config.squeeze_factor # take care of any params that are overridden by the Wav2VecCtc model if is_finetuned: lowerCamelCase_ = model.cfg lowerCamelCase_ = fs_config.final_dropout lowerCamelCase_ = fs_config.layerdrop lowerCamelCase_ = fs_config.activation_dropout lowerCamelCase_ = fs_config.mask_prob > 0 or fs_config.mask_channel_prob > 0 lowerCamelCase_ = fs_config.attention_dropout lowerCamelCase_ = fs_config.dropout_input lowerCamelCase_ = fs_config.dropout lowerCamelCase_ = fs_config.mask_channel_length lowerCamelCase_ = fs_config.mask_channel_prob lowerCamelCase_ = fs_config.mask_length lowerCamelCase_ = fs_config.mask_prob lowerCamelCase_ = "Wav2Vec2FeatureExtractor" lowerCamelCase_ = "Wav2Vec2CTCTokenizer" return config @torch.no_grad() def __snake_case ( UpperCAmelCase_ : int , UpperCAmelCase_ : Optional[int] , UpperCAmelCase_ : List[str]=None , UpperCAmelCase_ : List[Any]=None , UpperCAmelCase_ : int=True ): if is_finetuned: lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task( [checkpoint_path] , arg_overrides={"data": "/".join(dict_path.split("/" )[:-1] )} ) else: lowerCamelCase_ ,lowerCamelCase_ ,lowerCamelCase_ = fairseq.checkpoint_utils.load_model_ensemble_and_task([checkpoint_path] ) if config_path is not None: lowerCamelCase_ = SEWConfig.from_pretrained(UpperCAmelCase_ ) else: lowerCamelCase_ = convert_config(model[0] , UpperCAmelCase_ ) lowerCamelCase_ = model[0].eval() lowerCamelCase_ = True if config.feat_extract_norm == "layer" else False lowerCamelCase_ = WavaVecaFeatureExtractor( feature_size=1 , sampling_rate=16000 , padding_value=0 , do_normalize=UpperCAmelCase_ , return_attention_mask=UpperCAmelCase_ , ) if is_finetuned: if dict_path: lowerCamelCase_ = Dictionary.load(UpperCAmelCase_ ) # important change bos & pad token id since CTC symbol is <pad> and # not <s> as in fairseq lowerCamelCase_ = target_dict.pad_index lowerCamelCase_ = target_dict.bos_index lowerCamelCase_ = target_dict.pad_index lowerCamelCase_ = target_dict.bos_index lowerCamelCase_ = target_dict.eos_index lowerCamelCase_ = len(target_dict.symbols ) lowerCamelCase_ = os.path.join(UpperCAmelCase_ , "vocab.json" ) if not os.path.isdir(UpperCAmelCase_ ): logger.error("--pytorch_dump_folder_path ({}) should be a directory".format(UpperCAmelCase_ ) ) return os.makedirs(UpperCAmelCase_ , exist_ok=UpperCAmelCase_ ) with open(UpperCAmelCase_ , "w" , encoding="utf-8" ) as vocab_handle: json.dump(target_dict.indices , UpperCAmelCase_ ) lowerCamelCase_ = WavaVecaCTCTokenizer( UpperCAmelCase_ , unk_token=target_dict.unk_word , pad_token=target_dict.pad_word , bos_token=target_dict.bos_word , eos_token=target_dict.eos_word , word_delimiter_token="|" , do_lower_case=UpperCAmelCase_ , ) lowerCamelCase_ = WavaVecaProcessor(feature_extractor=UpperCAmelCase_ , tokenizer=UpperCAmelCase_ ) processor.save_pretrained(UpperCAmelCase_ ) lowerCamelCase_ = SEWForCTC(UpperCAmelCase_ ) else: lowerCamelCase_ = SEWModel(UpperCAmelCase_ ) feature_extractor.save_pretrained(UpperCAmelCase_ ) recursively_load_weights(UpperCAmelCase_ , UpperCAmelCase_ , UpperCAmelCase_ ) hf_model.save_pretrained(UpperCAmelCase_ ) if __name__ == "__main__": a_ : Any = argparse.ArgumentParser() parser.add_argument("""--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model.""") parser.add_argument("""--checkpoint_path""", default=None, type=str, help="""Path to fairseq checkpoint""") parser.add_argument("""--dict_path""", default=None, type=str, help="""Path to dict of fine-tuned model""") parser.add_argument("""--config_path""", default=None, type=str, help="""Path to hf config.json of model to convert""") parser.add_argument( """--is_finetuned""", action="""store_true""", help="""Whether the model to convert is a fine-tuned model or not""" ) a_ : int = parser.parse_args() convert_sew_checkpoint( args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.dict_path, args.is_finetuned )
55
from typing import Dict, Optional import numpy as np import datasets SCREAMING_SNAKE_CASE :List[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' SCREAMING_SNAKE_CASE :List[str] = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' SCREAMING_SNAKE_CASE :str = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Tuple: """simple docstring""" if label_map is not None: for old_id, new_id in label_map.items(): __A = new_id # turn into Numpy arrays __A = np.array(a_ ) __A = np.array(a_ ) if reduce_labels: __A = 2_5_5 __A = label - 1 __A = 2_5_5 __A = label != ignore_index __A = np.not_equal(a_ , a_ ) __A = pred_label[mask] __A = np.array(a_ )[mask] __A = pred_label[pred_label == label] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Union[str, Any]: """simple docstring""" __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(a_ , a_ ): __A , __A , __A , __A = intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = None , a_ = False , ) -> str: """simple docstring""" __A , __A , __A , __A = total_intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) # compute metrics __A = {} __A = total_area_intersect.sum() / total_area_label.sum() __A = total_area_intersect / total_area_union __A = total_area_intersect / total_area_label __A = np.nanmean(a_ ) __A = np.nanmean(a_ ) __A = all_acc __A = iou __A = acc if nan_to_num is not None: __A = {metric: np.nan_to_num(a_ , nan=a_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), } ) ,reference_urls=[ "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py" ] ,) def UpperCamelCase_ ( self : int ,A : Optional[Any] ,A : Optional[Any] ,A : int ,A : bool ,A : Optional[int] = None ,A : Optional[Dict[int, int]] = None ,A : bool = False ,): __A = mean_iou( results=A ,gt_seg_maps=A ,num_labels=A ,ignore_index=A ,nan_to_num=A ,label_map=A ,reduce_labels=A ,) return iou_result
15
0
'''simple docstring''' import unittest from transformers import BarthezTokenizer, BarthezTokenizerFast, BatchEncoding from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow from ...test_tokenization_common import TokenizerTesterMixin @require_tokenizers @require_sentencepiece @slow # see https://github.com/huggingface/transformers/issues/11457 class a ( _lowerCamelCase , unittest.TestCase ): snake_case_ = BarthezTokenizer snake_case_ = BarthezTokenizerFast snake_case_ = True snake_case_ = True def A_ ( self : List[str] ): super().setUp() snake_case_ = BarthezTokenizerFast.from_pretrained('''moussaKam/mbarthez''' ) tokenizer.save_pretrained(self.tmpdirname ) tokenizer.save_pretrained(self.tmpdirname , legacy_format=lowercase_ ) snake_case_ = tokenizer def A_ ( self : Optional[Any] ): snake_case_ = '''<pad>''' snake_case_ = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ) , lowercase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ) , lowercase_ ) def A_ ( self : List[Any] ): snake_case_ = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '''<s>''' ) self.assertEqual(vocab_keys[1] , '''<pad>''' ) self.assertEqual(vocab_keys[-1] , '''<mask>''' ) self.assertEqual(len(lowercase_ ) , 10_1122 ) def A_ ( self : int ): self.assertEqual(self.get_tokenizer().vocab_size , 10_1122 ) @require_torch def A_ ( self : str ): snake_case_ = ['''A long paragraph for summarization.''', '''Another paragraph for summarization.'''] snake_case_ = [0, 57, 3018, 7_0307, 91, 2] snake_case_ = self.tokenizer( lowercase_ , max_length=len(lowercase_ ) , padding=lowercase_ , truncation=lowercase_ , return_tensors='''pt''' ) self.assertIsInstance(lowercase_ , lowercase_ ) self.assertEqual((2, 6) , batch.input_ids.shape ) self.assertEqual((2, 6) , batch.attention_mask.shape ) snake_case_ = batch.input_ids.tolist()[0] self.assertListEqual(lowercase_ , lowercase_ ) def A_ ( self : Tuple ): if not self.test_rust_tokenizer: return snake_case_ = self.get_tokenizer() snake_case_ = self.get_rust_tokenizer() snake_case_ = '''I was born in 92000, and this is falsé.''' snake_case_ = tokenizer.tokenize(lowercase_ ) snake_case_ = rust_tokenizer.tokenize(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) snake_case_ = tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) snake_case_ = rust_tokenizer.encode(lowercase_ , add_special_tokens=lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) snake_case_ = self.get_rust_tokenizer() snake_case_ = tokenizer.encode(lowercase_ ) snake_case_ = rust_tokenizer.encode(lowercase_ ) self.assertListEqual(lowercase_ , lowercase_ ) @slow def A_ ( self : List[Any] ): # fmt: off snake_case_ = {'''input_ids''': [[0, 490, 1_4328, 4507, 354, 47, 4_3669, 95, 25, 7_8117, 2_0215, 1_9779, 190, 22, 400, 4, 3_5343, 8_0310, 603, 86, 2_4937, 105, 3_3438, 9_4762, 196, 3_9642, 7, 15, 1_5933, 173, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 1_0534, 87, 25, 66, 3358, 196, 5_5289, 8, 8_2961, 81, 2204, 7_5203, 7, 15, 763, 1_2956, 216, 178, 1_4328, 9595, 1377, 6_9693, 7, 448, 7_1021, 196, 1_8106, 1437, 1_3974, 108, 9083, 4, 4_9315, 7, 39, 86, 1326, 2793, 4_6333, 4, 448, 196, 7_4588, 7, 4_9315, 7, 39, 21, 822, 3_8470, 74, 21, 6_6723, 6_2480, 8, 2_2050, 5, 2]], '''attention_mask''': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]} # noqa: E501 # fmt: on # moussaKam/mbarthez is a french model. So we also use french texts. snake_case_ = [ '''Le transformeur est un modèle d\'apprentissage profond introduit en 2017, ''' '''utilisé principalement dans le domaine du traitement automatique des langues (TAL).''', '''À l\'instar des réseaux de neurones récurrents (RNN), les transformeurs sont conçus ''' '''pour gérer des données séquentielles, telles que le langage naturel, pour des tâches ''' '''telles que la traduction et la synthèse de texte.''', ] self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='''moussaKam/mbarthez''' , revision='''c2e4ecbca5e3cd2c37fe1ac285ca4fbdf1366fb6''' , sequences=lowercase_ , )
56
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE :List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :List[str] = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Dict = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE :Optional[Any] = { 'AI-Sweden/gpt-sw3-126m': 2048, 'AI-Sweden/gpt-sw3-350m': 2048, 'AI-Sweden/gpt-sw3-1.6b': 2048, 'AI-Sweden/gpt-sw3-6.7b': 2048, 'AI-Sweden/gpt-sw3-20b': 2048, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[int] ,A : Optional[Any] ,A : Optional[int]=False ,A : int=False ,A : Union[str, Any]=False ,A : int=None ,A : Optional[Any]=None ,A : Union[str, Any]=None ,A : Optional[Any]=None ,A : Optional[Dict[str, Any]] = None ,**A : Tuple ,): __A = {} if sp_model_kwargs is None else sp_model_kwargs __A = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) __A = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __A = "<|endoftext|>" if eos_token is None else eos_token __A = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __A = unk_token if pad_token is None else pad_token __A = eos_token if bos_token is None else bos_token else: __A = "<pad>" if pad_token is None else pad_token __A = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=A ,remove_space=A ,keep_accents=A ,bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = do_lower_case __A = remove_space __A = keep_accents __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) # Used for whitespace normalization in input texts # fmt : off __A = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __A = re.compile( f'''[{''.join(map(A ,list(range(0 ,9 ) ) + list(range(11 ,32 ) ) + list(range(1_27 ,1_60 ) ) + [1_60, 1_73, 82_03] ) )}]''' ) def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Optional[Any] ,A : Union[str, Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCamelCase_ ( self : List[str] ): return len(self.sp_model ) def UpperCamelCase_ ( self : int ,A : str ): __A = self.non_printing_characters_re.sub("" ,A ) # Normalize whitespaces __A = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization __A = unicodedata.normalize("NFC" ,A ) return text def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,**A : Optional[int] ): __A = self.preprocess_text(A ) return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : int ): return self.sp_model.IdToPiece(A ) @staticmethod def UpperCamelCase_ ( A : str ): return out_string def UpperCamelCase_ ( self : str ,A : List[str] ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string def UpperCamelCase_ ( self : str ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : List[str] ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Union[str, Any] ,A : Union[str, List[str]] ,A : Union[str, bool] = False ): if isinstance(A ,A ): __A = self.preprocess_text(A ) __A = self.sp_model.encode(A ) else: __A = [self.preprocess_text(A ) for t in text] __A = self.sp_model.encode(A ) if return_tensors is True or return_tensors == "pt": __A = torch.tensor(A ) return token_ids def UpperCamelCase_ ( self : List[Any] ,A : Union[int, List[int]] ): return self.sp_model.decode(A ) def UpperCamelCase_ ( self : List[str] ,A : "Conversation" ): __A = [f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __A = ( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(A ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=A )
15
0
"""simple docstring""" import unittest from transformers import is_torch_available, is_vision_available from transformers.testing_utils import require_torch, require_vision, slow, torch_device if is_torch_available(): import torch from transformers import AutoModelForImageClassification if is_vision_available(): from transformers import AutoImageProcessor @require_torch @require_vision class _UpperCamelCase ( unittest.TestCase ): '''simple docstring''' @slow def snake_case ( self ): __lowerCAmelCase = AutoImageProcessor.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) __lowerCAmelCase = AutoModelForImageClassification.from_pretrained("microsoft/dit-base-finetuned-rvlcdip" ) model.to(__a ) from datasets import load_dataset __lowerCAmelCase = load_dataset("nielsr/rvlcdip-demo" ) __lowerCAmelCase = dataset["train"][0]["image"].convert("RGB" ) __lowerCAmelCase = image_processor(__a , return_tensors="pt" ).to(__a ) # forward pass with torch.no_grad(): __lowerCAmelCase = model(**__a ) __lowerCAmelCase = outputs.logits __lowerCAmelCase = torch.Size((1, 16) ) self.assertEqual(logits.shape , __a ) __lowerCAmelCase = torch.tensor( [-0.4_1_5_8, -0.4_0_9_2, -0.4_3_4_7] , device=__a , dtype=torch.float , ) self.assertTrue(torch.allclose(logits[0, :3] , __a , atol=1e-4 ) )
57
import numpy as np def UpperCAmelCase ( a_ , a_ , a_ = 1E-12 , a_ = 1_0_0 , ) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(a_ )[0] == np.shape(a_ )[1] # Ensure proper dimensionality. assert np.shape(a_ )[0] == np.shape(a_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a_ ) == np.iscomplexobj(a_ ) __A = np.iscomplexobj(a_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __A = False __A = 0 __A = 0 __A = 1E12 while not convergence: # Multiple matrix by the vector. __A = np.dot(a_ , a_ ) # Normalize the resulting output vector. __A = w / np.linalg.norm(a_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __A = vector.conj().T if is_complex else vector.T __A = np.dot(a_ , np.dot(a_ , a_ ) ) # Check convergence. __A = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __A = True __A = lambda_ if is_complex: __A = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase ( ) -> None: """simple docstring""" __A = np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]] ) __A = np.array([4_1, 4, 2_0] ) __A = real_input_matrix.astype(np.complexaaa ) __A = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __A = np.array([4_1, 4, 2_0] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __A = real_input_matrix __A = real_vector elif problem_type == "complex": __A = complex_input_matrix __A = complex_vector # Our implementation. __A , __A = power_iteration(a_ , a_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __A , __A = np.linalg.eigh(a_ ) # Last eigenvalue is the maximum one. __A = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __A = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a_ ) - np.abs(a_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
0
'''simple docstring''' from collections.abc import Sequence def lowerCamelCase ( __lowerCamelCase : Sequence[float] , __lowerCamelCase : bool = False ) ->float: if not arr: return 0 _SCREAMING_SNAKE_CASE = 0 if allow_empty_subarrays else float("""-inf""" ) _SCREAMING_SNAKE_CASE = 0.0 for num in arr: _SCREAMING_SNAKE_CASE = max(0 if allow_empty_subarrays else num , curr_sum + num ) _SCREAMING_SNAKE_CASE = max(__lowerCamelCase , __lowerCamelCase ) return max_sum if __name__ == "__main__": from doctest import testmod testmod() lowercase_ = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(f"""{max_subarray_sum(nums) = }""")
58
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig SCREAMING_SNAKE_CASE :str = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE :str = 'RegNetConfig' # Base docstring SCREAMING_SNAKE_CASE :List[str] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Union[str, Any] = [1, 1088, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE :Optional[int] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Any = 'tabby, tabby cat' SCREAMING_SNAKE_CASE :Optional[int] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : int ,A : int = 3 ,A : int = 1 ,A : int = 1 ,A : Optional[str] = "relu" ,**A : Dict ,): super().__init__(**A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __A = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=A ,strides=A ,padding="VALID" ,groups=A ,use_bias=A ,name="convolution" ,) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) __A = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : List[Any] ,A : Any ): __A = self.convolution(self.padding(A ) ) __A = self.normalization(A ) __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : RegNetConfig ,**A : str ): super().__init__(**A ) __A = config.num_channels __A = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name="embedder" ,) def UpperCamelCase_ ( self : Tuple ,A : Optional[Any] ): __A = shape_list(A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __A = tf.transpose(A ,perm=(0, 2, 3, 1) ) __A = self.embedder(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Optional[int] ,A : int ,A : int = 2 ,**A : Tuple ): super().__init__(**A ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=1 ,strides=A ,use_bias=A ,name="convolution" ) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) def UpperCamelCase_ ( self : Union[str, Any] ,A : tf.Tensor ,A : bool = False ): return self.normalization(self.convolution(A ) ,training=A ) class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Dict ,A : int ,A : int ,**A : str ): super().__init__(**A ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) __A = [ tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="relu" ,name="attention.0" ), tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="sigmoid" ,name="attention.2" ), ] def UpperCamelCase_ ( self : Dict ,A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __A = self.pooler(A ) for layer_module in self.attention: __A = layer_module(A ) __A = hidden_state * pooled return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : Optional[int] ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.2" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : int ,A : Optional[int] ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : str ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetSELayer(A ,reduced_channels=int(round(in_channels / 4 ) ) ,name="layer.2" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.3" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict ,A : Any ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 2 ,A : int = 2 ,**A : Optional[int] ): super().__init__(**A ) __A = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __A = [ # downsampling is done in the first layer with stride of 2 layer(A ,A ,A ,stride=A ,name="layers.0" ), *[layer(A ,A ,A ,name=f'''layers.{i+1}''' ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Any ,A : List[str] ): for layer_module in self.layers: __A = layer_module(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any ,A : RegNetConfig ,**A : List[str] ): super().__init__(**A ) __A = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( A ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name="stages.0" ,) ) __A = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(A ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(A ,A ,A ,depth=A ,name=f'''stages.{i+1}''' ) ) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor ,A : bool = False ,A : bool = True ): __A = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __A = hidden_states + (hidden_state,) __A = stage_module(A ) if output_hidden_states: __A = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=A ,hidden_states=A ) @keras_serializable class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' snake_case_ = RegNetConfig def __init__( self : int ,A : Optional[int] ,**A : Dict ): super().__init__(**A ) __A = config __A = TFRegNetEmbeddings(A ,name="embedder" ) __A = TFRegNetEncoder(A ,name="encoder" ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) @unpack_inputs def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : bool = False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.embedder(A ,training=A ) __A = self.encoder( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = encoder_outputs[0] __A = self.pooler(A ) # Change to NCHW output format have uniformity in the modules __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __A = tuple([tf.transpose(A ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A ,pooler_output=A ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = RegNetConfig snake_case_ = "regnet" snake_case_ = "pixel_values" @property def UpperCamelCase_ ( self : Optional[Any] ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} SCREAMING_SNAKE_CASE :Dict = R'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' SCREAMING_SNAKE_CASE :Dict = R'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,*A : List[Any] ,**A : str ): super().__init__(A ,*A ,**A ) __A = TFRegNetMainLayer(A ,name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=A ,config_class=_CONFIG_FOR_DOC ,modality="vision" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : int=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( pixel_values=A ,output_hidden_states=A ,return_dict=A ,training=A ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Optional[int] ,A : RegNetConfig ,*A : str ,**A : Tuple ): super().__init__(A ,*A ,**A ) __A = config.num_labels __A = TFRegNetMainLayer(A ,name="regnet" ) # classification head __A = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=A ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor = None ,A : tf.Tensor = None ,A : bool = None ,A : bool = None ,A : Union[str, Any]=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = outputs.pooler_output if return_dict else outputs[1] __A = self.classifier[0](A ) __A = self.classifier[1](A ) __A = None if labels is None else self.hf_compute_loss(labels=A ,logits=A ) if not return_dict: __A = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=A ,logits=A ,hidden_states=outputs.hidden_states )
15
0
import operator as op __lowerCamelCase = """scaler.pt""" __lowerCamelCase = """pytorch_model""" __lowerCamelCase = """random_states""" __lowerCamelCase = """optimizer""" __lowerCamelCase = """scheduler""" __lowerCamelCase = """pytorch_model.bin""" __lowerCamelCase = """pytorch_model.bin.index.json""" __lowerCamelCase = """model.safetensors""" __lowerCamelCase = """model.safetensors.index.json""" __lowerCamelCase = """1.10.2""" __lowerCamelCase = """py38""" __lowerCamelCase = """4.17.0""" __lowerCamelCase = ["""ml.p3.16xlarge""", """ml.p3dn.24xlarge""", """ml.p4dn.24xlarge"""] __lowerCamelCase = ["""FULL_SHARD""", """SHARD_GRAD_OP""", """NO_SHARD""", """HYBRID_SHARD""", """HYBRID_SHARD_ZERO2"""] __lowerCamelCase = ["""TRANSFORMER_BASED_WRAP""", """SIZE_BASED_WRAP""", """NO_WRAP"""] __lowerCamelCase = ["""BACKWARD_PRE""", """BACKWARD_POST""", """NO_PREFETCH"""] __lowerCamelCase = ["""FULL_STATE_DICT""", """LOCAL_STATE_DICT""", """SHARDED_STATE_DICT"""] __lowerCamelCase = """2.0.1""" __lowerCamelCase = ["""pdsh""", """standard""", """openmpi""", """mvapich"""] __lowerCamelCase = ["""default""", """reduce-overhead""", """max-autotune"""] __lowerCamelCase = {""">""": op.gt, """>=""": op.ge, """==""": op.eq, """!=""": op.ne, """<=""": op.le, """<""": op.lt} # These are the args for `torch.distributed.launch` for pytorch < 1.9 __lowerCamelCase = [ """nnodes""", """nproc_per_node""", """rdzv_backend""", """rdzv_endpoint""", """rdzv_id""", """rdzv_conf""", """standalone""", """max_restarts""", """monitor_interval""", """start_method""", """role""", """module""", """m""", """no_python""", """run_path""", """log_dir""", """r""", """redirects""", """t""", """tee""", """node_rank""", """master_addr""", """master_port""", ] __lowerCamelCase = ["""DEEPSPEED""", """MULTI_GPU""", """FSDP""", """MEGATRON_LM"""] __lowerCamelCase = ["""DEEPSPEED""", """MULTI_XPU""", """FSDP"""]
59
import math def UpperCAmelCase ( a_ , a_ = 0 , a_ = 0 ) -> list: """simple docstring""" __A = end or len(a_ ) for i in range(a_ , a_ ): __A = i __A = array[i] while temp_index != start and temp_index_value < array[temp_index - 1]: __A = array[temp_index - 1] temp_index -= 1 __A = temp_index_value return array def UpperCAmelCase ( a_ , a_ , a_ ) -> None: # Max Heap """simple docstring""" __A = index __A = 2 * index + 1 # Left Node __A = 2 * index + 2 # Right Node if left_index < heap_size and array[largest] < array[left_index]: __A = left_index if right_index < heap_size and array[largest] < array[right_index]: __A = right_index if largest != index: __A , __A = array[largest], array[index] heapify(a_ , a_ , a_ ) def UpperCAmelCase ( a_ ) -> list: """simple docstring""" __A = len(a_ ) for i in range(n // 2 , -1 , -1 ): heapify(a_ , a_ , a_ ) for i in range(n - 1 , 0 , -1 ): __A , __A = array[0], array[i] heapify(a_ , 0 , a_ ) return array def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" if (array[first_index] > array[middle_index]) != ( array[first_index] > array[last_index] ): return array[first_index] elif (array[middle_index] > array[first_index]) != ( array[middle_index] > array[last_index] ): return array[middle_index] else: return array[last_index] def UpperCAmelCase ( a_ , a_ , a_ , a_ ) -> int: """simple docstring""" __A = low __A = high while True: while array[i] < pivot: i += 1 j -= 1 while pivot < array[j]: j -= 1 if i >= j: return i __A , __A = array[j], array[i] i += 1 def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) == 0: return array __A = 2 * math.ceil(math.loga(len(a_ ) ) ) __A = 1_6 return intro_sort(a_ , 0 , len(a_ ) , a_ , a_ ) def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ ) -> list: """simple docstring""" while end - start > size_threshold: if max_depth == 0: return heap_sort(a_ ) max_depth -= 1 __A = median_of_a(a_ , a_ , start + ((end - start) // 2) + 1 , end - 1 ) __A = partition(a_ , a_ , a_ , a_ ) intro_sort(a_ , a_ , a_ , a_ , a_ ) __A = p return insertion_sort(a_ , a_ , a_ ) if __name__ == "__main__": import doctest doctest.testmod() SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma : ').strip() SCREAMING_SNAKE_CASE :str = [float(item) for item in user_input.split(',')] print(sort(unsorted))
15
0
"""simple docstring""" import os def _snake_case ( _snake_case : str = "matrix.txt" ): with open(os.path.join(os.path.dirname(_snake_case ) , _snake_case ) ) as in_file: lowerCAmelCase : Tuple = in_file.read() lowerCAmelCase : Dict = [[int(_snake_case ) for cell in row.split(''',''' )] for row in data.strip().splitlines()] lowerCAmelCase : Dict = [[0 for cell in row] for row in grid] lowerCAmelCase : List[str] = len(grid[0] ) lowerCAmelCase : Tuple = [[0 for i in range(_snake_case )] for j in range(_snake_case )] lowerCAmelCase : Union[str, Any] = grid[0][0] for i in range(1 , _snake_case ): lowerCAmelCase : List[str] = grid[0][i] + dp[0][i - 1] for i in range(1 , _snake_case ): lowerCAmelCase : Tuple = grid[i][0] + dp[i - 1][0] for i in range(1 , _snake_case ): for j in range(1 , _snake_case ): lowerCAmelCase : Optional[int] = grid[i][j] + min(dp[i - 1][j] , dp[i][j - 1] ) return dp[-1][-1] if __name__ == "__main__": print(f"""{solution() = }""")
60
import dataclasses import json import sys import types from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, ArgumentTypeError from copy import copy from enum import Enum from inspect import isclass from pathlib import Path from typing import Any, Callable, Dict, Iterable, List, Literal, NewType, Optional, Tuple, Union, get_type_hints import yaml SCREAMING_SNAKE_CASE :Optional[int] = NewType('DataClass', Any) SCREAMING_SNAKE_CASE :int = NewType('DataClassType', Any) def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" if isinstance(a_ , a_ ): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise ArgumentTypeError( F'''Truthy value expected: got {v} but expected one of yes/no, true/false, t/f, y/n, 1/0 (case insensitive).''' ) def UpperCAmelCase ( a_ ) -> Callable[[str], Any]: """simple docstring""" __A = {str(a_ ): choice for choice in choices} return lambda a_ : str_to_choice.get(a_ , a_ ) def UpperCAmelCase ( *, a_ = None , a_ = None , a_ = dataclasses.MISSING , a_ = dataclasses.MISSING , a_ = None , **a_ , ) -> dataclasses.Field: """simple docstring""" if metadata is None: # Important, don't use as default param in function signature because dict is mutable and shared across function calls __A = {} if aliases is not None: __A = aliases if help is not None: __A = help return dataclasses.field(metadata=a_ , default=a_ , default_factory=a_ , **a_ ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 def __init__( self : Union[str, Any] ,A : Union[DataClassType, Iterable[DataClassType]] ,**A : List[Any] ): # To make the default appear when using --help if "formatter_class" not in kwargs: __A = ArgumentDefaultsHelpFormatter super().__init__(**A ) if dataclasses.is_dataclass(A ): __A = [dataclass_types] __A = list(A ) for dtype in self.dataclass_types: self._add_dataclass_arguments(A ) @staticmethod def UpperCamelCase_ ( A : ArgumentParser ,A : dataclasses.Field ): __A = f'''--{field.name}''' __A = field.metadata.copy() # field.metadata is not used at all by Data Classes, # it is provided as a third-party extension mechanism. if isinstance(field.type ,A ): raise RuntimeError( "Unresolved type detected, which should have been done with the help of " "`typing.get_type_hints` method by default" ) __A = kwargs.pop("aliases" ,[] ) if isinstance(A ,A ): __A = [aliases] __A = getattr(field.type ,"__origin__" ,field.type ) if origin_type is Union or (hasattr(A ,"UnionType" ) and isinstance(A ,types.UnionType )): if str not in field.type.__args__ and ( len(field.type.__args__ ) != 2 or type(A ) not in field.type.__args__ ): raise ValueError( "Only `Union[X, NoneType]` (i.e., `Optional[X]`) is allowed for `Union` because" " the argument parser only supports one type per argument." f''' Problem encountered in field \'{field.name}\'.''' ) if type(A ) not in field.type.__args__: # filter `str` in Union __A = field.type.__args__[0] if field.type.__args__[1] == str else field.type.__args__[1] __A = getattr(field.type ,"__origin__" ,field.type ) elif bool not in field.type.__args__: # filter `NoneType` in Union (except for `Union[bool, NoneType]`) __A = ( field.type.__args__[0] if isinstance(A ,field.type.__args__[1] ) else field.type.__args__[1] ) __A = getattr(field.type ,"__origin__" ,field.type ) # A variable to store kwargs for a boolean field, if needed # so that we can init a `no_*` complement argument (see below) __A = {} if origin_type is Literal or (isinstance(field.type ,A ) and issubclass(field.type ,A )): if origin_type is Literal: __A = field.type.__args__ else: __A = [x.value for x in field.type] __A = make_choice_type_function(kwargs["choices"] ) if field.default is not dataclasses.MISSING: __A = field.default else: __A = True elif field.type is bool or field.type == Optional[bool]: # Copy the currect kwargs to use to instantiate a `no_*` complement argument below. # We do not initialize it here because the `no_*` alternative must be instantiated after the real argument __A = copy(A ) # Hack because type=bool in argparse does not behave as we want. __A = string_to_bool if field.type is bool or (field.default is not None and field.default is not dataclasses.MISSING): # Default value is False if we have no default when of type bool. __A = False if field.default is dataclasses.MISSING else field.default # This is the value that will get picked if we don't include --field_name in any way __A = default # This tells argparse we accept 0 or 1 value after --field_name __A = "?" # This is the value that will get picked if we do --field_name (without value) __A = True elif isclass(A ) and issubclass(A ,A ): __A = field.type.__args__[0] __A = "+" if field.default_factory is not dataclasses.MISSING: __A = field.default_factory() elif field.default is dataclasses.MISSING: __A = True else: __A = field.type if field.default is not dataclasses.MISSING: __A = field.default elif field.default_factory is not dataclasses.MISSING: __A = field.default_factory() else: __A = True parser.add_argument(A ,*A ,**A ) # Add a complement `no_*` argument for a boolean field AFTER the initial field has already been added. # Order is important for arguments with the same destination! # We use a copy of earlier kwargs because the original kwargs have changed a lot before reaching down # here and we do not need those changes/additional keys. if field.default is True and (field.type is bool or field.type == Optional[bool]): __A = False parser.add_argument(f'''--no_{field.name}''' ,action="store_false" ,dest=field.name ,**A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : DataClassType ): if hasattr(A ,"_argument_group_name" ): __A = self.add_argument_group(dtype._argument_group_name ) else: __A = self try: __A = get_type_hints(A ) except NameError: raise RuntimeError( f'''Type resolution failed for {dtype}. Try declaring the class in global scope or ''' "removing line of `from __future__ import annotations` which opts in Postponed " "Evaluation of Annotations (PEP 563)" ) except TypeError as ex: # Remove this block when we drop Python 3.9 support if sys.version_info[:2] < (3, 10) and "unsupported operand type(s) for |" in str(A ): __A = ".".join(map(A ,sys.version_info[:3] ) ) raise RuntimeError( f'''Type resolution failed for {dtype} on Python {python_version}. Try removing ''' "line of `from __future__ import annotations` which opts in union types as " "`X | Y` (PEP 604) via Postponed Evaluation of Annotations (PEP 563). To " "support Python versions that lower than 3.10, you need to use " "`typing.Union[X, Y]` instead of `X | Y` and `typing.Optional[X]` instead of " "`X | None`." ) from ex raise for field in dataclasses.fields(A ): if not field.init: continue __A = type_hints[field.name] self._parse_dataclass_field(A ,A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : List[Any]=None ,A : List[Any]=False ,A : Optional[Any]=True ,A : Union[str, Any]=None ,A : Union[str, Any]=None ,): if args_file_flag or args_filename or (look_for_args_file and len(sys.argv )): __A = [] if args_filename: args_files.append(Path(A ) ) elif look_for_args_file and len(sys.argv ): args_files.append(Path(sys.argv[0] ).with_suffix(".args" ) ) # args files specified via command line flag should overwrite default args files so we add them last if args_file_flag: # Create special parser just to extract the args_file_flag values __A = ArgumentParser() args_file_parser.add_argument(A ,type=A ,action="append" ) # Use only remaining args for further parsing (remove the args_file_flag) __A , __A = args_file_parser.parse_known_args(args=A ) __A = vars(A ).get(args_file_flag.lstrip("-" ) ,A ) if cmd_args_file_paths: args_files.extend([Path(A ) for p in cmd_args_file_paths] ) __A = [] for args_file in args_files: if args_file.exists(): file_args += args_file.read_text().split() # in case of duplicate arguments the last one has precedence # args specified via the command line should overwrite args from files, so we add them last __A = file_args + args if args is not None else file_args + sys.argv[1:] __A , __A = self.parse_known_args(args=A ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in vars(A ).items() if k in keys} for k in keys: delattr(A ,A ) __A = dtype(**A ) outputs.append(A ) if len(namespace.__dict__ ) > 0: # additional namespace. outputs.append(A ) if return_remaining_strings: return (*outputs, remaining_args) else: if remaining_args: raise ValueError(f'''Some specified arguments are not used by the HfArgumentParser: {remaining_args}''' ) return (*outputs,) def UpperCamelCase_ ( self : Dict ,A : Dict[str, Any] ,A : bool = False ): __A = set(args.keys() ) __A = [] for dtype in self.dataclass_types: __A = {f.name for f in dataclasses.fields(A ) if f.init} __A = {k: v for k, v in args.items() if k in keys} unused_keys.difference_update(inputs.keys() ) __A = dtype(**A ) outputs.append(A ) if not allow_extra_keys and unused_keys: raise ValueError(f'''Some keys are not used by the HfArgumentParser: {sorted(A )}''' ) return tuple(A ) def UpperCamelCase_ ( self : List[str] ,A : str ,A : bool = False ): with open(Path(A ) ,encoding="utf-8" ) as open_json_file: __A = json.loads(open_json_file.read() ) __A = self.parse_dict(A ,allow_extra_keys=A ) return tuple(A ) def UpperCamelCase_ ( self : int ,A : str ,A : bool = False ): __A = self.parse_dict(yaml.safe_load(Path(A ).read_text() ) ,allow_extra_keys=A ) return tuple(A )
15
0
"""simple docstring""" from __future__ import annotations from decimal import Decimal from numpy import array def __a ( __lowerCamelCase ): UpperCAmelCase_ : Any = Decimal # Check if the provided matrix has 2 rows and 2 columns # since this implementation only works for 2x2 matrices if len(__lowerCamelCase ) == 2 and len(matrix[0] ) == 2 and len(matrix[1] ) == 2: # Calculate the determinant of the matrix UpperCAmelCase_ : Optional[Any] = float( d(matrix[0][0] ) * d(matrix[1][1] ) - d(matrix[1][0] ) * d(matrix[0][1] ) ) if determinant == 0: raise ValueError("This matrix has no inverse." ) # Creates a copy of the matrix with swapped positions of the elements UpperCAmelCase_ : Union[str, Any] = [[0.0, 0.0], [0.0, 0.0]] UpperCAmelCase_ , UpperCAmelCase_ : Any = matrix[1][1], matrix[0][0] UpperCAmelCase_ , UpperCAmelCase_ : Dict = -matrix[1][0], -matrix[0][1] # Calculate the inverse of the matrix return [ [(float(d(__lowerCamelCase ) ) / determinant) or 0.0 for n in row] for row in swapped_matrix ] elif ( len(__lowerCamelCase ) == 3 and len(matrix[0] ) == 3 and len(matrix[1] ) == 3 and len(matrix[2] ) == 3 ): # Calculate the determinant of the matrix using Sarrus rule UpperCAmelCase_ : int = float( ( (d(matrix[0][0] ) * d(matrix[1][1] ) * d(matrix[2][2] )) + (d(matrix[0][1] ) * d(matrix[1][2] ) * d(matrix[2][0] )) + (d(matrix[0][2] ) * d(matrix[1][0] ) * d(matrix[2][1] )) ) - ( (d(matrix[0][2] ) * d(matrix[1][1] ) * d(matrix[2][0] )) + (d(matrix[0][1] ) * d(matrix[1][0] ) * d(matrix[2][2] )) + (d(matrix[0][0] ) * d(matrix[1][2] ) * d(matrix[2][1] )) ) ) if determinant == 0: raise ValueError("This matrix has no inverse." ) # Creating cofactor matrix UpperCAmelCase_ : Optional[Any] = [ [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], [d(0.0 ), d(0.0 ), d(0.0 )], ] UpperCAmelCase_ : int = (d(matrix[1][1] ) * d(matrix[2][2] )) - ( d(matrix[1][2] ) * d(matrix[2][1] ) ) UpperCAmelCase_ : int = -( (d(matrix[1][0] ) * d(matrix[2][2] )) - (d(matrix[1][2] ) * d(matrix[2][0] )) ) UpperCAmelCase_ : int = (d(matrix[1][0] ) * d(matrix[2][1] )) - ( d(matrix[1][1] ) * d(matrix[2][0] ) ) UpperCAmelCase_ : Dict = -( (d(matrix[0][1] ) * d(matrix[2][2] )) - (d(matrix[0][2] ) * d(matrix[2][1] )) ) UpperCAmelCase_ : List[str] = (d(matrix[0][0] ) * d(matrix[2][2] )) - ( d(matrix[0][2] ) * d(matrix[2][0] ) ) UpperCAmelCase_ : int = -( (d(matrix[0][0] ) * d(matrix[2][1] )) - (d(matrix[0][1] ) * d(matrix[2][0] )) ) UpperCAmelCase_ : List[Any] = (d(matrix[0][1] ) * d(matrix[1][2] )) - ( d(matrix[0][2] ) * d(matrix[1][1] ) ) UpperCAmelCase_ : int = -( (d(matrix[0][0] ) * d(matrix[1][2] )) - (d(matrix[0][2] ) * d(matrix[1][0] )) ) UpperCAmelCase_ : str = (d(matrix[0][0] ) * d(matrix[1][1] )) - ( d(matrix[0][1] ) * d(matrix[1][0] ) ) # Transpose the cofactor matrix (Adjoint matrix) UpperCAmelCase_ : Dict = array(__lowerCamelCase ) for i in range(3 ): for j in range(3 ): UpperCAmelCase_ : Optional[int] = cofactor_matrix[j][i] # Inverse of the matrix using the formula (1/determinant) * adjoint matrix UpperCAmelCase_ : Union[str, Any] = array(__lowerCamelCase ) for i in range(3 ): for j in range(3 ): inverse_matrix[i][j] /= d(__lowerCamelCase ) # Calculate the inverse of the matrix return [[float(d(__lowerCamelCase ) ) or 0.0 for n in row] for row in inverse_matrix] raise ValueError("Please provide a matrix of size 2x2 or 3x3." )
61
SCREAMING_SNAKE_CASE :Any = 256 # Modulus to hash a string SCREAMING_SNAKE_CASE :Union[str, Any] = 100_0003 def UpperCAmelCase ( a_ , a_ ) -> bool: """simple docstring""" __A = len(a_ ) __A = len(a_ ) if p_len > t_len: return False __A = 0 __A = 0 __A = 1 # Calculating the hash of pattern and substring of text for i in range(a_ ): __A = (ord(pattern[i] ) + p_hash * alphabet_size) % modulus __A = (ord(text[i] ) + text_hash * alphabet_size) % modulus if i == p_len - 1: continue __A = (modulus_power * alphabet_size) % modulus for i in range(0 , t_len - p_len + 1 ): if text_hash == p_hash and text[i : i + p_len] == pattern: return True if i == t_len - p_len: continue # Calculate the https://en.wikipedia.org/wiki/Rolling_hash __A = ( (text_hash - ord(text[i] ) * modulus_power) * alphabet_size + ord(text[i + p_len] ) ) % modulus return False def UpperCAmelCase ( ) -> None: """simple docstring""" __A = "abc1abc12" __A = "alskfjaldsabc1abc1abc12k23adsfabcabc" __A = "alskfjaldsk23adsfabcabc" assert rabin_karp(a_ , a_ ) and not rabin_karp(a_ , a_ ) # Test 2) __A = "ABABX" __A = "ABABZABABYABABX" assert rabin_karp(a_ , a_ ) # Test 3) __A = "AAAB" __A = "ABAAAAAB" assert rabin_karp(a_ , a_ ) # Test 4) __A = "abcdabcy" __A = "abcxabcdabxabcdabcdabcy" assert rabin_karp(a_ , a_ ) # Test 5) __A = "Lü" __A = "Lüsai" assert rabin_karp(a_ , a_ ) __A = "Lue" assert not rabin_karp(a_ , a_ ) print("Success." ) if __name__ == "__main__": test_rabin_karp()
15
0
import requests _A = 'YOUR API KEY' def _UpperCAmelCase ( SCREAMING_SNAKE_CASE__ : str , SCREAMING_SNAKE_CASE__ : str = giphy_api_key ): __UpperCamelCase ='+'.join(query.split() ) __UpperCamelCase =F'https://api.giphy.com/v1/gifs/search?q={formatted_query}&api_key={api_key}' __UpperCamelCase =requests.get(SCREAMING_SNAKE_CASE__ ).json()['data'] return [gif["url"] for gif in gifs] if __name__ == "__main__": print('\n'.join(get_gifs('space ship')))
62
import argparse import json import os import torch from transformers.file_utils import has_file from diffusers import UNetaDConditionModel, UNetaDModel SCREAMING_SNAKE_CASE :Union[str, Any] = False SCREAMING_SNAKE_CASE :Any = True SCREAMING_SNAKE_CASE :Tuple = False if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--repo_path', default=None, type=str, required=True, help='The config json file corresponding to the architecture.', ) parser.add_argument('--dump_path', default=None, type=str, required=True, help='Path to the output model.') SCREAMING_SNAKE_CASE :Union[str, Any] = parser.parse_args() SCREAMING_SNAKE_CASE :Dict = { 'image_size': 'sample_size', 'num_res_blocks': 'layers_per_block', 'block_channels': 'block_out_channels', 'down_blocks': 'down_block_types', 'up_blocks': 'up_block_types', 'downscale_freq_shift': 'freq_shift', 'resnet_num_groups': 'norm_num_groups', 'resnet_act_fn': 'act_fn', 'resnet_eps': 'norm_eps', 'num_head_channels': 'attention_head_dim', } SCREAMING_SNAKE_CASE :Optional[int] = { 'time_steps': 'time_proj', 'mid': 'mid_block', 'downsample_blocks': 'down_blocks', 'upsample_blocks': 'up_blocks', } SCREAMING_SNAKE_CASE :int = '' if has_file(args.repo_path, 'config.json') else 'unet' with open(os.path.join(args.repo_path, subfolder, 'config.json'), 'r', encoding='utf-8') as reader: SCREAMING_SNAKE_CASE :Dict = reader.read() SCREAMING_SNAKE_CASE :List[str] = json.loads(text) if do_only_config: for key in config_parameters_to_change.keys(): config.pop(key, None) if has_file(args.repo_path, 'config.json'): SCREAMING_SNAKE_CASE :Optional[int] = UNetaDModel(**config) else: SCREAMING_SNAKE_CASE :Optional[Any] = UNetaDConditionModel if 'ldm-text2im-large-256' in args.repo_path else UNetaDModel SCREAMING_SNAKE_CASE :List[str] = class_name(**config) if do_only_config: model.save_config(os.path.join(args.repo_path, subfolder)) SCREAMING_SNAKE_CASE :List[str] = dict(model.config) if do_only_renaming: for key, value in config_parameters_to_change.items(): if key in config: SCREAMING_SNAKE_CASE :Optional[Any] = config[key] del config[key] SCREAMING_SNAKE_CASE :Optional[Any] = [k.replace('UNetRes', '') for k in config['down_block_types']] SCREAMING_SNAKE_CASE :List[Any] = [k.replace('UNetRes', '') for k in config['up_block_types']] if do_only_weights: SCREAMING_SNAKE_CASE :Tuple = torch.load(os.path.join(args.repo_path, subfolder, 'diffusion_pytorch_model.bin')) SCREAMING_SNAKE_CASE :Any = {} for param_key, param_value in state_dict.items(): if param_key.endswith('.op.bias') or param_key.endswith('.op.weight'): continue SCREAMING_SNAKE_CASE :List[str] = False for key, new_key in key_parameters_to_change.items(): if not has_changed and param_key.split('.')[0] == key: SCREAMING_SNAKE_CASE :List[Any] = param_value SCREAMING_SNAKE_CASE :str = True if not has_changed: SCREAMING_SNAKE_CASE :List[str] = param_value model.load_state_dict(new_state_dict) model.save_pretrained(os.path.join(args.repo_path, subfolder))
15
0
'''simple docstring''' import warnings from typing import List, Optional, Union from ...processing_utils import ProcessorMixin from ...tokenization_utils_base import BatchEncoding, PaddingStrategy, PreTokenizedInput, TextInput, TruncationStrategy from ...utils import TensorType class __SCREAMING_SNAKE_CASE (lowerCamelCase_ ): """simple docstring""" __a =['image_processor', 'tokenizer'] __a ='LayoutLMv3ImageProcessor' __a =('LayoutLMv3Tokenizer', 'LayoutLMv3TokenizerFast') def __init__( self : Tuple , __a : int=None , __a : Union[str, Any]=None , **__a : Optional[Any] ): _a = None if "feature_extractor" in kwargs: warnings.warn( "The `feature_extractor` argument is deprecated and will be removed in v5, use `image_processor`" " instead." , __a , ) _a = kwargs.pop("feature_extractor" ) _a = image_processor if image_processor is not None else feature_extractor if image_processor is None: raise ValueError("You need to specify an `image_processor`." ) if tokenizer is None: raise ValueError("You need to specify a `tokenizer`." ) super().__init__(__a , __a ) def __call__( self : Any , __a : List[str] , __a : Union[TextInput, PreTokenizedInput, List[TextInput], List[PreTokenizedInput]] = None , __a : Optional[Union[PreTokenizedInput, List[PreTokenizedInput]]] = None , __a : Union[List[List[int]], List[List[List[int]]]] = None , __a : Optional[Union[List[int], List[List[int]]]] = None , __a : bool = True , __a : Union[bool, str, PaddingStrategy] = False , __a : Union[bool, str, TruncationStrategy] = None , __a : Optional[int] = None , __a : int = 0 , __a : Optional[int] = None , __a : Optional[bool] = None , __a : Optional[bool] = None , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = False , __a : bool = True , __a : Optional[Union[str, TensorType]] = None , **__a : Dict , ): # verify input if self.image_processor.apply_ocr and (boxes is not None): raise ValueError( "You cannot provide bounding boxes if you initialized the image processor with apply_ocr set to True." ) if self.image_processor.apply_ocr and (word_labels is not None): raise ValueError( "You cannot provide word labels if you initialized the image processor with apply_ocr set to True." ) # first, apply the image processor _a = self.image_processor(images=__a , return_tensors=__a ) # second, apply the tokenizer if text is not None and self.image_processor.apply_ocr and text_pair is None: if isinstance(__a , __a ): _a = [text] # add batch dimension (as the image processor always adds a batch dimension) _a = features["words"] _a = self.tokenizer( text=text if text is not None else features["words"] , text_pair=text_pair if text_pair is not None else None , boxes=boxes if boxes is not None else features["boxes"] , word_labels=__a , add_special_tokens=__a , padding=__a , truncation=__a , max_length=__a , stride=__a , pad_to_multiple_of=__a , return_token_type_ids=__a , return_attention_mask=__a , return_overflowing_tokens=__a , return_special_tokens_mask=__a , return_offsets_mapping=__a , return_length=__a , verbose=__a , return_tensors=__a , **__a , ) # add pixel values _a = features.pop("pixel_values" ) if return_overflowing_tokens is True: _a = self.get_overflowing_images(__a , encoded_inputs["overflow_to_sample_mapping"] ) _a = images return encoded_inputs def UpperCamelCase__ ( self : Optional[int] , __a : str , __a : List[Any] ): # in case there's an overflow, ensure each `input_ids` sample is mapped to its corresponding image _a = [] for sample_idx in overflow_to_sample_mapping: images_with_overflow.append(images[sample_idx] ) if len(__a ) != len(__a ): raise ValueError( "Expected length of images to be the same as the length of `overflow_to_sample_mapping`, but got" f' {len(__a )} and {len(__a )}' ) return images_with_overflow def UpperCamelCase__ ( self : int , *__a : str , **__a : Tuple ): return self.tokenizer.batch_decode(*__a , **__a ) def UpperCamelCase__ ( self : str , *__a : List[Any] , **__a : List[str] ): return self.tokenizer.decode(*__a , **__a ) @property def UpperCamelCase__ ( self : Tuple ): return ["input_ids", "bbox", "attention_mask", "pixel_values"] @property def UpperCamelCase__ ( self : int ): warnings.warn( "`feature_extractor_class` is deprecated and will be removed in v5. Use `image_processor_class` instead." , __a , ) return self.image_processor_class @property def UpperCamelCase__ ( self : List[str] ): warnings.warn( "`feature_extractor` is deprecated and will be removed in v5. Use `image_processor` instead." , __a , ) return self.image_processor
63
import argparse import math import traceback import dateutil.parser as date_parser import requests def UpperCAmelCase ( a_ ) -> str: """simple docstring""" __A = {} __A = job["started_at"] __A = job["completed_at"] __A = date_parser.parse(a_ ) __A = date_parser.parse(a_ ) __A = round((end_datetime - start_datetime).total_seconds() / 60.0 ) __A = start __A = end __A = duration_in_min return job_info def UpperCAmelCase ( a_ , a_=None ) -> str: """simple docstring""" __A = None if token is not None: __A = {"Accept": "application/vnd.github+json", "Authorization": F'''Bearer {token}'''} __A = F'''https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100''' __A = requests.get(a_ , headers=a_ ).json() __A = {} try: job_time.update({job["name"]: extract_time_from_single_job(a_ ) for job in result["jobs"]} ) __A = math.ceil((result["total_count"] - 1_0_0) / 1_0_0 ) for i in range(a_ ): __A = requests.get(url + F'''&page={i + 2}''' , headers=a_ ).json() job_time.update({job["name"]: extract_time_from_single_job(a_ ) for job in result["jobs"]} ) return job_time except Exception: print(F'''Unknown error, could not fetch links:\n{traceback.format_exc()}''' ) return {} if __name__ == "__main__": SCREAMING_SNAKE_CASE :Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() SCREAMING_SNAKE_CASE :Union[str, Any] = get_job_time(args.workflow_run_id) SCREAMING_SNAKE_CASE :Optional[int] = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) for k, v in job_time.items(): print(f'''{k}: {v["duration"]}''')
15
0
"""simple docstring""" import gc import unittest import numpy as np import torch from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..pipeline_params import ( CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS, CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS, ) from ..test_pipelines_common import PipelineTesterMixin enable_full_determinism() class lowercase( __a , unittest.TestCase ): '''simple docstring''' lowercase__ = DiTPipeline lowercase__ = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS lowercase__ = PipelineTesterMixin.required_optional_params - { "latents", "num_images_per_prompt", "callback", "callback_steps", } lowercase__ = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS lowercase__ = False def UpperCamelCase_ ( self: Any ): '''simple docstring''' torch.manual_seed(0 ) _snake_case : Tuple = TransformeraDModel( sample_size=16, num_layers=2, patch_size=4, attention_head_dim=8, num_attention_heads=2, in_channels=4, out_channels=8, attention_bias=a_, activation_fn="""gelu-approximate""", num_embeds_ada_norm=1_000, norm_type="""ada_norm_zero""", norm_elementwise_affine=a_, ) _snake_case : List[Any] = AutoencoderKL() _snake_case : Any = DDIMScheduler() _snake_case : Optional[Any] = {"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler} return components def UpperCamelCase_ ( self: Any, a_: Dict, a_: List[Any]=0 ): '''simple docstring''' if str(a_ ).startswith("""mps""" ): _snake_case : str = torch.manual_seed(a_ ) else: _snake_case : Dict = torch.Generator(device=a_ ).manual_seed(a_ ) _snake_case : Union[str, Any] = { """class_labels""": [1], """generator""": generator, """num_inference_steps""": 2, """output_type""": """numpy""", } return inputs def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Tuple = """cpu""" _snake_case : str = self.get_dummy_components() _snake_case : Union[str, Any] = self.pipeline_class(**a_ ) pipe.to(a_ ) pipe.set_progress_bar_config(disable=a_ ) _snake_case : int = self.get_dummy_inputs(a_ ) _snake_case : Any = pipe(**a_ ).images _snake_case : Tuple = image[0, -3:, -3:, -1] self.assertEqual(image.shape, (1, 16, 16, 3) ) _snake_case : List[str] = np.array([0.2_946, 0.6_601, 0.4_329, 0.3_296, 0.4_144, 0.5_319, 0.7_273, 0.5_013, 0.4_457] ) _snake_case : Optional[Any] = np.abs(image_slice.flatten() - expected_slice ).max() self.assertLessEqual(a_, 1E-3 ) def UpperCamelCase_ ( self: Dict ): '''simple docstring''' self._test_inference_batch_single_identical(relax_max_difference=a_, expected_max_diff=1E-3 ) @unittest.skipIf( torch_device != """cuda""" or not is_xformers_available(), reason="""XFormers attention is only available with CUDA and `xformers` installed""", ) def UpperCamelCase_ ( self: Any ): '''simple docstring''' self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3 ) @require_torch_gpu @slow class lowercase( unittest.TestCase ): '''simple docstring''' def UpperCamelCase_ ( self: Optional[int] ): '''simple docstring''' super().tearDown() gc.collect() torch.cuda.empty_cache() def UpperCamelCase_ ( self: str ): '''simple docstring''' _snake_case : List[Any] = torch.manual_seed(0 ) _snake_case : Dict = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256""" ) pipe.to("""cuda""" ) _snake_case : Optional[Any] = ["""vase""", """umbrella""", """white shark""", """white wolf"""] _snake_case : List[str] = pipe.get_label_ids(a_ ) _snake_case : List[str] = pipe(a_, generator=a_, num_inference_steps=40, output_type="""np""" ).images for word, image in zip(a_, a_ ): _snake_case : Dict = load_numpy( f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy" ) assert np.abs((expected_image - image).max() ) < 1E-2 def UpperCamelCase_ ( self: Dict ): '''simple docstring''' _snake_case : Dict = DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512""" ) _snake_case : List[Any] = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config ) pipe.to("""cuda""" ) _snake_case : Dict = ["""vase""", """umbrella"""] _snake_case : List[str] = pipe.get_label_ids(a_ ) _snake_case : Tuple = torch.manual_seed(0 ) _snake_case : Dict = pipe(a_, generator=a_, num_inference_steps=25, output_type="""np""" ).images for word, image in zip(a_, a_ ): _snake_case : int = load_numpy( """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main""" f"/dit/{word}_512.npy" ) assert np.abs((expected_image - image).max() ) < 1E-1
64
import argparse import os import shutil import torch from emmental.modules import MagnitudeBinarizer, ThresholdBinarizer, TopKBinarizer def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" __A = args.pruning_method __A = args.threshold __A = args.model_name_or_path.rstrip("/" ) __A = args.target_model_path print(F'''Load fine-pruned model from {model_name_or_path}''' ) __A = torch.load(os.path.join(a_ , "pytorch_model.bin" ) ) __A = {} for name, tensor in model.items(): if "embeddings" in name or "LayerNorm" in name or "pooler" in name: __A = tensor print(F'''Copied layer {name}''' ) elif "classifier" in name or "qa_output" in name: __A = tensor print(F'''Copied layer {name}''' ) elif "bias" in name: __A = tensor print(F'''Copied layer {name}''' ) else: if pruning_method == "magnitude": __A = MagnitudeBinarizer.apply(inputs=a_ , threshold=a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "topK": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A = TopKBinarizer.apply(a_ , a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "sigmoied_threshold": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A = ThresholdBinarizer.apply(a_ , a_ , a_ ) __A = tensor * mask print(F'''Pruned layer {name}''' ) elif pruning_method == "l0": if "mask_scores" in name: continue __A = name[:-6] __A = model[F'''{prefix_}mask_scores'''] __A , __A = -0.1, 1.1 __A = torch.sigmoid(a_ ) __A = s * (r - l) + l __A = s_bar.clamp(min=0.0 , max=1.0 ) __A = tensor * mask print(F'''Pruned layer {name}''' ) else: raise ValueError("Unknown pruning method" ) if target_model_path is None: __A = os.path.join( os.path.dirname(a_ ) , F'''bertarized_{os.path.basename(a_ )}''' ) if not os.path.isdir(a_ ): shutil.copytree(a_ , a_ ) print(F'''\nCreated folder {target_model_path}''' ) torch.save(a_ , os.path.join(a_ , "pytorch_model.bin" ) ) print("\nPruned model saved! See you later!" ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Tuple = argparse.ArgumentParser() parser.add_argument( '--pruning_method', choices=['l0', 'magnitude', 'topK', 'sigmoied_threshold'], type=str, required=True, help=( 'Pruning Method (l0 = L0 regularization, magnitude = Magnitude pruning, topK = Movement pruning,' ' sigmoied_threshold = Soft movement pruning)' ), ) parser.add_argument( '--threshold', type=float, required=False, help=( 'For `magnitude` and `topK`, it is the level of remaining weights (in %) in the fine-pruned model.' 'For `sigmoied_threshold`, it is the threshold \tau against which the (sigmoied) scores are compared.' 'Not needed for `l0`' ), ) parser.add_argument( '--model_name_or_path', type=str, required=True, help='Folder containing the model that was previously fine-pruned', ) parser.add_argument( '--target_model_path', default=None, type=str, required=False, help='Folder containing the model that was previously fine-pruned', ) SCREAMING_SNAKE_CASE :str = parser.parse_args() main(args)
15
0
import copy import os from typing import TYPE_CHECKING, List, Union if TYPE_CHECKING: pass from ...configuration_utils import PretrainedConfig from ...utils import logging UpperCamelCase__ = logging.get_logger(__name__) UpperCamelCase__ = { 'kakaobrain/align-base': 'https://huggingface.co/kakaobrain/align-base/resolve/main/config.json', } class A ( UpperCAmelCase_ ): __UpperCAmelCase : List[str] = 'align_text_model' def __init__(self : Dict , __UpperCAmelCase : List[str]=3_0_5_2_2 , __UpperCAmelCase : str=7_6_8 , __UpperCAmelCase : int=1_2 , __UpperCAmelCase : List[str]=1_2 , __UpperCAmelCase : Any=3_0_7_2 , __UpperCAmelCase : Any="gelu" , __UpperCAmelCase : Optional[int]=0.1 , __UpperCAmelCase : int=0.1 , __UpperCAmelCase : Dict=5_1_2 , __UpperCAmelCase : Dict=2 , __UpperCAmelCase : Tuple=0.02 , __UpperCAmelCase : int=1E-12 , __UpperCAmelCase : Dict=0 , __UpperCAmelCase : Optional[int]="absolute" , __UpperCAmelCase : str=True , **__UpperCAmelCase : List[Any] , ) -> Dict: """simple docstring""" super().__init__(**__UpperCAmelCase ) UpperCAmelCase__ = vocab_size UpperCAmelCase__ = hidden_size UpperCAmelCase__ = num_hidden_layers UpperCAmelCase__ = num_attention_heads UpperCAmelCase__ = hidden_act UpperCAmelCase__ = intermediate_size UpperCAmelCase__ = hidden_dropout_prob UpperCAmelCase__ = attention_probs_dropout_prob UpperCAmelCase__ = max_position_embeddings UpperCAmelCase__ = type_vocab_size UpperCAmelCase__ = initializer_range UpperCAmelCase__ = layer_norm_eps UpperCAmelCase__ = position_embedding_type UpperCAmelCase__ = use_cache UpperCAmelCase__ = pad_token_id @classmethod def lowercase_ (cls : Tuple , __UpperCAmelCase : Union[str, os.PathLike] , **__UpperCAmelCase : int ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__UpperCAmelCase ) UpperCAmelCase__ , UpperCAmelCase__ = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the text config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": UpperCAmelCase__ = config_dict["text_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class A ( UpperCAmelCase_ ): __UpperCAmelCase : List[Any] = 'align_vision_model' def __init__(self : Any , __UpperCAmelCase : int = 3 , __UpperCAmelCase : int = 6_0_0 , __UpperCAmelCase : float = 2.0 , __UpperCAmelCase : float = 3.1 , __UpperCAmelCase : int = 8 , __UpperCAmelCase : List[int] = [3, 3, 5, 3, 5, 5, 3] , __UpperCAmelCase : List[int] = [3_2, 1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2] , __UpperCAmelCase : List[int] = [1_6, 2_4, 4_0, 8_0, 1_1_2, 1_9_2, 3_2_0] , __UpperCAmelCase : List[int] = [] , __UpperCAmelCase : List[int] = [1, 2, 2, 2, 1, 2, 1] , __UpperCAmelCase : List[int] = [1, 2, 2, 3, 3, 4, 1] , __UpperCAmelCase : List[int] = [1, 6, 6, 6, 6, 6, 6] , __UpperCAmelCase : float = 0.25 , __UpperCAmelCase : str = "swish" , __UpperCAmelCase : int = 2_5_6_0 , __UpperCAmelCase : str = "mean" , __UpperCAmelCase : float = 0.02 , __UpperCAmelCase : float = 0.001 , __UpperCAmelCase : float = 0.99 , __UpperCAmelCase : float = 0.2 , **__UpperCAmelCase : List[Any] , ) -> Union[str, Any]: """simple docstring""" super().__init__(**__UpperCAmelCase ) UpperCAmelCase__ = num_channels UpperCAmelCase__ = image_size UpperCAmelCase__ = width_coefficient UpperCAmelCase__ = depth_coefficient UpperCAmelCase__ = depth_divisor UpperCAmelCase__ = kernel_sizes UpperCAmelCase__ = in_channels UpperCAmelCase__ = out_channels UpperCAmelCase__ = depthwise_padding UpperCAmelCase__ = strides UpperCAmelCase__ = num_block_repeats UpperCAmelCase__ = expand_ratios UpperCAmelCase__ = squeeze_expansion_ratio UpperCAmelCase__ = hidden_act UpperCAmelCase__ = hidden_dim UpperCAmelCase__ = pooling_type UpperCAmelCase__ = initializer_range UpperCAmelCase__ = batch_norm_eps UpperCAmelCase__ = batch_norm_momentum UpperCAmelCase__ = drop_connect_rate UpperCAmelCase__ = sum(__UpperCAmelCase ) * 4 @classmethod def lowercase_ (cls : List[str] , __UpperCAmelCase : Union[str, os.PathLike] , **__UpperCAmelCase : Any ) -> "PretrainedConfig": """simple docstring""" cls._set_token_in_kwargs(__UpperCAmelCase ) UpperCAmelCase__ , UpperCAmelCase__ = cls.get_config_dict(__UpperCAmelCase , **__UpperCAmelCase ) # get the vision config dict if we are loading from AlignConfig if config_dict.get("model_type" ) == "align": UpperCAmelCase__ = config_dict["vision_config"] if "model_type" in config_dict and hasattr(cls , "model_type" ) and config_dict["model_type"] != cls.model_type: logger.warning( f"""You are using a model of type {config_dict["model_type"]} to instantiate a model of type """ f"""{cls.model_type}. This is not supported for all configurations of models and can yield errors.""" ) return cls.from_dict(__UpperCAmelCase , **__UpperCAmelCase ) class A ( UpperCAmelCase_ ): __UpperCAmelCase : Any = 'align' __UpperCAmelCase : str = True def __init__(self : str , __UpperCAmelCase : Any=None , __UpperCAmelCase : Union[str, Any]=None , __UpperCAmelCase : Tuple=6_4_0 , __UpperCAmelCase : int=1.0 , __UpperCAmelCase : List[str]=0.02 , **__UpperCAmelCase : Optional[int] , ) -> Any: """simple docstring""" super().__init__(**__UpperCAmelCase ) if text_config is None: UpperCAmelCase__ = {} logger.info("text_config is None. Initializing the AlignTextConfig with default values." ) if vision_config is None: UpperCAmelCase__ = {} logger.info("vision_config is None. Initializing the AlignVisionConfig with default values." ) UpperCAmelCase__ = AlignTextConfig(**__UpperCAmelCase ) UpperCAmelCase__ = AlignVisionConfig(**__UpperCAmelCase ) UpperCAmelCase__ = projection_dim UpperCAmelCase__ = temperature_init_value UpperCAmelCase__ = initializer_range @classmethod def lowercase_ (cls : int , __UpperCAmelCase : AlignTextConfig , __UpperCAmelCase : AlignVisionConfig , **__UpperCAmelCase : int ) -> Dict: """simple docstring""" return cls(text_config=text_config.to_dict() , vision_config=vision_config.to_dict() , **__UpperCAmelCase ) def lowercase_ (self : str ) -> Union[str, Any]: """simple docstring""" UpperCAmelCase__ = copy.deepcopy(self.__dict__ ) UpperCAmelCase__ = self.text_config.to_dict() UpperCAmelCase__ = self.vision_config.to_dict() UpperCAmelCase__ = self.__class__.model_type return output
65
import os import re from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :List[Any] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :int = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Union[str, Any] = { 'vocab_file': { 'google/bigbird-roberta-base': 'https://huggingface.co/google/bigbird-roberta-base/resolve/main/spiece.model', 'google/bigbird-roberta-large': ( 'https://huggingface.co/google/bigbird-roberta-large/resolve/main/spiece.model' ), 'google/bigbird-base-trivia-itc': ( 'https://huggingface.co/google/bigbird-base-trivia-itc/resolve/main/spiece.model' ), } } SCREAMING_SNAKE_CASE :int = { 'google/bigbird-roberta-base': 4096, 'google/bigbird-roberta-large': 4096, 'google/bigbird-base-trivia-itc': 4096, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] snake_case_ = [] def __init__( self : Any ,A : List[str] ,A : str="<unk>" ,A : int="<s>" ,A : Union[str, Any]="</s>" ,A : List[str]="<pad>" ,A : int="[SEP]" ,A : Optional[Any]="[MASK]" ,A : Tuple="[CLS]" ,A : Optional[Dict[str, Any]] = None ,**A : Any ,): __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else bos_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else eos_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else unk_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else pad_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else cls_token __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else sep_token # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sep_token=A ,mask_token=A ,cls_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) @property def UpperCamelCase_ ( self : List[str] ): return self.sp_model.get_piece_size() def UpperCamelCase_ ( self : Optional[Any] ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : str ,A : Optional[Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Tuple ): return self.sp_model.piece_to_id(A ) def UpperCamelCase_ ( self : List[Any] ,A : Tuple ): __A = self.sp_model.IdToPiece(A ) return token def UpperCamelCase_ ( self : List[Any] ,A : int ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def UpperCamelCase_ ( self : Tuple ,A : List[int] ,A : bool = False ,A : bool = None ,A : bool = True ,**A : Union[str, Any] ,): __A = kwargs.pop("use_source_tokenizer" ,A ) __A = self.convert_ids_to_tokens(A ,skip_special_tokens=A ) # To avoid mixing byte-level and unicode for byte-level BPT # we need to build string separately for added tokens and byte-level tokens # cf. https://github.com/huggingface/transformers/issues/1133 __A = [] __A = [] for token in filtered_tokens: if skip_special_tokens and token in self.all_special_ids: continue if token in self.added_tokens_encoder: if current_sub_text: sub_texts.append(self.convert_tokens_to_string(A ) ) __A = [] sub_texts.append(A ) else: current_sub_text.append(A ) if current_sub_text: sub_texts.append(self.convert_tokens_to_string(A ) ) # Mimic the behavior of the Rust tokenizer: # No space before [MASK] and [SEP] if spaces_between_special_tokens: __A = re.sub(R" (\[(MASK|SEP)\])" ,R"\1" ," ".join(A ) ) else: __A = "".join(A ) __A = ( clean_up_tokenization_spaces if clean_up_tokenization_spaces is not None else self.clean_up_tokenization_spaces ) if clean_up_tokenization_spaces: __A = self.clean_up_tokenization(A ) return clean_text else: return text def UpperCamelCase_ ( self : str ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Dict ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + token_ids_a + sep def UpperCamelCase_ ( self : Optional[int] ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Any ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [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]
15
0
"""simple docstring""" import json from typing import Iterator, List, Union from tokenizers import AddedToken, Regex, Tokenizer, decoders, normalizers, pre_tokenizers, trainers from tokenizers.implementations.base_tokenizer import BaseTokenizer from tokenizers.models import Unigram from tokenizers.processors import TemplateProcessing class lowerCamelCase ( _lowerCAmelCase ): '''simple docstring''' def __init__( self: List[Any] , snake_case: str = "▁" , snake_case: bool = True , snake_case: Union[str, AddedToken] = "<unk>" , snake_case: Union[str, AddedToken] = "</s>" , snake_case: Union[str, AddedToken] = "<pad>" , ) -> Any: snake_case_ :Any = { """pad""": {"""id""": 0, """token""": pad_token}, """eos""": {"""id""": 1, """token""": eos_token}, """unk""": {"""id""": 2, """token""": unk_token}, } snake_case_ :Dict = [None] * len(self.special_tokens ) for token_dict in self.special_tokens.values(): snake_case_ :Tuple = token_dict["""token"""] snake_case_ :Union[str, Any] = Tokenizer(Unigram() ) snake_case_ :Tuple = normalizers.Sequence( [ normalizers.Nmt(), normalizers.NFKC(), normalizers.Replace(Regex(""" {2,}""" ) , """ """ ), normalizers.Lowercase(), ] ) snake_case_ :str = pre_tokenizers.Sequence( [ pre_tokenizers.Metaspace(replacement=snake_case , add_prefix_space=snake_case ), pre_tokenizers.Digits(individual_digits=snake_case ), pre_tokenizers.Punctuation(), ] ) snake_case_ :Dict = decoders.Metaspace(replacement=snake_case , add_prefix_space=snake_case ) snake_case_ :str = TemplateProcessing( single=f"""$A {self.special_tokens['eos']['token']}""" , special_tokens=[(self.special_tokens["""eos"""]["""token"""], self.special_tokens["""eos"""]["""id"""])] , ) snake_case_ :Tuple = { """model""": """SentencePieceUnigram""", """replacement""": replacement, """add_prefix_space""": add_prefix_space, } super().__init__(snake_case , snake_case ) def lowerCAmelCase_ ( self: Dict , snake_case: Union[str, List[str]] , snake_case: int = 8_000 , snake_case: bool = True , ) -> int: snake_case_ :List[Any] = trainers.UnigramTrainer( vocab_size=snake_case , special_tokens=self.special_tokens_list , show_progress=snake_case , ) if isinstance(snake_case , snake_case ): snake_case_ :int = [files] self._tokenizer.train(snake_case , trainer=snake_case ) self.add_unk_id() def lowerCAmelCase_ ( self: Dict , snake_case: Union[Iterator[str], Iterator[Iterator[str]]] , snake_case: int = 8_000 , snake_case: bool = True , ) -> List[str]: snake_case_ :Optional[Any] = trainers.UnigramTrainer( vocab_size=snake_case , special_tokens=self.special_tokens_list , show_progress=snake_case , ) self._tokenizer.train_from_iterator(snake_case , trainer=snake_case ) self.add_unk_id() def lowerCAmelCase_ ( self: List[Any] ) -> Tuple: snake_case_ :Dict = json.loads(self._tokenizer.to_str() ) snake_case_ :Optional[int] = self.special_tokens["""unk"""]["""id"""] snake_case_ :Optional[int] = Tokenizer.from_str(json.dumps(snake_case ) )
66
import PIL.Image import PIL.ImageOps from packaging import version from PIL import Image if version.parse(version.parse(PIL.__version__).base_version) >= version.parse('9.1.0'): SCREAMING_SNAKE_CASE :Any = { 'linear': PIL.Image.Resampling.BILINEAR, 'bilinear': PIL.Image.Resampling.BILINEAR, 'bicubic': PIL.Image.Resampling.BICUBIC, 'lanczos': PIL.Image.Resampling.LANCZOS, 'nearest': PIL.Image.Resampling.NEAREST, } else: SCREAMING_SNAKE_CASE :int = { 'linear': PIL.Image.LINEAR, 'bilinear': PIL.Image.BILINEAR, 'bicubic': PIL.Image.BICUBIC, 'lanczos': PIL.Image.LANCZOS, 'nearest': PIL.Image.NEAREST, } def UpperCAmelCase ( a_ ) -> Optional[Any]: """simple docstring""" __A = (images / 2 + 0.5).clamp(0 , 1 ) __A = images.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() __A = numpy_to_pil(a_ ) return images def UpperCAmelCase ( a_ ) -> int: """simple docstring""" if images.ndim == 3: __A = images[None, ...] __A = (images * 2_5_5).round().astype("uint8" ) if images.shape[-1] == 1: # special case for grayscale (single channel) images __A = [Image.fromarray(image.squeeze() , mode="L" ) for image in images] else: __A = [Image.fromarray(a_ ) for image in images] return pil_images
15
0
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices __UpperCAmelCase =logging.get_logger(__name__) __UpperCAmelCase ={ "facebook/convnextv2-tiny-1k-224": "https://huggingface.co/facebook/convnextv2-tiny-1k-224/resolve/main/config.json", } class a__ ( UpperCAmelCase__ , UpperCAmelCase__ ): lowerCamelCase : Optional[int] ="convnextv2" def __init__( self : int , a : Dict=3 , a : List[str]=4 , a : str=4 , a : Dict=None , a : List[str]=None , a : Tuple="gelu" , a : Tuple=0.02 , a : Dict=1e-1_2 , a : Any=0.0 , a : List[str]=2_24 , a : Optional[Any]=None , a : int=None , **a : Any , ): """simple docstring""" super().__init__(**a ) __lowerCamelCase = num_channels __lowerCamelCase = patch_size __lowerCamelCase = num_stages __lowerCamelCase = [96, 1_92, 3_84, 7_68] if hidden_sizes is None else hidden_sizes __lowerCamelCase = [3, 3, 9, 3] if depths is None else depths __lowerCamelCase = hidden_act __lowerCamelCase = initializer_range __lowerCamelCase = layer_norm_eps __lowerCamelCase = drop_path_rate __lowerCamelCase = image_size __lowerCamelCase = ['''stem'''] + [f"""stage{idx}""" for idx in range(1 , len(self.depths ) + 1 )] __lowerCamelCase , __lowerCamelCase = get_aligned_output_features_output_indices( out_features=a , out_indices=a , stage_names=self.stage_names )
67
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 :Optional[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 UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = "yolos" def __init__( self : Any ,A : Optional[Any]=7_68 ,A : Dict=12 ,A : Any=12 ,A : str=30_72 ,A : Any="gelu" ,A : str=0.0 ,A : List[str]=0.0 ,A : Dict=0.02 ,A : int=1E-12 ,A : Tuple=[5_12, 8_64] ,A : List[Any]=16 ,A : str=3 ,A : str=True ,A : Any=1_00 ,A : Dict=True ,A : Dict=False ,A : Tuple=1 ,A : Union[str, Any]=5 ,A : Optional[Any]=2 ,A : Union[str, Any]=5 ,A : int=2 ,A : int=0.1 ,**A : List[str] ,): super().__init__(**A ) __A = hidden_size __A = num_hidden_layers __A = num_attention_heads __A = intermediate_size __A = hidden_act __A = hidden_dropout_prob __A = attention_probs_dropout_prob __A = initializer_range __A = layer_norm_eps __A = image_size __A = patch_size __A = num_channels __A = qkv_bias __A = num_detection_tokens __A = use_mid_position_embeddings __A = auxiliary_loss # Hungarian matcher __A = class_cost __A = bbox_cost __A = giou_cost # Loss coefficients __A = bbox_loss_coefficient __A = giou_loss_coefficient __A = eos_coefficient class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = version.parse("1.11" ) @property def UpperCamelCase_ ( self : str ): return OrderedDict( [ ("pixel_values", {0: "batch", 1: "num_channels", 2: "height", 3: "width"}), ] ) @property def UpperCamelCase_ ( self : List[Any] ): return 1E-4 @property def UpperCamelCase_ ( self : Optional[Any] ): return 12
15
0
import enum import os from hashlib import shaaaa from typing import Optional from .. import config from .logging import get_logger lowerCAmelCase__ = get_logger(__name__) class a__ ( enum.Enum ): """simple docstring""" __lowerCamelCase = 'all_checks' __lowerCamelCase = 'basic_checks' __lowerCamelCase = 'no_checks' class a__ ( snake_case ): """simple docstring""" class a__ ( snake_case ): """simple docstring""" class a__ ( snake_case ): """simple docstring""" class a__ ( snake_case ): """simple docstring""" def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[dict] , SCREAMING_SNAKE_CASE_: dict , SCREAMING_SNAKE_CASE_: Tuple=None ) -> Union[str, Any]: '''simple docstring''' if expected_checksums is None: logger.info("Unable to verify checksums." ) return if len(set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) ) > 0: raise ExpectedMoreDownloadedFiles(str(set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) ) ) if len(set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) ) > 0: raise UnexpectedDownloadedFile(str(set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) ) ) A__ = [url for url in expected_checksums if expected_checksums[url] != recorded_checksums[url]] A__ = " for " + verification_name if verification_name is not None else "" if len(SCREAMING_SNAKE_CASE_ ) > 0: raise NonMatchingChecksumError( F'Checksums didn\'t match{for_verification_name}:\n' F'{bad_urls}\n' "Set `verification_mode='no_checks'` to skip checksums verification and ignore this error" ) logger.info("All the checksums matched successfully" + for_verification_name ) class a__ ( snake_case ): """simple docstring""" class a__ ( snake_case ): """simple docstring""" class a__ ( snake_case ): """simple docstring""" class a__ ( snake_case ): """simple docstring""" def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[dict] , SCREAMING_SNAKE_CASE_: dict ) -> List[str]: '''simple docstring''' if expected_splits is None: logger.info("Unable to verify splits sizes." ) return if len(set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) ) > 0: raise ExpectedMoreSplits(str(set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) ) ) if len(set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) ) > 0: raise UnexpectedSplits(str(set(SCREAMING_SNAKE_CASE_ ) - set(SCREAMING_SNAKE_CASE_ ) ) ) A__ = [ {"expected": expected_splits[name], "recorded": recorded_splits[name]} for name in expected_splits if expected_splits[name].num_examples != recorded_splits[name].num_examples ] if len(SCREAMING_SNAKE_CASE_ ) > 0: raise NonMatchingSplitsSizesError(str(SCREAMING_SNAKE_CASE_ ) ) logger.info("All the splits matched successfully." ) def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: str , SCREAMING_SNAKE_CASE_: bool = True ) -> dict: '''simple docstring''' if record_checksum: A__ = shaaaa() with open(SCREAMING_SNAKE_CASE_ , "rb" ) as f: for chunk in iter(lambda: f.read(1 << 2_0 ) , b"" ): m.update(SCREAMING_SNAKE_CASE_ ) A__ = m.hexdigest() else: A__ = None return {"num_bytes": os.path.getsize(SCREAMING_SNAKE_CASE_ ), "checksum": checksum} def lowerCAmelCase__ ( SCREAMING_SNAKE_CASE_: Optional[int] ) -> str: '''simple docstring''' if dataset_size and config.IN_MEMORY_MAX_SIZE: return dataset_size < config.IN_MEMORY_MAX_SIZE else: return False
68
# Copyright 2021 The HuggingFace Inc. team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from packaging import version from .. import __version__ from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD from .doc import ( add_code_sample_docstrings, add_end_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, copy_func, replace_return_docstrings, ) from .generic import ( ContextManagers, ExplicitEnum, ModelOutput, PaddingStrategy, TensorType, add_model_info_to_auto_map, cached_property, can_return_loss, expand_dims, find_labels, flatten_dict, infer_framework, is_jax_tensor, is_numpy_array, is_tensor, is_tf_symbolic_tensor, is_tf_tensor, is_torch_device, is_torch_dtype, is_torch_tensor, reshape, squeeze, strtobool, tensor_size, to_numpy, to_py_obj, transpose, working_or_temp_dir, ) from .hub import ( CLOUDFRONT_DISTRIB_PREFIX, DISABLE_TELEMETRY, HF_MODULES_CACHE, HUGGINGFACE_CO_PREFIX, HUGGINGFACE_CO_RESOLVE_ENDPOINT, PYTORCH_PRETRAINED_BERT_CACHE, PYTORCH_TRANSFORMERS_CACHE, S3_BUCKET_PREFIX, TRANSFORMERS_CACHE, TRANSFORMERS_DYNAMIC_MODULE_NAME, EntryNotFoundError, PushToHubMixin, RepositoryNotFoundError, RevisionNotFoundError, cached_file, default_cache_path, define_sagemaker_information, download_url, extract_commit_hash, get_cached_models, get_file_from_repo, get_full_repo_name, has_file, http_user_agent, is_offline_mode, is_remote_url, move_cache, send_example_telemetry, try_to_load_from_cache, ) from .import_utils import ( ENV_VARS_TRUE_AND_AUTO_VALUES, ENV_VARS_TRUE_VALUES, TORCH_FX_REQUIRED_VERSION, USE_JAX, USE_TF, USE_TORCH, DummyObject, OptionalDependencyNotAvailable, _LazyModule, ccl_version, direct_transformers_import, get_torch_version, is_accelerate_available, is_apex_available, is_bitsandbytes_available, is_bsa_available, is_coloredlogs_available, is_cython_available, is_datasets_available, is_decord_available, is_detectrona_available, is_faiss_available, is_flax_available, is_ftfy_available, is_in_notebook, is_ipex_available, is_jieba_available, is_jumanpp_available, is_kenlm_available, is_keras_nlp_available, is_librosa_available, is_natten_available, is_ninja_available, is_onnx_available, is_openai_available, is_optimum_available, is_pandas_available, is_peft_available, is_phonemizer_available, is_protobuf_available, is_psutil_available, is_pyanvml_available, is_pyctcdecode_available, is_pytesseract_available, is_pytest_available, is_pytorch_quantization_available, is_rjieba_available, is_sacremoses_available, is_safetensors_available, is_sagemaker_dp_enabled, is_sagemaker_mp_enabled, is_scipy_available, is_sentencepiece_available, is_seqio_available, is_sklearn_available, is_soundfile_availble, is_spacy_available, is_speech_available, is_sudachi_available, is_tensorflow_probability_available, is_tensorflow_text_available, is_tfaonnx_available, is_tf_available, is_timm_available, is_tokenizers_available, is_torch_available, is_torch_bfaa_available, is_torch_bfaa_cpu_available, is_torch_bfaa_gpu_available, is_torch_compile_available, is_torch_cuda_available, is_torch_fx_available, is_torch_fx_proxy, is_torch_mps_available, is_torch_neuroncore_available, is_torch_tensorrt_fx_available, is_torch_tfaa_available, is_torch_tpu_available, is_torchaudio_available, is_torchdistx_available, is_torchdynamo_available, is_torchvision_available, is_training_run_on_sagemaker, is_vision_available, requires_backends, torch_only_method, ) SCREAMING_SNAKE_CASE :List[str] = 'pytorch_model.bin' SCREAMING_SNAKE_CASE :str = 'pytorch_model.bin.index.json' SCREAMING_SNAKE_CASE :Optional[int] = 'adapter_config.json' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.bin' SCREAMING_SNAKE_CASE :Dict = 'adapter_model.safetensors' SCREAMING_SNAKE_CASE :str = 'tf_model.h5' SCREAMING_SNAKE_CASE :List[Any] = 'tf_model.h5.index.json' SCREAMING_SNAKE_CASE :str = 'model.ckpt' SCREAMING_SNAKE_CASE :List[Any] = 'flax_model.msgpack' SCREAMING_SNAKE_CASE :Optional[int] = 'flax_model.msgpack.index.json' SCREAMING_SNAKE_CASE :Tuple = 'model.safetensors' SCREAMING_SNAKE_CASE :List[Any] = 'model.safetensors.index.json' SCREAMING_SNAKE_CASE :str = 'config.json' SCREAMING_SNAKE_CASE :int = 'preprocessor_config.json' SCREAMING_SNAKE_CASE :Optional[Any] = FEATURE_EXTRACTOR_NAME SCREAMING_SNAKE_CASE :Optional[int] = 'generation_config.json' SCREAMING_SNAKE_CASE :List[str] = 'modelcard.json' SCREAMING_SNAKE_CASE :Optional[int] = '▁' SCREAMING_SNAKE_CASE :Optional[Any] = SENTENCEPIECE_UNDERLINE # Kept for backward compatibility SCREAMING_SNAKE_CASE :str = [ [[0, 1, 0, 1], [1, 0, 0, 1]] ] * 2 # Needs to have 0s and 1s only since XLM uses it for langs too. SCREAMING_SNAKE_CASE :Optional[Any] = [[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]] SCREAMING_SNAKE_CASE :List[Any] = [[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]] def UpperCAmelCase ( a_ ) -> Dict: """simple docstring""" if version.parse(a_ ) < version.parse(a_ ): if "dev" in min_version: __A = ( "This example requires a source install from HuggingFace Transformers (see " "`https://huggingface.co/docs/transformers/installation#install-from-source`)," ) else: __A = F'''This example requires a minimum version of {min_version},''' error_message += F''' but the version found is {__version__}.\n''' raise ImportError( error_message + "Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other " "versions of HuggingFace Transformers." )
15
0
"""simple docstring""" import numpy as np import torch from torch.utils.data import Dataset, IterableDataset from ..utils.generic import ModelOutput class UpperCamelCase ( lowerCAmelCase__ ): def __init__( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__) -> List[Any]: snake_case_ = dataset snake_case_ = process snake_case_ = params def __len__( self) -> Optional[Any]: return len(self.dataset) def __getitem__( self, lowerCAmelCase__) -> Optional[int]: snake_case_ = self.dataset[i] snake_case_ = self.process(lowerCAmelCase__, **self.params) return processed class UpperCamelCase ( lowerCAmelCase__ ): def __init__( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__=None) -> Optional[Any]: snake_case_ = loader snake_case_ = infer snake_case_ = params if loader_batch_size == 1: # Let's spare some time by deactivating altogether snake_case_ = None snake_case_ = loader_batch_size # Internal bookkeeping snake_case_ = None snake_case_ = None def __len__( self) -> str: return len(self.loader) def __iter__( self) -> List[Any]: snake_case_ = iter(self.loader) return self def a_ ( self) -> Dict: if isinstance(self._loader_batch_data, torch.Tensor): # Batch data is simple tensor, just fetch the slice snake_case_ = self._loader_batch_data[self._loader_batch_index] else: # Batch data is assumed to be BaseModelOutput (or dict) snake_case_ = {} for k, element in self._loader_batch_data.items(): if isinstance(lowerCAmelCase__, lowerCAmelCase__): # Convert ModelOutput to tuple first snake_case_ = element.to_tuple() if isinstance(element[0], torch.Tensor): snake_case_ = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element) elif isinstance(element[0], np.ndarray): snake_case_ = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element) continue if k in {"hidden_states", "past_key_values", "attentions"} and isinstance(lowerCAmelCase__, lowerCAmelCase__): # Those are stored as lists of tensors so need specific unbatching. if isinstance(element[0], torch.Tensor): snake_case_ = tuple(el[self._loader_batch_index].unsqueeze(0) for el in element) elif isinstance(element[0], np.ndarray): snake_case_ = tuple(np.expand_dims(el[self._loader_batch_index], 0) for el in element) continue if element is None: # This can happen for optional data that get passed around snake_case_ = None elif isinstance(element[self._loader_batch_index], torch.Tensor): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers snake_case_ = element[self._loader_batch_index].unsqueeze(0) elif isinstance(element[self._loader_batch_index], np.ndarray): # Take correct batch data, but make it looked like batch_size=1 # For compatibility with other methods within transformers snake_case_ = np.expand_dims(element[self._loader_batch_index], 0) else: # This is typically a list, so no need to `unsqueeze`. snake_case_ = element[self._loader_batch_index] # Recreate the element by reusing the original class to make it look # batch_size=1 snake_case_ = self._loader_batch_data.__class__(lowerCAmelCase__) self._loader_batch_index += 1 return result def a_ ( self) -> Optional[int]: if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: # We are currently unrolling a batch so we just need to return # the current item within a batch return self.loader_batch_item() # We're out of items within a batch snake_case_ = next(self.iterator) snake_case_ = self.infer(lowerCAmelCase__, **self.params) # We now have a batch of "inferred things". if self.loader_batch_size is not None: # Try to infer the size of the batch if isinstance(lowerCAmelCase__, torch.Tensor): snake_case_ = processed else: snake_case_ = list(processed.keys())[0] snake_case_ = processed[key] if isinstance(lowerCAmelCase__, lowerCAmelCase__): snake_case_ = len(lowerCAmelCase__) else: snake_case_ = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. snake_case_ = observed_batch_size # Setting internal index to unwrap the batch snake_case_ = processed snake_case_ = 0 return self.loader_batch_item() else: # We're not unrolling batches return processed class UpperCamelCase ( lowerCAmelCase__ ): def __init__( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__=None) -> Any: super().__init__(lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__) def __iter__( self) -> str: snake_case_ = iter(self.loader) snake_case_ = None return self def a_ ( self) -> Optional[int]: if self.subiterator is None: snake_case_ = self.infer(next(self.iterator), **self.params) try: # Try to return next item snake_case_ = next(self.subiterator) except StopIteration: # When a preprocess iterator ends, we can start lookig at the next item # ChunkIterator will keep feeding until ALL elements of iterator # all have created their subiterator and have been iterating against. # # Another way to look at it, is we're basically flattening lists of lists # into a single list, but with generators snake_case_ = self.infer(next(self.iterator), **self.params) snake_case_ = next(self.subiterator) return processed class UpperCamelCase ( lowerCAmelCase__ ): def __iter__( self) -> Any: snake_case_ = iter(self.loader) return self def a_ ( self) -> Tuple: # Extremely similar to PipelineIterator in its unpacking mechanism # BUT, we have an extra required item which is the presence of `is_last` # That is because everything is flattened by `PipelineChunkIterator` we # need to keep track of how to regroup here in the original `process` # boundaries so that `process` and `postprocess` see the same data. # This iterator accumulates items (possibly while unbatching) until it # its a `is_last` and then just passes it on to the caller. snake_case_ = False snake_case_ = [] if self._loader_batch_index is not None and self._loader_batch_index < self.loader_batch_size: while self._loader_batch_index < self.loader_batch_size: snake_case_ = self.loader_batch_item() snake_case_ = item.pop('is_last') accumulator.append(lowerCAmelCase__) if is_last: return accumulator while not is_last: snake_case_ = self.infer(next(self.iterator), **self.params) if self.loader_batch_size is not None: if isinstance(lowerCAmelCase__, torch.Tensor): snake_case_ = processed else: snake_case_ = list(processed.keys())[0] snake_case_ = processed[key] if isinstance(lowerCAmelCase__, lowerCAmelCase__): snake_case_ = len(lowerCAmelCase__) else: snake_case_ = first_tensor.shape[0] if 0 < observed_batch_size < self.loader_batch_size: # could be last batch so we can't unroll as many # elements. snake_case_ = observed_batch_size snake_case_ = processed snake_case_ = 0 while self._loader_batch_index < self.loader_batch_size: snake_case_ = self.loader_batch_item() snake_case_ = item.pop('is_last') accumulator.append(lowerCAmelCase__) if is_last: return accumulator else: snake_case_ = processed snake_case_ = item.pop('is_last') accumulator.append(lowerCAmelCase__) return accumulator class UpperCamelCase ( lowerCAmelCase__ ): def __init__( self, lowerCAmelCase__, lowerCAmelCase__) -> Tuple: snake_case_ = dataset snake_case_ = key def __len__( self) -> str: return len(self.dataset) def __getitem__( self, lowerCAmelCase__) -> List[Any]: return self.dataset[i][self.key] class UpperCamelCase ( lowerCAmelCase__ ): def __init__( self, lowerCAmelCase__, lowerCAmelCase__, lowerCAmelCase__) -> List[str]: snake_case_ = dataset snake_case_ = keya snake_case_ = keya def __len__( self) -> str: return len(self.dataset) def __getitem__( self, lowerCAmelCase__) -> Any: return {"text": self.dataset[i][self.keya], "text_pair": self.dataset[i][self.keya]}
69
def UpperCAmelCase ( a_ ) -> Optional[int]: """simple docstring""" __A = [0] * len(a_ ) __A = [] __A = [1] * len(a_ ) for values in graph.values(): for i in values: indegree[i] += 1 for i in range(len(a_ ) ): if indegree[i] == 0: queue.append(a_ ) while queue: __A = queue.pop(0 ) for x in graph[vertex]: indegree[x] -= 1 if long_dist[vertex] + 1 > long_dist[x]: __A = long_dist[vertex] + 1 if indegree[x] == 0: queue.append(a_ ) print(max(a_ ) ) # Adjacency list of Graph SCREAMING_SNAKE_CASE :List[Any] = {0: [2, 3, 4], 1: [2, 7], 2: [5], 3: [5, 7], 4: [7], 5: [6], 6: [7], 7: []} longest_distance(graph)
15
0
'''simple docstring''' import logging import os from dataclasses import dataclass from typing import List, Optional, Union import tqdm from filelock import FileLock from transformers import ( BartTokenizer, BartTokenizerFast, DataProcessor, PreTrainedTokenizer, RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, is_tf_available, is_torch_available, ) A__ : Dict =logging.getLogger(__name__) @dataclass(frozen=snake_case_ ) class UpperCAmelCase : _lowercase: str _lowercase: str _lowercase: Optional[str] = None _lowercase: Optional[str] = None _lowercase: Optional[str] = None @dataclass(frozen=snake_case_ ) class UpperCAmelCase : _lowercase: List[int] _lowercase: Optional[List[int]] = None _lowercase: Optional[List[int]] = None _lowercase: Optional[Union[int, float]] = None _lowercase: Optional[int] = None if is_torch_available(): import torch from torch.utils.data import Dataset class UpperCAmelCase ( snake_case_ ): _lowercase: List[InputFeatures] def __init__( self : str , __snake_case : str , __snake_case : PreTrainedTokenizer , __snake_case : str , __snake_case : Optional[int] = None , __snake_case : int=False , __snake_case : bool = False , ) -> Optional[int]: _lowerCAmelCase = hans_processors[task]() _lowerCAmelCase = os.path.join( __snake_case , """cached_{}_{}_{}_{}""".format( """dev""" if evaluate else """train""" , tokenizer.__class__.__name__ , str(__snake_case ) , __snake_case , ) , ) _lowerCAmelCase = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) _lowerCAmelCase , _lowerCAmelCase = label_list[2], label_list[1] _lowerCAmelCase = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. _lowerCAmelCase = cached_features_file + """.lock""" with FileLock(__snake_case ): if os.path.exists(__snake_case ) and not overwrite_cache: logger.info(f"Loading features from cached file {cached_features_file}" ) _lowerCAmelCase = torch.load(__snake_case ) else: logger.info(f"Creating features from dataset file at {data_dir}" ) _lowerCAmelCase = ( processor.get_dev_examples(__snake_case ) if evaluate else processor.get_train_examples(__snake_case ) ) logger.info("""Training examples: %s""" , len(__snake_case ) ) _lowerCAmelCase = hans_convert_examples_to_features(__snake_case , __snake_case , __snake_case , __snake_case ) logger.info("""Saving features into cached file %s""" , __snake_case ) torch.save(self.features , __snake_case ) def __len__( self : List[str] ) -> List[Any]: return len(self.features ) def __getitem__( self : Union[str, Any] , __snake_case : Union[str, Any] ) -> InputFeatures: return self.features[i] def lowercase__ ( self : List[Any] ) -> int: return self.label_list if is_tf_available(): import tensorflow as tf class UpperCAmelCase : _lowercase: List[InputFeatures] def __init__( self : List[Any] , __snake_case : str , __snake_case : PreTrainedTokenizer , __snake_case : str , __snake_case : Optional[int] = 1_28 , __snake_case : Dict=False , __snake_case : bool = False , ) -> Union[str, Any]: _lowerCAmelCase = hans_processors[task]() _lowerCAmelCase = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) _lowerCAmelCase , _lowerCAmelCase = label_list[2], label_list[1] _lowerCAmelCase = label_list _lowerCAmelCase = processor.get_dev_examples(__snake_case ) if evaluate else processor.get_train_examples(__snake_case ) _lowerCAmelCase = hans_convert_examples_to_features(__snake_case , __snake_case , __snake_case , __snake_case ) def gen(): for ex_index, ex in tqdm.tqdm(enumerate(self.features ) , desc="""convert examples to features""" ): if ex_index % 1_00_00 == 0: logger.info("""Writing example %d of %d""" % (ex_index, len(__snake_case )) ) yield ( { "example_id": 0, "input_ids": ex.input_ids, "attention_mask": ex.attention_mask, "token_type_ids": ex.token_type_ids, }, ex.label, ) _lowerCAmelCase = tf.data.Dataset.from_generator( __snake_case , ( { """example_id""": tf.intaa, """input_ids""": tf.intaa, """attention_mask""": tf.intaa, """token_type_ids""": tf.intaa, }, tf.intaa, ) , ( { """example_id""": tf.TensorShape([] ), """input_ids""": tf.TensorShape([None, None] ), """attention_mask""": tf.TensorShape([None, None] ), """token_type_ids""": tf.TensorShape([None, None] ), }, tf.TensorShape([] ), ) , ) def lowercase__ ( self : Optional[Any] ) -> Optional[int]: return self.dataset def __len__( self : Any ) -> List[Any]: return len(self.features ) def __getitem__( self : Any , __snake_case : Optional[Any] ) -> InputFeatures: return self.features[i] def lowercase__ ( self : Dict ) -> str: return self.label_list class UpperCAmelCase ( snake_case_ ): def lowercase__ ( self : Optional[Any] , __snake_case : str ) -> int: return self._create_examples(self._read_tsv(os.path.join(__snake_case , """heuristics_train_set.txt""" ) ) , """train""" ) def lowercase__ ( self : str , __snake_case : List[Any] ) -> Optional[int]: return self._create_examples(self._read_tsv(os.path.join(__snake_case , """heuristics_evaluation_set.txt""" ) ) , """dev""" ) def lowercase__ ( self : int ) -> Optional[int]: return ["contradiction", "entailment", "neutral"] def lowercase__ ( self : List[Any] , __snake_case : Any , __snake_case : Optional[Any] ) -> int: _lowerCAmelCase = [] for i, line in enumerate(__snake_case ): if i == 0: continue _lowerCAmelCase = """%s-%s""" % (set_type, line[0]) _lowerCAmelCase = line[5] _lowerCAmelCase = line[6] _lowerCAmelCase = line[7][2:] if line[7].startswith("""ex""" ) else line[7] _lowerCAmelCase = line[0] examples.append(InputExample(guid=__snake_case , text_a=__snake_case , text_b=__snake_case , label=__snake_case , pairID=__snake_case ) ) return examples def UpperCamelCase__ ( lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , lowerCAmelCase , ): """simple docstring""" _lowerCAmelCase = {label: i for i, label in enumerate(lowerCAmelCase )} _lowerCAmelCase = [] for ex_index, example in tqdm.tqdm(enumerate(lowerCAmelCase ) , desc="""convert examples to features""" ): if ex_index % 1_00_00 == 0: logger.info("""Writing example %d""" % (ex_index) ) _lowerCAmelCase = tokenizer( example.text_a , example.text_b , add_special_tokens=lowerCAmelCase , max_length=lowerCAmelCase , padding="""max_length""" , truncation=lowerCAmelCase , return_overflowing_tokens=lowerCAmelCase , ) _lowerCAmelCase = label_map[example.label] if example.label in label_map else 0 _lowerCAmelCase = int(example.pairID ) features.append(InputFeatures(**lowerCAmelCase , label=lowerCAmelCase , pairID=lowerCAmelCase ) ) for i, example in enumerate(examples[:5] ): logger.info("""*** Example ***""" ) logger.info(f"guid: {example}" ) logger.info(f"features: {features[i]}" ) return features A__ : List[Any] ={ '''hans''': 3, } A__ : Any ={ '''hans''': HansProcessor, }
70
import argparse import os import torch from transformers import FlavaConfig, FlavaForPreTraining from transformers.models.flava.convert_dalle_to_flava_codebook import convert_dalle_checkpoint def UpperCAmelCase ( a_ ) -> List[str]: """simple docstring""" return sum(param.float().sum() if "encoder.embeddings" not in key else 0 for key, param in state_dict.items() ) def UpperCAmelCase ( a_ , a_ ) -> Tuple: """simple docstring""" __A = {} for key, value in state_dict.items(): if "text_encoder.embeddings" in key or "image_encoder.embeddings" in key: continue __A = key.replace("heads.cmd.mim_head.cls.predictions" , "mmm_image_head" ) __A = key.replace("heads.cmd.mlm_head.cls.predictions" , "mmm_text_head" ) __A = key.replace("heads.cmd.itm_head.cls" , "itm_head" ) __A = key.replace("heads.cmd.itm_head.pooler" , "itm_head.pooler" ) __A = key.replace("heads.cmd.clip_head.logit_scale" , "flava.logit_scale" ) __A = key.replace("heads.fairseq_mlm.cls.predictions" , "mlm_head" ) __A = key.replace("heads.imagenet.mim_head.cls.predictions" , "mim_head" ) __A = key.replace("mm_text_projection" , "flava.text_to_mm_projection" ) __A = key.replace("mm_image_projection" , "flava.image_to_mm_projection" ) __A = key.replace("image_encoder.module" , "flava.image_model" ) __A = key.replace("text_encoder.module" , "flava.text_model" ) __A = key.replace("mm_encoder.module.encoder.cls_token" , "flava.multimodal_model.cls_token" ) __A = key.replace("mm_encoder.module" , "flava.multimodal_model" ) __A = key.replace("text_projection" , "flava.text_projection" ) __A = key.replace("image_projection" , "flava.image_projection" ) __A = value.float() for key, value in codebook_state_dict.items(): __A = value return upgrade @torch.no_grad() def UpperCAmelCase ( a_ , a_ , a_ , a_=None ) -> Tuple: """simple docstring""" if config_path is not None: __A = FlavaConfig.from_pretrained(a_ ) else: __A = FlavaConfig() __A = FlavaForPreTraining(a_ ).eval() __A = convert_dalle_checkpoint(a_ , a_ , save_checkpoint=a_ ) if os.path.exists(a_ ): __A = torch.load(a_ , map_location="cpu" ) else: __A = torch.hub.load_state_dict_from_url(a_ , map_location="cpu" ) __A = upgrade_state_dict(a_ , a_ ) hf_model.load_state_dict(a_ ) __A = hf_model.state_dict() __A = count_parameters(a_ ) __A = count_parameters(a_ ) + count_parameters(a_ ) assert torch.allclose(a_ , a_ , atol=1E-3 ) hf_model.save_pretrained(a_ ) if __name__ == "__main__": SCREAMING_SNAKE_CASE :Any = argparse.ArgumentParser() parser.add_argument('--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model.') parser.add_argument('--checkpoint_path', default=None, type=str, help='Path to flava checkpoint') parser.add_argument('--codebook_path', default=None, type=str, help='Path to flava codebook checkpoint') parser.add_argument('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') SCREAMING_SNAKE_CASE :Optional[int] = parser.parse_args() convert_flava_checkpoint(args.checkpoint_path, args.codebook_path, args.pytorch_dump_folder_path, args.config_path)
15
0
from __future__ import annotations import unittest from transformers import XGLMConfig, XGLMTokenizer, is_tf_available from transformers.testing_utils import require_tf, slow from ...test_configuration_common import ConfigTester from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_tf_available(): import tensorflow as tf from transformers.models.xglm.modeling_tf_xglm import ( TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST, TFXGLMForCausalLM, TFXGLMModel, ) @require_tf class __A : """simple docstring""" UpperCamelCase__ : int =XGLMConfig UpperCamelCase__ : Optional[Any] ={} UpperCamelCase__ : List[str] ="""gelu""" def __init__( self , lowerCamelCase__ , lowerCamelCase__=14 , lowerCamelCase__=7 , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=True , lowerCamelCase__=99 , lowerCamelCase__=32 , lowerCamelCase__=2 , lowerCamelCase__=4 , lowerCamelCase__=37 , lowerCamelCase__="gelu" , lowerCamelCase__=0.1 , lowerCamelCase__=0.1 , lowerCamelCase__=512 , lowerCamelCase__=0.02 , ): """simple docstring""" __UpperCamelCase : Tuple =parent __UpperCamelCase : List[str] =batch_size __UpperCamelCase : str =seq_length __UpperCamelCase : Dict =is_training __UpperCamelCase : Tuple =use_input_mask __UpperCamelCase : List[Any] =use_labels __UpperCamelCase : Any =vocab_size __UpperCamelCase : List[Any] =d_model __UpperCamelCase : Optional[int] =num_hidden_layers __UpperCamelCase : List[str] =num_attention_heads __UpperCamelCase : Optional[int] =ffn_dim __UpperCamelCase : str =activation_function __UpperCamelCase : Any =activation_dropout __UpperCamelCase : Optional[int] =attention_dropout __UpperCamelCase : Optional[int] =max_position_embeddings __UpperCamelCase : Any =initializer_range __UpperCamelCase : Dict =None __UpperCamelCase : Optional[int] =0 __UpperCamelCase : Optional[Any] =2 __UpperCamelCase : str =1 def __lowercase ( self ): """simple docstring""" return XGLMConfig.from_pretrained('facebook/xglm-564M' ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[Any] =tf.clip_by_value( ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) , clip_value_min=0 , clip_value_max=3 ) __UpperCamelCase : Union[str, Any] =None if self.use_input_mask: __UpperCamelCase : Dict =random_attention_mask([self.batch_size, self.seq_length] ) __UpperCamelCase : Any =self.get_config() __UpperCamelCase : Optional[Any] =floats_tensor([self.num_hidden_layers, self.num_attention_heads] , 2 ) return ( config, input_ids, input_mask, head_mask, ) def __lowercase ( self ): """simple docstring""" return XGLMConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , num_layers=self.num_hidden_layers , attention_heads=self.num_attention_heads , ffn_dim=self.ffn_dim , activation_function=self.activation_function , activation_dropout=self.activation_dropout , attention_dropout=self.attention_dropout , max_position_embeddings=self.max_position_embeddings , initializer_range=self.initializer_range , use_cache=lowerCamelCase__ , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , return_dict=lowerCamelCase__ , ) def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =self.prepare_config_and_inputs() ( ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ( __UpperCamelCase ) , ) : int =config_and_inputs __UpperCamelCase : Optional[Any] ={ 'input_ids': input_ids, 'head_mask': head_mask, } return config, inputs_dict @require_tf class __A ( a , a , unittest.TestCase ): """simple docstring""" UpperCamelCase__ : Union[str, Any] =(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else () UpperCamelCase__ : str =(TFXGLMForCausalLM,) if is_tf_available() else () UpperCamelCase__ : Optional[Any] =( {"""feature-extraction""": TFXGLMModel, """text-generation""": TFXGLMForCausalLM} if is_tf_available() else {} ) UpperCamelCase__ : Tuple =False UpperCamelCase__ : Tuple =False UpperCamelCase__ : Optional[Any] =False def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =TFXGLMModelTester(self ) __UpperCamelCase : Dict =ConfigTester(self , config_class=lowerCamelCase__ , n_embd=37 ) def __lowercase ( self ): """simple docstring""" self.config_tester.run_common_tests() @slow def __lowercase ( self ): """simple docstring""" for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: __UpperCamelCase : Optional[Any] =TFXGLMModel.from_pretrained(lowerCamelCase__ ) self.assertIsNotNone(lowerCamelCase__ ) @unittest.skip(reason='Currently, model embeddings are going to undergo a major refactor.' ) def __lowercase ( self ): """simple docstring""" super().test_resize_token_embeddings() @require_tf class __A ( unittest.TestCase ): """simple docstring""" @slow def __lowercase ( self , lowerCamelCase__=True ): """simple docstring""" __UpperCamelCase : int =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : List[str] =tf.convert_to_tensor([[2, 268, 9865]] , dtype=tf.intaa ) # The dog # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other # fmt: off __UpperCamelCase : str =[2, 268, 9865, 67, 11, 1988, 57252, 9865, 5, 984, 67, 1988, 213838, 1658, 53, 70446, 33, 6657, 278, 1581] # fmt: on __UpperCamelCase : Optional[Any] =model.generate(lowerCamelCase__ , do_sample=lowerCamelCase__ , num_beams=1 ) if verify_outputs: self.assertListEqual(output_ids[0].numpy().tolist() , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : List[str] =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Union[str, Any] =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) tf.random.set_seed(0 ) __UpperCamelCase : str =tokenizer('Today is a nice day and' , return_tensors='tf' ) __UpperCamelCase : Union[str, Any] =tokenized.input_ids # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices) with tf.device(':/CPU:0' ): __UpperCamelCase : Any =model.generate(lowerCamelCase__ , do_sample=lowerCamelCase__ , seed=[7, 0] ) __UpperCamelCase : Tuple =tokenizer.decode(output_ids[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : List[Any] =( 'Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due' ) self.assertEqual(lowerCamelCase__ , lowerCamelCase__ ) @slow def __lowercase ( self ): """simple docstring""" __UpperCamelCase : Tuple =TFXGLMForCausalLM.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Optional[Any] =XGLMTokenizer.from_pretrained('facebook/xglm-564M' ) __UpperCamelCase : Optional[Any] ='left' # use different length sentences to test batching __UpperCamelCase : Optional[int] =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When', 'Hello, my dog is a little', ] __UpperCamelCase : List[Any] =tokenizer(lowerCamelCase__ , return_tensors='tf' , padding=lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =inputs['input_ids'] __UpperCamelCase : Dict =model.generate(input_ids=lowerCamelCase__ , attention_mask=inputs['attention_mask'] , max_new_tokens=12 ) __UpperCamelCase : List[Any] =tokenizer(sentences[0] , return_tensors='tf' ).input_ids __UpperCamelCase : Dict =model.generate(input_ids=lowerCamelCase__ , max_new_tokens=12 ) __UpperCamelCase : Any =tokenizer(sentences[1] , return_tensors='tf' ).input_ids __UpperCamelCase : Optional[Any] =model.generate(input_ids=lowerCamelCase__ , max_new_tokens=12 ) __UpperCamelCase : Optional[int] =tokenizer.batch_decode(lowerCamelCase__ , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : Union[str, Any] =tokenizer.decode(output_non_padded[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : int =tokenizer.decode(output_padded[0] , skip_special_tokens=lowerCamelCase__ ) __UpperCamelCase : Any =[ 'This is an extremelly long sentence that only exists to test the ability of the model to cope with ' 'left-padding, such as in batched generation. The output for the sequence below should be the same ' 'regardless of whether left padding is applied or not. When left padding is applied, the sequence will be ' 'a single', 'Hello, my dog is a little bit of a shy one, but he is very friendly', ] self.assertListEqual(lowerCamelCase__ , lowerCamelCase__ ) self.assertListEqual(lowerCamelCase__ , [non_padded_sentence, padded_sentence] )
71
import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import AddedToken, PreTrainedTokenizer from ...utils import logging SCREAMING_SNAKE_CASE :Optional[int] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :Optional[int] = {'vocab_file': 'sentencepiece.bpe.model'} SCREAMING_SNAKE_CASE :Tuple = { 'vocab_file': { 'camembert-base': 'https://huggingface.co/camembert-base/resolve/main/sentencepiece.bpe.model', } } SCREAMING_SNAKE_CASE :List[Any] = { 'camembert-base': 512, } SCREAMING_SNAKE_CASE :List[str] = '▁' class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[Any] ,A : List[str] ,A : List[Any]="<s>" ,A : Tuple="</s>" ,A : Any="</s>" ,A : Optional[Any]="<s>" ,A : Tuple="<unk>" ,A : str="<pad>" ,A : int="<mask>" ,A : Optional[int]=["<s>NOTUSED", "</s>NOTUSED"] ,A : Optional[Dict[str, Any]] = None ,**A : Optional[Any] ,): # Mask token behave like a normal word, i.e. include the space before it __A = AddedToken(A ,lstrip=A ,rstrip=A ) if isinstance(A ,A ) else mask_token __A = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( bos_token=A ,eos_token=A ,unk_token=A ,sep_token=A ,cls_token=A ,pad_token=A ,mask_token=A ,additional_special_tokens=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(str(A ) ) __A = vocab_file # HACK: These tokens were added by fairseq but don't seem to be actually used when duplicated in the actual # sentencepiece vocabulary (this is the case for <s> and </s> __A = {"<s>NOTUSED": 0, "<pad>": 1, "</s>NOTUSED": 2, "<unk>": 3} __A = len(self.fairseq_tokens_to_ids ) __A = len(self.sp_model ) + len(self.fairseq_tokens_to_ids ) __A = {v: k for k, v in self.fairseq_tokens_to_ids.items()} def UpperCamelCase_ ( self : int ,A : List[int] ,A : Optional[List[int]] = None ): if token_ids_a is None: return [self.cls_token_id] + token_ids_a + [self.sep_token_id] __A = [self.cls_token_id] __A = [self.sep_token_id] return cls + token_ids_a + sep + sep + token_ids_a + sep def UpperCamelCase_ ( self : Dict ,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 ) if token_ids_a is None: return [1] + ([0] * len(A )) + [1] return [1] + ([0] * len(A )) + [1, 1] + ([0] * len(A )) + [1] def UpperCamelCase_ ( self : Union[str, Any] ,A : List[int] ,A : Optional[List[int]] = None ): __A = [self.sep_token_id] __A = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] @property def UpperCamelCase_ ( self : Dict ): return len(self.fairseq_tokens_to_ids ) + len(self.sp_model ) def UpperCamelCase_ ( self : int ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : List[str] ,A : Dict ): if token in self.fairseq_tokens_to_ids: return self.fairseq_tokens_to_ids[token] elif self.sp_model.PieceToId(A ) == 0: # Convert sentence piece unk token to fairseq unk token index return self.unk_token_id return self.fairseq_offset + self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : Tuple ): if index in self.fairseq_ids_to_tokens: return self.fairseq_ids_to_tokens[index] return self.sp_model.IdToPiece(index - self.fairseq_offset ) def UpperCamelCase_ ( self : Optional[Any] ,A : Dict ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string.strip() def __getstate__( self : Dict ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Union[str, Any] ,A : Any ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def UpperCamelCase_ ( self : Any ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,)
15
0
"""simple docstring""" import warnings from .generation import TFGenerationMixin class __snake_case ( _lowercase): # warning at import time warnings.warn( "Importing `TFGenerationMixin` from `src/transformers/generation_tf_utils.py` is deprecated and will " "be removed in Transformers v5. Import as `from transformers import TFGenerationMixin` instead." , _lowercase , )
72
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return [tuple(a_ )] __A = [] def generate(a_ , a_ ): if k == 1: res.append(tuple(arr[:] ) ) return generate(k - 1 , a_ ) for i in range(k - 1 ): if k % 2 == 0: # k is even __A , __A = arr[k - 1], arr[i] else: # k is odd __A , __A = arr[k - 1], arr[0] generate(k - 1 , a_ ) generate(len(a_ ) , a_ ) return res if __name__ == "__main__": SCREAMING_SNAKE_CASE :int = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :Dict = [int(item) for item in user_input.split(',')] print(heaps(arr))
15
0
import csv from collections import defaultdict from dataclasses import dataclass, field from typing import List, Optional import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import ScalarFormatter from transformers import HfArgumentParser def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__=None , lowerCamelCase__=None ) -> Any: return field(default_factory=lambda: default , metadata=lowerCamelCase__ ) @dataclass class A_ : _UpperCAmelCase : str = field( metadata={'''help''': '''The csv file to plot.'''} , ) _UpperCAmelCase : bool = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Whether to plot along batch size or sequence length. Defaults to sequence length.'''} , ) _UpperCAmelCase : bool = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Whether the csv file has time results or memory results. Defaults to memory results.'''} , ) _UpperCAmelCase : bool = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Disable logarithmic scale when plotting'''} , ) _UpperCAmelCase : bool = field( default=SCREAMING_SNAKE_CASE , metadata={ '''help''': '''Whether the csv file has training results or inference results. Defaults to inference results.''' } , ) _UpperCAmelCase : Optional[str] = field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''Filename under which the plot will be saved. If unused no plot is saved.'''} , ) _UpperCAmelCase : Optional[List[str]] = list_field( default=SCREAMING_SNAKE_CASE , metadata={'''help''': '''List of model names that are used instead of the ones in the csv file.'''} ) def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> Any: try: int(lowerCamelCase__ ) return True except ValueError: return False def SCREAMING_SNAKE_CASE__ ( lowerCamelCase__ ) -> List[Any]: try: float(lowerCamelCase__ ) return True except ValueError: return False class A_ : def __init__( self : Optional[int] ,SCREAMING_SNAKE_CASE__ : Dict): __lowerCamelCase : str = args __lowerCamelCase : Any = defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}) with open(self.args.csv_file ,newline='') as csv_file: __lowerCamelCase : Any = csv.DictReader(SCREAMING_SNAKE_CASE__) for row in reader: __lowerCamelCase : Any = row['model'] self.result_dict[model_name]["bsz"].append(int(row['batch_size'])) self.result_dict[model_name]["seq_len"].append(int(row['sequence_length'])) if can_convert_to_int(row['result']): # value is not None __lowerCamelCase : Tuple = int(row['result']) elif can_convert_to_float(row['result']): # value is not None __lowerCamelCase : List[Any] = float(row['result']) def lowerCAmelCase ( self : List[str]): __lowerCamelCase , __lowerCamelCase : List[Any] = plt.subplots() __lowerCamelCase : Union[str, Any] = 'Time usage' if self.args.is_time else 'Memory usage' __lowerCamelCase : Optional[Any] = title_str + ' for training' if self.args.is_train else title_str + ' for inference' if not self.args.no_log_scale: # set logarithm scales ax.set_xscale('log') ax.set_yscale('log') for axis in [ax.xaxis, ax.yaxis]: axis.set_major_formatter(ScalarFormatter()) for model_name_idx, model_name in enumerate(self.result_dict.keys()): __lowerCamelCase : int = sorted(set(self.result_dict[model_name]['bsz'])) __lowerCamelCase : Tuple = sorted(set(self.result_dict[model_name]['seq_len'])) __lowerCamelCase : int = self.result_dict[model_name]['result'] ((__lowerCamelCase) , (__lowerCamelCase)) : List[str] = ( (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes) ) __lowerCamelCase : List[str] = ( model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx] ) for inner_loop_value in inner_loop_array: if self.args.plot_along_batch: __lowerCamelCase : int = np.asarray( [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] ,dtype=SCREAMING_SNAKE_CASE__ ,) else: __lowerCamelCase : Union[str, Any] = np.asarray( [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] ,dtype=np.floataa ,) ((__lowerCamelCase) , (__lowerCamelCase)) : Optional[Any] = ( ('batch_size', 'len') if self.args.plot_along_batch else ('in #tokens', 'bsz') ) __lowerCamelCase : Tuple = np.asarray(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__)[: len(SCREAMING_SNAKE_CASE__)] plt.scatter( SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,label=F"{label_model_name} - {inner_loop_label}: {inner_loop_value}") plt.plot(SCREAMING_SNAKE_CASE__ ,SCREAMING_SNAKE_CASE__ ,'--') title_str += F" {label_model_name} vs." __lowerCamelCase : List[Any] = title_str[:-4] __lowerCamelCase : int = 'Time in s' if self.args.is_time else 'Memory in MB' # plot plt.title(SCREAMING_SNAKE_CASE__) plt.xlabel(SCREAMING_SNAKE_CASE__) plt.ylabel(SCREAMING_SNAKE_CASE__) plt.legend() if self.args.figure_png_file is not None: plt.savefig(self.args.figure_png_file) else: plt.show() def SCREAMING_SNAKE_CASE__ ( ) -> Dict: __lowerCamelCase : Optional[Any] = HfArgumentParser(lowerCamelCase__ ) __lowerCamelCase : List[str] = parser.parse_args_into_dataclasses()[0] __lowerCamelCase : str = Plot(args=lowerCamelCase__ ) plot.plot() if __name__ == "__main__": main()
73
def UpperCAmelCase ( a_ ) -> list: """simple docstring""" if len(a_ ) <= 1: return lst __A = 1 while i < len(a_ ): if lst[i - 1] <= lst[i]: i += 1 else: __A , __A = lst[i], lst[i - 1] i -= 1 if i == 0: __A = 1 return lst if __name__ == "__main__": SCREAMING_SNAKE_CASE :List[Any] = input('Enter numbers separated by a comma:\n').strip() SCREAMING_SNAKE_CASE :List[Any] = [int(item) for item in user_input.split(',')] print(gnome_sort(unsorted))
15
0
"""simple docstring""" import unittest from transformers import DonutProcessor _lowercase = '''naver-clova-ix/donut-base''' class lowerCAmelCase_ ( unittest.TestCase ): '''simple docstring''' def _SCREAMING_SNAKE_CASE ( self : Any ) -> Any: A = DonutProcessor.from_pretrained(A_ ) def _SCREAMING_SNAKE_CASE ( self : List[Any] ) -> Optional[int]: A = { 'name': 'John Doe', 'age': '99', 'city': 'Atlanta', 'state': 'GA', 'zip': '30301', 'phone': '123-4567', 'nicknames': [{'nickname': 'Johnny'}, {'nickname': 'JD'}], } A = ( '<s_name>John Doe</s_name><s_age>99</s_age><s_city>Atlanta</s_city>' '<s_state>GA</s_state><s_zip>30301</s_zip><s_phone>123-4567</s_phone>' '<s_nicknames><s_nickname>Johnny</s_nickname>' '<sep/><s_nickname>JD</s_nickname></s_nicknames>' ) A = self.processor.tokenajson(A_ ) self.assertDictEqual(A_ ,A_ )
74
from dataclasses import dataclass from typing import Optional, Tuple, Union import numpy as np import torch from ..configuration_utils import ConfigMixin, register_to_config from ..utils import BaseOutput, randn_tensor from .scheduling_utils import SchedulerMixin @dataclass class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 42 snake_case_ = 42 snake_case_ = None class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = 2 @register_to_config def __init__( self : str ,A : float = 0.02 ,A : float = 1_00 ,A : float = 1.0_07 ,A : float = 80 ,A : float = 0.05 ,A : float = 50 ,): # standard deviation of the initial noise distribution __A = sigma_max # setable values __A = None __A = None __A = None # sigma(t_i) def UpperCamelCase_ ( self : str ,A : torch.FloatTensor ,A : Optional[int] = None ): return sample def UpperCamelCase_ ( self : Dict ,A : int ,A : Union[str, torch.device] = None ): __A = num_inference_steps __A = np.arange(0 ,self.num_inference_steps )[::-1].copy() __A = torch.from_numpy(A ).to(A ) __A = [ ( self.config.sigma_max**2 * (self.config.sigma_min**2 / self.config.sigma_max**2) ** (i / (num_inference_steps - 1)) ) for i in self.timesteps ] __A = torch.tensor(A ,dtype=torch.floataa ,device=A ) def UpperCamelCase_ ( self : Union[str, Any] ,A : torch.FloatTensor ,A : float ,A : Optional[torch.Generator] = None ): if self.config.s_min <= sigma <= self.config.s_max: __A = min(self.config.s_churn / self.num_inference_steps ,2**0.5 - 1 ) else: __A = 0 # sample eps ~ N(0, S_noise^2 * I) __A = self.config.s_noise * randn_tensor(sample.shape ,generator=A ).to(sample.device ) __A = sigma + gamma * sigma __A = sample + ((sigma_hat**2 - sigma**2) ** 0.5 * eps) return sample_hat, sigma_hat def UpperCamelCase_ ( self : Dict ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_hat + sigma_hat * model_output __A = (sample_hat - pred_original_sample) / sigma_hat __A = sample_hat + (sigma_prev - sigma_hat) * derivative if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : Optional[int] ,A : torch.FloatTensor ,A : float ,A : float ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : torch.FloatTensor ,A : bool = True ,): __A = sample_prev + sigma_prev * model_output __A = (sample_prev - pred_original_sample) / sigma_prev __A = sample_hat + (sigma_prev - sigma_hat) * (0.5 * derivative + 0.5 * derivative_corr) if not return_dict: return (sample_prev, derivative) return KarrasVeOutput( prev_sample=A ,derivative=A ,pred_original_sample=A ) def UpperCamelCase_ ( self : List[Any] ,A : Dict ,A : List[str] ,A : str ): raise NotImplementedError()
15
0
'''simple docstring''' import json import logging import os import socket import git import numpy as np import torch logging.basicConfig( format="""%(asctime)s - %(levelname)s - %(name)s - PID: %(process)d - %(message)s""", datefmt="""%m/%d/%Y %H:%M:%S""", level=logging.INFO, ) a_ : Dict = logging.getLogger(__name__) def a_ ( __snake_case : str ) -> Union[str, Any]: """simple docstring""" lowerCamelCase_ =git.Repo(search_parent_directories=__snake_case ) lowerCamelCase_ ={ '''repo_id''': str(__snake_case ), '''repo_sha''': str(repo.head.object.hexsha ), '''repo_branch''': str(repo.active_branch ), } with open(os.path.join(__snake_case , '''git_log.json''' ) , '''w''' ) as f: json.dump(__snake_case , __snake_case , indent=4 ) def a_ ( __snake_case : Union[str, Any] ) -> List[Any]: """simple docstring""" if params.n_gpu <= 0: lowerCamelCase_ =0 lowerCamelCase_ =-1 lowerCamelCase_ =True lowerCamelCase_ =False return assert torch.cuda.is_available() logger.info('''Initializing GPUs''' ) if params.n_gpu > 1: assert params.local_rank != -1 lowerCamelCase_ =int(os.environ['''WORLD_SIZE'''] ) lowerCamelCase_ =int(os.environ['''N_GPU_NODE'''] ) lowerCamelCase_ =int(os.environ['''RANK'''] ) # number of nodes / node ID lowerCamelCase_ =params.world_size // params.n_gpu_per_node lowerCamelCase_ =params.global_rank // params.n_gpu_per_node lowerCamelCase_ =True assert params.n_nodes == int(os.environ['''N_NODES'''] ) assert params.node_id == int(os.environ['''NODE_RANK'''] ) # local job (single GPU) else: assert params.local_rank == -1 lowerCamelCase_ =1 lowerCamelCase_ =0 lowerCamelCase_ =0 lowerCamelCase_ =0 lowerCamelCase_ =1 lowerCamelCase_ =1 lowerCamelCase_ =False # sanity checks assert params.n_nodes >= 1 assert 0 <= params.node_id < params.n_nodes assert 0 <= params.local_rank <= params.global_rank < params.world_size assert params.world_size == params.n_nodes * params.n_gpu_per_node # define whether this is the master process / if we are in multi-node distributed mode lowerCamelCase_ =params.node_id == 0 and params.local_rank == 0 lowerCamelCase_ =params.n_nodes > 1 # summary lowerCamelCase_ =F'''--- Global rank: {params.global_rank} - ''' logger.info(PREFIX + '''Number of nodes: %i''' % params.n_nodes ) logger.info(PREFIX + '''Node ID : %i''' % params.node_id ) logger.info(PREFIX + '''Local rank : %i''' % params.local_rank ) logger.info(PREFIX + '''World size : %i''' % params.world_size ) logger.info(PREFIX + '''GPUs per node : %i''' % params.n_gpu_per_node ) logger.info(PREFIX + '''Master : %s''' % str(params.is_master ) ) logger.info(PREFIX + '''Multi-node : %s''' % str(params.multi_node ) ) logger.info(PREFIX + '''Multi-GPU : %s''' % str(params.multi_gpu ) ) logger.info(PREFIX + '''Hostname : %s''' % socket.gethostname() ) # set GPU device torch.cuda.set_device(params.local_rank ) # initialize multi-GPU if params.multi_gpu: logger.info('''Initializing PyTorch distributed''' ) torch.distributed.init_process_group( init_method='''env://''' , backend='''nccl''' , ) def a_ ( __snake_case : Optional[int] ) -> Tuple: """simple docstring""" np.random.seed(args.seed ) torch.manual_seed(args.seed ) if args.n_gpu > 0: torch.cuda.manual_seed_all(args.seed )
75
# Lint as: python3 import os import re import urllib.parse from pathlib import Path from typing import Callable, List, Optional, Union from zipfile import ZipFile from ..utils.file_utils import cached_path, hf_github_url from ..utils.logging import get_logger from ..utils.version import Version SCREAMING_SNAKE_CASE :Union[str, Any] = get_logger(__name__) class UpperCAmelCase : '''simple docstring''' snake_case_ = "dummy_data" snake_case_ = "datasets" snake_case_ = False def __init__( self : Optional[int] ,A : str ,A : str ,A : Union[Version, str] ,A : Optional[str] = None ,A : bool = False ,A : bool = True ,A : Optional[List[Callable]] = None ,): __A = 0 __A = dataset_name __A = cache_dir __A = use_local_dummy_data __A = config # download_callbacks take a single url as input __A = download_callbacks or [] # if False, it doesn't load existing files and it returns the paths of the dummy files relative # to the dummy_data zip file root __A = load_existing_dummy_data # TODO(PVP, QL) might need to make this more general __A = str(A ) # to be downloaded __A = None __A = None @property def UpperCamelCase_ ( self : Union[str, Any] ): if self._dummy_file is None: __A = self.download_dummy_data() return self._dummy_file @property def UpperCamelCase_ ( self : Optional[Any] ): if self.config is not None: # structure is dummy / config_name / version_name return os.path.join("dummy" ,self.config.name ,self.version_name ) # structure is dummy / version_name return os.path.join("dummy" ,self.version_name ) @property def UpperCamelCase_ ( self : List[Any] ): return os.path.join(self.dummy_data_folder ,"dummy_data.zip" ) def UpperCamelCase_ ( self : Tuple ): __A = ( self.local_path_to_dummy_data if self.use_local_dummy_data is True else self.github_path_to_dummy_data ) __A = cached_path( A ,cache_dir=self.cache_dir ,extract_compressed_file=A ,force_extract=A ) return os.path.join(A ,self.dummy_file_name ) @property def UpperCamelCase_ ( self : str ): return os.path.join(self.datasets_scripts_dir ,self.dataset_name ,self.dummy_zip_file ) @property def UpperCamelCase_ ( self : Any ): if self._bucket_url is None: __A = hf_github_url(self.dataset_name ,self.dummy_zip_file.replace(os.sep ,"/" ) ) return self._bucket_url @property def UpperCamelCase_ ( self : Tuple ): # return full path if its a dir if os.path.isdir(self.dummy_file ): return self.dummy_file # else cut off path to file -> example `xsum`. return "/".join(self.dummy_file.replace(os.sep ,"/" ).split("/" )[:-1] ) def UpperCamelCase_ ( self : List[str] ,A : List[Any] ,*A : Dict ): if self.load_existing_dummy_data: # dummy data is downloaded and tested __A = self.dummy_file else: # dummy data cannot be downloaded and only the path to dummy file is returned __A = self.dummy_file_name # special case when data_url is a dict if isinstance(A ,A ): return self.create_dummy_data_dict(A ,A ) elif isinstance(A ,(list, tuple) ): return self.create_dummy_data_list(A ,A ) else: return self.create_dummy_data_single(A ,A ) def UpperCamelCase_ ( self : str ,A : List[Any] ,*A : List[Any] ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : List[str] ,A : List[str] ,A : Tuple ): return self.download_and_extract(A ) def UpperCamelCase_ ( self : Any ,A : Any ,*A : Optional[Any] ,**A : List[str] ): return path def UpperCamelCase_ ( self : str ): return {} def UpperCamelCase_ ( self : int ,A : int ,A : Tuple ): __A = {} for key, single_urls in data_url.items(): for download_callback in self.download_callbacks: if isinstance(A ,A ): for single_url in single_urls: download_callback(A ) else: __A = single_urls download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus if isinstance(A ,A ): __A = [os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) for x in single_urls] else: __A = single_urls __A = os.path.join(A ,urllib.parse.quote_plus(Path(A ).name ) ) __A = value # make sure that values are unique if all(isinstance(A ,A ) for i in dummy_data_dict.values() ) and len(set(dummy_data_dict.values() ) ) < len( dummy_data_dict.values() ): # append key to value to make its name unique __A = {key: value + key for key, value in dummy_data_dict.items()} return dummy_data_dict def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,A : str ): __A = [] # trick: if there are many shards named like `data.txt-000001-of-00300`, only use the first one __A = all(bool(re.findall("[0-9]{3,}-of-[0-9]{3,}" ,A ) ) for url in data_url ) __A = all( url.startswith("https://ftp.ncbi.nlm.nih.gov/pubmed/baseline/pubmed" ) for url in data_url ) if data_url and (is_tf_records or is_pubmed_records): __A = [data_url[0]] * len(A ) for single_url in data_url: for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(single_url.split("/" )[-1] ) ) dummy_data_list.append(A ) return dummy_data_list def UpperCamelCase_ ( self : str ,A : List[Any] ,A : Optional[Any] ): for download_callback in self.download_callbacks: download_callback(A ) # we force the name of each key to be the last file / folder name of the url path # if the url has arguments, we need to encode them with urllib.parse.quote_plus __A = os.path.join(A ,urllib.parse.quote_plus(data_url.split("/" )[-1] ) ) if os.path.exists(A ) or not self.load_existing_dummy_data: return value else: # Backward compatibility, maybe deprecate at one point. # For many datasets with single url calls to dl_manager.download_and_extract, # the dummy_data.zip file is actually the zipped downloaded file # while now we expected the dummy_data.zip file to be a directory containing # the downloaded file. return path_to_dummy_data def UpperCamelCase_ ( self : int ): pass def UpperCamelCase_ ( self : Dict ): pass def UpperCamelCase_ ( self : Optional[Any] ,A : List[Any] ): def _iter_archive_members(A : Optional[Any] ): # this preserves the order of the members inside the ZIP archive __A = Path(self.dummy_file ).parent __A = path.relative_to(A ) with ZipFile(self.local_path_to_dummy_data ) as zip_file: __A = zip_file.namelist() for member in members: if member.startswith(relative_path.as_posix() ): yield dummy_parent_path.joinpath(A ) __A = Path(A ) __A = _iter_archive_members(A ) if self.use_local_dummy_data else path.rglob("*" ) for file_path in file_paths: if file_path.is_file() and not file_path.name.startswith((".", "__") ): yield file_path.relative_to(A ).as_posix(), file_path.open("rb" ) def UpperCamelCase_ ( self : List[Any] ,A : Any ): if not isinstance(A ,A ): __A = [paths] for path in paths: if os.path.isfile(A ): if os.path.basename(A ).startswith((".", "__") ): return yield path else: for dirpath, dirnames, filenames in os.walk(A ): if os.path.basename(A ).startswith((".", "__") ): continue dirnames.sort() for filename in sorted(A ): if filename.startswith((".", "__") ): continue yield os.path.join(A ,A )
15
0
import requests def lowerCamelCase__ ( _a , _a): SCREAMING_SNAKE_CASE : Dict = {"Content-Type": "application/json"} SCREAMING_SNAKE_CASE : Optional[int] = requests.post(_a , json={"text": message_body} , headers=_a) if response.status_code != 200: SCREAMING_SNAKE_CASE : Dict = ( "Request to slack returned an error " f"{response.status_code}, the response is:\n{response.text}" ) raise ValueError(_a) 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>')
76
from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available SCREAMING_SNAKE_CASE :List[Any] = {} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: SCREAMING_SNAKE_CASE :List[str] = ['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 :Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
15
0
"""simple docstring""" import math class UpperCAmelCase_ : def _UpperCAmelCase ( self , a , a ) -> int: lowercase__ : Tuple = 0.0 lowercase__ : str = 0.0 for i in range(len(a ) ): da += math.pow((sample[i] - weights[0][i]) , 2 ) da += math.pow((sample[i] - weights[1][i]) , 2 ) return 0 if da > da else 1 return 0 def _UpperCAmelCase ( self , a , a , a , a ) -> list[list[int | float]]: for i in range(len(a ) ): weights[j][i] += alpha * (sample[i] - weights[j][i]) return weights def a_ ( ): '''simple docstring''' lowercase__ : str = [[1, 1, 0, 0], [0, 0, 0, 1], [1, 0, 0, 0], [0, 0, 1, 1]] # weight initialization ( n, C ) lowercase__ : int = [[0.2, 0.6, 0.5, 0.9], [0.8, 0.4, 0.7, 0.3]] # training lowercase__ : Optional[int] = SelfOrganizingMap() lowercase__ : Dict = 3 lowercase__ : List[Any] = 0.5 for _ in range(_lowerCAmelCase ): for j in range(len(_lowerCAmelCase ) ): # training sample lowercase__ : Tuple = training_samples[j] # Compute the winning vector lowercase__ : str = self_organizing_map.get_winner(_lowerCAmelCase , _lowerCAmelCase ) # Update the winning vector lowercase__ : List[Any] = self_organizing_map.update(_lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase , _lowerCAmelCase ) # classify test sample lowercase__ : int = [0, 0, 0, 1] lowercase__ : Union[str, Any] = self_organizing_map.get_winner(_lowerCAmelCase , _lowerCAmelCase ) # results print(f"""Clusters that the test sample belongs to : {winner}""" ) print(f"""Weights that have been trained : {weights}""" ) # running the main() function if __name__ == "__main__": main()
77
from typing import Dict, Optional import numpy as np import datasets SCREAMING_SNAKE_CASE :List[Any] = '\nIoU is the area of overlap between the predicted segmentation and the ground truth divided by the area of union\nbetween the predicted segmentation and the ground truth. For binary (two classes) or multi-class segmentation,\nthe mean IoU of the image is calculated by taking the IoU of each class and averaging them.\n' SCREAMING_SNAKE_CASE :List[str] = '\nArgs:\n predictions (`List[ndarray]`):\n List of predicted segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n references (`List[ndarray]`):\n List of ground truth segmentation maps, each of shape (height, width). Each segmentation map can be of a different size.\n num_labels (`int`):\n Number of classes (categories).\n ignore_index (`int`):\n Index that will be ignored during evaluation.\n nan_to_num (`int`, *optional*):\n If specified, NaN values will be replaced by the number defined by the user.\n label_map (`dict`, *optional*):\n If specified, dictionary mapping old label indices to new label indices.\n reduce_labels (`bool`, *optional*, defaults to `False`):\n Whether or not to reduce all label values of segmentation maps by 1. Usually used for datasets where 0 is used for background,\n and background itself is not included in all classes of a dataset (e.g. ADE20k). The background label will be replaced by 255.\n\nReturns:\n `Dict[str, float | ndarray]` comprising various elements:\n - *mean_iou* (`float`):\n Mean Intersection-over-Union (IoU averaged over all categories).\n - *mean_accuracy* (`float`):\n Mean accuracy (averaged over all categories).\n - *overall_accuracy* (`float`):\n Overall accuracy on all images.\n - *per_category_accuracy* (`ndarray` of shape `(num_labels,)`):\n Per category accuracy.\n - *per_category_iou* (`ndarray` of shape `(num_labels,)`):\n Per category IoU.\n\nExamples:\n\n >>> import numpy as np\n\n >>> mean_iou = datasets.load_metric("mean_iou")\n\n >>> # suppose one has 3 different segmentation maps predicted\n >>> predicted_1 = np.array([[1, 2], [3, 4], [5, 255]])\n >>> actual_1 = np.array([[0, 3], [5, 4], [6, 255]])\n\n >>> predicted_2 = np.array([[2, 7], [9, 2], [3, 6]])\n >>> actual_2 = np.array([[1, 7], [9, 2], [3, 6]])\n\n >>> predicted_3 = np.array([[2, 2, 3], [8, 2, 4], [3, 255, 2]])\n >>> actual_3 = np.array([[1, 2, 2], [8, 2, 1], [3, 255, 1]])\n\n >>> predicted = [predicted_1, predicted_2, predicted_3]\n >>> ground_truth = [actual_1, actual_2, actual_3]\n\n >>> results = mean_iou.compute(predictions=predicted, references=ground_truth, num_labels=10, ignore_index=255, reduce_labels=False)\n >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n {\'mean_iou\': 0.47750000000000004, \'mean_accuracy\': 0.5916666666666666, \'overall_accuracy\': 0.5263157894736842, \'per_category_iou\': array([0. , 0. , 0.375, 0.4 , 0.5 , 0. , 0.5 , 1. , 1. , 1. ]), \'per_category_accuracy\': array([0. , 0. , 0.75 , 0.66666667, 1. , 0. , 0.5 , 1. , 1. , 1. ])}\n' SCREAMING_SNAKE_CASE :str = '\\n@software{MMSegmentation_Contributors_OpenMMLab_Semantic_Segmentation_2020,\nauthor = {{MMSegmentation Contributors}},\nlicense = {Apache-2.0},\nmonth = {7},\ntitle = {{OpenMMLab Semantic Segmentation Toolbox and Benchmark}},\nurl = {https://github.com/open-mmlab/mmsegmentation},\nyear = {2020}\n}' def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Tuple: """simple docstring""" if label_map is not None: for old_id, new_id in label_map.items(): __A = new_id # turn into Numpy arrays __A = np.array(a_ ) __A = np.array(a_ ) if reduce_labels: __A = 2_5_5 __A = label - 1 __A = 2_5_5 __A = label != ignore_index __A = np.not_equal(a_ , a_ ) __A = pred_label[mask] __A = np.array(a_ )[mask] __A = pred_label[pred_label == label] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = np.histogram(a_ , bins=a_ , range=(0, num_labels - 1) )[0] __A = area_pred_label + area_label - area_intersect return area_intersect, area_union, area_pred_label, area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = False , ) -> Union[str, Any]: """simple docstring""" __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) __A = np.zeros((num_labels,) , dtype=np.floataa ) for result, gt_seg_map in zip(a_ , a_ ): __A , __A , __A , __A = intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) total_area_intersect += area_intersect total_area_union += area_union total_area_pred_label += area_pred_label total_area_label += area_label return total_area_intersect, total_area_union, total_area_pred_label, total_area_label def UpperCAmelCase ( a_ , a_ , a_ , a_ , a_ = None , a_ = None , a_ = False , ) -> str: """simple docstring""" __A , __A , __A , __A = total_intersect_and_union( a_ , a_ , a_ , a_ , a_ , a_ ) # compute metrics __A = {} __A = total_area_intersect.sum() / total_area_label.sum() __A = total_area_intersect / total_area_union __A = total_area_intersect / total_area_label __A = np.nanmean(a_ ) __A = np.nanmean(a_ ) __A = all_acc __A = iou __A = acc if nan_to_num is not None: __A = {metric: np.nan_to_num(a_ , nan=a_ ) for metric, metric_value in metrics.items()} return metrics @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class UpperCAmelCase ( datasets.Metric ): '''simple docstring''' def UpperCamelCase_ ( self : List[Any] ): return datasets.MetricInfo( description=_DESCRIPTION ,citation=_CITATION ,inputs_description=_KWARGS_DESCRIPTION ,features=datasets.Features( # 1st Seq - height dim, 2nd - width dim { "predictions": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), "references": datasets.Sequence(datasets.Sequence(datasets.Value("uint16" ) ) ), } ) ,reference_urls=[ "https://github.com/open-mmlab/mmsegmentation/blob/71c201b1813267d78764f306a297ca717827c4bf/mmseg/core/evaluation/metrics.py" ] ,) def UpperCamelCase_ ( self : int ,A : Optional[Any] ,A : Optional[Any] ,A : int ,A : bool ,A : Optional[int] = None ,A : Optional[Dict[int, int]] = None ,A : bool = False ,): __A = mean_iou( results=A ,gt_seg_maps=A ,num_labels=A ,ignore_index=A ,nan_to_num=A ,label_map=A ,reduce_labels=A ,) return iou_result
15
0
"""simple docstring""" import shutil import tempfile import unittest from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartaaTokenizer, MBartaaTokenizerFast, is_torch_available from transformers.testing_utils import ( get_tests_dir, nested_simplify, require_sentencepiece, require_tokenizers, require_torch, slow, ) from ...test_tokenization_common import TokenizerTesterMixin snake_case_ = get_tests_dir("""fixtures/test_sentencepiece.model""") if is_torch_available(): from transformers.models.mbart.modeling_mbart import shift_tokens_right snake_case_ = 25_0004 snake_case_ = 25_0020 @require_sentencepiece @require_tokenizers class A_ ( SCREAMING_SNAKE_CASE_ , unittest.TestCase ): """simple docstring""" __UpperCamelCase = MBartaaTokenizer __UpperCamelCase = MBartaaTokenizerFast __UpperCamelCase = True __UpperCamelCase = True def UpperCAmelCase__ ( self :Dict ) -> Dict: super().setUp() # We have a SentencePiece fixture for testing UpperCAmelCase = MBartaaTokenizer(lowercase_ , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=lowercase_ ) tokenizer.save_pretrained(self.tmpdirname ) def UpperCAmelCase__ ( self :Optional[int] ) -> Optional[Any]: UpperCAmelCase = '<s>' UpperCAmelCase = 0 self.assertEqual(self.get_tokenizer()._convert_token_to_id(lowercase_ ) , lowercase_ ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(lowercase_ ) , lowercase_ ) def UpperCAmelCase__ ( self :Any ) -> Optional[Any]: UpperCAmelCase = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<s>' ) self.assertEqual(vocab_keys[1] , '<pad>' ) self.assertEqual(vocab_keys[-1] , '<mask>' ) self.assertEqual(len(lowercase_ ) , 10_54 ) def UpperCAmelCase__ ( self :Optional[Any] ) -> Optional[int]: self.assertEqual(self.get_tokenizer().vocab_size , 10_54 ) def UpperCAmelCase__ ( self :Any ) -> Dict: UpperCAmelCase = MBartaaTokenizer(lowercase_ , src_lang='en_XX' , tgt_lang='ro_RO' , keep_accents=lowercase_ ) UpperCAmelCase = tokenizer.tokenize('This is a test' ) self.assertListEqual(lowercase_ , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(lowercase_ ) , [value + tokenizer.fairseq_offset for value in [2_85, 46, 10, 1_70, 3_82]] , ) UpperCAmelCase = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( lowercase_ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.'] , ) UpperCAmelCase = tokenizer.convert_tokens_to_ids(lowercase_ ) self.assertListEqual( lowercase_ , [ value + tokenizer.fairseq_offset for value in [8, 21, 84, 55, 24, 19, 7, 2, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 2, 4] ] , ) UpperCAmelCase = tokenizer.convert_ids_to_tokens(lowercase_ ) self.assertListEqual( lowercase_ , [SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.'] , ) @slow def UpperCAmelCase__ ( self :Optional[Any] ) -> Any: # fmt: off UpperCAmelCase = {'input_ids': [[25_00_04, 1_10_62, 8_27_72, 7, 15, 8_27_72, 5_38, 5_15_29, 2_37, 1_71_98, 12_90, 2_06, 9, 21_51_75, 13_14, 1_36, 1_71_98, 12_90, 2_06, 9, 5_63_59, 42, 12_20_09, 9, 1_64_66, 16, 8_73_44, 45_37, 9, 47_17, 7_83_81, 6, 15_99_58, 7, 15, 2_44_80, 6_18, 4, 5_27, 2_26_93, 54_28, 4, 27_77, 2_44_80, 98_74, 4, 4_35_23, 5_94, 4, 8_03, 1_83_92, 3_31_89, 18, 4, 4_35_23, 2_44_47, 1_23_99, 1_00, 2_49_55, 8_36_58, 96_26, 14_40_57, 15, 8_39, 2_23_35, 16, 1_36, 2_49_55, 8_36_58, 8_34_79, 15, 3_91_02, 7_24, 16, 6_78, 6_45, 27_89, 13_28, 45_89, 42, 12_20_09, 11_57_74, 23, 8_05, 13_28, 4_68_76, 7, 1_36, 5_38_94, 19_40, 4_22_27, 4_11_59, 1_77_21, 8_23, 4_25, 4, 2_75_12, 9_87_22, 2_06, 1_36, 55_31, 49_70, 9_19, 1_73_36, 5, 2], [25_00_04, 2_00_80, 6_18, 83, 8_27_75, 47, 4_79, 9, 15_17, 73, 5_38_94, 3_33, 8_05_81, 11_01_17, 1_88_11, 52_56, 12_95, 51, 15_25_26, 2_97, 79_86, 3_90, 12_44_16, 5_38, 3_54_31, 2_14, 98, 1_50_44, 2_57_37, 1_36, 71_08, 4_37_01, 23, 7_56, 13_53_55, 7, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [25_00_04, 5_81, 6_37_73, 11_94_55, 6, 14_77_97, 8_82_03, 7, 6_45, 70, 21, 32_85, 1_02_69, 5, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=lowercase_ , model_name='facebook/mbart-large-50' , revision='d3913889c59cd5c9e456b269c376325eabad57e2' , ) def UpperCAmelCase__ ( self :List[str] ) -> Dict: if not self.test_slow_tokenizer: # as we don't have a slow version, we can't compare the outputs between slow and fast versions return UpperCAmelCase = (self.rust_tokenizer_class, 'hf-internal-testing/tiny-random-mbart50', {}) 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(lowercase_ , **lowercase_ ) UpperCAmelCase = self.tokenizer_class.from_pretrained(lowercase_ , **lowercase_ ) UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(lowercase_ ) UpperCAmelCase = tokenizer_p.save_pretrained(lowercase_ ) # Checks it save with the same files + the tokenizer.json file for the fast one self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) UpperCAmelCase = tuple(f for f in tokenizer_r_files if 'tokenizer.json' not in f ) self.assertSequenceEqual(lowercase_ , lowercase_ ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(lowercase_ ) UpperCAmelCase = tokenizer_p.from_pretrained(lowercase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase_ , lowercase_ ) ) # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) shutil.rmtree(lowercase_ ) # Save tokenizer rust, legacy_format=True UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(lowercase_ , legacy_format=lowercase_ ) UpperCAmelCase = tokenizer_p.save_pretrained(lowercase_ ) # Checks it save with the same files self.assertSequenceEqual(lowercase_ , lowercase_ ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(lowercase_ ) UpperCAmelCase = tokenizer_p.from_pretrained(lowercase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase_ , lowercase_ ) ) shutil.rmtree(lowercase_ ) # Save tokenizer rust, legacy_format=False UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = tokenizer_r.save_pretrained(lowercase_ , legacy_format=lowercase_ ) UpperCAmelCase = tokenizer_p.save_pretrained(lowercase_ ) # Checks it saved the tokenizer.json file self.assertTrue(any('tokenizer.json' in f for f in tokenizer_r_files ) ) # Checks everything loads correctly in the same way UpperCAmelCase = tokenizer_r.from_pretrained(lowercase_ ) UpperCAmelCase = tokenizer_p.from_pretrained(lowercase_ ) # Check special tokens are set accordingly on Rust and Python for key in tokenizer_pp.special_tokens_map: self.assertTrue(hasattr(lowercase_ , lowercase_ ) ) shutil.rmtree(lowercase_ ) @require_torch @require_sentencepiece @require_tokenizers class A_ ( unittest.TestCase ): """simple docstring""" __UpperCamelCase = """facebook/mbart-large-50-one-to-many-mmt""" __UpperCamelCase = [ """ UN Chief Says There Is No Military Solution in Syria""", """ Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for Syria is that \"there is no military solution\" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.""", ] __UpperCamelCase = [ """Şeful ONU declară că nu există o soluţie militară în Siria""", """Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei""" """ pentru Siria este că \"nu există o soluţie militară\" la conflictul de aproape cinci ani şi că noi arme nu vor""" """ face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.""", ] __UpperCamelCase = [EN_CODE, 82_74, 12_78_73, 2_59_16, 7, 86_22, 20_71, 4_38, 6_74_85, 53, 18_78_95, 23, 5_17_12, 2] @classmethod def UpperCAmelCase__ ( cls :int ) -> Optional[int]: UpperCAmelCase = MBartaaTokenizer.from_pretrained( cls.checkpoint_name , src_lang='en_XX' , tgt_lang='ro_RO' ) UpperCAmelCase = 1 return cls def UpperCAmelCase__ ( self :Optional[Any] ) -> Optional[Any]: self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ar_AR'] , 25_00_01 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['en_EN'] , 25_00_04 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['ro_RO'] , 25_00_20 ) self.assertEqual(self.tokenizer.fairseq_tokens_to_ids['mr_IN'] , 25_00_38 ) def UpperCAmelCase__ ( self :Dict ) -> Tuple: UpperCAmelCase = self.tokenizer.batch_encode_plus(self.src_text ).input_ids[0] self.assertListEqual(self.expected_src_tokens , lowercase_ ) def UpperCAmelCase__ ( self :int ) -> List[Any]: self.assertIn(lowercase_ , self.tokenizer.all_special_ids ) UpperCAmelCase = [RO_CODE, 8_84, 90_19, 96, 9, 9_16, 8_67_92, 36, 1_87_43, 1_55_96, 5, 2] UpperCAmelCase = self.tokenizer.decode(lowercase_ , skip_special_tokens=lowercase_ ) UpperCAmelCase = self.tokenizer.decode(generated_ids[1:] , skip_special_tokens=lowercase_ ) self.assertEqual(lowercase_ , lowercase_ ) self.assertNotIn(self.tokenizer.eos_token , lowercase_ ) def UpperCAmelCase__ ( self :Tuple ) -> str: UpperCAmelCase = ['this is gunna be a long sentence ' * 20] assert isinstance(src_text[0] , lowercase_ ) UpperCAmelCase = 10 UpperCAmelCase = self.tokenizer(lowercase_ , max_length=lowercase_ , truncation=lowercase_ ).input_ids[0] self.assertEqual(ids[0] , lowercase_ ) self.assertEqual(ids[-1] , 2 ) self.assertEqual(len(lowercase_ ) , lowercase_ ) def UpperCAmelCase__ ( self :List[Any] ) -> List[Any]: self.assertListEqual(self.tokenizer.convert_tokens_to_ids(['<mask>', 'ar_AR'] ) , [25_00_53, 25_00_01] ) def UpperCAmelCase__ ( self :List[str] ) -> Optional[Any]: UpperCAmelCase = tempfile.mkdtemp() UpperCAmelCase = self.tokenizer.fairseq_tokens_to_ids self.tokenizer.save_pretrained(lowercase_ ) UpperCAmelCase = MBartaaTokenizer.from_pretrained(lowercase_ ) self.assertDictEqual(new_tok.fairseq_tokens_to_ids , lowercase_ ) @require_torch def UpperCAmelCase__ ( self :Tuple ) -> Any: UpperCAmelCase = self.tokenizer(self.src_text , text_target=self.tgt_text , padding=lowercase_ , return_tensors='pt' ) UpperCAmelCase = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) # fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4 assert batch.input_ids[1][0] == EN_CODE assert batch.input_ids[1][-1] == 2 assert batch.labels[1][0] == RO_CODE assert batch.labels[1][-1] == 2 assert batch.decoder_input_ids[1][:2].tolist() == [2, RO_CODE] @require_torch def UpperCAmelCase__ ( self :Tuple ) -> Dict: UpperCAmelCase = self.tokenizer( self.src_text , text_target=self.tgt_text , padding=lowercase_ , truncation=lowercase_ , max_length=len(self.expected_src_tokens ) , return_tensors='pt' , ) UpperCAmelCase = shift_tokens_right(batch['labels'] , self.tokenizer.pad_token_id ) self.assertIsInstance(lowercase_ , lowercase_ ) self.assertEqual((2, 14) , batch.input_ids.shape ) self.assertEqual((2, 14) , batch.attention_mask.shape ) UpperCAmelCase = batch.input_ids.tolist()[0] self.assertListEqual(self.expected_src_tokens , lowercase_ ) self.assertEqual(2 , batch.decoder_input_ids[0, 0] ) # decoder_start_token_id # Test that special tokens are reset self.assertEqual(self.tokenizer.prefix_tokens , [EN_CODE] ) self.assertEqual(self.tokenizer.suffix_tokens , [self.tokenizer.eos_token_id] ) def UpperCAmelCase__ ( self :Tuple ) -> Any: UpperCAmelCase = self.tokenizer(self.src_text , padding=lowercase_ , truncation=lowercase_ , max_length=3 , return_tensors='pt' ) UpperCAmelCase = self.tokenizer( text_target=self.tgt_text , padding=lowercase_ , truncation=lowercase_ , max_length=10 , return_tensors='pt' ) UpperCAmelCase = targets['input_ids'] UpperCAmelCase = shift_tokens_right(lowercase_ , self.tokenizer.pad_token_id ) self.assertEqual(batch.input_ids.shape[1] , 3 ) self.assertEqual(batch.decoder_input_ids.shape[1] , 10 ) @require_torch def UpperCAmelCase__ ( self :Tuple ) -> Any: UpperCAmelCase = self.tokenizer._build_translation_inputs( 'A test' , return_tensors='pt' , src_lang='en_XX' , tgt_lang='ar_AR' ) self.assertEqual( nested_simplify(lowercase_ ) , { # en_XX, A, test, EOS 'input_ids': [[25_00_04, 62, 30_34, 2]], 'attention_mask': [[1, 1, 1, 1]], # ar_AR 'forced_bos_token_id': 25_00_01, } , )
78
import os import re import unicodedata from shutil import copyfile from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple, Union import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import is_torch_available, logging if is_torch_available(): import torch if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation SCREAMING_SNAKE_CASE :List[str] = logging.get_logger(__name__) SCREAMING_SNAKE_CASE :List[str] = {'vocab_file': 'spiece.model'} SCREAMING_SNAKE_CASE :Dict = { 'vocab_file': { 'AI-Sweden/gpt-sw3-126m': 'https://huggingface.co/AI-Sweden/gpt-sw3-126m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-350m': 'https://huggingface.co/AI-Sweden/gpt-sw3-350m/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-1.6b': 'https://huggingface.co/AI-Sweden/gpt-sw3-1.6b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-6.7b': 'https://huggingface.co/AI-Sweden/gpt-sw3-6.7b/resolve/main/spiece.model', 'AI-Sweden/gpt-sw3-20b': 'https://huggingface.co/AI-Sweden/gpt-sw3-20b/resolve/main/spiece.model', } } SCREAMING_SNAKE_CASE :Optional[Any] = { 'AI-Sweden/gpt-sw3-126m': 2048, 'AI-Sweden/gpt-sw3-350m': 2048, 'AI-Sweden/gpt-sw3-1.6b': 2048, 'AI-Sweden/gpt-sw3-6.7b': 2048, 'AI-Sweden/gpt-sw3-20b': 2048, } class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = VOCAB_FILES_NAMES snake_case_ = PRETRAINED_VOCAB_FILES_MAP snake_case_ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES snake_case_ = ["input_ids", "attention_mask"] def __init__( self : Optional[int] ,A : Optional[Any] ,A : Optional[int]=False ,A : int=False ,A : Union[str, Any]=False ,A : int=None ,A : Optional[Any]=None ,A : Union[str, Any]=None ,A : Optional[Any]=None ,A : Optional[Dict[str, Any]] = None ,**A : Tuple ,): __A = {} if sp_model_kwargs is None else sp_model_kwargs __A = kwargs.get("name_or_path" ) if name_or_path is None: logger.warning( "name_or_path not provided, will work for all GPTSw3 models except gpt-sw3-7b," " you are testing the model, this can safely be ignored" ) __A = "None" # Default definitions for our 2 tokenizer versions, with None-checks to enable proper testing __A = "<|endoftext|>" if eos_token is None else eos_token __A = "<unk>" if unk_token is None else unk_token if "gpt-sw3-7b" in name_or_path: __A = unk_token if pad_token is None else pad_token __A = eos_token if bos_token is None else bos_token else: __A = "<pad>" if pad_token is None else pad_token __A = "<s>" if bos_token is None else bos_token super().__init__( do_lower_case=A ,remove_space=A ,keep_accents=A ,bos_token=A ,eos_token=A ,unk_token=A ,pad_token=A ,sp_model_kwargs=self.sp_model_kwargs ,**A ,) __A = do_lower_case __A = remove_space __A = keep_accents __A = vocab_file __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(A ) # Used for whitespace normalization in input texts # fmt : off __A = {" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "", "„"} # fmt : on # Regular expression to remove non-printing characters (e.g. some unicode control chars) in preprocessing __A = re.compile( f'''[{''.join(map(A ,list(range(0 ,9 ) ) + list(range(11 ,32 ) ) + list(range(1_27 ,1_60 ) ) + [1_60, 1_73, 82_03] ) )}]''' ) def __getstate__( self : Optional[int] ): __A = self.__dict__.copy() __A = None return state def __setstate__( self : Optional[Any] ,A : Union[str, Any] ): __A = d # for backward compatibility if not hasattr(self ,"sp_model_kwargs" ): __A = {} __A = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) @property # Copied from transformers.models.albert.tokenization_albert.AlbertTokenizer.vocab_size def UpperCamelCase_ ( self : List[str] ): return len(self.sp_model ) def UpperCamelCase_ ( self : int ,A : str ): __A = self.non_printing_characters_re.sub("" ,A ) # Normalize whitespaces __A = "".join([char if char not in self.whitespaces else " " for char in text] ) # NFC Unicode normalization __A = unicodedata.normalize("NFC" ,A ) return text def UpperCamelCase_ ( self : Union[str, Any] ,A : str ,**A : Optional[int] ): __A = self.preprocess_text(A ) return self.sp_model.encode(A ,out_type=A ) def UpperCamelCase_ ( self : Any ,A : str ): return self.sp_model.PieceToId(A ) def UpperCamelCase_ ( self : Dict ,A : int ): return self.sp_model.IdToPiece(A ) @staticmethod def UpperCamelCase_ ( A : str ): return out_string def UpperCamelCase_ ( self : str ,A : List[str] ): __A = [] __A = "" __A = False for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: # TODO: Check if this is needed, as it ensures that decode(encode(doc)) != doc by adding extra whitespace in the decoded document if not prev_is_special: out_string += " " out_string += self.sp_model.decode(A ) + token __A = True __A = [] else: current_sub_tokens.append(A ) __A = False out_string += self.sp_model.decode(A ) return out_string def UpperCamelCase_ ( self : str ): __A = {self.convert_ids_to_tokens(A ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def UpperCamelCase_ ( self : List[str] ,A : str ,A : Optional[str] = None ): if not os.path.isdir(A ): logger.error(f'''Vocabulary path ({save_directory}) should be a directory''' ) return __A = os.path.join( A ,(filename_prefix + "-" if filename_prefix else "") + VOCAB_FILES_NAMES["vocab_file"] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(A ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file ,A ) elif not os.path.isfile(self.vocab_file ): with open(A ,"wb" ) as fi: __A = self.sp_model.serialized_model_proto() fi.write(A ) return (out_vocab_file,) def UpperCamelCase_ ( self : Union[str, Any] ,A : Union[str, List[str]] ,A : Union[str, bool] = False ): if isinstance(A ,A ): __A = self.preprocess_text(A ) __A = self.sp_model.encode(A ) else: __A = [self.preprocess_text(A ) for t in text] __A = self.sp_model.encode(A ) if return_tensors is True or return_tensors == "pt": __A = torch.tensor(A ) return token_ids def UpperCamelCase_ ( self : List[Any] ,A : Union[int, List[int]] ): return self.sp_model.decode(A ) def UpperCamelCase_ ( self : List[str] ,A : "Conversation" ): __A = [f'''User: {text}''' if is_user else f'''Bot: {text}''' for is_user, text in conversation.iter_texts()] __A = ( f'''{self.eos_token}{self.bos_token}''' + f'''{self.bos_token}'''.join(A ) + f'''{self.bos_token}Bot:''' ) return self.encode(text=A )
15
0
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from typing import Optional import numpy as np import torch from datasets import load_dataset from torchvision.transforms import Compose, Lambda, Normalize, RandomHorizontalFlip, RandomResizedCrop, ToTensor import transformers from transformers import ( CONFIG_MAPPING, IMAGE_PROCESSOR_MAPPING, MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING, AutoConfig, AutoImageProcessor, AutoModelForMaskedImageModeling, HfArgumentParser, Trainer, TrainingArguments, ) from transformers.trainer_utils import get_last_checkpoint from transformers.utils import check_min_version, send_example_telemetry from transformers.utils.versions import require_version lowerCamelCase_ = logging.getLogger(__name__) # Will error if the minimal version of Transformers is not installed. Remove at your own risks. check_min_version('''4.31.0''') require_version('''datasets>=1.8.0''', '''To fix: pip install -r examples/pytorch/image-pretraining/requirements.txt''') lowerCamelCase_ = list(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING.keys()) lowerCamelCase_ = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class _UpperCAmelCase : """simple docstring""" snake_case = field( default='''cifar10''' , metadata={'''help''': '''Name of a dataset from the datasets package'''} ) snake_case = field( default=snake_case_ , metadata={'''help''': '''The configuration name of the dataset to use (via the datasets library).'''} ) snake_case = field( default=snake_case_ , metadata={'''help''': '''The column name of the images in the files. If not set, will try to use \'image\' or \'img\'.'''} , ) snake_case = field(default=snake_case_ , metadata={'''help''': '''A folder containing the training data.'''} ) snake_case = field(default=snake_case_ , metadata={'''help''': '''A folder containing the validation data.'''} ) snake_case = field( default=0.15 , metadata={'''help''': '''Percent to split off of train for validation.'''} ) snake_case = field(default=32 , metadata={'''help''': '''The size of the square patches to use for masking.'''} ) snake_case = field( default=0.6 , metadata={'''help''': '''Percentage of patches to mask.'''} , ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of training examples to this ''' '''value if set.''' ) } , ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''For debugging purposes or quicker training, truncate the number of evaluation examples to this ''' '''value if set.''' ) } , ) def lowerCAmelCase ( self : Any ): '''simple docstring''' _A = {} if self.train_dir is not None: _A = self.train_dir if self.validation_dir is not None: _A = self.validation_dir _A = data_files if data_files else None @dataclass class _UpperCAmelCase : """simple docstring""" snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''The model checkpoint for weights initialization. Can be a local path to a pytorch_model.bin or a ''' '''checkpoint identifier on the hub. ''' '''Don\'t set if you want to train a model from scratch.''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''If training from scratch, pass a model type from the list: ''' + ''', '''.join(snake_case_ )} , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Pretrained config name or path if not the same as model_name'''} ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''Override some existing default config settings when a model is trained from scratch. Example: ''' '''n_embd=10,resid_pdrop=0.2,scale_attn_weights=false,summary_type=cls_index''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Where do you want to store (cache) the pretrained models/datasets downloaded from the hub'''} , ) snake_case = field( default='''main''' , metadata={'''help''': '''The specific model version to use (can be a branch name, tag name or commit id).'''} , ) snake_case = field(default=snake_case_ , metadata={'''help''': '''Name or path of preprocessor config.'''} ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''Will use the token generated when running `huggingface-cli login` (necessary to use this script ''' '''with private models).''' ) } , ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''The size (resolution) of each image. If not specified, will use `image_size` of the configuration.''' ) } , ) snake_case = field( default=snake_case_ , metadata={ '''help''': ( '''The size (resolution) of each patch. If not specified, will use `patch_size` of the configuration.''' ) } , ) snake_case = field( default=snake_case_ , metadata={'''help''': '''Stride to use for the encoder.'''} , ) class _UpperCAmelCase : """simple docstring""" def __init__( self : Tuple , __UpperCAmelCase : Optional[int]=192 , __UpperCAmelCase : Dict=32 , __UpperCAmelCase : int=4 , __UpperCAmelCase : int=0.6 ): '''simple docstring''' _A = input_size _A = mask_patch_size _A = model_patch_size _A = mask_ratio if self.input_size % self.mask_patch_size != 0: raise ValueError("Input size must be divisible by mask patch size" ) if self.mask_patch_size % self.model_patch_size != 0: raise ValueError("Mask patch size must be divisible by model patch size" ) _A = self.input_size // self.mask_patch_size _A = self.mask_patch_size // self.model_patch_size _A = self.rand_size**2 _A = int(np.ceil(self.token_count * self.mask_ratio ) ) def __call__( self : Any ): '''simple docstring''' _A = np.random.permutation(self.token_count )[: self.mask_count] _A = np.zeros(self.token_count , dtype=__UpperCAmelCase ) _A = 1 _A = mask.reshape((self.rand_size, self.rand_size) ) _A = mask.repeat(self.scale , axis=0 ).repeat(self.scale , axis=1 ) return torch.tensor(mask.flatten() ) def __lowercase ( __lowercase ) -> str: '''simple docstring''' _A = torch.stack([example["pixel_values"] for example in examples] ) _A = torch.stack([example["mask"] for example in examples] ) return {"pixel_values": pixel_values, "bool_masked_pos": mask} def __lowercase ( ) -> Dict: '''simple docstring''' _A = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments) ) if len(sys.argv ) == 2 and sys.argv[1].endswith(".json" ): # If we pass only one argument to the script and it's the path to a json file, # let's parse it to get our arguments. _A , _A , _A = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: _A , _A , _A = parser.parse_args_into_dataclasses() # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The # information sent is the one passed as arguments along with your Python/PyTorch versions. send_example_telemetry("run_mim" , __lowercase , __lowercase ) # Setup logging logging.basicConfig( format="%(asctime)s - %(levelname)s - %(name)s - %(message)s" , datefmt="%m/%d/%Y %H:%M:%S" , handlers=[logging.StreamHandler(sys.stdout )] , ) if training_args.should_log: # The default of training_args.log_level is passive, so we set log level at info here to have that default. transformers.utils.logging.set_verbosity_info() _A = training_args.get_process_log_level() logger.setLevel(__lowercase ) transformers.utils.logging.set_verbosity(__lowercase ) transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() # Log on each process the small summary: logger.warning( F'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}''' + F'''distributed training: {bool(training_args.local_rank != -1 )}, 16-bits training: {training_args.fpaa}''' ) logger.info(F'''Training/evaluation parameters {training_args}''' ) # Detecting last checkpoint. _A = None if os.path.isdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir: _A = get_last_checkpoint(training_args.output_dir ) if last_checkpoint is None and len(os.listdir(training_args.output_dir ) ) > 0: raise ValueError( F'''Output directory ({training_args.output_dir}) already exists and is not empty. ''' "Use --overwrite_output_dir to overcome." ) elif last_checkpoint is not None and training_args.resume_from_checkpoint is None: logger.info( F'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change ''' "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." ) # Initialize our dataset. _A = load_dataset( data_args.dataset_name , data_args.dataset_config_name , data_files=data_args.data_files , cache_dir=model_args.cache_dir , use_auth_token=True if model_args.use_auth_token else None , ) # If we don't have a validation split, split off a percentage of train as validation. _A = None if "validation" in ds.keys() else data_args.train_val_split if isinstance(data_args.train_val_split , __lowercase ) and data_args.train_val_split > 0.0: _A = ds["train"].train_test_split(data_args.train_val_split ) _A = split["train"] _A = split["test"] # Create config # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. _A = { "cache_dir": model_args.cache_dir, "revision": model_args.model_revision, "use_auth_token": True if model_args.use_auth_token else None, } if model_args.config_name_or_path: _A = AutoConfig.from_pretrained(model_args.config_name_or_path , **__lowercase ) elif model_args.model_name_or_path: _A = AutoConfig.from_pretrained(model_args.model_name_or_path , **__lowercase ) else: _A = CONFIG_MAPPING[model_args.model_type]() logger.warning("You are instantiating a new config instance from scratch." ) if model_args.config_overrides is not None: logger.info(F'''Overriding config: {model_args.config_overrides}''' ) config.update_from_string(model_args.config_overrides ) logger.info(F'''New config: {config}''' ) # make sure the decoder_type is "simmim" (only relevant for BEiT) if hasattr(__lowercase , "decoder_type" ): _A = "simmim" # adapt config _A = model_args.image_size if model_args.image_size is not None else config.image_size _A = model_args.patch_size if model_args.patch_size is not None else config.patch_size _A = ( model_args.encoder_stride if model_args.encoder_stride is not None else config.encoder_stride ) config.update( { "image_size": model_args.image_size, "patch_size": model_args.patch_size, "encoder_stride": model_args.encoder_stride, } ) # create image processor if model_args.image_processor_name: _A = AutoImageProcessor.from_pretrained(model_args.image_processor_name , **__lowercase ) elif model_args.model_name_or_path: _A = AutoImageProcessor.from_pretrained(model_args.model_name_or_path , **__lowercase ) else: _A = { conf.model_type: image_processor_class for conf, image_processor_class in IMAGE_PROCESSOR_MAPPING.items() } _A = IMAGE_PROCESSOR_TYPES[model_args.model_type]() # create model if model_args.model_name_or_path: _A = AutoModelForMaskedImageModeling.from_pretrained( model_args.model_name_or_path , from_tf=bool(".ckpt" in model_args.model_name_or_path ) , config=__lowercase , cache_dir=model_args.cache_dir , revision=model_args.model_revision , use_auth_token=True if model_args.use_auth_token else None , ) else: logger.info("Training new model from scratch" ) _A = AutoModelForMaskedImageModeling.from_config(__lowercase ) if training_args.do_train: _A = ds["train"].column_names else: _A = ds["validation"].column_names if data_args.image_column_name is not None: _A = data_args.image_column_name elif "image" in column_names: _A = "image" elif "img" in column_names: _A = "img" else: _A = column_names[0] # transformations as done in original SimMIM paper # source: https://github.com/microsoft/SimMIM/blob/main/data/data_simmim.py _A = Compose( [ Lambda(lambda __lowercase : img.convert("RGB" ) if img.mode != "RGB" else img ), RandomResizedCrop(model_args.image_size , scale=(0.67, 1.0) , ratio=(3.0 / 4.0, 4.0 / 3.0) ), RandomHorizontalFlip(), ToTensor(), Normalize(mean=image_processor.image_mean , std=image_processor.image_std ), ] ) # create mask generator _A = MaskGenerator( input_size=model_args.image_size , mask_patch_size=data_args.mask_patch_size , model_patch_size=model_args.patch_size , mask_ratio=data_args.mask_ratio , ) def preprocess_images(__lowercase ): _A = [transforms(__lowercase ) for image in examples[image_column_name]] _A = [mask_generator() for i in range(len(examples[image_column_name] ) )] return examples if training_args.do_train: if "train" not in ds: raise ValueError("--do_train requires a train dataset" ) if data_args.max_train_samples is not None: _A = ds["train"].shuffle(seed=training_args.seed ).select(range(data_args.max_train_samples ) ) # Set the training transforms ds["train"].set_transform(__lowercase ) if training_args.do_eval: if "validation" not in ds: raise ValueError("--do_eval requires a validation dataset" ) if data_args.max_eval_samples is not None: _A = ( ds["validation"].shuffle(seed=training_args.seed ).select(range(data_args.max_eval_samples ) ) ) # Set the validation transforms ds["validation"].set_transform(__lowercase ) # Initialize our trainer _A = Trainer( model=__lowercase , args=__lowercase , train_dataset=ds["train"] if training_args.do_train else None , eval_dataset=ds["validation"] if training_args.do_eval else None , tokenizer=__lowercase , data_collator=__lowercase , ) # Training if training_args.do_train: _A = None if training_args.resume_from_checkpoint is not None: _A = training_args.resume_from_checkpoint elif last_checkpoint is not None: _A = last_checkpoint _A = trainer.train(resume_from_checkpoint=__lowercase ) trainer.save_model() trainer.log_metrics("train" , train_result.metrics ) trainer.save_metrics("train" , train_result.metrics ) trainer.save_state() # Evaluation if training_args.do_eval: _A = trainer.evaluate() trainer.log_metrics("eval" , __lowercase ) trainer.save_metrics("eval" , __lowercase ) # Write model card and (optionally) push to hub _A = { "finetuned_from": model_args.model_name_or_path, "tasks": "masked-image-modeling", "dataset": data_args.dataset_name, "tags": ["masked-image-modeling"], } if training_args.push_to_hub: trainer.push_to_hub(**__lowercase ) else: trainer.create_model_card(**__lowercase ) if __name__ == "__main__": main()
79
import numpy as np def UpperCAmelCase ( a_ , a_ , a_ = 1E-12 , a_ = 1_0_0 , ) -> tuple[float, np.ndarray]: """simple docstring""" assert np.shape(a_ )[0] == np.shape(a_ )[1] # Ensure proper dimensionality. assert np.shape(a_ )[0] == np.shape(a_ )[0] # Ensure inputs are either both complex or both real assert np.iscomplexobj(a_ ) == np.iscomplexobj(a_ ) __A = np.iscomplexobj(a_ ) if is_complex: # Ensure complex input_matrix is Hermitian assert np.array_equal(a_ , input_matrix.conj().T ) # Set convergence to False. Will define convergence when we exceed max_iterations # or when we have small changes from one iteration to next. __A = False __A = 0 __A = 0 __A = 1E12 while not convergence: # Multiple matrix by the vector. __A = np.dot(a_ , a_ ) # Normalize the resulting output vector. __A = w / np.linalg.norm(a_ ) # Find rayleigh quotient # (faster than usual b/c we know vector is normalized already) __A = vector.conj().T if is_complex else vector.T __A = np.dot(a_ , np.dot(a_ , a_ ) ) # Check convergence. __A = np.abs(lambda_ - lambda_previous ) / lambda_ iterations += 1 if error <= error_tol or iterations >= max_iterations: __A = True __A = lambda_ if is_complex: __A = np.real(lambda_ ) return lambda_, vector def UpperCAmelCase ( ) -> None: """simple docstring""" __A = np.array([[4_1, 4, 2_0], [4, 2_6, 3_0], [2_0, 3_0, 5_0]] ) __A = np.array([4_1, 4, 2_0] ) __A = real_input_matrix.astype(np.complexaaa ) __A = np.triu(1J * complex_input_matrix , 1 ) complex_input_matrix += imag_matrix complex_input_matrix += -1 * imag_matrix.T __A = np.array([4_1, 4, 2_0] ).astype(np.complexaaa ) for problem_type in ["real", "complex"]: if problem_type == "real": __A = real_input_matrix __A = real_vector elif problem_type == "complex": __A = complex_input_matrix __A = complex_vector # Our implementation. __A , __A = power_iteration(a_ , a_ ) # Numpy implementation. # Get eigenvalues and eigenvectors using built-in numpy # eigh (eigh used for symmetric or hermetian matrices). __A , __A = np.linalg.eigh(a_ ) # Last eigenvalue is the maximum one. __A = eigen_values[-1] # Last column in this matrix is eigenvector corresponding to largest eigenvalue. __A = eigen_vectors[:, -1] # Check our implementation and numpy gives close answers. assert np.abs(eigen_value - eigen_value_max ) <= 1E-6 # Take absolute values element wise of each eigenvector. # as they are only unique to a minus sign. assert np.linalg.norm(np.abs(a_ ) - np.abs(a_ ) ) <= 1E-6 if __name__ == "__main__": import doctest doctest.testmod() test_power_iteration()
15
0
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available a__ : Any = { 'configuration_bloom': ['BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BloomConfig', 'BloomOnnxConfig'], } try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Any = ['BloomTokenizerFast'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: a__ : Optional[Any] = [ 'BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST', 'BloomForCausalLM', 'BloomModel', 'BloomPreTrainedModel', 'BloomForSequenceClassification', 'BloomForTokenClassification', 'BloomForQuestionAnswering', ] if TYPE_CHECKING: from .configuration_bloom import BLOOM_PRETRAINED_CONFIG_ARCHIVE_MAP, BloomConfig, BloomOnnxConfig try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_bloom_fast import BloomTokenizerFast try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_bloom import ( BLOOM_PRETRAINED_MODEL_ARCHIVE_LIST, BloomForCausalLM, BloomForQuestionAnswering, BloomForSequenceClassification, BloomForTokenClassification, BloomModel, BloomPreTrainedModel, ) else: import sys a__ : Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
80
from typing import Optional, Tuple, Union import tensorflow as tf from ...activations_tf import ACTaFN from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward from ...modeling_tf_outputs import ( TFBaseModelOutputWithNoAttention, TFBaseModelOutputWithPoolingAndNoAttention, TFSequenceClassifierOutput, ) from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs from ...tf_utils import shape_list from ...utils import logging from .configuration_regnet import RegNetConfig SCREAMING_SNAKE_CASE :str = logging.get_logger(__name__) # General docstring SCREAMING_SNAKE_CASE :str = 'RegNetConfig' # Base docstring SCREAMING_SNAKE_CASE :List[str] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Union[str, Any] = [1, 1088, 7, 7] # Image classification docstring SCREAMING_SNAKE_CASE :Optional[int] = 'facebook/regnet-y-040' SCREAMING_SNAKE_CASE :Any = 'tabby, tabby cat' SCREAMING_SNAKE_CASE :Optional[int] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : int ,A : int = 3 ,A : int = 1 ,A : int = 1 ,A : Optional[str] = "relu" ,**A : Dict ,): super().__init__(**A ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb __A = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=A ,strides=A ,padding="VALID" ,groups=A ,use_bias=A ,name="convolution" ,) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) __A = ACTaFN[activation] if activation is not None else tf.identity def UpperCamelCase_ ( self : List[Any] ,A : Any ): __A = self.convolution(self.padding(A ) ) __A = self.normalization(A ) __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Tuple ,A : RegNetConfig ,**A : str ): super().__init__(**A ) __A = config.num_channels __A = TFRegNetConvLayer( out_channels=config.embedding_size ,kernel_size=3 ,stride=2 ,activation=config.hidden_act ,name="embedder" ,) def UpperCamelCase_ ( self : Tuple ,A : Optional[Any] ): __A = shape_list(A )[1] if tf.executing_eagerly() and num_channels != self.num_channels: raise ValueError( "Make sure that the channel dimension of the pixel values match with the one set in the configuration." ) # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format. # So change the input format from `NCHW` to `NHWC`. # shape = (batch_size, in_height, in_width, in_channels=num_channels) __A = tf.transpose(A ,perm=(0, 2, 3, 1) ) __A = self.embedder(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Optional[int] ,A : int ,A : int = 2 ,**A : Tuple ): super().__init__(**A ) __A = tf.keras.layers.ConvaD( filters=A ,kernel_size=1 ,strides=A ,use_bias=A ,name="convolution" ) __A = tf.keras.layers.BatchNormalization(epsilon=1E-5 ,momentum=0.9 ,name="normalization" ) def UpperCamelCase_ ( self : Union[str, Any] ,A : tf.Tensor ,A : bool = False ): return self.normalization(self.convolution(A ) ,training=A ) class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Dict ,A : int ,A : int ,**A : str ): super().__init__(**A ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) __A = [ tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="relu" ,name="attention.0" ), tf.keras.layers.ConvaD(filters=A ,kernel_size=1 ,activation="sigmoid" ,name="attention.2" ), ] def UpperCamelCase_ ( self : Dict ,A : List[Any] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] __A = self.pooler(A ) for layer_module in self.attention: __A = layer_module(A ) __A = hidden_state * pooled return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : Optional[int] ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) # `self.layers` instead of `self.layer` because that is a reserved argument. __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.2" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : int ,A : Optional[int] ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,A : int ,A : int ,A : int = 1 ,**A : str ): super().__init__(**A ) __A = in_channels != out_channels or stride != 1 __A = max(1 ,out_channels // config.groups_width ) __A = ( TFRegNetShortCut(A ,stride=A ,name="shortcut" ) if should_apply_shortcut else tf.keras.layers.Activation("linear" ,name="shortcut" ) ) __A = [ TFRegNetConvLayer(A ,kernel_size=1 ,activation=config.hidden_act ,name="layer.0" ), TFRegNetConvLayer( A ,stride=A ,groups=A ,activation=config.hidden_act ,name="layer.1" ), TFRegNetSELayer(A ,reduced_channels=int(round(in_channels / 4 ) ) ,name="layer.2" ), TFRegNetConvLayer(A ,kernel_size=1 ,activation=A ,name="layer.3" ), ] __A = ACTaFN[config.hidden_act] def UpperCamelCase_ ( self : Dict ,A : Any ): __A = hidden_state for layer_module in self.layers: __A = layer_module(A ) __A = self.shortcut(A ) hidden_state += residual __A = self.activation(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : List[str] ,A : RegNetConfig ,A : int ,A : int ,A : int = 2 ,A : int = 2 ,**A : Optional[int] ): super().__init__(**A ) __A = TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer __A = [ # downsampling is done in the first layer with stride of 2 layer(A ,A ,A ,stride=A ,name="layers.0" ), *[layer(A ,A ,A ,name=f'''layers.{i+1}''' ) for i in range(depth - 1 )], ] def UpperCamelCase_ ( self : Any ,A : List[str] ): for layer_module in self.layers: __A = layer_module(A ) return hidden_state class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' def __init__( self : Any ,A : RegNetConfig ,**A : List[str] ): super().__init__(**A ) __A = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( A ,config.embedding_size ,config.hidden_sizes[0] ,stride=2 if config.downsample_in_first_stage else 1 ,depth=config.depths[0] ,name="stages.0" ,) ) __A = zip(config.hidden_sizes ,config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(A ,config.depths[1:] ) ): self.stages.append(TFRegNetStage(A ,A ,A ,depth=A ,name=f'''stages.{i+1}''' ) ) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor ,A : bool = False ,A : bool = True ): __A = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: __A = hidden_states + (hidden_state,) __A = stage_module(A ) if output_hidden_states: __A = hidden_states + (hidden_state,) if not return_dict: return tuple(v for v in [hidden_state, hidden_states] if v is not None ) return TFBaseModelOutputWithNoAttention(last_hidden_state=A ,hidden_states=A ) @keras_serializable class UpperCAmelCase ( tf.keras.layers.Layer ): '''simple docstring''' snake_case_ = RegNetConfig def __init__( self : int ,A : Optional[int] ,**A : Dict ): super().__init__(**A ) __A = config __A = TFRegNetEmbeddings(A ,name="embedder" ) __A = TFRegNetEncoder(A ,name="encoder" ) __A = tf.keras.layers.GlobalAveragePoolingaD(keepdims=A ,name="pooler" ) @unpack_inputs def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : bool = False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.embedder(A ,training=A ) __A = self.encoder( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = encoder_outputs[0] __A = self.pooler(A ) # Change to NCHW output format have uniformity in the modules __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) __A = tf.transpose(A ,perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: __A = tuple([tf.transpose(A ,perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] ) if not return_dict: return (last_hidden_state, pooled_output) + encoder_outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=A ,pooler_output=A ,hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states ,) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' snake_case_ = RegNetConfig snake_case_ = "regnet" snake_case_ = "pixel_values" @property def UpperCamelCase_ ( self : Optional[Any] ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) ,dtype=tf.floataa )} SCREAMING_SNAKE_CASE :Dict = R'\n Parameters:\n This model is a Tensorflow\n [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n behavior.\n config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n Initializing with a config file does not load the weights associated with the model, only the\n configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n' SCREAMING_SNAKE_CASE :Dict = R'\n Args:\n pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n [`ConveNextImageProcessor.__call__`] for details.\n output_hidden_states (`bool`, *optional*):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n return_dict (`bool`, *optional*):\n Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n' @add_start_docstrings( "The bare RegNet model outputting raw features without any specific head on top." , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : List[Any] ,A : RegNetConfig ,*A : List[Any] ,**A : str ): super().__init__(A ,*A ,**A ) __A = TFRegNetMainLayer(A ,name="regnet" ) @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC ,output_type=A ,config_class=_CONFIG_FOR_DOC ,modality="vision" ,expected_output=_EXPECTED_OUTPUT_SHAPE ,) def UpperCamelCase_ ( self : Tuple ,A : tf.Tensor ,A : Optional[bool] = None ,A : Optional[bool] = None ,A : int=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( pixel_values=A ,output_hidden_states=A ,return_dict=A ,training=A ,) if not return_dict: return (outputs[0],) + outputs[1:] return TFBaseModelOutputWithPoolingAndNoAttention( last_hidden_state=outputs.last_hidden_state ,pooler_output=outputs.pooler_output ,hidden_states=outputs.hidden_states ,) @add_start_docstrings( "\n RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n ImageNet.\n " , __SCREAMING_SNAKE_CASE , ) class UpperCAmelCase ( __SCREAMING_SNAKE_CASE , __SCREAMING_SNAKE_CASE ): '''simple docstring''' def __init__( self : Optional[int] ,A : RegNetConfig ,*A : str ,**A : Tuple ): super().__init__(A ,*A ,**A ) __A = config.num_labels __A = TFRegNetMainLayer(A ,name="regnet" ) # classification head __A = [ tf.keras.layers.Flatten(), tf.keras.layers.Dense(config.num_labels ,name="classifier.1" ) if config.num_labels > 0 else tf.identity, ] @unpack_inputs @add_start_docstrings_to_model_forward(A ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT ,output_type=A ,config_class=_CONFIG_FOR_DOC ,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,) def UpperCamelCase_ ( self : List[str] ,A : tf.Tensor = None ,A : tf.Tensor = None ,A : bool = None ,A : bool = None ,A : Union[str, Any]=False ,): __A = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) __A = return_dict if return_dict is not None else self.config.use_return_dict __A = self.regnet( A ,output_hidden_states=A ,return_dict=A ,training=A ) __A = outputs.pooler_output if return_dict else outputs[1] __A = self.classifier[0](A ) __A = self.classifier[1](A ) __A = None if labels is None else self.hf_compute_loss(labels=A ,logits=A ) if not return_dict: __A = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=A ,logits=A ,hidden_states=outputs.hidden_states )
15
0