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
'''simple docstring''' lowerCAmelCase: Optional[int] = [4, 1, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowerCAmelCase: List[str] = [3, 7, 7, 4, 2, 6, 4, 1, 5, 3, 7, 5] lowerCAmelCase: Tuple = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', } def lowerCamelCase__ ( _A , _A , _A ): assert len(str(_A ) ) > 2, "year should be in YYYY format" assert 1 <= month <= 12, "month should be between 1 to 12" assert 1 <= day <= 31, "day should be between 1 to 31" # Doomsday algorithm: a : List[str] = year // 100 a : Dict = (5 * (century % 4) + 2) % 7 a : str = year % 100 a : Union[str, Any] = centurian % 12 a : Dict = ( (centurian // 12) + centurian_m + (centurian_m // 4) + century_anchor ) % 7 a : List[Any] = ( DOOMSDAY_NOT_LEAP[month - 1] if (year % 4 != 0) or (centurian == 0 and (year % 400) == 0) else DOOMSDAY_LEAP[month - 1] ) a : Tuple = (dooms_day + day - day_anchor) % 7 return WEEK_DAY_NAMES[week_day] if __name__ == "__main__": import doctest doctest.testmod()
297
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( _A , _A , _A ): if isinstance(_A , torch.Tensor ): return image elif isinstance(_A , PIL.Image.Image ): a : Any = [image] if isinstance(image[0] , PIL.Image.Image ): a : List[str] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] a : int = np.concatenate(_A , axis=0 ) a : int = np.array(_A ).astype(np.floataa ) / 255.0 a : str = image.transpose(0 , 3 , 1 , 2 ) a : str = 2.0 * image - 1.0 a : Optional[int] = torch.from_numpy(_A ) elif isinstance(image[0] , torch.Tensor ): a : Optional[Any] = torch.cat(_A , dim=0 ) return image def lowerCamelCase__ ( _A , _A , _A , _A=0.9995 ): if not isinstance(_A , np.ndarray ): a : Dict = True a : Optional[Any] = va.device a : Optional[int] = va.cpu().numpy() a : Union[str, Any] = va.cpu().numpy() a : Any = np.sum(va * va / (np.linalg.norm(_A ) * np.linalg.norm(_A )) ) if np.abs(_A ) > DOT_THRESHOLD: a : Any = (1 - t) * va + t * va else: a : Any = np.arccos(_A ) a : Tuple = np.sin(_A ) a : Optional[Any] = theta_a * t a : List[Any] = np.sin(_A ) a : Dict = np.sin(theta_a - theta_t ) / sin_theta_a a : int = sin_theta_t / sin_theta_a a : Any = sa * va + sa * va if inputs_are_torch: a : Dict = torch.from_numpy(_A ).to(_A ) return va def lowerCamelCase__ ( _A , _A ): a : Optional[int] = F.normalize(_A , dim=-1 ) a : str = F.normalize(_A , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( _A , _A ): for param in model.parameters(): a : int = value class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : AutoencoderKL , __snake_case : CLIPTextModel , __snake_case : CLIPModel , __snake_case : CLIPTokenizer , __snake_case : UNetaDConditionModel , __snake_case : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , __snake_case : CLIPFeatureExtractor , __snake_case : List[str]=None , __snake_case : List[str]=None , __snake_case : List[Any]=None , ): super().__init__() self.register_modules( vae=__snake_case , text_encoder=__snake_case , clip_model=__snake_case , tokenizer=__snake_case , unet=__snake_case , scheduler=__snake_case , feature_extractor=__snake_case , coca_model=__snake_case , coca_tokenizer=__snake_case , coca_transform=__snake_case , ) a : Optional[Any] = ( feature_extractor.size if isinstance(feature_extractor.size , __snake_case ) else feature_extractor.size['shortest_edge'] ) a : Optional[int] = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , __snake_case ) set_requires_grad(self.clip_model , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory a : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__snake_case ) def lowercase_ ( self : Union[str, Any] ): self.enable_attention_slicing(__snake_case ) def lowercase_ ( self : Optional[Any] ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : Tuple ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : int ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : Union[str, Any] ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : int , __snake_case : Dict , __snake_case : str , __snake_case : Optional[int] ): # get the original timestep using init_timestep a : Optional[Any] = min(int(num_inference_steps * strength ) , __snake_case ) a : Union[str, Any] = max(num_inference_steps - init_timestep , 0 ) a : List[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase_ ( self : Dict , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Any , __snake_case : Optional[Any]=None ): if not isinstance(__snake_case , torch.Tensor ): raise ValueError(F"""`image` has to be of type `torch.Tensor` but is {type(__snake_case )}""" ) a : Optional[Any] = image.to(device=__snake_case , dtype=__snake_case ) if isinstance(__snake_case , __snake_case ): a : Optional[int] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__snake_case ) ] a : Optional[Any] = torch.cat(__snake_case , dim=0 ) else: a : Union[str, Any] = self.vae.encode(__snake_case ).latent_dist.sample(__snake_case ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : List[str] = 0.18215 * init_latents a : str = init_latents.repeat_interleave(__snake_case , dim=0 ) a : Dict = randn_tensor(init_latents.shape , generator=__snake_case , device=__snake_case , dtype=__snake_case ) # get latents a : Dict = self.scheduler.add_noise(__snake_case , __snake_case , __snake_case ) a : int = init_latents return latents def lowercase_ ( self : List[str] , __snake_case : Dict ): a : List[Any] = self.coca_transform(__snake_case ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): a : Optional[Any] = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) a : Union[str, Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('<end_of_text>' )[0].replace('<start_of_text>' , '' ).rstrip(' .,' ) def lowercase_ ( self : Tuple , __snake_case : Any , __snake_case : Optional[Any] ): a : List[Any] = self.feature_extractor.preprocess(__snake_case ) a : Optional[Any] = torch.from_numpy(clip_image_input['pixel_values'][0] ).unsqueeze(0 ).to(self.device ).half() a : int = self.clip_model.get_image_features(__snake_case ) a : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : Tuple = image_embeddings_clip.repeat_interleave(__snake_case , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowercase_ ( self : Tuple , __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : List[Any] , ): a : Optional[Any] = latents.detach().requires_grad_() a : List[Any] = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : Any = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): a : int = self.scheduler.alphas_cumprod[timestep] a : Any = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf a : List[str] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 a : Tuple = torch.sqrt(__snake_case ) a : str = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , __snake_case ): a : List[Any] = self.scheduler.sigmas[index] a : Optional[int] = latents - sigma * noise_pred else: raise ValueError(F"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Union[str, Any] = 1 / 0.18215 * sample a : str = self.vae.decode(__snake_case ).sample a : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) a : Tuple = transforms.Resize(self.feature_extractor_size )(__snake_case ) a : List[str] = self.normalize(__snake_case ).to(latents.dtype ) a : List[str] = self.clip_model.get_image_features(__snake_case ) a : Tuple = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : int = spherical_dist_loss(__snake_case , __snake_case ).mean() * clip_guidance_scale a : List[str] = -torch.autograd.grad(__snake_case , __snake_case )[0] if isinstance(self.scheduler , __snake_case ): a : List[Any] = latents.detach() + grads * (sigma**2) a : Optional[int] = noise_pred_original else: a : List[Any] = noise_pred_original - torch.sqrt(__snake_case ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Optional[int] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Optional[str] = None , __snake_case : Optional[str] = None , __snake_case : Optional[int] = 5_12 , __snake_case : Optional[int] = 5_12 , __snake_case : float = 0.6 , __snake_case : Optional[int] = 50 , __snake_case : Optional[float] = 7.5 , __snake_case : Optional[int] = 1 , __snake_case : float = 0.0 , __snake_case : Optional[float] = 1_00 , __snake_case : Optional[torch.Generator] = None , __snake_case : Optional[str] = "pil" , __snake_case : bool = True , __snake_case : float = 0.8 , __snake_case : float = 0.1 , __snake_case : float = 0.1 , ): if isinstance(__snake_case , __snake_case ) and len(__snake_case ) != batch_size: raise ValueError(F"""You have passed {batch_size} batch_size, but only {len(__snake_case )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(__snake_case , torch.Generator ) and batch_size > 1: a : Dict = [generator] + [None] * (batch_size - 1) a : Any = [ ('model', self.coca_model is None), ('tokenizer', self.coca_tokenizer is None), ('transform', self.coca_transform is None), ] a : List[str] = [x[0] for x in coca_is_none if x[1]] a : List[str] = ', '.join(__snake_case ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(__snake_case ): raise ValueError( F"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" F"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : int = self.get_image_description(__snake_case ) if style_prompt is None: if len(__snake_case ): raise ValueError( F"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" F""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : Union[str, Any] = self.get_image_description(__snake_case ) # get prompt text embeddings for content and style a : Optional[Any] = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] a : Dict = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] a : Any = slerp(__snake_case , __snake_case , __snake_case ) # duplicate text embeddings for each generation per prompt a : Optional[Any] = text_embeddings.repeat_interleave(__snake_case , dim=0 ) # set timesteps a : int = 'offset' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) a : Any = {} if accepts_offset: a : Optional[Any] = 1 self.scheduler.set_timesteps(__snake_case , **__snake_case ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) a , a : Tuple = self.get_timesteps(__snake_case , __snake_case , self.device ) a : Optional[int] = timesteps[:1].repeat(__snake_case ) # Preprocess image a : Optional[Any] = preprocess(__snake_case , __snake_case , __snake_case ) a : List[Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : str = preprocess(__snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : Union[str, Any] = slerp(__snake_case , __snake_case , __snake_case ) if clip_guidance_scale > 0: a : Dict = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : int = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : List[str] = slerp( __snake_case , __snake_case , __snake_case ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. a : int = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: a : Any = content_text_input.input_ids.shape[-1] a : List[Any] = self.tokenizer([''] , padding='max_length' , max_length=__snake_case , return_tensors='pt' ) a : List[str] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt a : Dict = uncond_embeddings.repeat_interleave(__snake_case , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a : Any = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. a : List[str] = (batch_size, self.unet.config.in_channels, height // 8, width // 8) a : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps a : int = torch.randn(__snake_case , generator=__snake_case , device='cpu' , dtype=__snake_case ).to( self.device ) else: a : Optional[int] = torch.randn(__snake_case , generator=__snake_case , device=self.device , dtype=__snake_case ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) a : List[str] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler a : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a : Optional[Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a : Union[str, Any] = {} if accepts_eta: a : List[str] = eta # check if the scheduler accepts generator a : List[Any] = 'generator' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: a : Any = generator with self.progress_bar(total=__snake_case ): for i, t in enumerate(__snake_case ): # expand the latents if we are doing classifier free guidance a : Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a : Dict = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : List[Any] = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample # perform classifier free guidance if do_classifier_free_guidance: a , a : List[str] = noise_pred.chunk(2 ) a : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: a : Optional[Any] = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) a , a : Union[str, Any] = self.cond_fn( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ) # compute the previous noisy sample x_t -> x_t-1 a : Any = self.scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Tuple = 1 / 0.18215 * latents a : Optional[int] = self.vae.decode(__snake_case ).sample a : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) a : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a : str = self.numpy_to_pil(__snake_case ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=__snake_case , nsfw_content_detected=__snake_case )
297
1
'''simple docstring''' from __future__ import annotations import math class a__: def __init__( self : List[str] , __snake_case : int ): a : str = size # approximate the overall size of segment tree with given value a : Optional[int] = [0 for i in range(0 , 4 * size )] # create array to store lazy update a : Any = [0 for i in range(0 , 4 * size )] a : Dict = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowercase_ ( self : int , __snake_case : int ): return idx * 2 def lowercase_ ( self : Dict , __snake_case : int ): return idx * 2 + 1 def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : list[int] ): if left_element == right_element: a : Tuple = a[left_element - 1] else: a : Tuple = (left_element + right_element) // 2 self.build(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case ) self.build(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case ) a : Union[str, Any] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : int = self.lazy[idx] a : Union[str, Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : int = self.lazy[idx] a : Tuple = True a : Optional[Any] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: a : int = val if left_element != right_element: a : int = val a : Dict = val a : List[str] = True a : List[str] = True return True a : Tuple = (left_element + right_element) // 2 self.update(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) self.update(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case , __snake_case ) a : Optional[int] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) return True def lowercase_ ( self : Union[str, Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : str = self.lazy[idx] a : Optional[Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : Union[str, Any] = self.lazy[idx] a : Dict = True a : int = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] a : Dict = (left_element + right_element) // 2 a : Optional[int] = self.query(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.query(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case ) return max(__snake_case , __snake_case ) def __str__( self : Any ): return str([self.query(1 , 1 , self.size , __snake_case , __snake_case ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] lowerCAmelCase: int = 1_5 lowerCAmelCase: Optional[int] = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A , _A , _A , _A , ): a : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: a : Union[str, Any] = 1 - (matter_density + radiation_density + dark_energy) a : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) a : int = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation lowerCAmelCase: Optional[Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
297
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase: Union[str, Any] = {'configuration_wavlm': ['WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP', 'WavLMConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Optional[Any] = [ 'WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST', 'WavLMForAudioFrameClassification', 'WavLMForCTC', 'WavLMForSequenceClassification', 'WavLMForXVector', 'WavLMModel', 'WavLMPreTrainedModel', ] if TYPE_CHECKING: from .configuration_wavlm import WAVLM_PRETRAINED_CONFIG_ARCHIVE_MAP, WavLMConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_wavlm import ( WAVLM_PRETRAINED_MODEL_ARCHIVE_LIST, WavLMForAudioFrameClassification, WavLMForCTC, WavLMForSequenceClassification, WavLMForXVector, WavLMModel, WavLMPreTrainedModel, ) else: import sys lowerCAmelCase: Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
'''simple docstring''' from __future__ import annotations import math class a__: def __init__( self : List[str] , __snake_case : int ): a : str = size # approximate the overall size of segment tree with given value a : Optional[int] = [0 for i in range(0 , 4 * size )] # create array to store lazy update a : Any = [0 for i in range(0 , 4 * size )] a : Dict = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowercase_ ( self : int , __snake_case : int ): return idx * 2 def lowercase_ ( self : Dict , __snake_case : int ): return idx * 2 + 1 def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : list[int] ): if left_element == right_element: a : Tuple = a[left_element - 1] else: a : Tuple = (left_element + right_element) // 2 self.build(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case ) self.build(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case ) a : Union[str, Any] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : int = self.lazy[idx] a : Union[str, Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : int = self.lazy[idx] a : Tuple = True a : Optional[Any] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: a : int = val if left_element != right_element: a : int = val a : Dict = val a : List[str] = True a : List[str] = True return True a : Tuple = (left_element + right_element) // 2 self.update(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) self.update(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case , __snake_case ) a : Optional[int] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) return True def lowercase_ ( self : Union[str, Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : str = self.lazy[idx] a : Optional[Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : Union[str, Any] = self.lazy[idx] a : Dict = True a : int = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] a : Dict = (left_element + right_element) // 2 a : Optional[int] = self.query(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.query(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case ) return max(__snake_case , __snake_case ) def __str__( self : Any ): return str([self.query(1 , 1 , self.size , __snake_case , __snake_case ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] lowerCAmelCase: int = 1_5 lowerCAmelCase: Optional[int] = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
297
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase: List[str] = logging.get_logger(__name__) lowerCAmelCase: List[str] = { 'MIT/ast-finetuned-audioset-10-10-0.4593': ( 'https://huggingface.co/MIT/ast-finetuned-audioset-10-10-0.4593/resolve/main/config.json' ), } class a__( lowerCamelCase__ ): lowercase__ = """audio-spectrogram-transformer""" def __init__( self : Optional[Any] , __snake_case : Tuple=7_68 , __snake_case : str=12 , __snake_case : int=12 , __snake_case : Any=30_72 , __snake_case : Tuple="gelu" , __snake_case : Tuple=0.0 , __snake_case : Dict=0.0 , __snake_case : Optional[int]=0.02 , __snake_case : Dict=1e-1_2 , __snake_case : Union[str, Any]=16 , __snake_case : Optional[Any]=True , __snake_case : Union[str, Any]=10 , __snake_case : Tuple=10 , __snake_case : Any=10_24 , __snake_case : Tuple=1_28 , **__snake_case : Any , ): super().__init__(**__snake_case ) a : Dict = hidden_size a : List[Any] = num_hidden_layers a : Optional[Any] = num_attention_heads a : Tuple = intermediate_size a : str = hidden_act a : str = hidden_dropout_prob a : Any = attention_probs_dropout_prob a : Tuple = initializer_range a : List[str] = layer_norm_eps a : int = patch_size a : Dict = qkv_bias a : Union[str, Any] = frequency_stride a : Dict = time_stride a : int = max_length a : Union[str, Any] = num_mel_bins
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A ): while second != 0: a : Union[str, Any] = first & second first ^= second a : Tuple = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase: Optional[int] = int(input('Enter the first number: ').strip()) lowerCAmelCase: Union[str, Any] = int(input('Enter the second number: ').strip()) print(F"{add(first, second) = }")
297
1
'''simple docstring''' from dataclasses import dataclass, field from typing import ClassVar, Dict from ..features import Features, Value from .base import TaskTemplate @dataclass(frozen=lowerCamelCase__ ) class a__( lowerCamelCase__ ): lowercase__ = field(default="""language-modeling""" , metadata={"""include_in_asdict_even_if_is_default""": True} ) lowercase__ = Features({"""text""": Value("""string""" )} ) lowercase__ = Features({} ) lowercase__ = "text" @property def lowercase_ ( self : Any ): return {self.text_column: "text"}
297
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ ( _A , _A ): assert isinstance(_A , _A ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Optional[int] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , keep_in_memory=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Tuple = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Dict = features.copy() if features else default_expected_features a : Union[str, Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Tuple = tmp_path / 'cache' a : Optional[Any] = {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} a : Optional[int] = features.copy() if features else default_expected_features a : Dict = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Optional[int] = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCamelCase__ ( _A , _A ): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} a : Dict = {'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} a : int = features.copy() a : List[Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Dict = tmp_path / 'cache' a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[str] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , split=_A ).read() _check_json_dataset(_A , _A ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def lowerCamelCase__ ( _A , _A , _A ): if issubclass(_A , _A ): a : Optional[int] = jsonl_path elif issubclass(_A , _A ): a : Optional[int] = [jsonl_path] a : List[str] = tmp_path / 'cache' a : Dict = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) def lowerCamelCase__ ( _A , _A , _A=("train",) ): assert isinstance(_A , _A ) for split in splits: a : str = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : Any = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : int = JsonDatasetReader({'train': jsonl_path} , cache_dir=_A , keep_in_memory=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[Any] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = features.copy() if features else default_expected_features a : Any = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : List[str] = JsonDatasetReader({'train': jsonl_path} , features=_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): if split: a : Any = {split: jsonl_path} else: a : List[Any] = 'train' a : List[str] = {'train': jsonl_path, 'test': jsonl_path} a : List[Any] = tmp_path / 'cache' a : str = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase__ ( _A ): return json.load(_A ) def lowerCamelCase__ ( _A ): return [json.loads(_A ) for line in buffer] class a__: @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : Tuple , __snake_case : int , __snake_case : Optional[int] , __snake_case : Any ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case ).write() buffer.seek(0 ) a : List[str] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Tuple , __snake_case : Tuple , __snake_case : Any , __snake_case : Any , __snake_case : List[str] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : List[Any] , __snake_case : Any , __snake_case : Optional[int] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : List[Any] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Optional[int] , __snake_case : Any , __snake_case : str , __snake_case : int , __snake_case : List[Any] , __snake_case : Dict ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 def lowercase_ ( self : List[str] , __snake_case : str ): with pytest.raises(__snake_case ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def lowercase_ ( self : Tuple , __snake_case : Dict , __snake_case : List[Any] , __snake_case : int , __snake_case : List[str] , __snake_case : Optional[int] ): a : Tuple = tmp_path_factory.mktemp('data' ) / F"""test.json.{extension}""" a : List[Any] = str(shared_datadir / F"""test_file.json.{extension}""" ) JsonDatasetWriter(__snake_case , __snake_case , compression=__snake_case ).write() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() assert exported_content == original_content
297
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase: int = {'configuration_vit_msn': ['VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'ViTMSNConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[str] = [ 'VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST', 'ViTMSNModel', 'ViTMSNForImageClassification', 'ViTMSNPreTrainedModel', ] if TYPE_CHECKING: from .configuration_vit_msn import VIT_MSN_PRETRAINED_CONFIG_ARCHIVE_MAP, ViTMSNConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_vit_msn import ( VIT_MSN_PRETRAINED_MODEL_ARCHIVE_LIST, ViTMSNForImageClassification, ViTMSNModel, ViTMSNPreTrainedModel, ) else: import sys lowerCAmelCase: Dict = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCamelCase__ ( _A = "laptop" ): a : Any = f"""https://www.amazon.in/laptop/s?k={product}""" a : Tuple = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5', } a : Any = BeautifulSoup(requests.get(_A , headers=_A ).text ) # Initialize a Pandas dataframe with the column titles a : Any = DataFrame( columns=[ 'Product Title', 'Product Link', 'Current Price of the product', 'Product Rating', 'MRP of the product', 'Discount', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( 'div' , attrs={'class': 's-result-item', 'data-component-type': 's-search-result'} , ) , soup.find_all('div' , attrs={'class': 'a-row a-size-base a-color-base'} ) , ): try: a : Optional[int] = item.ha.text a : str = 'https://www.amazon.in/' + item.ha.a['href'] a : List[str] = item.find('span' , attrs={'class': 'a-offscreen'} ).text try: a : Optional[Any] = item.find('span' , attrs={'class': 'a-icon-alt'} ).text except AttributeError: a : Union[str, Any] = 'Not available' try: a : str = ( '₹' + item.find( 'span' , attrs={'class': 'a-price a-text-price'} ).text.split('₹' )[1] ) except AttributeError: a : int = '' try: a : Union[str, Any] = float( ( ( float(product_mrp.strip('₹' ).replace(',' , '' ) ) - float(product_price.strip('₹' ).replace(',' , '' ) ) ) / float(product_mrp.strip('₹' ).replace(',' , '' ) ) ) * 100 ) except ValueError: a : Any = float('nan' ) except AttributeError: pass a : Any = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] a : Any = ' ' a : List[str] = ' ' data_frame.index += 1 return data_frame if __name__ == "__main__": lowerCAmelCase: str = 'headphones' get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
297
1
'''simple docstring''' import os from shutil import copyfile from typing import Any, Dict, List, Optional, Tuple import sentencepiece as spm from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase: Optional[int] = logging.get_logger(__name__) lowerCAmelCase: Tuple = '▁' lowerCAmelCase: Union[str, Any] = {'vocab_file': 'spiece.model'} lowerCAmelCase: Union[str, Any] = { 'vocab_file': { 'google/reformer-crime-and-punishment': ( 'https://huggingface.co/google/reformer-crime-and-punishment/resolve/main/spiece.model' ) } } lowerCAmelCase: str = { 'google/reformer-crime-and-punishment': 5_2_4_2_8_8, } class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] def __init__( self : Any , __snake_case : Optional[int] , __snake_case : str="</s>" , __snake_case : List[str]="<unk>" , __snake_case : Tuple=[] , __snake_case : Optional[Dict[str, Any]] = None , **__snake_case : Optional[int] , ): a : Tuple = {} if sp_model_kwargs is None else sp_model_kwargs super().__init__( eos_token=__snake_case , unk_token=__snake_case , additional_special_tokens=__snake_case , sp_model_kwargs=self.sp_model_kwargs , **__snake_case , ) a : Union[str, Any] = vocab_file a : Any = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(__snake_case ) @property def lowercase_ ( self : Dict ): return self.sp_model.get_piece_size() def lowercase_ ( self : Union[str, Any] ): a : int = {self.convert_ids_to_tokens(__snake_case ): i for i in range(self.vocab_size )} vocab.update(self.added_tokens_encoder ) return vocab def __getstate__( self : Union[str, Any] ): a : int = self.__dict__.copy() a : Optional[Any] = None return state def __setstate__( self : List[Any] , __snake_case : Optional[int] ): a : Union[str, Any] = d # for backward compatibility if not hasattr(self , 'sp_model_kwargs' ): a : Optional[Any] = {} a : Union[str, Any] = spm.SentencePieceProcessor(**self.sp_model_kwargs ) self.sp_model.Load(self.vocab_file ) def lowercase_ ( self : Union[str, Any] , __snake_case : str ): return self.sp_model.encode(__snake_case , out_type=__snake_case ) def lowercase_ ( self : List[Any] , __snake_case : int ): return self.sp_model.piece_to_id(__snake_case ) def lowercase_ ( self : Dict , __snake_case : Tuple ): if index < self.sp_model.get_piece_size(): a : Union[str, Any] = self.sp_model.IdToPiece(__snake_case ) return token def lowercase_ ( self : Any , __snake_case : Optional[int] ): a : Optional[int] = [] a : int = '' for token in tokens: # make sure that special tokens are not decoded using sentencepiece model if token in self.all_special_tokens: out_string += self.sp_model.decode(__snake_case ) + token a : Optional[Any] = [] else: current_sub_tokens.append(__snake_case ) out_string += self.sp_model.decode(__snake_case ) return out_string.strip() def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] = None ): if not os.path.isdir(__snake_case ): logger.error(F"""Vocabulary path ({save_directory}) should be a directory""" ) return a : Dict = os.path.join( __snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) if os.path.abspath(self.vocab_file ) != os.path.abspath(__snake_case ) and os.path.isfile(self.vocab_file ): copyfile(self.vocab_file , __snake_case ) elif not os.path.isfile(self.vocab_file ): with open(__snake_case , 'wb' ) as fi: a : Dict = self.sp_model.serialized_model_proto() fi.write(__snake_case ) return (out_vocab_file,)
297
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = StableUnCLIPImgaImgPipeline lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase__ = frozenset([] ) def lowercase_ ( self : int ): a : Dict = 32 a : str = embedder_hidden_size # image encoding components a : List[Any] = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) a : Dict = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=__snake_case , projection_dim=__snake_case , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) a : Dict = StableUnCLIPImageNormalizer(embedding_dim=__snake_case ) a : Optional[int] = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) a : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) a : Tuple = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__snake_case , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) a : Union[str, Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__snake_case , layers_per_block=1 , upcast_attention=__snake_case , use_linear_projection=__snake_case , ) torch.manual_seed(0 ) a : List[Any] = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.00085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=__snake_case , steps_offset=1 , ) torch.manual_seed(0 ) a : List[str] = AutoencoderKL() a : str = { # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def lowercase_ ( self : Tuple , __snake_case : List[str] , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=True ): if str(__snake_case ).startswith('mps' ): a : Tuple = torch.manual_seed(__snake_case ) else: a : List[Any] = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) a : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__snake_case ) ).to(__snake_case ) if pil_image: a : Optional[Any] = input_image * 0.5 + 0.5 a : Optional[Any] = input_image.clamp(0 , 1 ) a : Dict = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() a : int = DiffusionPipeline.numpy_to_pil(__snake_case )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def lowercase_ ( self : Optional[Any] ): a : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a : Union[str, Any] = self.get_dummy_components() a : Any = StableUnCLIPImgaImgPipeline(**__snake_case ) a : Tuple = sd_pipe.to(__snake_case ) sd_pipe.set_progress_bar_config(disable=__snake_case ) a : Union[str, Any] = self.get_dummy_inputs(__snake_case ) inputs.update({'image_embeds': None} ) a : str = sd_pipe(**__snake_case ).images a : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) a : Optional[int] = np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase_ ( self : List[str] ): a : int = torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=__snake_case ) def lowercase_ ( self : int ): a : Optional[int] = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=__snake_case ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def lowercase_ ( self : Dict ): self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__snake_case ) @slow @require_torch_gpu class a__( unittest.TestCase ): def lowercase_ ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Optional[Any] ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Union[str, Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) a : Optional[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = torch.Generator(device='cpu' ).manual_seed(0 ) a : Optional[int] = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Optional[int] ): a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) a : Union[str, Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a : str = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Any ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) a : Optional[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = pipe( __snake_case , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) a : int = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
297
1
'''simple docstring''' import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class a__: def __init__( self : List[Any] , __snake_case : Union[str, Any] ): if isinstance(__snake_case , __snake_case ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden a : str = deepcopy(__snake_case ) elif os.path.exists(__snake_case ): with io.open(__snake_case , 'r' , encoding='utf-8' ) as f: a : Optional[Any] = json.load(__snake_case ) else: try: a : Any = baseaa.urlsafe_baadecode(__snake_case ).decode('utf-8' ) a : Union[str, Any] = json.loads(__snake_case ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) a : List[str] = config self.set_stage_and_offload() def lowercase_ ( self : List[str] ): # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. a : Dict = self.get_value('zero_optimization.stage' , -1 ) # offload a : str = False if self.is_zeroa() or self.is_zeroa(): a : Union[str, Any] = set(['cpu', 'nvme'] ) a : Optional[Any] = set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: a : List[str] = True def lowercase_ ( self : Optional[Any] , __snake_case : Optional[Any] ): a : str = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) a : Dict = nodes.pop() for node in nodes: a : List[Any] = config.get(__snake_case ) if config is None: return None, ds_key return config, ds_key def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] , __snake_case : Any=None ): a , a : List[Any] = self.find_config_node(__snake_case ) if config is None: return default return config.get(__snake_case , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Any] , __snake_case : List[str]=False ): a : Optional[Any] = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) for node in nodes: a : str = config a : Dict = config.get(__snake_case ) if config is None: if must_exist: raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] ): a : Union[str, Any] = self.get_value(__snake_case ) return False if value is None else bool(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str ): a : Optional[Any] = self.get_value(__snake_case ) return False if value is None else not bool(__snake_case ) def lowercase_ ( self : Optional[Any] ): return self._stage == 2 def lowercase_ ( self : Union[str, Any] ): return self._stage == 3 def lowercase_ ( self : str ): return self._offload class a__: def __init__( self : Tuple , __snake_case : str ): a : Optional[Any] = engine def lowercase_ ( self : Union[str, Any] , __snake_case : str , **__snake_case : Tuple ): # runs backpropagation and handles mixed precision self.engine.backward(__snake_case , **__snake_case ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : List[str] ): super().__init__(__snake_case , device_placement=__snake_case , scaler=__snake_case ) a : Optional[Any] = hasattr(self.optimizer , 'overflow' ) def lowercase_ ( self : Dict , __snake_case : Dict=None ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def lowercase_ ( self : Optional[Any] ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def lowercase_ ( self : Tuple ): if self.__has_overflow__: return self.optimizer.overflow return False class a__( lowerCamelCase__ ): def __init__( self : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any] ): super().__init__(__snake_case , __snake_case ) def lowercase_ ( self : Any ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class a__: def __init__( self : List[Any] , __snake_case : str , __snake_case : Dict=0.001 , __snake_case : Union[str, Any]=0 , **__snake_case : List[Any] ): a : Optional[Any] = params a : str = lr a : List[str] = weight_decay a : str = kwargs class a__: def __init__( self : str , __snake_case : Optional[Any] , __snake_case : List[str]=None , __snake_case : Tuple=0 , **__snake_case : Any ): a : Union[str, Any] = optimizer a : Any = total_num_steps a : List[str] = warmup_num_steps a : int = kwargs
297
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowerCAmelCase: Union[str, Any] = logging.get_logger(__name__) lowerCAmelCase: List[str] = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """t5""" lowercase__ = ["""past_key_values"""] lowercase__ = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : Union[str, Any] , __snake_case : int=3_21_28 , __snake_case : str=5_12 , __snake_case : Dict=64 , __snake_case : Optional[int]=20_48 , __snake_case : Tuple=6 , __snake_case : Any=None , __snake_case : Optional[int]=8 , __snake_case : str=32 , __snake_case : Union[str, Any]=1_28 , __snake_case : Optional[int]=0.1 , __snake_case : Dict=1e-6 , __snake_case : int=1.0 , __snake_case : Optional[int]="relu" , __snake_case : Any=True , __snake_case : List[str]=True , __snake_case : Union[str, Any]=0 , __snake_case : Dict=1 , **__snake_case : Optional[int] , ): a : Optional[int] = vocab_size a : Dict = d_model a : Union[str, Any] = d_kv a : Dict = d_ff a : Tuple = num_layers a : Dict = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a : int = num_heads a : str = relative_attention_num_buckets a : List[Any] = relative_attention_max_distance a : int = dropout_rate a : Tuple = layer_norm_epsilon a : str = initializer_factor a : List[Any] = feed_forward_proj a : Union[str, Any] = use_cache a : List[str] = self.feed_forward_proj.split('-' ) a : int = act_info[-1] a : Union[str, Any] = act_info[0] == 'gated' if len(__snake_case ) > 1 and act_info[0] != "gated" or len(__snake_case ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a : Optional[Any] = 'gelu_new' super().__init__( pad_token_id=__snake_case , eos_token_id=__snake_case , is_encoder_decoder=__snake_case , **__snake_case , ) class a__( lowerCamelCase__ ): @property def lowercase_ ( self : Optional[int] ): a : Dict = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: a : Dict = 'past_encoder_sequence + sequence' a : Dict = {0: 'batch'} a : Any = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: a : Optional[Any] = {0: 'batch', 1: 'decoder_sequence'} a : List[str] = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__snake_case , direction='inputs' ) return common_inputs @property def lowercase_ ( self : List[Any] ): return 13
297
1
'''simple docstring''' def lowerCamelCase__ ( _A , _A , _A , _A , _A , ): a : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: a : Union[str, Any] = 1 - (matter_density + radiation_density + dark_energy) a : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) a : int = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation lowerCAmelCase: Optional[Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
297
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def lowerCamelCase__ ( _A , _A ): if inductance <= 0: raise ValueError('Inductance cannot be 0 or negative' ) elif capacitance <= 0: raise ValueError('Capacitance cannot be 0 or negative' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
297
1
'''simple docstring''' from typing import List, Optional, Union import torch from ...models import UNetaDConditionModel, VQModel from ...pipelines import DiffusionPipeline from ...pipelines.pipeline_utils import ImagePipelineOutput from ...schedulers import DDPMScheduler from ...utils import ( is_accelerate_available, is_accelerate_version, logging, randn_tensor, replace_example_docstring, ) lowerCAmelCase: Any = logging.get_logger(__name__) # pylint: disable=invalid-name lowerCAmelCase: List[Any] = '\n Examples:\n ```py\n >>> from diffusers import KandinskyV22Pipeline, KandinskyV22PriorPipeline\n >>> import torch\n\n >>> pipe_prior = KandinskyV22PriorPipeline.from_pretrained("kandinsky-community/kandinsky-2-2-prior")\n >>> pipe_prior.to("cuda")\n >>> prompt = "red cat, 4k photo"\n >>> out = pipe_prior(prompt)\n >>> image_emb = out.image_embeds\n >>> zero_image_emb = out.negative_image_embeds\n >>> pipe = KandinskyV22Pipeline.from_pretrained("kandinsky-community/kandinsky-2-2-decoder")\n >>> pipe.to("cuda")\n >>> image = pipe(\n ... image_embeds=image_emb,\n ... negative_image_embeds=zero_image_emb,\n ... height=768,\n ... width=768,\n ... num_inference_steps=50,\n ... ).images\n >>> image[0].save("cat.png")\n ```\n' def lowerCamelCase__ ( _A , _A , _A=8 ): a : Tuple = height // scale_factor**2 if height % scale_factor**2 != 0: new_height += 1 a : Optional[int] = width // scale_factor**2 if width % scale_factor**2 != 0: new_width += 1 return new_height * scale_factor, new_width * scale_factor class a__( lowerCamelCase__ ): def __init__( self : Dict , __snake_case : UNetaDConditionModel , __snake_case : DDPMScheduler , __snake_case : VQModel , ): super().__init__() self.register_modules( unet=__snake_case , scheduler=__snake_case , movq=__snake_case , ) a : List[str] = 2 ** (len(self.movq.config.block_out_channels ) - 1) def lowercase_ ( self : Dict , __snake_case : Union[str, Any] , __snake_case : Tuple , __snake_case : List[Any] , __snake_case : Optional[Any] , __snake_case : Dict , __snake_case : Dict ): if latents is None: a : Union[str, Any] = randn_tensor(__snake_case , generator=__snake_case , device=__snake_case , dtype=__snake_case ) else: if latents.shape != shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {shape}""" ) a : List[str] = latents.to(__snake_case ) a : str = latents * scheduler.init_noise_sigma return latents def lowercase_ ( self : List[str] , __snake_case : Optional[Any]=0 ): if is_accelerate_available(): from accelerate import cpu_offload else: raise ImportError('Please install accelerate via `pip install accelerate`' ) a : Dict = torch.device(F"""cuda:{gpu_id}""" ) a : Optional[int] = [ self.unet, self.movq, ] for cpu_offloaded_model in models: if cpu_offloaded_model is not None: cpu_offload(__snake_case , __snake_case ) def lowercase_ ( self : str , __snake_case : Optional[Any]=0 ): if is_accelerate_available() and is_accelerate_version('>=' , '0.17.0.dev0' ): from accelerate import cpu_offload_with_hook else: raise ImportError('`enable_model_cpu_offload` requires `accelerate v0.17.0` or higher.' ) a : str = torch.device(F"""cuda:{gpu_id}""" ) if self.device.type != "cpu": self.to('cpu' , silence_dtype_warnings=__snake_case ) torch.cuda.empty_cache() # otherwise we don't see the memory savings (but they probably exist) a : Dict = None for cpu_offloaded_model in [self.unet, self.movq]: a , a : List[str] = cpu_offload_with_hook(__snake_case , __snake_case , prev_module_hook=__snake_case ) # We'll offload the last model manually. a : Union[str, Any] = hook @property # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device def lowercase_ ( self : str ): if not hasattr(self.unet , '_hf_hook' ): return self.device for module in self.unet.modules(): if ( hasattr(__snake_case , '_hf_hook' ) and hasattr(module._hf_hook , 'execution_device' ) and module._hf_hook.execution_device is not None ): return torch.device(module._hf_hook.execution_device ) return self.device @torch.no_grad() @replace_example_docstring(__snake_case ) def __call__( self : Optional[Any] , __snake_case : Union[torch.FloatTensor, List[torch.FloatTensor]] , __snake_case : Union[torch.FloatTensor, List[torch.FloatTensor]] , __snake_case : int = 5_12 , __snake_case : int = 5_12 , __snake_case : int = 1_00 , __snake_case : float = 4.0 , __snake_case : int = 1 , __snake_case : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __snake_case : Optional[torch.FloatTensor] = None , __snake_case : Optional[str] = "pil" , __snake_case : bool = True , ): a : List[str] = self._execution_device a : Dict = guidance_scale > 1.0 if isinstance(__snake_case , __snake_case ): a : Optional[Any] = torch.cat(__snake_case , dim=0 ) a : Optional[int] = image_embeds.shape[0] * num_images_per_prompt if isinstance(__snake_case , __snake_case ): a : Tuple = torch.cat(__snake_case , dim=0 ) if do_classifier_free_guidance: a : Dict = image_embeds.repeat_interleave(__snake_case , dim=0 ) a : Union[str, Any] = negative_image_embeds.repeat_interleave(__snake_case , dim=0 ) a : List[Any] = torch.cat([negative_image_embeds, image_embeds] , dim=0 ).to(dtype=self.unet.dtype , device=__snake_case ) self.scheduler.set_timesteps(__snake_case , device=__snake_case ) a : Optional[Any] = self.scheduler.timesteps a : List[str] = self.unet.config.in_channels a , a : Dict = downscale_height_and_width(__snake_case , __snake_case , self.movq_scale_factor ) # create initial latent a : Dict = self.prepare_latents( (batch_size, num_channels_latents, height, width) , image_embeds.dtype , __snake_case , __snake_case , __snake_case , self.scheduler , ) for i, t in enumerate(self.progress_bar(__snake_case ) ): # expand the latents if we are doing classifier free guidance a : str = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a : Any = {'image_embeds': image_embeds} a : int = self.unet( sample=__snake_case , timestep=__snake_case , encoder_hidden_states=__snake_case , added_cond_kwargs=__snake_case , return_dict=__snake_case , )[0] if do_classifier_free_guidance: a , a : Tuple = noise_pred.split(latents.shape[1] , dim=1 ) a , a : Optional[Any] = noise_pred.chunk(2 ) a , a : Optional[Any] = variance_pred.chunk(2 ) a : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) a : int = torch.cat([noise_pred, variance_pred_text] , dim=1 ) if not ( hasattr(self.scheduler.config , 'variance_type' ) and self.scheduler.config.variance_type in ["learned", "learned_range"] ): a , a : str = noise_pred.split(latents.shape[1] , dim=1 ) # compute the previous noisy sample x_t -> x_t-1 a : List[str] = self.scheduler.step( __snake_case , __snake_case , __snake_case , generator=__snake_case , )[0] # post-processing a : Any = self.movq.decode(__snake_case , force_not_quantize=__snake_case )['sample'] if output_type not in ["pt", "np", "pil"]: raise ValueError(F"""Only the output types `pt`, `pil` and `np` are supported not output_type={output_type}""" ) if output_type in ["np", "pil"]: a : str = image * 0.5 + 0.5 a : Union[str, Any] = image.clamp(0 , 1 ) a : Any = image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() if output_type == "pil": a : str = self.numpy_to_pil(__snake_case ) if not return_dict: return (image,) return ImagePipelineOutput(images=__snake_case )
297
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase: Any = logging.get_logger(__name__) lowerCAmelCase: Any = {'vocab_file': 'vocab.txt'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } lowerCAmelCase: str = { 'openbmb/cpm-ant-10b': 1_0_2_4, } def lowerCamelCase__ ( _A ): a : Union[str, Any] = collections.OrderedDict() with open(_A , 'r' , encoding='utf-8' ) as reader: a : int = reader.readlines() for index, token in enumerate(_A ): a : int = token.rstrip('\n' ) a : List[Any] = index return vocab class a__( lowerCamelCase__ ): def __init__( self : Dict , __snake_case : Any , __snake_case : Dict="<unk>" , __snake_case : str=2_00 ): a : List[Any] = vocab a : Any = unk_token a : List[str] = max_input_chars_per_word def lowercase_ ( self : Optional[int] , __snake_case : Union[str, Any] ): a : Optional[Any] = list(__snake_case ) if len(__snake_case ) > self.max_input_chars_per_word: return [self.unk_token] a : Any = 0 a : Optional[Any] = [] while start < len(__snake_case ): a : Optional[int] = len(__snake_case ) a : str = None while start < end: a : Optional[Any] = ''.join(chars[start:end] ) if substr in self.vocab: a : List[str] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(__snake_case ) a : List[str] = end return sub_tokens class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = False def __init__( self : Any , __snake_case : str , __snake_case : Tuple="<d>" , __snake_case : List[str]="</d>" , __snake_case : Dict="<s>" , __snake_case : List[Any]="</s>" , __snake_case : int="<pad>" , __snake_case : Any="<unk>" , __snake_case : List[str]="</n>" , __snake_case : int="</_>" , __snake_case : Optional[Any]="left" , **__snake_case : Dict , ): requires_backends(self , ['jieba'] ) super().__init__( bod_token=__snake_case , eod_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , pad_token=__snake_case , unk_token=__snake_case , line_token=__snake_case , space_token=__snake_case , padding_side=__snake_case , **__snake_case , ) a : Union[str, Any] = bod_token a : Any = eod_token a : List[str] = load_vocab(__snake_case ) a : Optional[int] = self.encoder[space_token] a : str = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] a : str = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) a : Tuple = {v: k for k, v in self.encoder.items()} a : List[str] = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def lowercase_ ( self : Optional[int] ): return self.encoder[self.bod_token] @property def lowercase_ ( self : Dict ): return self.encoder[self.eod_token] @property def lowercase_ ( self : Any ): return self.encoder["\n"] @property def lowercase_ ( self : Tuple ): return len(self.encoder ) def lowercase_ ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def lowercase_ ( self : Union[str, Any] , __snake_case : List[str] ): a : List[str] = [] for x in jieba.cut(__snake_case , cut_all=__snake_case ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(__snake_case ) ) return output_tokens def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[Any] , **__snake_case : Optional[Any] ): a : Optional[int] = [i for i in token_ids if i >= 0] a : Any = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(__snake_case , **__snake_case ) def lowercase_ ( self : Optional[int] , __snake_case : int ): return token in self.encoder def lowercase_ ( self : int , __snake_case : List[str] ): return "".join(__snake_case ) def lowercase_ ( self : List[str] , __snake_case : Union[str, Any] ): return self.encoder.get(__snake_case , self.encoder.get(self.unk_token ) ) def lowercase_ ( self : Tuple , __snake_case : List[str] ): return self.decoder.get(__snake_case , self.unk_token ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] = None ): if os.path.isdir(__snake_case ): a : Optional[int] = os.path.join( __snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: a : int = (filename_prefix + '-' if filename_prefix else '') + save_directory a : Any = 0 if " " in self.encoder: a : Union[str, Any] = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: a : Tuple = self.encoder['\n'] del self.encoder["\n"] a : Dict = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) with open(__snake_case , 'w' , encoding='utf-8' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ' Please check that the vocabulary is not corrupted!' ) a : List[Any] = token_index writer.write(token + '\n' ) index += 1 return (vocab_file,) def lowercase_ ( self : Union[str, Any] , __snake_case : List[int] , __snake_case : List[int] = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowercase_ ( self : Dict , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) if token_ids_a is not None: return [1] + ([0] * len(__snake_case )) + [1] + ([0] * len(__snake_case )) return [1] + ([0] * len(__snake_case ))
297
1
'''simple docstring''' import sys def lowerCamelCase__ ( _A ): a : Tuple = len(_A ) a : Dict = [[0 for x in range(_A )] for x in range(_A )] a : int = [[0 for x in range(_A )] for x in range(_A )] for chain_length in range(2 , _A ): for a in range(1 , n - chain_length + 1 ): a : Optional[Any] = a + chain_length - 1 a : Tuple = sys.maxsize for c in range(_A , _A ): a : str = ( matrix[a][c] + matrix[c + 1][b] + array[a - 1] * array[c] * array[b] ) if cost < matrix[a][b]: a : List[Any] = cost a : Optional[int] = c return matrix, sol def lowerCamelCase__ ( _A , _A , _A ): if i == j: print('A' + str(_A ) , end=' ' ) else: print('(' , end=' ' ) print_optiomal_solution(_A , _A , optimal_solution[i][j] ) print_optiomal_solution(_A , optimal_solution[i][j] + 1 , _A ) print(')' , end=' ' ) def lowerCamelCase__ ( ): a : List[Any] = [30, 35, 15, 5, 10, 20, 25] a : Any = len(_A ) # Size of matrix created from above array will be # 30*35 35*15 15*5 5*10 10*20 20*25 a , a : str = matrix_chain_order(_A ) print('No. of Operation required: ' + str(matrix[1][n - 1] ) ) print_optiomal_solution(_A , 1 , n - 1 ) if __name__ == "__main__": main()
297
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class a__( unittest.TestCase ): @slow def lowercase_ ( self : List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[int] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = TFAutoModel.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModel.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Union[str, Any] = TFAutoModelForPreTraining.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = AutoModelForPreTraining.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Union[str, Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForCausalLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Any = TFAutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForCausalLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[str] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[int] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Optional[int] = TFAutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = AutoModelForMaskedLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = TFAutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : str = AutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForSequenceClassification.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSequenceClassification.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : int = TFAutoModelForQuestionAnswering.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModelForQuestionAnswering.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowercase_ ( self : Tuple ): a : List[Any] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[int] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) def lowercase_ ( self : Any ): a : int = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[Any] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 )
297
1
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class a__: def __init__( self : Tuple ): a : Optional[int] = '' a : Optional[Any] = '' a : str = [] a : int = 0 a : str = 2_56 a : Union[str, Any] = 0 a : Any = 0 a : Optional[int] = 0 a : List[str] = 0 def lowercase_ ( self : str , __snake_case : str ): a : Any = cva.imread(__snake_case , 0 ) a : Optional[Any] = copy.deepcopy(self.img ) a , a , a : int = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label='x' ) a : Optional[int] = np.sum(__snake_case ) for i in range(len(__snake_case ) ): a : Optional[Any] = x[i] / self.k self.sk += prk a : str = (self.L - 1) * self.sk if self.rem != 0: a : Optional[int] = int(last % last ) a : int = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__snake_case ) a : str = int(np.ma.count(self.img ) / self.img[1].size ) a : Optional[int] = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a : Any = self.img[j][i] if num != self.last_list[num]: a : str = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def lowercase_ ( self : Dict ): plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def lowercase_ ( self : List[Any] ): cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": lowerCAmelCase: Optional[Any] = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') lowerCAmelCase: Tuple = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
297
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase: List[Any] = logging.get_logger(__name__) lowerCAmelCase: List[Any] = { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """roberta""" def __init__( self : Tuple , __snake_case : List[str]=5_02_65 , __snake_case : int=7_68 , __snake_case : Union[str, Any]=12 , __snake_case : Dict=12 , __snake_case : Tuple=30_72 , __snake_case : Optional[Any]="gelu" , __snake_case : str=0.1 , __snake_case : Any=0.1 , __snake_case : str=5_12 , __snake_case : int=2 , __snake_case : Any=0.02 , __snake_case : int=1e-1_2 , __snake_case : str=1 , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=2 , __snake_case : Optional[int]="absolute" , __snake_case : Union[str, Any]=True , __snake_case : Union[str, Any]=None , **__snake_case : str , ): super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) a : List[str] = vocab_size a : str = hidden_size a : Tuple = num_hidden_layers a : Dict = num_attention_heads a : List[Any] = hidden_act a : str = intermediate_size a : Union[str, Any] = hidden_dropout_prob a : Optional[Any] = attention_probs_dropout_prob a : Any = max_position_embeddings a : Optional[int] = type_vocab_size a : str = initializer_range a : List[Any] = layer_norm_eps a : Optional[int] = position_embedding_type a : Dict = use_cache a : Any = classifier_dropout class a__( lowerCamelCase__ ): @property def lowercase_ ( self : int ): if self.task == "multiple-choice": a : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a : str = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
297
1
'''simple docstring''' import gc import random import unittest import numpy as np import torch from diffusers import DDIMScheduler, KandinskyVaaPipeline, KandinskyVaaPriorPipeline, UNetaDConditionModel, VQModel from diffusers.utils import floats_tensor, load_numpy, slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference enable_full_determinism() class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = KandinskyVaaPipeline lowercase__ = [ """image_embeds""", """negative_image_embeds""", ] lowercase__ = ["""image_embeds""", """negative_image_embeds"""] lowercase__ = [ """generator""", """height""", """width""", """latents""", """guidance_scale""", """num_inference_steps""", """return_dict""", """guidance_scale""", """num_images_per_prompt""", """output_type""", """return_dict""", ] lowercase__ = False @property def lowercase_ ( self : List[str] ): return 32 @property def lowercase_ ( self : Any ): return 32 @property def lowercase_ ( self : List[Any] ): return self.time_input_dim @property def lowercase_ ( self : Any ): return self.time_input_dim * 4 @property def lowercase_ ( self : Optional[int] ): return 1_00 @property def lowercase_ ( self : str ): torch.manual_seed(0 ) a : Optional[int] = { 'in_channels': 4, # Out channels is double in channels because predicts mean and variance 'out_channels': 8, 'addition_embed_type': 'image', 'down_block_types': ('ResnetDownsampleBlock2D', 'SimpleCrossAttnDownBlock2D'), 'up_block_types': ('SimpleCrossAttnUpBlock2D', 'ResnetUpsampleBlock2D'), 'mid_block_type': 'UNetMidBlock2DSimpleCrossAttn', 'block_out_channels': (self.block_out_channels_a, self.block_out_channels_a * 2), 'layers_per_block': 1, 'encoder_hid_dim': self.text_embedder_hidden_size, 'encoder_hid_dim_type': 'image_proj', 'cross_attention_dim': self.cross_attention_dim, 'attention_head_dim': 4, 'resnet_time_scale_shift': 'scale_shift', 'class_embed_type': None, } a : Optional[int] = UNetaDConditionModel(**__snake_case ) return model @property def lowercase_ ( self : List[str] ): return { "block_out_channels": [32, 64], "down_block_types": ["DownEncoderBlock2D", "AttnDownEncoderBlock2D"], "in_channels": 3, "latent_channels": 4, "layers_per_block": 1, "norm_num_groups": 8, "norm_type": "spatial", "num_vq_embeddings": 12, "out_channels": 3, "up_block_types": [ "AttnUpDecoderBlock2D", "UpDecoderBlock2D", ], "vq_embed_dim": 4, } @property def lowercase_ ( self : str ): torch.manual_seed(0 ) a : Dict = VQModel(**self.dummy_movq_kwargs ) return model def lowercase_ ( self : Tuple ): a : Optional[int] = self.dummy_unet a : Dict = self.dummy_movq a : Dict = DDIMScheduler( num_train_timesteps=10_00 , beta_schedule='linear' , beta_start=0.00085 , beta_end=0.012 , clip_sample=__snake_case , set_alpha_to_one=__snake_case , steps_offset=1 , prediction_type='epsilon' , thresholding=__snake_case , ) a : Optional[int] = { 'unet': unet, 'scheduler': scheduler, 'movq': movq, } return components def lowercase_ ( self : Optional[int] , __snake_case : List[str] , __snake_case : Dict=0 ): a : Optional[Any] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(__snake_case ) ).to(__snake_case ) a : List[str] = floats_tensor((1, self.text_embedder_hidden_size) , rng=random.Random(seed + 1 ) ).to( __snake_case ) if str(__snake_case ).startswith('mps' ): a : Union[str, Any] = torch.manual_seed(__snake_case ) else: a : List[Any] = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) a : Any = { 'image_embeds': image_embeds, 'negative_image_embeds': negative_image_embeds, 'generator': generator, 'height': 64, 'width': 64, 'guidance_scale': 4.0, 'num_inference_steps': 2, 'output_type': 'np', } return inputs def lowercase_ ( self : List[str] ): a : Optional[Any] = 'cpu' a : Union[str, Any] = self.get_dummy_components() a : List[str] = self.pipeline_class(**__snake_case ) a : Optional[int] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) a : int = pipe(**self.get_dummy_inputs(__snake_case ) ) a : List[str] = output.images a : List[str] = pipe( **self.get_dummy_inputs(__snake_case ) , return_dict=__snake_case , )[0] a : Dict = image[0, -3:, -3:, -1] a : List[Any] = image_from_tuple[0, -3:, -3:, -1] assert image.shape == (1, 64, 64, 3) a : Union[str, Any] = np.array( [0.6237976, 1.0, 0.36441332, 1.0, 0.70639634, 0.29877186, 0.85652125, 0.5216843, 0.54454046] ) assert ( np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_slice.flatten()}""" assert ( np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() < 1e-2 ), F""" expected_slice {expected_slice}, but got {image_from_tuple_slice.flatten()}""" @slow @require_torch_gpu class a__( unittest.TestCase ): def lowercase_ ( self : Union[str, Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Tuple ): a : Tuple = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main' '/kandinskyv22/kandinskyv22_text2img_cat_fp16.npy' ) a : List[Any] = KandinskyVaaPriorPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-prior' , torch_dtype=torch.floataa ) pipe_prior.to(__snake_case ) a : Optional[int] = KandinskyVaaPipeline.from_pretrained( 'kandinsky-community/kandinsky-2-2-decoder' , torch_dtype=torch.floataa ) a : Union[str, Any] = pipeline.to(__snake_case ) pipeline.set_progress_bar_config(disable=__snake_case ) a : Any = 'red cat, 4k photo' a : Any = torch.Generator(device='cuda' ).manual_seed(0 ) a , a : Dict = pipe_prior( __snake_case , generator=__snake_case , num_inference_steps=5 , negative_prompt='' , ).to_tuple() a : Union[str, Any] = torch.Generator(device='cuda' ).manual_seed(0 ) a : int = pipeline( image_embeds=__snake_case , negative_image_embeds=__snake_case , generator=__snake_case , num_inference_steps=1_00 , output_type='np' , ) a : List[str] = output.images[0] assert image.shape == (5_12, 5_12, 3) assert_mean_pixel_difference(__snake_case , __snake_case )
297
'''simple docstring''' def lowerCamelCase__ ( _A ): return 10 - x * x def lowerCamelCase__ ( _A , _A ): # Bolzano theory in order to find if there is a root between a and b if equation(_A ) * equation(_A ) >= 0: raise ValueError('Wrong space!' ) a : Tuple = a while (b - a) >= 0.01: # Find middle point a : Tuple = (a + b) / 2 # Check if middle point is root if equation(_A ) == 0.0: break # Decide the side to repeat the steps if equation(_A ) * equation(_A ) < 0: a : List[str] = c else: a : Tuple = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
297
1
'''simple docstring''' from __future__ import annotations lowerCAmelCase: Any = 'Muhammad Umer Farooq' lowerCAmelCase: Optional[Any] = 'MIT' lowerCAmelCase: Optional[int] = '1.0.0' lowerCAmelCase: Optional[Any] = 'Muhammad Umer Farooq' lowerCAmelCase: Tuple = 'contact@muhammadumerfarooq.me' lowerCAmelCase: List[str] = 'Alpha' import re from html.parser import HTMLParser from urllib import parse import requests class a__( lowerCamelCase__ ): def __init__( self : int , __snake_case : str ): super().__init__() a : list[str] = [] a : List[str] = domain def lowercase_ ( self : List[Any] , __snake_case : str , __snake_case : list[tuple[str, str | None]] ): # Only parse the 'anchor' tag. if tag == "a": # Check the list of defined attributes. for name, value in attrs: # If href is defined, and not empty nor # print it. if name == "href" and value != "#" and value != "": # If not already in urls. if value not in self.urls: a : Union[str, Any] = parse.urljoin(self.domain , __snake_case ) self.urls.append(__snake_case ) def lowerCamelCase__ ( _A ): return ".".join(get_sub_domain_name(_A ).split('.' )[-2:] ) def lowerCamelCase__ ( _A ): return parse.urlparse(_A ).netloc def lowerCamelCase__ ( _A = "https://github.com" ): a : List[Any] = get_domain_name(_A ) # Initialize the parser a : Any = Parser(_A ) try: # Open URL a : Tuple = requests.get(_A ) # pass the raw HTML to the parser to get links parser.feed(r.text ) # Get links and loop through a : int = set() for link in parser.urls: # open URL. # read = requests.get(link) try: a : int = requests.get(_A ) # Get the valid email. a : Any = re.findall('[a-zA-Z0-9]+@' + domain , read.text ) # If not in list then append it. for email in emails: valid_emails.add(_A ) except ValueError: pass except ValueError: raise SystemExit(1 ) # Finally return a sorted list of email addresses with no duplicates. return sorted(_A ) if __name__ == "__main__": lowerCAmelCase: Optional[Any] = emails_from_url('https://github.com') print(F"{len(emails)} emails found:") print('\n'.join(sorted(emails)))
297
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.esm.modeling_esmfold import EsmForProteinFolding class a__: def __init__( self : str , __snake_case : Union[str, Any] , __snake_case : List[str]=13 , __snake_case : Tuple=7 , __snake_case : Optional[Any]=False , __snake_case : Dict=True , __snake_case : List[Any]=False , __snake_case : Optional[int]=False , __snake_case : Optional[Any]=19 , __snake_case : Any=32 , __snake_case : Union[str, Any]=5 , __snake_case : Union[str, Any]=4 , __snake_case : int=37 , __snake_case : Union[str, Any]="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : List[str]=0.1 , __snake_case : int=5_12 , __snake_case : int=16 , __snake_case : Tuple=2 , __snake_case : str=0.02 , __snake_case : str=3 , __snake_case : Dict=4 , __snake_case : List[Any]=None , ): a : Tuple = parent a : List[str] = batch_size a : Optional[Any] = seq_length a : Tuple = is_training a : Optional[Any] = use_input_mask a : List[Any] = use_token_type_ids a : List[Any] = use_labels a : int = vocab_size a : Union[str, Any] = hidden_size a : Any = num_hidden_layers a : List[str] = num_attention_heads a : int = intermediate_size a : str = hidden_act a : Tuple = hidden_dropout_prob a : Union[str, Any] = attention_probs_dropout_prob a : List[str] = max_position_embeddings a : Any = type_vocab_size a : List[str] = type_sequence_label_size a : Union[str, Any] = initializer_range a : Optional[int] = num_labels a : Optional[Any] = num_choices a : Optional[int] = scope def lowercase_ ( self : List[Any] ): a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Dict = None if self.use_input_mask: a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a : Optional[Any] = None a : Optional[int] = None a : Dict = None if self.use_labels: a : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) a : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self : List[Any] ): a : Any = EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , is_folding_model=__snake_case , esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False} , ) return config def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : str , __snake_case : Optional[Any] , __snake_case : List[Any] , __snake_case : str , __snake_case : Any ): a : Tuple = EsmForProteinFolding(config=__snake_case ).float() model.to(__snake_case ) model.eval() a : Dict = model(__snake_case , attention_mask=__snake_case ) a : Union[str, Any] = model(__snake_case ) a : List[Any] = model(__snake_case ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def lowercase_ ( self : Optional[Any] ): a : Tuple = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : Optional[Any] = config_and_inputs a : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = False lowercase__ = (EsmForProteinFolding,) if is_torch_available() else () lowercase__ = () lowercase__ = {} if is_torch_available() else {} lowercase__ = False def lowercase_ ( self : int ): a : Tuple = EsmFoldModelTester(self ) a : Any = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase_ ( self : List[str] ): self.config_tester.run_common_tests() def lowercase_ ( self : Union[str, Any] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) @unittest.skip('Does not support attention outputs' ) def lowercase_ ( self : str ): pass @unittest.skip def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support passing input embeds!' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMfold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold only has one output format.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality' ) def lowercase_ ( self : Tuple ): pass @unittest.skip('ESMFold does not support input chunking.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t support data parallel.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowercase_ ( self : Union[str, Any] ): pass @require_torch class a__( lowerCamelCase__ ): @slow def lowercase_ ( self : Optional[int] ): a : Optional[Any] = EsmForProteinFolding.from_pretrained('facebook/esmfold_v1' ).float() model.eval() a : int = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) a : Any = model(__snake_case )['positions'] a : Dict = torch.tensor([2.5828, 0.7993, -10.9334] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , __snake_case , atol=1e-4 ) )
297
1
'''simple docstring''' import numpy as np import torch from imwatermark import WatermarkEncoder # Copied from https://github.com/Stability-AI/generative-models/blob/613af104c6b85184091d42d374fef420eddb356d/scripts/demo/streamlit_helpers.py#L66 lowerCAmelCase: List[str] = 0b1_0_1_1_0_0_1_1_1_1_1_0_1_1_0_0_1_0_0_1_0_0_0_0_0_1_1_1_1_0_1_1_1_0_1_1_0_0_0_1_1_0_0_1_1_1_1_0 # bin(x)[2:] gives bits of x as str, use int to convert them to 0/1 lowerCAmelCase: Any = [int(bit) for bit in bin(WATERMARK_MESSAGE)[2:]] class a__: def __init__( self : Tuple ): a : Optional[Any] = WATERMARK_BITS a : Dict = WatermarkEncoder() self.encoder.set_watermark('bits' , self.watermark ) def lowercase_ ( self : int , __snake_case : torch.FloatTensor ): # can't encode images that are smaller than 256 if images.shape[-1] < 2_56: return images a : int = (2_55 * (images / 2 + 0.5)).cpu().permute(0 , 2 , 3 , 1 ).float().numpy() a : List[Any] = [self.encoder.encode(__snake_case , 'dwtDct' ) for image in images] a : str = torch.from_numpy(np.array(__snake_case ) ).permute(0 , 3 , 1 , 2 ) a : Tuple = torch.clamp(2 * (images / 2_55 - 0.5) , min=-1.0 , max=1.0 ) return images
297
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class a__( nn.Module ): def __init__( self : Any , __snake_case : int = 16 , __snake_case : int = 88 , __snake_case : Optional[int] = None , __snake_case : int = 1 , __snake_case : float = 0.0 , __snake_case : int = 32 , __snake_case : Optional[int] = None , __snake_case : bool = False , __snake_case : Optional[int] = None , __snake_case : Optional[int] = None , __snake_case : str = "geglu" , __snake_case : Optional[int] = None , ): super().__init__() a : Optional[int] = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__snake_case , attention_head_dim=__snake_case , in_channels=__snake_case , num_layers=__snake_case , dropout=__snake_case , norm_num_groups=__snake_case , cross_attention_dim=__snake_case , attention_bias=__snake_case , sample_size=__snake_case , num_vector_embeds=__snake_case , activation_fn=__snake_case , num_embeds_ada_norm=__snake_case , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference a : Union[str, Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` a : Tuple = [77, 2_57] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` a : Any = [1, 0] def lowercase_ ( self : str , __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any]=None , __snake_case : int=None , __snake_case : Dict=None , __snake_case : bool = True , ): a : Dict = hidden_states a : Tuple = [] a : Optional[int] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens a : Union[str, Any] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] a : Tuple = self.transformer_index_for_condition[i] a : Union[str, Any] = self.transformers[transformer_index]( __snake_case , encoder_hidden_states=__snake_case , timestep=__snake_case , cross_attention_kwargs=__snake_case , return_dict=__snake_case , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] a : Optional[Any] = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) a : int = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__snake_case )
297
1
'''simple docstring''' from scipy.stats import pearsonr import datasets lowerCAmelCase: int = '\nPearson correlation coefficient and p-value for testing non-correlation.\nThe Pearson correlation coefficient measures the linear relationship between two datasets. The calculation of the p-value relies on the assumption that each dataset is normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations imply that as x increases, so does y. Negative correlations imply that as x increases, y decreases.\nThe p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets.\n' lowerCAmelCase: List[Any] = '\nArgs:\n predictions (`list` of `int`): Predicted class labels, as returned by a model.\n references (`list` of `int`): Ground truth labels.\n return_pvalue (`boolean`): If `True`, returns the p-value, along with the correlation coefficient. If `False`, returns only the correlation coefficient. Defaults to `False`.\n\nReturns:\n pearsonr (`float`): Pearson correlation coefficient. Minimum possible value is -1. Maximum possible value is 1. Values of 1 and -1 indicate exact linear positive and negative relationships, respectively. A value of 0 implies no correlation.\n p-value (`float`): P-value, which roughly indicates the probability of an The p-value roughly indicates the probability of an uncorrelated system producing datasets that have a Pearson correlation at least as extreme as the one computed from these datasets. Minimum possible value is 0. Maximum possible value is 1. Higher values indicate higher probabilities.\n\nExamples:\n\n Example 1-A simple example using only predictions and references.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5])\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n\n Example 2-The same as Example 1, but that also returns the `p-value`.\n >>> pearsonr_metric = datasets.load_metric("pearsonr")\n >>> results = pearsonr_metric.compute(predictions=[10, 9, 2.5, 6, 4], references=[1, 2, 3, 4, 5], return_pvalue=True)\n >>> print(sorted(list(results.keys())))\n [\'p-value\', \'pearsonr\']\n >>> print(round(results[\'pearsonr\'], 2))\n -0.74\n >>> print(round(results[\'p-value\'], 2))\n 0.15\n' lowerCAmelCase: str = '\n@article{2020SciPy-NMeth,\nauthor = {Virtanen, Pauli and Gommers, Ralf and Oliphant, Travis E. and\n Haberland, Matt and Reddy, Tyler and Cournapeau, David and\n Burovski, Evgeni and Peterson, Pearu and Weckesser, Warren and\n Bright, Jonathan and {van der Walt}, St{\'e}fan J. and\n Brett, Matthew and Wilson, Joshua and Millman, K. Jarrod and\n Mayorov, Nikolay and Nelson, Andrew R. J. and Jones, Eric and\n Kern, Robert and Larson, Eric and Carey, C J and\n Polat, Ilhan and Feng, Yu and Moore, Eric W. and\n {VanderPlas}, Jake and Laxalde, Denis and Perktold, Josef and\n Cimrman, Robert and Henriksen, Ian and Quintero, E. A. and\n Harris, Charles R. and Archibald, Anne M. and\n Ribeiro, Antonio H. and Pedregosa, Fabian and\n {van Mulbregt}, Paul and {SciPy 1.0 Contributors}},\ntitle = {{{SciPy} 1.0: Fundamental Algorithms for Scientific\n Computing in Python}},\njournal = {Nature Methods},\nyear = {2020},\nvolume = {17},\npages = {261--272},\nadsurl = {https://rdcu.be/b08Wh},\ndoi = {10.1038/s41592-019-0686-2},\n}\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__( datasets.Metric ): def lowercase_ ( self : Tuple ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('float' ), 'references': datasets.Value('float' ), } ) , reference_urls=['https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pearsonr.html'] , ) def lowercase_ ( self : Tuple , __snake_case : str , __snake_case : Dict , __snake_case : int=False ): if return_pvalue: a : Dict = pearsonr(__snake_case , __snake_case ) return {"pearsonr": results[0], "p-value": results[1]} else: return {"pearsonr": float(pearsonr(__snake_case , __snake_case )[0] )}
297
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase: Union[str, Any] = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[Any] = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Any = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
'''simple docstring''' import logging import os from typing import Dict, List, Optional, Union import torch import torch.nn as nn from accelerate.utils.imports import ( is_abit_bnb_available, is_abit_bnb_available, is_bnb_available, ) from ..big_modeling import dispatch_model, init_empty_weights from .dataclasses import BnbQuantizationConfig from .modeling import ( find_tied_parameters, get_balanced_memory, infer_auto_device_map, load_checkpoint_in_model, offload_weight, set_module_tensor_to_device, ) if is_bnb_available(): import bitsandbytes as bnb from copy import deepcopy lowerCAmelCase: Tuple = logging.getLogger(__name__) def lowerCamelCase__ ( _A , _A , _A = None , _A = None , _A = None , _A = None , _A = None , _A = False , ): a : Optional[int] = bnb_quantization_config.load_in_abit a : Tuple = bnb_quantization_config.load_in_abit if load_in_abit and not is_abit_bnb_available(): raise ImportError( 'You have a version of `bitsandbytes` that is not compatible with 8bit quantization,' ' make sure you have the latest version of `bitsandbytes` installed.' ) if load_in_abit and not is_abit_bnb_available(): raise ValueError( 'You have a version of `bitsandbytes` that is not compatible with 4bit quantization,' 'make sure you have the latest version of `bitsandbytes` installed.' ) a : int = [] # custom device map if isinstance(_A , _A ) and len(device_map.keys() ) > 1: a : Dict = [key for key, value in device_map.items() if value in ['disk', 'cpu']] # We keep some modules such as the lm_head in their original dtype for numerical stability reasons if bnb_quantization_config.skip_modules is None: a : Dict = get_keys_to_not_convert(_A ) # add cpu modules to skip modules only for 4-bit modules if load_in_abit: bnb_quantization_config.skip_modules.extend(_A ) a : int = bnb_quantization_config.skip_modules # We add the modules we want to keep in full precision if bnb_quantization_config.keep_in_fpaa_modules is None: a : Any = [] a : Any = bnb_quantization_config.keep_in_fpaa_modules modules_to_not_convert.extend(_A ) # compatibility with peft a : Any = load_in_abit a : Optional[int] = load_in_abit a : str = get_parameter_device(_A ) if model_device.type != "meta": # quantization of an already loaded model logger.warning( 'It is not recommended to quantize a loaded model. ' 'The model should be instantiated under the `init_empty_weights` context manager.' ) a : Tuple = replace_with_bnb_layers(_A , _A , modules_to_not_convert=_A ) # convert param to the right dtype a : Optional[int] = bnb_quantization_config.torch_dtype for name, param in model.state_dict().items(): if any(module_to_keep_in_fpaa in name for module_to_keep_in_fpaa in keep_in_fpaa_modules ): param.to(torch.floataa ) if param.dtype != torch.floataa: a : Tuple = name.replace('.weight' , '' ).replace('.bias' , '' ) a : List[str] = getattr(_A , _A , _A ) if param is not None: param.to(torch.floataa ) elif torch.is_floating_point(_A ): param.to(_A ) if model_device.type == "cuda": # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda model.cuda(torch.cuda.current_device() ) torch.cuda.empty_cache() elif torch.cuda.is_available(): model.to(torch.cuda.current_device() ) else: raise RuntimeError('No GPU found. A GPU is needed for quantization.' ) logger.info( f"""The model device type is {model_device.type}. However, cuda is needed for quantization.""" 'We move the model to cuda.' ) return model elif weights_location is None: raise RuntimeError( f"""`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} """ ) else: with init_empty_weights(): a : List[Any] = replace_with_bnb_layers( _A , _A , modules_to_not_convert=_A ) a : Union[str, Any] = get_quantized_model_device_map( _A , _A , _A , max_memory=_A , no_split_module_classes=_A , ) if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): a : int = True a : Optional[int] = any(x in list(device_map.values() ) for x in ['cpu', 'disk'] ) load_checkpoint_in_model( _A , _A , _A , dtype=bnb_quantization_config.torch_dtype , offload_folder=_A , offload_state_dict=_A , keep_in_fpaa_modules=bnb_quantization_config.keep_in_fpaa_modules , offload_abit_bnb=load_in_abit and offload , ) return dispatch_model(_A , device_map=_A , offload_dir=_A ) def lowerCamelCase__ ( _A , _A , _A=None , _A=None , _A=None ): if device_map is None: if torch.cuda.is_available(): a : List[str] = {'': torch.cuda.current_device()} else: raise RuntimeError('No GPU found. A GPU is needed for quantization.' ) logger.info('The device_map was not initialized.' 'Setting device_map to `{\'\':torch.cuda.current_device()}`.' ) if isinstance(_A , _A ): if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: raise ValueError( 'If passing a string for `device_map`, please choose \'auto\', \'balanced\', \'balanced_low_0\' or ' '\'sequential\'.' ) a : Tuple = {} special_dtypes.update( { name: bnb_quantization_config.torch_dtype for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.skip_modules ) } ) special_dtypes.update( { name: torch.floataa for name, _ in model.named_parameters() if any(m in name for m in bnb_quantization_config.keep_in_fpaa_modules ) } ) a : List[Any] = {} a : Tuple = special_dtypes a : Any = no_split_module_classes a : int = bnb_quantization_config.target_dtype # get max_memory for each device. if device_map != "sequential": a : Tuple = get_balanced_memory( _A , low_zero=(device_map == 'balanced_low_0') , max_memory=_A , **_A , ) a : Optional[Any] = max_memory a : Tuple = infer_auto_device_map(_A , **_A ) if isinstance(_A , _A ): # check if don't have any quantized module on the cpu a : Tuple = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fpaa_modules a : Optional[int] = { key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert } for device in ["cpu", "disk"]: if device in device_map_without_some_modules.values(): if bnb_quantization_config.load_in_abit: raise ValueError( '\n Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit\n the quantized model. If you want to dispatch the model on the CPU or the disk while keeping\n these modules in `torch_dtype`, you need to pass a custom `device_map` to\n `load_and_quantize_model`. Check\n https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk\n for more details.\n ' ) else: logger.info( 'Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit' ) del device_map_without_some_modules return device_map def lowerCamelCase__ ( _A , _A , _A=None , _A=None ): if modules_to_not_convert is None: a : List[str] = [] a , a : Dict = _replace_with_bnb_layers( _A , _A , _A , _A ) if not has_been_replaced: logger.warning( 'You are loading your model in 8bit or 4bit but no linear modules were found in your model.' ' this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers.' ' Please double check your model architecture, or submit an issue on github if you think this is' ' a bug.' ) return model def lowerCamelCase__ ( _A , _A , _A=None , _A=None , ): a : Union[str, Any] = False for name, module in model.named_children(): if current_key_name is None: a : int = [] current_key_name.append(_A ) if isinstance(_A , nn.Linear ) and name not in modules_to_not_convert: # Check if the current key is not in the `modules_to_not_convert` a : Any = '.'.join(_A ) a : List[str] = True for key in modules_to_not_convert: if ( (key in current_key_name_str) and (key + "." in current_key_name_str) ) or key == current_key_name_str: a : List[Any] = False break if proceed: # Load bnb module with empty weight and replace ``nn.Linear` module if bnb_quantization_config.load_in_abit: a : Union[str, Any] = bnb.nn.LinearabitLt( module.in_features , module.out_features , module.bias is not None , has_fpaa_weights=_A , threshold=bnb_quantization_config.llm_inta_threshold , ) elif bnb_quantization_config.load_in_abit: a : Dict = bnb.nn.Linearabit( module.in_features , module.out_features , module.bias is not None , bnb_quantization_config.bnb_abit_compute_dtype , compress_statistics=bnb_quantization_config.bnb_abit_use_double_quant , quant_type=bnb_quantization_config.bnb_abit_quant_type , ) else: raise ValueError('load_in_8bit and load_in_4bit can\'t be both False' ) a : str = module.weight.data if module.bias is not None: a : Optional[Any] = module.bias.data bnb_module.requires_grad_(_A ) setattr(_A , _A , _A ) a : Optional[Any] = True if len(list(module.children() ) ) > 0: a , a : List[str] = _replace_with_bnb_layers( _A , _A , _A , _A ) a : Union[str, Any] = has_been_replaced | _has_been_replaced # Remove the last key for recursion current_key_name.pop(-1 ) return model, has_been_replaced def lowerCamelCase__ ( _A ): # Create a copy of the model with init_empty_weights(): a : Any = deepcopy(_A ) # this has 0 cost since it is done inside `init_empty_weights` context manager` a : Optional[Any] = find_tied_parameters(_A ) # For compatibility with Accelerate < 0.18 if isinstance(_A , _A ): a : str = sum(list(tied_params.values() ) , [] ) + list(tied_params.keys() ) else: a : Any = sum(_A , [] ) a : List[str] = len(_A ) > 0 # Check if it is a base model a : Dict = False if hasattr(_A , 'base_model_prefix' ): a : Dict = not hasattr(_A , model.base_model_prefix ) # Ignore this for base models (BertModel, GPT2Model, etc.) if (not has_tied_params) and is_base_model: return [] # otherwise they have an attached head a : Tuple = list(model.named_children() ) a : Union[str, Any] = [list_modules[-1][0]] # add last module together with tied weights a : List[str] = set(_A ) - set(_A ) a : List[str] = list(set(_A ) ) + list(_A ) # remove ".weight" from the keys a : str = ['.weight', '.bias'] a : Tuple = [] for name in list_untouched: for name_to_remove in names_to_remove: if name_to_remove in name: a : str = name.replace(_A , '' ) filtered_module_names.append(_A ) return filtered_module_names def lowerCamelCase__ ( _A ): for m in model.modules(): if isinstance(_A , bnb.nn.Linearabit ): return True return False def lowerCamelCase__ ( _A ): return next(parameter.parameters() ).device def lowerCamelCase__ ( _A , _A , _A , _A , _A , _A , _A ): # if it is not quantized, we quantize and offload the quantized weights and the SCB stats if fpaa_statistics is None: set_module_tensor_to_device(_A , _A , 0 , dtype=_A , value=_A ) a : Tuple = param_name a : List[str] = model if "." in tensor_name: a : Tuple = tensor_name.split('.' ) for split in splits[:-1]: a : Dict = getattr(_A , _A ) if new_module is None: raise ValueError(f"""{module} has no attribute {split}.""" ) a : Optional[Any] = new_module a : Optional[Any] = splits[-1] # offload weights a : Dict = False offload_weight(module._parameters[tensor_name] , _A , _A , index=_A ) if hasattr(module._parameters[tensor_name] , 'SCB' ): offload_weight( module._parameters[tensor_name].SCB , param_name.replace('weight' , 'SCB' ) , _A , index=_A , ) else: offload_weight(_A , _A , _A , index=_A ) offload_weight(_A , param_name.replace('weight' , 'SCB' ) , _A , index=_A ) set_module_tensor_to_device(_A , _A , 'meta' , dtype=_A , value=torch.empty(*param.size() ) )
297
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase: str = { 'configuration_mgp_str': ['MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MgpstrConfig'], 'processing_mgp_str': ['MgpstrProcessor'], 'tokenization_mgp_str': ['MgpstrTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Optional[Any] = [ 'MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST', 'MgpstrModel', 'MgpstrPreTrainedModel', 'MgpstrForSceneTextRecognition', ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys lowerCAmelCase: Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
'''simple docstring''' def lowerCamelCase__ ( _A , _A , _A ): def update_area_of_max_square(_A , _A ) -> int: # BASE CASE if row >= rows or col >= cols: return 0 a : List[Any] = update_area_of_max_square(_A , col + 1 ) a : Any = update_area_of_max_square(row + 1 , col + 1 ) a : str = update_area_of_max_square(row + 1 , _A ) if mat[row][col]: a : str = 1 + min([right, diagonal, down] ) a : Optional[Any] = max(largest_square_area[0] , _A ) return sub_problem_sol else: return 0 a : Union[str, Any] = [0] update_area_of_max_square(0 , 0 ) return largest_square_area[0] def lowerCamelCase__ ( _A , _A , _A ): def update_area_of_max_square_using_dp_array( _A , _A , _A ) -> int: if row >= rows or col >= cols: return 0 if dp_array[row][col] != -1: return dp_array[row][col] a : Union[str, Any] = update_area_of_max_square_using_dp_array(_A , col + 1 , _A ) a : Dict = update_area_of_max_square_using_dp_array(row + 1 , col + 1 , _A ) a : Optional[Any] = update_area_of_max_square_using_dp_array(row + 1 , _A , _A ) if mat[row][col]: a : int = 1 + min([right, diagonal, down] ) a : Tuple = max(largest_square_area[0] , _A ) a : int = sub_problem_sol return sub_problem_sol else: return 0 a : Any = [0] a : int = [[-1] * cols for _ in range(_A )] update_area_of_max_square_using_dp_array(0 , 0 , _A ) return largest_square_area[0] def lowerCamelCase__ ( _A , _A , _A ): a : Tuple = [[0] * (cols + 1) for _ in range(rows + 1 )] a : Optional[int] = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): a : List[Any] = dp_array[row][col + 1] a : Optional[int] = dp_array[row + 1][col + 1] a : Optional[int] = dp_array[row + 1][col] if mat[row][col] == 1: a : Tuple = 1 + min(_A , _A , _A ) a : List[str] = max(dp_array[row][col] , _A ) else: a : Optional[Any] = 0 return largest_square_area def lowerCamelCase__ ( _A , _A , _A ): a : List[str] = [0] * (cols + 1) a : Union[str, Any] = [0] * (cols + 1) a : Any = 0 for row in range(rows - 1 , -1 , -1 ): for col in range(cols - 1 , -1 , -1 ): a : int = current_row[col + 1] a : int = next_row[col + 1] a : List[Any] = next_row[col] if mat[row][col] == 1: a : List[Any] = 1 + min(_A , _A , _A ) a : List[str] = max(current_row[col] , _A ) else: a : int = 0 a : str = current_row return largest_square_area if __name__ == "__main__": import doctest doctest.testmod() print(largest_square_area_in_matrix_bottom_up(2, 2, [[1, 1], [1, 1]]))
297
'''simple docstring''' import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer lowerCAmelCase: Dict = logging.get_logger(__name__) lowerCAmelCase: str = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json', }, 'merges_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt', }, 'tokenizer_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json', }, } lowerCAmelCase: str = { 'allenai/led-base-16384': 1_6_3_8_4, } class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = LEDTokenizer lowercase__ = ["""input_ids""", """attention_mask"""] def __init__( self : List[Any] , __snake_case : Optional[Any]=None , __snake_case : List[str]=None , __snake_case : Tuple=None , __snake_case : Dict="replace" , __snake_case : int="<s>" , __snake_case : Any="</s>" , __snake_case : Optional[Any]="</s>" , __snake_case : Optional[Any]="<s>" , __snake_case : Optional[Any]="<unk>" , __snake_case : List[str]="<pad>" , __snake_case : int="<mask>" , __snake_case : int=False , __snake_case : str=True , **__snake_case : Tuple , ): super().__init__( __snake_case , __snake_case , tokenizer_file=__snake_case , errors=__snake_case , bos_token=__snake_case , eos_token=__snake_case , sep_token=__snake_case , cls_token=__snake_case , unk_token=__snake_case , pad_token=__snake_case , mask_token=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case , **__snake_case , ) a : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : List[Any] = getattr(__snake_case , pre_tok_state.pop('type' ) ) a : Optional[Any] = add_prefix_space a : Optional[Any] = pre_tok_class(**__snake_case ) a : Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` a : Dict = 'post_processor' a : int = getattr(self.backend_tokenizer , __snake_case , __snake_case ) if tokenizer_component_instance: a : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a : Any = tuple(state['sep'] ) if "cls" in state: a : Any = tuple(state['cls'] ) a : Optional[Any] = False if state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : Any = add_prefix_space a : Optional[Any] = True if state.get('trim_offsets' , __snake_case ) != trim_offsets: a : List[Any] = trim_offsets a : Union[str, Any] = True if changes_to_apply: a : int = getattr(__snake_case , state.pop('type' ) ) a : List[Any] = component_class(**__snake_case ) setattr(self.backend_tokenizer , __snake_case , __snake_case ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def lowercase_ ( self : Dict ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def lowercase_ ( self : Dict , __snake_case : List[str] ): a : Tuple = AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else value a : Optional[int] = value def lowercase_ ( self : Optional[Any] , *__snake_case : Any , **__snake_case : Union[str, Any] ): a : Dict = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Union[str, Any] , *__snake_case : Optional[int] , **__snake_case : List[str] ): a : Optional[int] = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Dict , __snake_case : str , __snake_case : Optional[str] = None ): a : Union[str, Any] = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : int=None ): a : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase_ ( self : Optional[int] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : int = [self.sep_token_id] a : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase_ ( self : List[str] , __snake_case : Union[Dict[str, EncodedInput], BatchEncoding] , __snake_case : Optional[int] = None , __snake_case : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __snake_case : Optional[int] = None , __snake_case : Optional[bool] = None , ): a : Optional[Any] = super()._pad( encoded_inputs=__snake_case , max_length=__snake_case , padding_strategy=__snake_case , pad_to_multiple_of=__snake_case , return_attention_mask=__snake_case , ) # Load from model defaults if return_attention_mask is None: a : str = 'attention_mask' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: a : Any = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. a : Union[str, Any] = len(encoded_inputs['global_attention_mask'] ) != len(__snake_case ) if needs_to_be_padded: a : str = len(__snake_case ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` a : Dict = ( encoded_inputs['global_attention_mask'] + [-1] * difference ) elif self.padding_side == "left": a : Union[str, Any] = [-1] * difference + encoded_inputs[ 'global_attention_mask' ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
297
1
'''simple docstring''' # Copyright 2022 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import os import subprocess from packaging.version import Version, parse from accelerate.commands.config.config_args import default_config_file, load_config_from_file lowerCAmelCase: List[Any] = 'Run commands across TPU VMs for initial setup before running `accelerate launch`.' def lowerCamelCase__ ( _A=None ): if subparsers is not None: a : Dict = subparsers.add_parser('tpu-config' , description=_description ) else: a : Optional[int] = argparse.ArgumentParser('Accelerate tpu-config command' , description=_description ) # Core arguments a : Optional[int] = parser.add_argument_group( 'Config Arguments' , 'Arguments that can be configured through `accelerate config`.' ) config_args.add_argument( '--config_file' , type=_A , default=_A , help='Path to the config file to use for accelerate.' , ) config_args.add_argument( '--tpu_name' , default=_A , help='The name of the TPU to use. If not specified, will use the TPU specified in the config file.' , ) config_args.add_argument( '--tpu_zone' , default=_A , help='The zone of the TPU to use. If not specified, will use the zone specified in the config file.' , ) a : int = parser.add_argument_group('TPU Arguments' , 'Arguments for options ran inside the TPU.' ) pod_args.add_argument( '--use_alpha' , action='store_true' , help='Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.' , ) pod_args.add_argument( '--command_file' , default=_A , help='The path to the file containing the commands to run on the pod on startup.' , ) pod_args.add_argument( '--command' , action='append' , nargs='+' , help='A command to run on the pod. Can be passed multiple times.' , ) pod_args.add_argument( '--install_accelerate' , action='store_true' , help='Whether to install accelerate on the pod. Defaults to False.' , ) pod_args.add_argument( '--accelerate_version' , default='latest' , help='The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify \'dev\' to install from GitHub.' , ) pod_args.add_argument( '--debug' , action='store_true' , help='If set, will print the command that would be run instead of running it.' ) if subparsers is not None: parser.set_defaults(func=_A ) return parser def lowerCamelCase__ ( _A ): a : Union[str, Any] = None # Get the default from the config file if it exists. if args.config_file is not None or os.path.isfile(_A ): a : List[Any] = load_config_from_file(args.config_file ) if not args.command_file and defaults.command_file is not None and not args.command: a : Tuple = defaults.command_file if not args.command and defaults.commands is not None: a : Any = defaults.commands if not args.tpu_name: a : Optional[int] = defaults.tpu_name if not args.tpu_zone: a : int = defaults.tpu_zone if args.accelerate_version == "dev": a : str = 'git+https://github.com/huggingface/accelerate.git' elif args.accelerate_version == "latest": a : Any = 'accelerate -U' elif isinstance(parse(args.accelerate_version ) , _A ): a : int = f"""accelerate=={args.accelerate_version}""" if not args.command_file and not args.command: raise ValueError('You must specify either a command file or a command to run on the pod.' ) if args.command_file: with open(args.command_file , 'r' ) as f: a : int = [f.read().splitlines()] # To turn list of lists into list of strings if isinstance(args.command[0] , _A ): a : Tuple = [line for cmd in args.command for line in cmd] # Default to the shared folder and install accelerate a : Union[str, Any] = ['cd /usr/share'] if args.install_accelerate: new_cmd += [f"""pip install {args.accelerate_version}"""] new_cmd += args.command a : Optional[int] = '; '.join(_A ) # Then send it to gcloud # Eventually try to use google-api-core to do this instead of subprocess a : str = ['gcloud'] if args.use_alpha: cmd += ["alpha"] cmd += [ "compute", "tpus", "tpu-vm", "ssh", args.tpu_name, "--zone", args.tpu_zone, "--command", args.command, "--worker", "all", ] if args.debug: print(f"""Running {" ".join(_A )}""" ) return subprocess.run(_A ) print('Successfully setup pod.' ) def lowerCamelCase__ ( ): a : Optional[Any] = tpu_command_parser() a : str = parser.parse_args() tpu_command_launcher(_A )
297
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class a__: def __init__( self : Tuple ): a : Optional[int] = '' a : Optional[Any] = '' a : str = [] a : int = 0 a : str = 2_56 a : Union[str, Any] = 0 a : Any = 0 a : Optional[int] = 0 a : List[str] = 0 def lowercase_ ( self : str , __snake_case : str ): a : Any = cva.imread(__snake_case , 0 ) a : Optional[Any] = copy.deepcopy(self.img ) a , a , a : int = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label='x' ) a : Optional[int] = np.sum(__snake_case ) for i in range(len(__snake_case ) ): a : Optional[Any] = x[i] / self.k self.sk += prk a : str = (self.L - 1) * self.sk if self.rem != 0: a : Optional[int] = int(last % last ) a : int = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__snake_case ) a : str = int(np.ma.count(self.img ) / self.img[1].size ) a : Optional[int] = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a : Any = self.img[j][i] if num != self.last_list[num]: a : str = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def lowercase_ ( self : Dict ): plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def lowercase_ ( self : List[Any] ): cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": lowerCAmelCase: Optional[Any] = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') lowerCAmelCase: Tuple = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
297
1
'''simple docstring''' import unittest from queue import Empty from threading import Thread from transformers import AutoTokenizer, TextIteratorStreamer, TextStreamer, is_torch_available from transformers.testing_utils import CaptureStdout, require_torch, torch_device from ..test_modeling_common import ids_tensor if is_torch_available(): import torch from transformers import AutoModelForCausalLM @require_torch class a__( unittest.TestCase ): def lowercase_ ( self : Optional[int] ): a : List[str] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) a : List[str] = AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(__snake_case ) a : Tuple = -1 a : Union[str, Any] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__snake_case ) a : Any = model.generate(__snake_case , max_new_tokens=10 , do_sample=__snake_case ) a : int = tokenizer.decode(greedy_ids[0] ) with CaptureStdout() as cs: a : str = TextStreamer(__snake_case ) model.generate(__snake_case , max_new_tokens=10 , do_sample=__snake_case , streamer=__snake_case ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer a : List[str] = cs.out[:-1] self.assertEqual(__snake_case , __snake_case ) def lowercase_ ( self : Union[str, Any] ): a : Union[str, Any] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) a : List[str] = AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(__snake_case ) a : Tuple = -1 a : str = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__snake_case ) a : List[str] = model.generate(__snake_case , max_new_tokens=10 , do_sample=__snake_case ) a : int = tokenizer.decode(greedy_ids[0] ) a : List[Any] = TextIteratorStreamer(__snake_case ) a : List[Any] = {'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer} a : Dict = Thread(target=model.generate , kwargs=__snake_case ) thread.start() a : Dict = '' for new_text in streamer: streamer_text += new_text self.assertEqual(__snake_case , __snake_case ) def lowercase_ ( self : Any ): a : List[str] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) a : Any = AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(__snake_case ) a : List[Any] = -1 a : str = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__snake_case ) a : List[str] = model.generate(__snake_case , max_new_tokens=10 , do_sample=__snake_case ) a : int = greedy_ids[:, input_ids.shape[1] :] a : Dict = tokenizer.decode(new_greedy_ids[0] ) with CaptureStdout() as cs: a : List[Any] = TextStreamer(__snake_case , skip_prompt=__snake_case ) model.generate(__snake_case , max_new_tokens=10 , do_sample=__snake_case , streamer=__snake_case ) # The greedy text should be printed to stdout, except for the final "\n" in the streamer a : Union[str, Any] = cs.out[:-1] self.assertEqual(__snake_case , __snake_case ) def lowercase_ ( self : Union[str, Any] ): # Tests that we can pass `decode_kwargs` to the streamer to control how the tokens are decoded. Must be tested # with actual models -- the dummy models' tokenizers are not aligned with their models, and # `skip_special_tokens=True` has no effect on them a : Optional[int] = AutoTokenizer.from_pretrained('distilgpt2' ) a : int = AutoModelForCausalLM.from_pretrained('distilgpt2' ).to(__snake_case ) a : Optional[Any] = -1 a : str = torch.ones((1, 5) , device=__snake_case ).long() * model.config.bos_token_id with CaptureStdout() as cs: a : List[Any] = TextStreamer(__snake_case , skip_special_tokens=__snake_case ) model.generate(__snake_case , max_new_tokens=1 , do_sample=__snake_case , streamer=__snake_case ) # The prompt contains a special token, so the streamer should not print it. As such, the output text, when # re-tokenized, must only contain one token a : Optional[Any] = cs.out[:-1] # Remove the final "\n" a : Tuple = tokenizer(__snake_case , return_tensors='pt' ) self.assertEqual(streamer_text_tokenized.input_ids.shape , (1, 1) ) def lowercase_ ( self : Any ): a : Optional[int] = AutoTokenizer.from_pretrained('hf-internal-testing/tiny-random-gpt2' ) a : Optional[Any] = AutoModelForCausalLM.from_pretrained('hf-internal-testing/tiny-random-gpt2' ).to(__snake_case ) a : Optional[Any] = -1 a : List[str] = ids_tensor((1, 5) , vocab_size=model.config.vocab_size ).to(__snake_case ) a : Union[str, Any] = TextIteratorStreamer(__snake_case , timeout=0.001 ) a : Dict = {'input_ids': input_ids, 'max_new_tokens': 10, 'do_sample': False, 'streamer': streamer} a : List[Any] = Thread(target=model.generate , kwargs=__snake_case ) thread.start() # The streamer will timeout after 0.001 seconds, so an exception will be raised with self.assertRaises(__snake_case ): a : Optional[int] = '' for new_text in streamer: streamer_text += new_text
297
'''simple docstring''' import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class a__: def __init__( self : List[Any] , __snake_case : Union[str, Any] ): if isinstance(__snake_case , __snake_case ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden a : str = deepcopy(__snake_case ) elif os.path.exists(__snake_case ): with io.open(__snake_case , 'r' , encoding='utf-8' ) as f: a : Optional[Any] = json.load(__snake_case ) else: try: a : Any = baseaa.urlsafe_baadecode(__snake_case ).decode('utf-8' ) a : Union[str, Any] = json.loads(__snake_case ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) a : List[str] = config self.set_stage_and_offload() def lowercase_ ( self : List[str] ): # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. a : Dict = self.get_value('zero_optimization.stage' , -1 ) # offload a : str = False if self.is_zeroa() or self.is_zeroa(): a : Union[str, Any] = set(['cpu', 'nvme'] ) a : Optional[Any] = set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: a : List[str] = True def lowercase_ ( self : Optional[Any] , __snake_case : Optional[Any] ): a : str = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) a : Dict = nodes.pop() for node in nodes: a : List[Any] = config.get(__snake_case ) if config is None: return None, ds_key return config, ds_key def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] , __snake_case : Any=None ): a , a : List[Any] = self.find_config_node(__snake_case ) if config is None: return default return config.get(__snake_case , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Any] , __snake_case : List[str]=False ): a : Optional[Any] = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) for node in nodes: a : str = config a : Dict = config.get(__snake_case ) if config is None: if must_exist: raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] ): a : Union[str, Any] = self.get_value(__snake_case ) return False if value is None else bool(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str ): a : Optional[Any] = self.get_value(__snake_case ) return False if value is None else not bool(__snake_case ) def lowercase_ ( self : Optional[Any] ): return self._stage == 2 def lowercase_ ( self : Union[str, Any] ): return self._stage == 3 def lowercase_ ( self : str ): return self._offload class a__: def __init__( self : Tuple , __snake_case : str ): a : Optional[Any] = engine def lowercase_ ( self : Union[str, Any] , __snake_case : str , **__snake_case : Tuple ): # runs backpropagation and handles mixed precision self.engine.backward(__snake_case , **__snake_case ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : List[str] ): super().__init__(__snake_case , device_placement=__snake_case , scaler=__snake_case ) a : Optional[Any] = hasattr(self.optimizer , 'overflow' ) def lowercase_ ( self : Dict , __snake_case : Dict=None ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def lowercase_ ( self : Optional[Any] ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def lowercase_ ( self : Tuple ): if self.__has_overflow__: return self.optimizer.overflow return False class a__( lowerCamelCase__ ): def __init__( self : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any] ): super().__init__(__snake_case , __snake_case ) def lowercase_ ( self : Any ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class a__: def __init__( self : List[Any] , __snake_case : str , __snake_case : Dict=0.001 , __snake_case : Union[str, Any]=0 , **__snake_case : List[Any] ): a : Optional[Any] = params a : str = lr a : List[str] = weight_decay a : str = kwargs class a__: def __init__( self : str , __snake_case : Optional[Any] , __snake_case : List[str]=None , __snake_case : Tuple=0 , **__snake_case : Any ): a : Union[str, Any] = optimizer a : Any = total_num_steps a : List[str] = warmup_num_steps a : int = kwargs
297
1
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList lowerCAmelCase: List[str] = ['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif'] class a__( lowerCamelCase__ ): def __init__( self : Any , __snake_case : List[str] , __snake_case : Union[str, Any] , __snake_case : List[Any]=None , __snake_case : Optional[Any]=1 ): a : Union[str, Any] = tokenizer a : Union[str, Any] = dataset a : Any = len(__snake_case ) if n_tasks is None else n_tasks a : List[str] = n_copies def __iter__( self : str ): a : List[Any] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['prompt'].strip() ) a : Dict = self.tokenizer(__snake_case , padding=__snake_case , return_tensors='pt' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class a__( lowerCamelCase__ ): def __init__( self : Union[str, Any] , __snake_case : int , __snake_case : Optional[Any] , __snake_case : str ): a : Dict = start_length a : Dict = eof_strings a : str = tokenizer def __call__( self : Optional[Any] , __snake_case : Optional[Any] , __snake_case : Any , **__snake_case : Union[str, Any] ): a : int = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) a : Optional[int] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(__snake_case ) def lowerCamelCase__ ( _A ): a : Optional[Any] = re.split('(%s)' % '|'.join(_A ) , _A ) # last string should be "" return "".join(string_list[:-2] ) def lowerCamelCase__ ( _A , _A , _A , _A , _A , _A=20 , **_A ): a : Optional[Any] = defaultdict(_A ) # dict of list of generated tokens for step, batch in tqdm(enumerate(_A ) ): with torch.no_grad(): a : Optional[Any] = batch['ids'].shape[-1] a : Optional[Any] = accelerator.unwrap_model(_A ).generate( input_ids=batch['ids'][:, : batch['input_len']] , num_return_sequences=_A , **_A ) # each task is generated batch_size times a : Tuple = batch['task_id'].repeat(_A ) a : List[Any] = accelerator.pad_across_processes( _A , dim=1 , pad_index=tokenizer.pad_token_id ) a , a : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) a : List[str] = generated_tokens.cpu().numpy() a : int = generated_tasks.cpu().numpy() for task, generated_tokens in zip(_A , _A ): gen_token_dict[task].append(_A ) a : Any = [[] for _ in range(_A )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: a : Optional[int] = tokenizer.decode(_A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) code_gens[task].append(remove_last_block(_A ) ) return code_gens def lowerCamelCase__ ( ): # Setup configuration a : Dict = HfArgumentParser(_A ) a : Any = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric a : List[Any] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing a : int = 'false' if args.num_workers is None: a : Dict = multiprocessing.cpu_count() # Use dataset load to feed to accelerate a : List[Any] = Accelerator() set_seed(args.seed , device_specific=_A ) # Load model and tokenizer a : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) a : str = tokenizer.eos_token a : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings a : Optional[Any] = { 'do_sample': args.do_sample, 'temperature': args.temperature, 'max_new_tokens': args.max_new_tokens, 'top_p': args.top_p, 'top_k': args.top_k, 'stopping_criteria': StoppingCriteriaList([EndOfFunctionCriteria(0 , _A , _A )] ), } # Load evaluation dataset and metric a : Optional[int] = load_dataset('openai_humaneval' ) a : Optional[Any] = load_metric('code_eval' ) a : Optional[int] = args.num_tasks if args.num_tasks is not None else len(human_eval['test'] ) a : Optional[Any] = args.n_samples // args.batch_size a : Any = TokenizedDataset(_A , human_eval['test'] , n_copies=_A , n_tasks=_A ) # do not confuse args.batch_size, which is actually the num_return_sequences a : int = DataLoader(_A , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: a : int = code_eval_metric.compute(references=[''] , predictions=[['']] ) except ValueError as exception: print( 'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`' ' flag to enable code evaluation.' ) raise exception a , a : int = accelerator.prepare(_A , _A ) a : int = complete_code( _A , _A , _A , _A , n_tasks=_A , batch_size=args.batch_size , **_A , ) if accelerator.is_main_process: a : List[str] = [] for task in tqdm(range(_A ) ): a : int = human_eval['test'][task]['test'] a : int = f"""check({human_eval["test"][task]["entry_point"]})""" references.append('\n' + test_func + '\n' + entry_point ) # Evaluate completions with "code_eval" metric a , a : Tuple = code_eval_metric.compute( references=_A , predictions=_A , num_workers=args.num_workers ) print(f"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , 'w' ) as fp: json.dump(_A , _A ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
297
'''simple docstring''' import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) lowerCAmelCase: int = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class a__( unittest.TestCase ): def lowercase_ ( self : int , __snake_case : str , __snake_case : bool , __snake_case : str = None , __snake_case : list = None ): a : Optional[int] = None a : Tuple = os.path.abspath(os.path.join('examples' , 'by_feature' ) ) a : List[str] = os.path.abspath('examples' ) for item in os.listdir(__snake_case ): if item not in EXCLUDE_EXAMPLES: a : int = os.path.join(__snake_case , __snake_case ) if os.path.isfile(__snake_case ) and ".py" in item_path: with self.subTest( tested_script=__snake_case , feature_script=__snake_case , tested_section='main()' if parser_only else 'training_function()' , ): a : List[Any] = compare_against_test( os.path.join(__snake_case , __snake_case ) , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = '\n'.join(__snake_case ) if special_strings is not None: for string in special_strings: a : Union[str, Any] = diff.replace(__snake_case , '' ) self.assertEqual(__snake_case , '' ) def lowercase_ ( self : Optional[Any] ): self.one_complete_example('complete_nlp_example.py' , __snake_case ) self.one_complete_example('complete_nlp_example.py' , __snake_case ) def lowercase_ ( self : Any ): a : Dict = os.path.abspath(os.path.join('examples' , 'cv_example.py' ) ) a : int = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , __snake_case , __snake_case , __snake_case ) self.one_complete_example('complete_cv_example.py' , __snake_case , __snake_case , __snake_case ) @mock.patch.dict(os.environ , {"""TESTING_MOCKED_DATALOADERS""": """1"""} ) class a__( lowerCamelCase__ ): lowercase__ = False @classmethod def lowercase_ ( cls : Optional[int] ): super().setUpClass() a : List[str] = tempfile.mkdtemp() a : Tuple = os.path.join(cls._tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) a : Optional[int] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def lowercase_ ( cls : Optional[int] ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def lowercase_ ( self : Tuple ): a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0' ) ) ) def lowercase_ ( self : Dict ): a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} """.split() a : int = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2' ) ) ) def lowercase_ ( self : Any ): a : Tuple = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0" )} """.split() a : int = run_command(self._launch_args + testargs , return_stdout=__snake_case ) self.assertNotIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) def lowercase_ ( self : int ): a : Optional[int] = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2" )} """.split() a : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=__snake_case ) if torch.cuda.is_available(): a : Any = torch.cuda.device_count() else: a : str = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) else: self.assertIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) @slow def lowercase_ ( self : Tuple ): a : Tuple = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'} ): a : Any = run_command(self._launch_args + testargs , return_stdout=__snake_case ) a : Optional[Any] = re.findall('({.+})' , __snake_case ) a : str = [r for r in results if 'accuracy' in r][-1] a : str = ast.literal_eval(__snake_case ) self.assertGreaterEqual(results['accuracy'] , 0.75 ) def lowercase_ ( self : Optional[int] ): a : int = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def lowercase_ ( self : Optional[int] ): with tempfile.TemporaryDirectory() as tmpdir: a : Optional[Any] = F""" examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(__snake_case , 'tracking' ) ) ) def lowercase_ ( self : List[str] ): a : Optional[Any] = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs ) def lowercase_ ( self : int ): a : Optional[Any] = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs )
297
1
'''simple docstring''' import argparse import re import torch from CLAP import create_model from transformers import AutoFeatureExtractor, ClapConfig, ClapModel lowerCAmelCase: Dict = { 'text_branch': 'text_model', 'audio_branch': 'audio_model.audio_encoder', 'attn': 'attention.self', 'self.proj': 'output.dense', 'attention.self_mask': 'attn_mask', 'mlp.fc1': 'intermediate.dense', 'mlp.fc2': 'output.dense', 'norm1': 'layernorm_before', 'norm2': 'layernorm_after', 'bn0': 'batch_norm', } lowerCAmelCase: Any = AutoFeatureExtractor.from_pretrained('laion/clap-htsat-unfused', truncation='rand_trunc') def lowerCamelCase__ ( _A , _A=False ): a , a : int = create_model( 'HTSAT-tiny' , 'roberta' , _A , precision='fp32' , device='cuda:0' if torch.cuda.is_available() else 'cpu' , enable_fusion=_A , fusion_type='aff_2d' if enable_fusion else None , ) return model, model_cfg def lowerCamelCase__ ( _A ): a : Optional[int] = {} a : Optional[int] = r'.*sequential.(\d+).*' a : List[Any] = r'.*_projection.(\d+).*' for key, value in state_dict.items(): # check if any key needs to be modified for key_to_modify, new_key in KEYS_TO_MODIFY_MAPPING.items(): if key_to_modify in key: a : Optional[Any] = key.replace(_A , _A ) if re.match(_A , _A ): # replace sequential layers with list a : int = re.match(_A , _A ).group(1 ) a : Optional[int] = key.replace(f"""sequential.{sequential_layer}.""" , f"""layers.{int(_A )//3}.linear.""" ) elif re.match(_A , _A ): a : int = int(re.match(_A , _A ).group(1 ) ) # Because in CLAP they use `nn.Sequential`... a : int = 1 if projecton_layer == 0 else 2 a : Optional[int] = key.replace(f"""_projection.{projecton_layer}.""" , f"""_projection.linear{transformers_projection_layer}.""" ) if "audio" and "qkv" in key: # split qkv into query key and value a : str = value a : Any = mixed_qkv.size(0 ) // 3 a : List[Any] = mixed_qkv[:qkv_dim] a : Optional[int] = mixed_qkv[qkv_dim : qkv_dim * 2] a : Optional[Any] = mixed_qkv[qkv_dim * 2 :] a : List[Any] = query_layer a : List[Any] = key_layer a : int = value_layer else: a : Optional[Any] = value return model_state_dict def lowerCamelCase__ ( _A , _A , _A , _A=False ): a , a : Any = init_clap(_A , enable_fusion=_A ) clap_model.eval() a : List[Any] = clap_model.state_dict() a : Optional[Any] = rename_state_dict(_A ) a : Any = ClapConfig() a : Optional[int] = enable_fusion a : Optional[int] = ClapModel(_A ) # ignore the spectrogram embedding layer model.load_state_dict(_A , strict=_A ) model.save_pretrained(_A ) transformers_config.save_pretrained(_A ) if __name__ == "__main__": lowerCAmelCase: str = 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('--config_path', default=None, type=str, help='Path to hf config.json of model to convert') parser.add_argument('--enable_fusion', action='store_true', help='Whether to enable fusion or not') lowerCAmelCase: int = parser.parse_args() convert_clap_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.config_path, args.enable_fusion)
297
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList lowerCAmelCase: List[str] = ['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif'] class a__( lowerCamelCase__ ): def __init__( self : Any , __snake_case : List[str] , __snake_case : Union[str, Any] , __snake_case : List[Any]=None , __snake_case : Optional[Any]=1 ): a : Union[str, Any] = tokenizer a : Union[str, Any] = dataset a : Any = len(__snake_case ) if n_tasks is None else n_tasks a : List[str] = n_copies def __iter__( self : str ): a : List[Any] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['prompt'].strip() ) a : Dict = self.tokenizer(__snake_case , padding=__snake_case , return_tensors='pt' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class a__( lowerCamelCase__ ): def __init__( self : Union[str, Any] , __snake_case : int , __snake_case : Optional[Any] , __snake_case : str ): a : Dict = start_length a : Dict = eof_strings a : str = tokenizer def __call__( self : Optional[Any] , __snake_case : Optional[Any] , __snake_case : Any , **__snake_case : Union[str, Any] ): a : int = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) a : Optional[int] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(__snake_case ) def lowerCamelCase__ ( _A ): a : Optional[Any] = re.split('(%s)' % '|'.join(_A ) , _A ) # last string should be "" return "".join(string_list[:-2] ) def lowerCamelCase__ ( _A , _A , _A , _A , _A , _A=20 , **_A ): a : Optional[Any] = defaultdict(_A ) # dict of list of generated tokens for step, batch in tqdm(enumerate(_A ) ): with torch.no_grad(): a : Optional[Any] = batch['ids'].shape[-1] a : Optional[Any] = accelerator.unwrap_model(_A ).generate( input_ids=batch['ids'][:, : batch['input_len']] , num_return_sequences=_A , **_A ) # each task is generated batch_size times a : Tuple = batch['task_id'].repeat(_A ) a : List[Any] = accelerator.pad_across_processes( _A , dim=1 , pad_index=tokenizer.pad_token_id ) a , a : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) a : List[str] = generated_tokens.cpu().numpy() a : int = generated_tasks.cpu().numpy() for task, generated_tokens in zip(_A , _A ): gen_token_dict[task].append(_A ) a : Any = [[] for _ in range(_A )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: a : Optional[int] = tokenizer.decode(_A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) code_gens[task].append(remove_last_block(_A ) ) return code_gens def lowerCamelCase__ ( ): # Setup configuration a : Dict = HfArgumentParser(_A ) a : Any = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric a : List[Any] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing a : int = 'false' if args.num_workers is None: a : Dict = multiprocessing.cpu_count() # Use dataset load to feed to accelerate a : List[Any] = Accelerator() set_seed(args.seed , device_specific=_A ) # Load model and tokenizer a : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) a : str = tokenizer.eos_token a : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings a : Optional[Any] = { 'do_sample': args.do_sample, 'temperature': args.temperature, 'max_new_tokens': args.max_new_tokens, 'top_p': args.top_p, 'top_k': args.top_k, 'stopping_criteria': StoppingCriteriaList([EndOfFunctionCriteria(0 , _A , _A )] ), } # Load evaluation dataset and metric a : Optional[int] = load_dataset('openai_humaneval' ) a : Optional[Any] = load_metric('code_eval' ) a : Optional[int] = args.num_tasks if args.num_tasks is not None else len(human_eval['test'] ) a : Optional[Any] = args.n_samples // args.batch_size a : Any = TokenizedDataset(_A , human_eval['test'] , n_copies=_A , n_tasks=_A ) # do not confuse args.batch_size, which is actually the num_return_sequences a : int = DataLoader(_A , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: a : int = code_eval_metric.compute(references=[''] , predictions=[['']] ) except ValueError as exception: print( 'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`' ' flag to enable code evaluation.' ) raise exception a , a : int = accelerator.prepare(_A , _A ) a : int = complete_code( _A , _A , _A , _A , n_tasks=_A , batch_size=args.batch_size , **_A , ) if accelerator.is_main_process: a : List[str] = [] for task in tqdm(range(_A ) ): a : int = human_eval['test'][task]['test'] a : int = f"""check({human_eval["test"][task]["entry_point"]})""" references.append('\n' + test_func + '\n' + entry_point ) # Evaluate completions with "code_eval" metric a , a : Tuple = code_eval_metric.compute( references=_A , predictions=_A , num_workers=args.num_workers ) print(f"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , 'w' ) as fp: json.dump(_A , _A ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
297
1
'''simple docstring''' import os from typing import List, Optional, Union from ...tokenization_utils import PreTrainedTokenizer from ...tokenization_utils_base import AddedToken from ...utils import logging lowerCAmelCase: Optional[Any] = logging.get_logger(__name__) lowerCAmelCase: int = {'vocab_file': 'vocab.txt'} lowerCAmelCase: Union[str, Any] = { 'vocab_file': { 'facebook/esm2_t6_8M_UR50D': 'https://huggingface.co/facebook/esm2_t6_8M_UR50D/resolve/main/vocab.txt', 'facebook/esm2_t12_35M_UR50D': 'https://huggingface.co/facebook/esm2_t12_35M_UR50D/resolve/main/vocab.txt', }, } lowerCAmelCase: Optional[Any] = { 'facebook/esm2_t6_8M_UR50D': 1_0_2_4, 'facebook/esm2_t12_35M_UR50D': 1_0_2_4, } def lowerCamelCase__ ( _A ): with open(_A , 'r' ) as f: a : Any = f.read().splitlines() return [l.strip() for l in lines] class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] def __init__( self : Any , __snake_case : List[Any] , __snake_case : Optional[int]="<unk>" , __snake_case : int="<cls>" , __snake_case : Dict="<pad>" , __snake_case : str="<mask>" , __snake_case : str="<eos>" , **__snake_case : List[str] , ): super().__init__(**__snake_case ) a : List[Any] = load_vocab_file(__snake_case ) a : Dict = dict(enumerate(self.all_tokens ) ) a : Tuple = {tok: ind for ind, tok in enumerate(self.all_tokens )} a : str = unk_token a : Union[str, Any] = cls_token a : List[str] = pad_token a : Optional[Any] = mask_token a : Union[str, Any] = eos_token a : List[str] = self.all_tokens self._create_trie(self.unique_no_split_tokens ) def lowercase_ ( self : Dict , __snake_case : int ): return self._id_to_token.get(__snake_case , self.unk_token ) def lowercase_ ( self : Optional[int] , __snake_case : str ): return self._token_to_id.get(__snake_case , self._token_to_id.get(self.unk_token ) ) def lowercase_ ( self : Optional[int] , __snake_case : str , **__snake_case : Optional[int] ): return text.split() def lowercase_ ( self : Union[str, Any] , __snake_case : Any=False ): return len(self._id_to_token ) def lowercase_ ( self : List[str] ): return {token: i for i, token in enumerate(self.all_tokens )} def lowercase_ ( self : List[str] , __snake_case : str ): return self._token_to_id.get(__snake_case , self._token_to_id.get(self.unk_token ) ) def lowercase_ ( self : Any , __snake_case : int ): return self._id_to_token.get(__snake_case , self.unk_token ) def lowercase_ ( self : Dict , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : str = [self.cls_token_id] a : Dict = [self.eos_token_id] # No sep token in ESM vocabulary if token_ids_a is None: if self.eos_token_id is None: return cls + token_ids_a else: return cls + token_ids_a + sep elif self.eos_token_id is None: raise ValueError('Cannot tokenize multiple sequences when EOS token is not set!' ) return cls + token_ids_a + sep + token_ids_a + sep # Multiple inputs always have an EOS token def lowercase_ ( self : List[str] , __snake_case : List , __snake_case : Optional[List] = None , __snake_case : bool = False ): if already_has_special_tokens: if token_ids_a is not None: raise ValueError( 'You should not supply a second sequence if the provided sequence of ' 'ids is already formatted with special tokens for the model.' ) return [1 if token in self.all_special_ids else 0 for token in token_ids_a] a : List[str] = [1] + ([0] * len(__snake_case )) + [1] if token_ids_a is not None: mask += [0] * len(__snake_case ) + [1] return mask def lowercase_ ( self : Dict , __snake_case : Union[str, Any] , __snake_case : Optional[Any] ): a : List[str] = os.path.join(__snake_case , (filename_prefix + '-' if filename_prefix else '') + 'vocab.txt' ) with open(__snake_case , 'w' ) as f: f.write('\n'.join(self.all_tokens ) ) return (vocab_file,) @property def lowercase_ ( self : int ): return self.get_vocab_size(with_added_tokens=__snake_case ) def lowercase_ ( self : Optional[int] , __snake_case : Union[List[str], List[AddedToken]] , __snake_case : bool = False ): return super()._add_tokens(__snake_case , special_tokens=__snake_case )
297
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( _A , _A , _A ): if isinstance(_A , torch.Tensor ): return image elif isinstance(_A , PIL.Image.Image ): a : Any = [image] if isinstance(image[0] , PIL.Image.Image ): a : List[str] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] a : int = np.concatenate(_A , axis=0 ) a : int = np.array(_A ).astype(np.floataa ) / 255.0 a : str = image.transpose(0 , 3 , 1 , 2 ) a : str = 2.0 * image - 1.0 a : Optional[int] = torch.from_numpy(_A ) elif isinstance(image[0] , torch.Tensor ): a : Optional[Any] = torch.cat(_A , dim=0 ) return image def lowerCamelCase__ ( _A , _A , _A , _A=0.9995 ): if not isinstance(_A , np.ndarray ): a : Dict = True a : Optional[Any] = va.device a : Optional[int] = va.cpu().numpy() a : Union[str, Any] = va.cpu().numpy() a : Any = np.sum(va * va / (np.linalg.norm(_A ) * np.linalg.norm(_A )) ) if np.abs(_A ) > DOT_THRESHOLD: a : Any = (1 - t) * va + t * va else: a : Any = np.arccos(_A ) a : Tuple = np.sin(_A ) a : Optional[Any] = theta_a * t a : List[Any] = np.sin(_A ) a : Dict = np.sin(theta_a - theta_t ) / sin_theta_a a : int = sin_theta_t / sin_theta_a a : Any = sa * va + sa * va if inputs_are_torch: a : Dict = torch.from_numpy(_A ).to(_A ) return va def lowerCamelCase__ ( _A , _A ): a : Optional[int] = F.normalize(_A , dim=-1 ) a : str = F.normalize(_A , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( _A , _A ): for param in model.parameters(): a : int = value class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : AutoencoderKL , __snake_case : CLIPTextModel , __snake_case : CLIPModel , __snake_case : CLIPTokenizer , __snake_case : UNetaDConditionModel , __snake_case : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , __snake_case : CLIPFeatureExtractor , __snake_case : List[str]=None , __snake_case : List[str]=None , __snake_case : List[Any]=None , ): super().__init__() self.register_modules( vae=__snake_case , text_encoder=__snake_case , clip_model=__snake_case , tokenizer=__snake_case , unet=__snake_case , scheduler=__snake_case , feature_extractor=__snake_case , coca_model=__snake_case , coca_tokenizer=__snake_case , coca_transform=__snake_case , ) a : Optional[Any] = ( feature_extractor.size if isinstance(feature_extractor.size , __snake_case ) else feature_extractor.size['shortest_edge'] ) a : Optional[int] = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , __snake_case ) set_requires_grad(self.clip_model , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory a : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__snake_case ) def lowercase_ ( self : Union[str, Any] ): self.enable_attention_slicing(__snake_case ) def lowercase_ ( self : Optional[Any] ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : Tuple ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : int ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : Union[str, Any] ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : int , __snake_case : Dict , __snake_case : str , __snake_case : Optional[int] ): # get the original timestep using init_timestep a : Optional[Any] = min(int(num_inference_steps * strength ) , __snake_case ) a : Union[str, Any] = max(num_inference_steps - init_timestep , 0 ) a : List[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase_ ( self : Dict , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Any , __snake_case : Optional[Any]=None ): if not isinstance(__snake_case , torch.Tensor ): raise ValueError(F"""`image` has to be of type `torch.Tensor` but is {type(__snake_case )}""" ) a : Optional[Any] = image.to(device=__snake_case , dtype=__snake_case ) if isinstance(__snake_case , __snake_case ): a : Optional[int] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__snake_case ) ] a : Optional[Any] = torch.cat(__snake_case , dim=0 ) else: a : Union[str, Any] = self.vae.encode(__snake_case ).latent_dist.sample(__snake_case ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : List[str] = 0.18215 * init_latents a : str = init_latents.repeat_interleave(__snake_case , dim=0 ) a : Dict = randn_tensor(init_latents.shape , generator=__snake_case , device=__snake_case , dtype=__snake_case ) # get latents a : Dict = self.scheduler.add_noise(__snake_case , __snake_case , __snake_case ) a : int = init_latents return latents def lowercase_ ( self : List[str] , __snake_case : Dict ): a : List[Any] = self.coca_transform(__snake_case ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): a : Optional[Any] = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) a : Union[str, Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('<end_of_text>' )[0].replace('<start_of_text>' , '' ).rstrip(' .,' ) def lowercase_ ( self : Tuple , __snake_case : Any , __snake_case : Optional[Any] ): a : List[Any] = self.feature_extractor.preprocess(__snake_case ) a : Optional[Any] = torch.from_numpy(clip_image_input['pixel_values'][0] ).unsqueeze(0 ).to(self.device ).half() a : int = self.clip_model.get_image_features(__snake_case ) a : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : Tuple = image_embeddings_clip.repeat_interleave(__snake_case , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowercase_ ( self : Tuple , __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : List[Any] , ): a : Optional[Any] = latents.detach().requires_grad_() a : List[Any] = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : Any = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): a : int = self.scheduler.alphas_cumprod[timestep] a : Any = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf a : List[str] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 a : Tuple = torch.sqrt(__snake_case ) a : str = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , __snake_case ): a : List[Any] = self.scheduler.sigmas[index] a : Optional[int] = latents - sigma * noise_pred else: raise ValueError(F"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Union[str, Any] = 1 / 0.18215 * sample a : str = self.vae.decode(__snake_case ).sample a : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) a : Tuple = transforms.Resize(self.feature_extractor_size )(__snake_case ) a : List[str] = self.normalize(__snake_case ).to(latents.dtype ) a : List[str] = self.clip_model.get_image_features(__snake_case ) a : Tuple = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : int = spherical_dist_loss(__snake_case , __snake_case ).mean() * clip_guidance_scale a : List[str] = -torch.autograd.grad(__snake_case , __snake_case )[0] if isinstance(self.scheduler , __snake_case ): a : List[Any] = latents.detach() + grads * (sigma**2) a : Optional[int] = noise_pred_original else: a : List[Any] = noise_pred_original - torch.sqrt(__snake_case ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Optional[int] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Optional[str] = None , __snake_case : Optional[str] = None , __snake_case : Optional[int] = 5_12 , __snake_case : Optional[int] = 5_12 , __snake_case : float = 0.6 , __snake_case : Optional[int] = 50 , __snake_case : Optional[float] = 7.5 , __snake_case : Optional[int] = 1 , __snake_case : float = 0.0 , __snake_case : Optional[float] = 1_00 , __snake_case : Optional[torch.Generator] = None , __snake_case : Optional[str] = "pil" , __snake_case : bool = True , __snake_case : float = 0.8 , __snake_case : float = 0.1 , __snake_case : float = 0.1 , ): if isinstance(__snake_case , __snake_case ) and len(__snake_case ) != batch_size: raise ValueError(F"""You have passed {batch_size} batch_size, but only {len(__snake_case )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(__snake_case , torch.Generator ) and batch_size > 1: a : Dict = [generator] + [None] * (batch_size - 1) a : Any = [ ('model', self.coca_model is None), ('tokenizer', self.coca_tokenizer is None), ('transform', self.coca_transform is None), ] a : List[str] = [x[0] for x in coca_is_none if x[1]] a : List[str] = ', '.join(__snake_case ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(__snake_case ): raise ValueError( F"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" F"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : int = self.get_image_description(__snake_case ) if style_prompt is None: if len(__snake_case ): raise ValueError( F"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" F""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : Union[str, Any] = self.get_image_description(__snake_case ) # get prompt text embeddings for content and style a : Optional[Any] = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] a : Dict = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] a : Any = slerp(__snake_case , __snake_case , __snake_case ) # duplicate text embeddings for each generation per prompt a : Optional[Any] = text_embeddings.repeat_interleave(__snake_case , dim=0 ) # set timesteps a : int = 'offset' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) a : Any = {} if accepts_offset: a : Optional[Any] = 1 self.scheduler.set_timesteps(__snake_case , **__snake_case ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) a , a : Tuple = self.get_timesteps(__snake_case , __snake_case , self.device ) a : Optional[int] = timesteps[:1].repeat(__snake_case ) # Preprocess image a : Optional[Any] = preprocess(__snake_case , __snake_case , __snake_case ) a : List[Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : str = preprocess(__snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : Union[str, Any] = slerp(__snake_case , __snake_case , __snake_case ) if clip_guidance_scale > 0: a : Dict = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : int = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : List[str] = slerp( __snake_case , __snake_case , __snake_case ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. a : int = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: a : Any = content_text_input.input_ids.shape[-1] a : List[Any] = self.tokenizer([''] , padding='max_length' , max_length=__snake_case , return_tensors='pt' ) a : List[str] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt a : Dict = uncond_embeddings.repeat_interleave(__snake_case , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a : Any = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. a : List[str] = (batch_size, self.unet.config.in_channels, height // 8, width // 8) a : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps a : int = torch.randn(__snake_case , generator=__snake_case , device='cpu' , dtype=__snake_case ).to( self.device ) else: a : Optional[int] = torch.randn(__snake_case , generator=__snake_case , device=self.device , dtype=__snake_case ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) a : List[str] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler a : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a : Optional[Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a : Union[str, Any] = {} if accepts_eta: a : List[str] = eta # check if the scheduler accepts generator a : List[Any] = 'generator' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: a : Any = generator with self.progress_bar(total=__snake_case ): for i, t in enumerate(__snake_case ): # expand the latents if we are doing classifier free guidance a : Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a : Dict = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : List[Any] = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample # perform classifier free guidance if do_classifier_free_guidance: a , a : List[str] = noise_pred.chunk(2 ) a : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: a : Optional[Any] = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) a , a : Union[str, Any] = self.cond_fn( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ) # compute the previous noisy sample x_t -> x_t-1 a : Any = self.scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Tuple = 1 / 0.18215 * latents a : Optional[int] = self.vae.decode(__snake_case ).sample a : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) a : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a : str = self.numpy_to_pil(__snake_case ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=__snake_case , nsfw_content_detected=__snake_case )
297
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_tokenizers_available, is_torch_available, is_vision_available, ) lowerCAmelCase: List[str] = {'processing_layoutxlm': ['LayoutXLMProcessor']} try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Dict = ['LayoutXLMTokenizer'] try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Union[str, Any] = ['LayoutXLMTokenizerFast'] if TYPE_CHECKING: from .processing_layoutxlm import LayoutXLMProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm import LayoutXLMTokenizer try: if not is_tokenizers_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_layoutxlm_fast import LayoutXLMTokenizerFast else: import sys lowerCAmelCase: Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A , _A , _A , _A , ): a : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: a : Union[str, Any] = 1 - (matter_density + radiation_density + dark_energy) a : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) a : int = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation lowerCAmelCase: Optional[Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
297
1
'''simple docstring''' import argparse import json import os from pathlib import Path import requests import torch from transformers import JukeboxConfig, JukeboxModel from transformers.utils import logging logging.set_verbosity_info() lowerCAmelCase: str = logging.get_logger(__name__) lowerCAmelCase: str = 'https://openaipublic.azureedge.net/jukebox/models/' lowerCAmelCase: str = { 'jukebox-1b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '1b_lyrics/prior_level_2.pth.tar', ], 'jukebox-5b-lyrics': [ '5b/vqvae.pth.tar', '5b/prior_level_0.pth.tar', '5b/prior_level_1.pth.tar', '5b_lyrics/prior_level_2.pth.tar', ], } def lowerCamelCase__ ( _A ): if key.endswith('.model.1.bias' ) and len(key.split('.' ) ) > 10: a : Tuple = key.replace('.model.1.bias' , '.conv1d_1.bias' ) elif key.endswith('.model.1.weight' ) and len(key.split('.' ) ) > 10: a : str = key.replace('.model.1.weight' , '.conv1d_1.weight' ) elif key.endswith('.model.3.bias' ) and len(key.split('.' ) ) > 10: a : List[str] = key.replace('.model.3.bias' , '.conv1d_2.bias' ) elif key.endswith('.model.3.weight' ) and len(key.split('.' ) ) > 10: a : Optional[int] = key.replace('.model.3.weight' , '.conv1d_2.weight' ) if "conditioner_blocks.0." in key: a : str = key.replace('conditioner_blocks.0' , 'conditioner_blocks' ) if "prime_prior" in key: a : Union[str, Any] = key.replace('prime_prior' , 'encoder' ) if ".emb." in key and "total" not in key and "absolute" not in key and "relative" not in key: a : List[str] = key.replace('.emb.' , '.' ) if key.endswith('k' ): # replace vqvae.X.k with vqvae.X.codebook return key.replace('.k' , '.codebook' ) if "y_emb." in key: return key.replace('y_emb.' , 'metadata_embedding.' ) if "x_emb.emb." in key: a : Optional[Any] = key.replace('0.x_emb.emb' , 'embed_tokens' ) if "prime_state_ln" in key: return key.replace('prime_state_ln' , 'encoder.final_layer_norm' ) if ".ln" in key: return key.replace('.ln' , '.layer_norm' ) if "_ln" in key: return key.replace('_ln' , '_layer_norm' ) if "prime_state_proj" in key: return key.replace('prime_state_proj' , 'encoder.proj_in' ) if "prime_x_out" in key: return key.replace('prime_x_out' , 'encoder.lm_head' ) if "prior.x_out" in key: return key.replace('x_out' , 'fc_proj_out' ) if "x_emb" in key: return key.replace('x_emb' , 'embed_tokens' ) return key def lowerCamelCase__ ( _A , _A , _A , _A ): a : Union[str, Any] = {} import re a : Dict = re.compile(r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' ) a : Optional[Any] = re.compile( r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) a : str = re.compile(r'encoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' ) a : Any = re.compile(r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).(bias|weight)' ) a : Any = re.compile( r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) a : List[str] = re.compile(r'decoders.(\d*).level_blocks.(\d*).model.(\d*).(bias|weight)' ) a : Dict = re.compile(r'conditioner_blocks.(\d*).cond.model.(\d*).(\d).(bias|weight)' ) a : str = re.compile( r'conditioner_blocks.(\d*).cond.model.(\d*).(\d).model.(\d*).model.(\d*).(bias|weight)' ) a : Optional[int] = re.compile(r'conditioner_blocks.(\d*).cond.model.(\d*).(bias|weight)' ) for original_key, value in state_dict.items(): # rename vqvae.encoder keys if re_encoder_block_conv_in.fullmatch(_A ): a : Any = re_encoder_block_conv_in.match(_A ) a : Dict = regex_match.groups() a : List[Any] = int(groups[2] ) * 2 + int(groups[3] ) a : Union[str, Any] = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.{groups[-1]}""" a : List[Any] = re_encoder_block_conv_in.sub(_A , _A ) elif re_encoder_block_resnet.fullmatch(_A ): a : List[str] = re_encoder_block_resnet.match(_A ) a : List[str] = regex_match.groups() a : str = int(groups[2] ) * 2 + int(groups[3] ) a : Any = {'1': 1, '3': 2}[groups[-2]] a : Dict = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.downsample_block.{block_index}.""" a : List[Any] = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" a : int = prefix + resnet_block a : Dict = re_encoder_block_resnet.sub(_A , _A ) elif re_encoder_block_proj_out.fullmatch(_A ): a : str = re_encoder_block_proj_out.match(_A ) a : Dict = regex_match.groups() a : Optional[int] = f"""encoders.{groups[0]}.level_blocks.{groups[1]}.proj_out.{groups[-1]}""" a : int = re_encoder_block_proj_out.sub(_A , _A ) # rename vqvae.decoder keys elif re_decoder_block_conv_out.fullmatch(_A ): a : str = re_decoder_block_conv_out.match(_A ) a : List[str] = regex_match.groups() a : List[str] = int(groups[2] ) * 2 + int(groups[3] ) - 2 a : List[str] = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.{groups[-1]}""" a : Union[str, Any] = re_decoder_block_conv_out.sub(_A , _A ) elif re_decoder_block_resnet.fullmatch(_A ): a : str = re_decoder_block_resnet.match(_A ) a : Union[str, Any] = regex_match.groups() a : Union[str, Any] = int(groups[2] ) * 2 + int(groups[3] ) - 2 a : Optional[int] = {'1': 1, '3': 2}[groups[-2]] a : str = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.upsample_block.{block_index}.""" a : Union[str, Any] = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" a : Dict = prefix + resnet_block a : List[Any] = re_decoder_block_resnet.sub(_A , _A ) elif re_decoder_block_proj_in.fullmatch(_A ): a : List[Any] = re_decoder_block_proj_in.match(_A ) a : List[Any] = regex_match.groups() a : Any = f"""decoders.{groups[0]}.level_blocks.{groups[1]}.proj_in.{groups[-1]}""" a : Union[str, Any] = re_decoder_block_proj_in.sub(_A , _A ) # rename prior cond.model to upsampler.upsample_block and resnet elif re_prior_cond_conv_out.fullmatch(_A ): a : Dict = re_prior_cond_conv_out.match(_A ) a : Union[str, Any] = regex_match.groups() a : str = int(groups[1] ) * 2 + int(groups[2] ) - 2 a : Optional[Any] = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.{groups[-1]}""" a : Union[str, Any] = re_prior_cond_conv_out.sub(_A , _A ) elif re_prior_cond_resnet.fullmatch(_A ): a : List[str] = re_prior_cond_resnet.match(_A ) a : Any = regex_match.groups() a : Dict = int(groups[1] ) * 2 + int(groups[2] ) - 2 a : Dict = {'1': 1, '3': 2}[groups[-2]] a : int = f"""conditioner_blocks.upsampler.upsample_block.{block_index}.""" a : Any = f"""resnet_block.{groups[-3]}.conv1d_{conv_index}.{groups[-1]}""" a : List[Any] = prefix + resnet_block a : Union[str, Any] = re_prior_cond_resnet.sub(_A , _A ) elif re_prior_cond_proj_in.fullmatch(_A ): a : Optional[Any] = re_prior_cond_proj_in.match(_A ) a : Optional[int] = regex_match.groups() a : Union[str, Any] = f"""conditioner_blocks.upsampler.proj_in.{groups[-1]}""" a : str = re_prior_cond_proj_in.sub(_A , _A ) # keep original key else: a : Any = original_key a : str = replace_key(_A ) if f"""{key_prefix}.{key}""" not in model_state_dict or key is None: print(f"""failed converting {original_key} to {key}, does not match""" ) # handle missmatched shape elif value.shape != model_state_dict[f"""{key_prefix}.{key}"""].shape: a : Union[str, Any] = model_state_dict[f"""{key_prefix}.{key}"""] print(f"""{original_key}-> {key} : \nshape {val.shape} and { value.shape}, do not match""" ) a : List[Any] = original_key a : Dict = original_key a : List[str] = value return new_dict @torch.no_grad() def lowerCamelCase__ ( _A=None , _A=None ): for file in MODEL_MAPPING[model_name]: if not os.path.isfile(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" ): a : List[str] = requests.get(f"""{PREFIX}{file}""" , allow_redirects=_A ) os.makedirs(f"""{pytorch_dump_folder_path}/""" , exist_ok=_A ) open(f"""{pytorch_dump_folder_path}/{file.split("/" )[-1]}""" , 'wb' ).write(r.content ) a : Tuple = MODEL_MAPPING[model_name.split('/' )[-1]] a : int = JukeboxConfig.from_pretrained(_A ) a : Dict = JukeboxModel(_A ) a : str = [] a : int = {} for i, dict_name in enumerate(_A ): a : Optional[Any] = torch.load(f"""{pytorch_dump_folder_path}/{dict_name.split("/" )[-1]}""" )['model'] a : Optional[Any] = {} for k in old_dic.keys(): if k.endswith('.b' ): a : Any = old_dic[k] elif k.endswith('.w' ): a : Union[str, Any] = old_dic[k] elif "level_2" not in dict_name and "cond.model." in k: a : int = old_dic[k] else: a : List[Any] = old_dic[k] a : Any = 'vqvae' if i == 0 else f"""priors.{3 - i}""" a : List[Any] = fix_jukebox_keys(_A , model.state_dict() , _A , _A ) weight_dict.append(_A ) a : List[Any] = weight_dict.pop(0 ) model.vqvae.load_state_dict(_A ) for i in range(len(_A ) ): model.priors[i].load_state_dict(weight_dict[2 - i] ) Path(_A ).mkdir(exist_ok=_A ) with open(f"""{pytorch_dump_folder_path}/mapping.json""" , 'w' ) as txtfile: json.dump(_A , _A ) print(f"""Saving model {model_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_A ) return weight_dict if __name__ == "__main__": lowerCAmelCase: str = argparse.ArgumentParser() # Required parameters parser.add_argument( '--model_name', default='jukebox-5b-lyrics', type=str, help='Name of the model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default='jukebox-5b-lyrics-converted', type=str, help='Path to the output PyTorch model directory.', ) lowerCAmelCase: List[Any] = parser.parse_args() convert_openai_checkpoint(args.model_name, args.pytorch_dump_folder_path)
297
'''simple docstring''' from __future__ import annotations import math class a__: def __init__( self : List[str] , __snake_case : int ): a : str = size # approximate the overall size of segment tree with given value a : Optional[int] = [0 for i in range(0 , 4 * size )] # create array to store lazy update a : Any = [0 for i in range(0 , 4 * size )] a : Dict = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowercase_ ( self : int , __snake_case : int ): return idx * 2 def lowercase_ ( self : Dict , __snake_case : int ): return idx * 2 + 1 def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : list[int] ): if left_element == right_element: a : Tuple = a[left_element - 1] else: a : Tuple = (left_element + right_element) // 2 self.build(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case ) self.build(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case ) a : Union[str, Any] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : int = self.lazy[idx] a : Union[str, Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : int = self.lazy[idx] a : Tuple = True a : Optional[Any] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: a : int = val if left_element != right_element: a : int = val a : Dict = val a : List[str] = True a : List[str] = True return True a : Tuple = (left_element + right_element) // 2 self.update(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) self.update(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case , __snake_case ) a : Optional[int] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) return True def lowercase_ ( self : Union[str, Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : str = self.lazy[idx] a : Optional[Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : Union[str, Any] = self.lazy[idx] a : Dict = True a : int = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] a : Dict = (left_element + right_element) // 2 a : Optional[int] = self.query(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.query(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case ) return max(__snake_case , __snake_case ) def __str__( self : Any ): return str([self.query(1 , 1 , self.size , __snake_case , __snake_case ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] lowerCAmelCase: int = 1_5 lowerCAmelCase: Optional[int] = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
297
1
'''simple docstring''' from PIL import Image def lowerCamelCase__ ( _A , _A ): a : Optional[Any] = (259 * (level + 255)) / (255 * (259 - level)) def contrast(_A ) -> int: return int(128 + factor * (c - 128) ) return img.point(_A ) if __name__ == "__main__": # Load image with Image.open('image_data/lena.jpg') as img: # Change contrast to 170 lowerCAmelCase: Tuple = change_contrast(img, 1_7_0) cont_img.save('image_data/lena_high_contrast.png', format='png')
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A ): while second != 0: a : Union[str, Any] = first & second first ^= second a : Tuple = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase: Optional[int] = int(input('Enter the first number: ').strip()) lowerCAmelCase: Union[str, Any] = int(input('Enter the second number: ').strip()) print(F"{add(first, second) = }")
297
1
'''simple docstring''' import unittest from transformers import JukeboxTokenizer from transformers.testing_utils import require_torch class a__( unittest.TestCase ): lowercase__ = JukeboxTokenizer lowercase__ = { """artist""": """Zac Brown Band""", """genres""": """Country""", """lyrics""": """I met a traveller from an antique land, Who said \"Two vast and trunkless legs of stone Stand in the desert. . . . Near them, on the sand, Half sunk a shattered visage lies, whose frown, And wrinkled lip, and sneer of cold command, Tell that its sculptor well those passions read Which yet survive, stamped on these lifeless things, The hand that mocked them, and the heart that fed; And on the pedestal, these words appear: My name is Ozymandias, King of Kings; Look on my Works, ye Mighty, and despair! Nothing beside remains. Round the decay Of that colossal Wreck, boundless and bare The lone and level sands stretch far away """, } @require_torch def lowercase_ ( self : str ): import torch a : str = JukeboxTokenizer.from_pretrained('openai/jukebox-1b-lyrics' ) a : Optional[int] = tokenizer(**self.metas )['input_ids'] # fmt: off a : Tuple = [ torch.tensor([[ 0, 0, 0, 71_69, 5_07, 9, 76, 39, 31, 46, 76, 27, 76, 46, 44, 27, 48, 31, 38, 38, 31, 44, 76, 32, 44, 41, 39, 76, 27, 40, 76, 27, 40, 46, 35, 43, 47, 31, 76, 38, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 41, 76, 45, 27, 35, 30, 76, 71, 20, 49, 41, 76, 48, 27, 45, 46, 76, 27, 40, 30, 76, 46, 44, 47, 40, 37, 38, 31, 45, 45, 76, 38, 31, 33, 45, 76, 41, 32, 76, 45, 46, 41, 40, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 19, 46, 27, 40, 30, 76, 35, 40, 76, 46, 34, 31, 76, 30, 31, 45, 31, 44, 46, 63, 76, 63, 76, 63, 76, 63, 76, 14, 31, 27, 44, 76, 46, 34, 31, 39, 64, 76, 41, 40, 76, 46, 34, 31, 76, 45, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 8, 27, 38, 32, 76, 45, 47, 40, 37, 76, 27, 76, 45, 34, 27, 46, 46, 31, 44, 31, 30, 76, 48, 35, 45, 27, 33, 31, 76, 38, 35, 31, 45, 64, 76, 49, 34, 41, 45, 31, 76, 32, 44, 41, 49, 40, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 49, 44, 35, 40, 37, 38, 31, 30, 76, 38, 35, 42, 64, 76, 27, 40, 30, 76, 45, 40, 31, 31, 44, 76, 41, 32, 76, 29, 41, 38, 30, 76, 29, 41, 39, 39, 27, 40, 30, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 31, 38, 38, 76, 46, 34, 27, 46, 76, 35, 46, 45, 76, 45, 29, 47, 38, 42, 46, 41, 44, 76, 49, 31, 38, 38, 76, 46, 34, 41, 45, 31, 76, 42, 27, 45, 45, 35, 41, 40, 45, 76, 44, 31, 27, 30, 78, 76, 76, 76, 76, 76, 76, 76, 76, 23, 34, 35, 29, 34, 76, 51, 31, 46, 76, 45, 47, 44, 48, 35, 48, 31, 64, 76, 45, 46, 27, 39, 42, 31, 30, 76, 41, 40, 76, 46, 34, 31, 45, 31, 76, 38, 35, 32, 31, 38, 31, 45, 45, 76, 46, 34, 35, 40, 33, 45, 64, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 34, 27, 40, 30, 76, 46, 34, 27, 46, 76, 39, 41, 29, 37, 31, 30, 76, 46, 34, 31, 39, 64, 76, 27, 40, 30, 76, 46, 34, 31, 76, 34, 31, 27, 44, 46, 76, 46, 34, 27, 46, 76, 32, 31, 30, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 1, 40, 30, 76, 41, 40, 76, 46, 34, 31, 76, 42, 31, 30, 31, 45, 46, 27, 38, 64, 76, 46, 34, 31, 45, 31, 76, 49, 41, 44, 30, 45, 76, 27, 42, 42, 31, 27, 44, 65, 78, 76, 76, 76, 76, 76, 76, 76, 76, 13, 51, 76, 40, 27, 39, 31, 76, 35, 45, 76, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 76, 11, 35, 40, 33, 76, 41, 32, 76, 11, 35, 40, 33, 45, 66, 78, 76, 76, 76, 76, 76, 76, 76, 76, 12, 41, 41, 37, 76, 41, 40, 76, 39, 51, 76, 23, 41, 44, 37, 45, 64, 76, 51, 31, 76, 13, 35, 33, 34, 46, 51, 64, 76, 27, 40, 30, 76, 30, 31, 45, 42, 27, 35, 44, 67, 78, 76, 76, 76, 76, 76, 76, 76, 76, 14, 41, 46, 34, 35, 40, 33, 76, 28, 31, 45, 35, 30, 31, 76, 44, 31, 39, 27, 35, 40, 45, 63, 76, 18, 41, 47, 40, 30, 76, 46, 34, 31, 76, 30, 31, 29, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76, 15, 32, 76, 46, 34, 27, 46, 76, 29, 41, 38, 41, 45, 45, 27, 38, 76, 23, 44, 31, 29, 37, 64, 76, 28, 41, 47, 40, 30, 38, 31, 45, 45, 76, 27, 40, 30, 76, 28, 27, 44, 31, 78, 76, 76, 76, 76, 76, 76, 76, 76, 20, 34, 31, 76, 38, 41, 40, 31, 76, 27, 40, 30, 76, 38, 31, 48, 31, 38, 76, 45, 27, 40, 30, 45, 76, 45, 46, 44, 31, 46, 29, 34, 76, 32, 27, 44, 76, 27, 49, 27, 51, 78, 76, 76, 76, 76, 76, 76, 76, 76]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), torch.tensor([[0, 0, 0, 10_69, 11]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) ) @require_torch def lowercase_ ( self : Union[str, Any] ): import torch a : Optional[Any] = JukeboxTokenizer.from_pretrained('openai/jukebox-5b-lyrics' ) a : Optional[int] = tokenizer(**self.metas )['input_ids'] # fmt: off a : Tuple = [ torch.tensor([[ 0, 0, 0, 10_69, 11, -1, -1, -1, -1, 9, 77, 39, 31, 46, 77, 27, 77, 46, 44, 27, 48, 31, 38, 38, 31, 44, 77, 32, 44, 41, 39, 77, 27, 40, 77, 27, 40, 46, 35, 43, 47, 31, 77, 38, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 41, 77, 45, 27, 35, 30, 77, 72, 20, 49, 41, 77, 48, 27, 45, 46, 77, 27, 40, 30, 77, 46, 44, 47, 40, 37, 38, 31, 45, 45, 77, 38, 31, 33, 45, 77, 41, 32, 77, 45, 46, 41, 40, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 19, 46, 27, 40, 30, 77, 35, 40, 77, 46, 34, 31, 77, 30, 31, 45, 31, 44, 46, 63, 77, 63, 77, 63, 77, 63, 77, 14, 31, 27, 44, 77, 46, 34, 31, 39, 64, 77, 41, 40, 77, 46, 34, 31, 77, 45, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 8, 27, 38, 32, 77, 45, 47, 40, 37, 77, 27, 77, 45, 34, 27, 46, 46, 31, 44, 31, 30, 77, 48, 35, 45, 27, 33, 31, 77, 38, 35, 31, 45, 64, 77, 49, 34, 41, 45, 31, 77, 32, 44, 41, 49, 40, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 49, 44, 35, 40, 37, 38, 31, 30, 77, 38, 35, 42, 64, 77, 27, 40, 30, 77, 45, 40, 31, 31, 44, 77, 41, 32, 77, 29, 41, 38, 30, 77, 29, 41, 39, 39, 27, 40, 30, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 31, 38, 38, 77, 46, 34, 27, 46, 77, 35, 46, 45, 77, 45, 29, 47, 38, 42, 46, 41, 44, 77, 49, 31, 38, 38, 77, 46, 34, 41, 45, 31, 77, 42, 27, 45, 45, 35, 41, 40, 45, 77, 44, 31, 27, 30, 79, 77, 77, 77, 77, 77, 77, 77, 77, 23, 34, 35, 29, 34, 77, 51, 31, 46, 77, 45, 47, 44, 48, 35, 48, 31, 64, 77, 45, 46, 27, 39, 42, 31, 30, 77, 41, 40, 77, 46, 34, 31, 45, 31, 77, 38, 35, 32, 31, 38, 31, 45, 45, 77, 46, 34, 35, 40, 33, 45, 64, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 34, 27, 40, 30, 77, 46, 34, 27, 46, 77, 39, 41, 29, 37, 31, 30, 77, 46, 34, 31, 39, 64, 77, 27, 40, 30, 77, 46, 34, 31, 77, 34, 31, 27, 44, 46, 77, 46, 34, 27, 46, 77, 32, 31, 30, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 1, 40, 30, 77, 41, 40, 77, 46, 34, 31, 77, 42, 31, 30, 31, 45, 46, 27, 38, 64, 77, 46, 34, 31, 45, 31, 77, 49, 41, 44, 30, 45, 77, 27, 42, 42, 31, 27, 44, 65, 79, 77, 77, 77, 77, 77, 77, 77, 77, 13, 51, 77, 40, 27, 39, 31, 77, 35, 45, 77, 15, 52, 51, 39, 27, 40, 30, 35, 27, 45, 64, 77, 11, 35, 40, 33, 77, 41, 32, 77, 11, 35, 40, 33, 45, 66, 79, 77, 77, 77, 77, 77, 77, 77, 77, 12, 41, 41, 37, 77, 41, 40, 77, 39, 51, 77, 23, 41, 44, 37, 45, 64, 77, 51, 31, 77, 13, 35, 33, 34, 46, 51, 64, 77, 27, 40, 30, 77, 30, 31, 45, 42, 27, 35, 44, 67, 79, 77, 77, 77, 77, 77, 77, 77, 77, 14, 41, 46, 34, 35, 40, 33, 77, 28, 31, 45, 35, 30, 31, 77, 44, 31, 39, 27, 35, 40, 45, 63, 77, 18, 41, 47, 40, 30, 77, 46, 34, 31, 77, 30, 31, 29, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77, 15, 32, 77, 46, 34, 27, 46, 77, 29, 41, 38, 41, 45, 45, 27, 38, 77, 23, 44, 31, 29, 37, 64, 77, 28, 41, 47, 40, 30, 38, 31, 45, 45, 77, 27, 40, 30, 77, 28, 27, 44, 31, 79, 77, 77, 77, 77, 77, 77, 77, 77, 20, 34, 31, 77, 38, 41, 40, 31, 77, 27, 40, 30, 77, 38, 31, 48, 31, 38, 77, 45, 27, 40, 30, 45, 77, 45, 46, 44, 31, 46, 29, 34, 77, 32, 27, 44, 77, 27, 49, 27, 51, 79, 77, 77, 77, 77, 77, 77, 77, 77]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), torch.tensor([[0, 0, 0, 10_69, 11, -1, -1, -1, -1]] ), ] # fmt: on self.assertTrue(torch.allclose(tokens[0] , EXPECTED_OUTPUT[0] ) ) self.assertTrue(torch.allclose(tokens[1] , EXPECTED_OUTPUT[1] ) ) self.assertTrue(torch.allclose(tokens[2] , EXPECTED_OUTPUT[2] ) )
297
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ ( _A , _A ): assert isinstance(_A , _A ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Optional[int] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , keep_in_memory=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Tuple = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Dict = features.copy() if features else default_expected_features a : Union[str, Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Tuple = tmp_path / 'cache' a : Optional[Any] = {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} a : Optional[int] = features.copy() if features else default_expected_features a : Dict = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Optional[int] = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCamelCase__ ( _A , _A ): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} a : Dict = {'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} a : int = features.copy() a : List[Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Dict = tmp_path / 'cache' a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[str] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , split=_A ).read() _check_json_dataset(_A , _A ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def lowerCamelCase__ ( _A , _A , _A ): if issubclass(_A , _A ): a : Optional[int] = jsonl_path elif issubclass(_A , _A ): a : Optional[int] = [jsonl_path] a : List[str] = tmp_path / 'cache' a : Dict = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) def lowerCamelCase__ ( _A , _A , _A=("train",) ): assert isinstance(_A , _A ) for split in splits: a : str = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : Any = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : int = JsonDatasetReader({'train': jsonl_path} , cache_dir=_A , keep_in_memory=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[Any] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = features.copy() if features else default_expected_features a : Any = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : List[str] = JsonDatasetReader({'train': jsonl_path} , features=_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): if split: a : Any = {split: jsonl_path} else: a : List[Any] = 'train' a : List[str] = {'train': jsonl_path, 'test': jsonl_path} a : List[Any] = tmp_path / 'cache' a : str = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase__ ( _A ): return json.load(_A ) def lowerCamelCase__ ( _A ): return [json.loads(_A ) for line in buffer] class a__: @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : Tuple , __snake_case : int , __snake_case : Optional[int] , __snake_case : Any ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case ).write() buffer.seek(0 ) a : List[str] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Tuple , __snake_case : Tuple , __snake_case : Any , __snake_case : Any , __snake_case : List[str] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : List[Any] , __snake_case : Any , __snake_case : Optional[int] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : List[Any] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Optional[int] , __snake_case : Any , __snake_case : str , __snake_case : int , __snake_case : List[Any] , __snake_case : Dict ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 def lowercase_ ( self : List[str] , __snake_case : str ): with pytest.raises(__snake_case ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def lowercase_ ( self : Tuple , __snake_case : Dict , __snake_case : List[Any] , __snake_case : int , __snake_case : List[str] , __snake_case : Optional[int] ): a : Tuple = tmp_path_factory.mktemp('data' ) / F"""test.json.{extension}""" a : List[Any] = str(shared_datadir / F"""test_file.json.{extension}""" ) JsonDatasetWriter(__snake_case , __snake_case , compression=__snake_case ).write() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() assert exported_content == original_content
297
1
'''simple docstring''' from __future__ import annotations from math import pi from typing import Protocol import matplotlib.pyplot as plt import numpy as np class a__( lowerCamelCase__ ): def lowercase_ ( self : Any , __snake_case : float ): return 0.0 def lowerCamelCase__ ( _A , _A ): a : Union[str, Any] = min([-20, np.min(fft_results[1 : samplerate // 2 - 1] )] ) a : int = max([20, np.max(fft_results[1 : samplerate // 2 - 1] )] ) return lowest, highest def lowerCamelCase__ ( _A , _A ): a : Dict = 512 a : Dict = [1] + [0] * (size - 1) a : Tuple = [filter_type.process(_A ) for item in inputs] a : Optional[Any] = [0] * (samplerate - size) # zero-padding outputs += filler a : List[str] = np.abs(np.fft.fft(_A ) ) a : List[Any] = 20 * np.logaa(_A ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) # Display within reasonable bounds a : str = get_bounds(_A , _A ) plt.ylim(max([-80, bounds[0]] ) , min([80, bounds[1]] ) ) plt.ylabel('Gain (dB)' ) plt.plot(_A ) plt.show() def lowerCamelCase__ ( _A , _A ): a : int = 512 a : Dict = [1] + [0] * (size - 1) a : Optional[Any] = [filter_type.process(_A ) for item in inputs] a : str = [0] * (samplerate - size) # zero-padding outputs += filler a : Tuple = np.angle(np.fft.fft(_A ) ) # Frequencies on log scale from 24 to nyquist frequency plt.xlim(24 , samplerate / 2 - 1 ) plt.xlabel('Frequency (Hz)' ) plt.xscale('log' ) plt.ylim(-2 * pi , 2 * pi ) plt.ylabel('Phase shift (Radians)' ) plt.plot(np.unwrap(_A , -2 * pi ) ) plt.show()
297
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCamelCase__ ( _A = "laptop" ): a : Any = f"""https://www.amazon.in/laptop/s?k={product}""" a : Tuple = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5', } a : Any = BeautifulSoup(requests.get(_A , headers=_A ).text ) # Initialize a Pandas dataframe with the column titles a : Any = DataFrame( columns=[ 'Product Title', 'Product Link', 'Current Price of the product', 'Product Rating', 'MRP of the product', 'Discount', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( 'div' , attrs={'class': 's-result-item', 'data-component-type': 's-search-result'} , ) , soup.find_all('div' , attrs={'class': 'a-row a-size-base a-color-base'} ) , ): try: a : Optional[int] = item.ha.text a : str = 'https://www.amazon.in/' + item.ha.a['href'] a : List[str] = item.find('span' , attrs={'class': 'a-offscreen'} ).text try: a : Optional[Any] = item.find('span' , attrs={'class': 'a-icon-alt'} ).text except AttributeError: a : Union[str, Any] = 'Not available' try: a : str = ( '₹' + item.find( 'span' , attrs={'class': 'a-price a-text-price'} ).text.split('₹' )[1] ) except AttributeError: a : int = '' try: a : Union[str, Any] = float( ( ( float(product_mrp.strip('₹' ).replace(',' , '' ) ) - float(product_price.strip('₹' ).replace(',' , '' ) ) ) / float(product_mrp.strip('₹' ).replace(',' , '' ) ) ) * 100 ) except ValueError: a : Any = float('nan' ) except AttributeError: pass a : Any = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] a : Any = ' ' a : List[str] = ' ' data_frame.index += 1 return data_frame if __name__ == "__main__": lowerCAmelCase: str = 'headphones' get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
297
1
'''simple docstring''' lowerCAmelCase: Optional[Any] = '0.18.2' from .configuration_utils import ConfigMixin from .utils import ( OptionalDependencyNotAvailable, is_flax_available, is_inflect_available, is_invisible_watermark_available, is_k_diffusion_available, is_k_diffusion_version, is_librosa_available, is_note_seq_available, is_onnx_available, is_scipy_available, is_torch_available, is_torchsde_available, is_transformers_available, is_transformers_version, is_unidecode_available, logging, ) try: if not is_onnx_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_onnx_objects import * # noqa F403 else: from .pipelines import OnnxRuntimeModel try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_pt_objects import * # noqa F403 else: from .models import ( AutoencoderKL, ControlNetModel, ModelMixin, PriorTransformer, TaFilmDecoder, TransformeraDModel, UNetaDModel, UNetaDConditionModel, UNetaDModel, UNetaDConditionModel, VQModel, ) from .optimization import ( get_constant_schedule, get_constant_schedule_with_warmup, get_cosine_schedule_with_warmup, get_cosine_with_hard_restarts_schedule_with_warmup, get_linear_schedule_with_warmup, get_polynomial_decay_schedule_with_warmup, get_scheduler, ) from .pipelines import ( AudioPipelineOutput, ConsistencyModelPipeline, DanceDiffusionPipeline, DDIMPipeline, DDPMPipeline, DiffusionPipeline, DiTPipeline, ImagePipelineOutput, KarrasVePipeline, LDMPipeline, LDMSuperResolutionPipeline, PNDMPipeline, RePaintPipeline, ScoreSdeVePipeline, ) from .schedulers import ( CMStochasticIterativeScheduler, DDIMInverseScheduler, DDIMParallelScheduler, DDIMScheduler, DDPMParallelScheduler, DDPMScheduler, DEISMultistepScheduler, DPMSolverMultistepInverseScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, EulerAncestralDiscreteScheduler, EulerDiscreteScheduler, HeunDiscreteScheduler, IPNDMScheduler, KarrasVeScheduler, KDPMaAncestralDiscreteScheduler, KDPMaDiscreteScheduler, PNDMScheduler, RePaintScheduler, SchedulerMixin, ScoreSdeVeScheduler, UnCLIPScheduler, UniPCMultistepScheduler, VQDiffusionScheduler, ) from .training_utils import EMAModel try: if not (is_torch_available() and is_scipy_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_scipy_objects import * # noqa F403 else: from .schedulers import LMSDiscreteScheduler try: if not (is_torch_available() and is_torchsde_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_torchsde_objects import * # noqa F403 else: from .schedulers import DPMSolverSDEScheduler try: if not (is_torch_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_objects import * # noqa F403 else: from .pipelines import ( AltDiffusionImgaImgPipeline, AltDiffusionPipeline, AudioLDMPipeline, CycleDiffusionPipeline, IFImgaImgPipeline, IFImgaImgSuperResolutionPipeline, IFInpaintingPipeline, IFInpaintingSuperResolutionPipeline, IFPipeline, IFSuperResolutionPipeline, ImageTextPipelineOutput, KandinskyImgaImgPipeline, KandinskyInpaintPipeline, KandinskyPipeline, KandinskyPriorPipeline, KandinskyVaaControlnetImgaImgPipeline, KandinskyVaaControlnetPipeline, KandinskyVaaImgaImgPipeline, KandinskyVaaInpaintPipeline, KandinskyVaaPipeline, KandinskyVaaPriorEmbaEmbPipeline, KandinskyVaaPriorPipeline, LDMTextToImagePipeline, PaintByExamplePipeline, SemanticStableDiffusionPipeline, ShapEImgaImgPipeline, ShapEPipeline, StableDiffusionAttendAndExcitePipeline, StableDiffusionControlNetImgaImgPipeline, StableDiffusionControlNetInpaintPipeline, StableDiffusionControlNetPipeline, StableDiffusionDepthaImgPipeline, StableDiffusionDiffEditPipeline, StableDiffusionImageVariationPipeline, StableDiffusionImgaImgPipeline, StableDiffusionInpaintPipeline, StableDiffusionInpaintPipelineLegacy, StableDiffusionInstructPixaPixPipeline, StableDiffusionLatentUpscalePipeline, StableDiffusionLDMaDPipeline, StableDiffusionModelEditingPipeline, StableDiffusionPanoramaPipeline, StableDiffusionParadigmsPipeline, StableDiffusionPipeline, StableDiffusionPipelineSafe, StableDiffusionPixaPixZeroPipeline, StableDiffusionSAGPipeline, StableDiffusionUpscalePipeline, StableUnCLIPImgaImgPipeline, StableUnCLIPPipeline, TextToVideoSDPipeline, TextToVideoZeroPipeline, UnCLIPImageVariationPipeline, UnCLIPPipeline, UniDiffuserModel, UniDiffuserPipeline, UniDiffuserTextDecoder, VersatileDiffusionDualGuidedPipeline, VersatileDiffusionImageVariationPipeline, VersatileDiffusionPipeline, VersatileDiffusionTextToImagePipeline, VideoToVideoSDPipeline, VQDiffusionPipeline, ) try: if not (is_torch_available() and is_transformers_available() and is_invisible_watermark_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_invisible_watermark_objects import * # noqa F403 else: from .pipelines import StableDiffusionXLImgaImgPipeline, StableDiffusionXLPipeline try: if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403 else: from .pipelines import StableDiffusionKDiffusionPipeline try: if not (is_torch_available() and is_transformers_available() and is_onnx_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_transformers_and_onnx_objects import * # noqa F403 else: from .pipelines import ( OnnxStableDiffusionImgaImgPipeline, OnnxStableDiffusionInpaintPipeline, OnnxStableDiffusionInpaintPipelineLegacy, OnnxStableDiffusionPipeline, OnnxStableDiffusionUpscalePipeline, StableDiffusionOnnxPipeline, ) try: if not (is_torch_available() and is_librosa_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_torch_and_librosa_objects import * # noqa F403 else: from .pipelines import AudioDiffusionPipeline, Mel try: if not (is_transformers_available() and is_torch_available() and is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_transformers_and_torch_and_note_seq_objects import * # noqa F403 else: from .pipelines import SpectrogramDiffusionPipeline try: if not is_flax_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_objects import * # noqa F403 else: from .models.controlnet_flax import FlaxControlNetModel from .models.modeling_flax_utils import FlaxModelMixin from .models.unet_ad_condition_flax import FlaxUNetaDConditionModel from .models.vae_flax import FlaxAutoencoderKL from .pipelines import FlaxDiffusionPipeline from .schedulers import ( FlaxDDIMScheduler, FlaxDDPMScheduler, FlaxDPMSolverMultistepScheduler, FlaxKarrasVeScheduler, FlaxLMSDiscreteScheduler, FlaxPNDMScheduler, FlaxSchedulerMixin, FlaxScoreSdeVeScheduler, ) try: if not (is_flax_available() and is_transformers_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_flax_and_transformers_objects import * # noqa F403 else: from .pipelines import ( FlaxStableDiffusionControlNetPipeline, FlaxStableDiffusionImgaImgPipeline, FlaxStableDiffusionInpaintPipeline, FlaxStableDiffusionPipeline, ) try: if not (is_note_seq_available()): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: from .utils.dummy_note_seq_objects import * # noqa F403 else: from .pipelines import MidiProcessor
297
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = StableUnCLIPImgaImgPipeline lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase__ = frozenset([] ) def lowercase_ ( self : int ): a : Dict = 32 a : str = embedder_hidden_size # image encoding components a : List[Any] = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) a : Dict = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=__snake_case , projection_dim=__snake_case , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) a : Dict = StableUnCLIPImageNormalizer(embedding_dim=__snake_case ) a : Optional[int] = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) a : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) a : Tuple = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__snake_case , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) a : Union[str, Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__snake_case , layers_per_block=1 , upcast_attention=__snake_case , use_linear_projection=__snake_case , ) torch.manual_seed(0 ) a : List[Any] = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.00085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=__snake_case , steps_offset=1 , ) torch.manual_seed(0 ) a : List[str] = AutoencoderKL() a : str = { # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def lowercase_ ( self : Tuple , __snake_case : List[str] , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=True ): if str(__snake_case ).startswith('mps' ): a : Tuple = torch.manual_seed(__snake_case ) else: a : List[Any] = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) a : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__snake_case ) ).to(__snake_case ) if pil_image: a : Optional[Any] = input_image * 0.5 + 0.5 a : Optional[Any] = input_image.clamp(0 , 1 ) a : Dict = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() a : int = DiffusionPipeline.numpy_to_pil(__snake_case )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def lowercase_ ( self : Optional[Any] ): a : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a : Union[str, Any] = self.get_dummy_components() a : Any = StableUnCLIPImgaImgPipeline(**__snake_case ) a : Tuple = sd_pipe.to(__snake_case ) sd_pipe.set_progress_bar_config(disable=__snake_case ) a : Union[str, Any] = self.get_dummy_inputs(__snake_case ) inputs.update({'image_embeds': None} ) a : str = sd_pipe(**__snake_case ).images a : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) a : Optional[int] = np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase_ ( self : List[str] ): a : int = torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=__snake_case ) def lowercase_ ( self : int ): a : Optional[int] = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=__snake_case ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def lowercase_ ( self : Dict ): self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__snake_case ) @slow @require_torch_gpu class a__( unittest.TestCase ): def lowercase_ ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Optional[Any] ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Union[str, Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) a : Optional[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = torch.Generator(device='cpu' ).manual_seed(0 ) a : Optional[int] = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Optional[int] ): a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) a : Union[str, Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a : str = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Any ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) a : Optional[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = pipe( __snake_case , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) a : int = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
297
1
'''simple docstring''' from collections import defaultdict from graphs.minimum_spanning_tree_prims import prisms_algorithm as mst def lowerCamelCase__ ( ): a , a : List[str] = 9, 14 # noqa: F841 a : Optional[Any] = [ [0, 1, 4], [0, 7, 8], [1, 2, 8], [7, 8, 7], [7, 6, 1], [2, 8, 2], [8, 6, 6], [2, 3, 7], [2, 5, 4], [6, 5, 2], [3, 5, 14], [3, 4, 9], [5, 4, 10], [1, 7, 11], ] a : str = defaultdict(_A ) for nodea, nodea, cost in edges: adjancency[nodea].append([nodea, cost] ) adjancency[nodea].append([nodea, cost] ) a : Any = mst(_A ) a : Optional[int] = [ [7, 6, 1], [2, 8, 2], [6, 5, 2], [0, 1, 4], [2, 5, 4], [2, 3, 7], [0, 7, 8], [3, 4, 9], ] for answer in expected: a : Union[str, Any] = tuple(answer[:2] ) a : Dict = tuple(edge[::-1] ) assert edge in result or reverse in result
297
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowerCAmelCase: Union[str, Any] = logging.get_logger(__name__) lowerCAmelCase: List[str] = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """t5""" lowercase__ = ["""past_key_values"""] lowercase__ = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : Union[str, Any] , __snake_case : int=3_21_28 , __snake_case : str=5_12 , __snake_case : Dict=64 , __snake_case : Optional[int]=20_48 , __snake_case : Tuple=6 , __snake_case : Any=None , __snake_case : Optional[int]=8 , __snake_case : str=32 , __snake_case : Union[str, Any]=1_28 , __snake_case : Optional[int]=0.1 , __snake_case : Dict=1e-6 , __snake_case : int=1.0 , __snake_case : Optional[int]="relu" , __snake_case : Any=True , __snake_case : List[str]=True , __snake_case : Union[str, Any]=0 , __snake_case : Dict=1 , **__snake_case : Optional[int] , ): a : Optional[int] = vocab_size a : Dict = d_model a : Union[str, Any] = d_kv a : Dict = d_ff a : Tuple = num_layers a : Dict = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a : int = num_heads a : str = relative_attention_num_buckets a : List[Any] = relative_attention_max_distance a : int = dropout_rate a : Tuple = layer_norm_epsilon a : str = initializer_factor a : List[Any] = feed_forward_proj a : Union[str, Any] = use_cache a : List[str] = self.feed_forward_proj.split('-' ) a : int = act_info[-1] a : Union[str, Any] = act_info[0] == 'gated' if len(__snake_case ) > 1 and act_info[0] != "gated" or len(__snake_case ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a : Optional[Any] = 'gelu_new' super().__init__( pad_token_id=__snake_case , eos_token_id=__snake_case , is_encoder_decoder=__snake_case , **__snake_case , ) class a__( lowerCamelCase__ ): @property def lowercase_ ( self : Optional[int] ): a : Dict = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: a : Dict = 'past_encoder_sequence + sequence' a : Dict = {0: 'batch'} a : Any = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: a : Optional[Any] = {0: 'batch', 1: 'decoder_sequence'} a : List[str] = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__snake_case , direction='inputs' ) return common_inputs @property def lowercase_ ( self : List[Any] ): return 13
297
1
'''simple docstring''' import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer lowerCAmelCase: Dict = logging.get_logger(__name__) lowerCAmelCase: str = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json', }, 'merges_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt', }, 'tokenizer_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json', }, } lowerCAmelCase: str = { 'allenai/led-base-16384': 1_6_3_8_4, } class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = LEDTokenizer lowercase__ = ["""input_ids""", """attention_mask"""] def __init__( self : List[Any] , __snake_case : Optional[Any]=None , __snake_case : List[str]=None , __snake_case : Tuple=None , __snake_case : Dict="replace" , __snake_case : int="<s>" , __snake_case : Any="</s>" , __snake_case : Optional[Any]="</s>" , __snake_case : Optional[Any]="<s>" , __snake_case : Optional[Any]="<unk>" , __snake_case : List[str]="<pad>" , __snake_case : int="<mask>" , __snake_case : int=False , __snake_case : str=True , **__snake_case : Tuple , ): super().__init__( __snake_case , __snake_case , tokenizer_file=__snake_case , errors=__snake_case , bos_token=__snake_case , eos_token=__snake_case , sep_token=__snake_case , cls_token=__snake_case , unk_token=__snake_case , pad_token=__snake_case , mask_token=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case , **__snake_case , ) a : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : List[Any] = getattr(__snake_case , pre_tok_state.pop('type' ) ) a : Optional[Any] = add_prefix_space a : Optional[Any] = pre_tok_class(**__snake_case ) a : Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` a : Dict = 'post_processor' a : int = getattr(self.backend_tokenizer , __snake_case , __snake_case ) if tokenizer_component_instance: a : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a : Any = tuple(state['sep'] ) if "cls" in state: a : Any = tuple(state['cls'] ) a : Optional[Any] = False if state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : Any = add_prefix_space a : Optional[Any] = True if state.get('trim_offsets' , __snake_case ) != trim_offsets: a : List[Any] = trim_offsets a : Union[str, Any] = True if changes_to_apply: a : int = getattr(__snake_case , state.pop('type' ) ) a : List[Any] = component_class(**__snake_case ) setattr(self.backend_tokenizer , __snake_case , __snake_case ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def lowercase_ ( self : Dict ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def lowercase_ ( self : Dict , __snake_case : List[str] ): a : Tuple = AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else value a : Optional[int] = value def lowercase_ ( self : Optional[Any] , *__snake_case : Any , **__snake_case : Union[str, Any] ): a : Dict = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Union[str, Any] , *__snake_case : Optional[int] , **__snake_case : List[str] ): a : Optional[int] = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Dict , __snake_case : str , __snake_case : Optional[str] = None ): a : Union[str, Any] = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : int=None ): a : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase_ ( self : Optional[int] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : int = [self.sep_token_id] a : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase_ ( self : List[str] , __snake_case : Union[Dict[str, EncodedInput], BatchEncoding] , __snake_case : Optional[int] = None , __snake_case : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __snake_case : Optional[int] = None , __snake_case : Optional[bool] = None , ): a : Optional[Any] = super()._pad( encoded_inputs=__snake_case , max_length=__snake_case , padding_strategy=__snake_case , pad_to_multiple_of=__snake_case , return_attention_mask=__snake_case , ) # Load from model defaults if return_attention_mask is None: a : str = 'attention_mask' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: a : Any = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. a : Union[str, Any] = len(encoded_inputs['global_attention_mask'] ) != len(__snake_case ) if needs_to_be_padded: a : str = len(__snake_case ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` a : Dict = ( encoded_inputs['global_attention_mask'] + [-1] * difference ) elif self.padding_side == "left": a : Union[str, Any] = [-1] * difference + encoded_inputs[ 'global_attention_mask' ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
297
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def lowerCamelCase__ ( _A , _A ): if inductance <= 0: raise ValueError('Inductance cannot be 0 or negative' ) elif capacitance <= 0: raise ValueError('Capacitance cannot be 0 or negative' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
297
1
'''simple docstring''' import unittest from transformers import BigBirdTokenizer, BigBirdTokenizerFast from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, require_torch, slow from transformers.utils import cached_property from ...test_tokenization_common import TokenizerTesterMixin lowerCAmelCase: Optional[int] = '▁' lowerCAmelCase: List[str] = get_tests_dir('fixtures/test_sentencepiece.model') @require_sentencepiece @require_tokenizers class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = BigBirdTokenizer lowercase__ = BigBirdTokenizerFast lowercase__ = True lowercase__ = True def lowercase_ ( self : Tuple ): super().setUp() a : Tuple = self.tokenizer_class(__snake_case , keep_accents=__snake_case ) tokenizer.save_pretrained(self.tmpdirname ) def lowercase_ ( self : Optional[int] ): a : Dict = '<s>' a : Tuple = 1 self.assertEqual(self.get_tokenizer()._convert_token_to_id(__snake_case ) , __snake_case ) self.assertEqual(self.get_tokenizer()._convert_id_to_token(__snake_case ) , __snake_case ) def lowercase_ ( self : str ): a : int = list(self.get_tokenizer().get_vocab().keys() ) self.assertEqual(vocab_keys[0] , '<unk>' ) self.assertEqual(vocab_keys[1] , '<s>' ) self.assertEqual(vocab_keys[-1] , '[MASK]' ) self.assertEqual(len(__snake_case ) , 10_04 ) def lowercase_ ( self : List[str] ): self.assertEqual(self.get_tokenizer().vocab_size , 10_00 ) def lowercase_ ( self : Dict ): if not self.test_rust_tokenizer: return a : Optional[Any] = self.get_tokenizer() a : Dict = self.get_rust_tokenizer() a : str = 'I was born in 92000, and this is falsé.' a : Optional[Any] = tokenizer.tokenize(__snake_case ) a : int = rust_tokenizer.tokenize(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) a : Tuple = tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) a : Tuple = rust_tokenizer.encode(__snake_case , add_special_tokens=__snake_case ) self.assertListEqual(__snake_case , __snake_case ) a : str = self.get_rust_tokenizer() a : Union[str, Any] = tokenizer.encode(__snake_case ) a : List[Any] = rust_tokenizer.encode(__snake_case ) self.assertListEqual(__snake_case , __snake_case ) def lowercase_ ( self : List[str] ): a : Union[str, Any] = BigBirdTokenizer(__snake_case , keep_accents=__snake_case ) a : List[Any] = tokenizer.tokenize('This is a test' ) self.assertListEqual(__snake_case , ['▁This', '▁is', '▁a', '▁t', 'est'] ) self.assertListEqual( tokenizer.convert_tokens_to_ids(__snake_case ) , [2_85, 46, 10, 1_70, 3_82] , ) a : Any = tokenizer.tokenize('I was born in 92000, and this is falsé.' ) self.assertListEqual( __snake_case , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '9', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', 'é', '.', ] , ) a : Dict = tokenizer.convert_tokens_to_ids(__snake_case ) self.assertListEqual( __snake_case , [8, 21, 84, 55, 24, 19, 7, 0, 6_02, 3_47, 3_47, 3_47, 3, 12, 66, 46, 72, 80, 6, 0, 4] , ) a : List[Any] = tokenizer.convert_ids_to_tokens(__snake_case ) self.assertListEqual( __snake_case , [ SPIECE_UNDERLINE + 'I', SPIECE_UNDERLINE + 'was', SPIECE_UNDERLINE + 'b', 'or', 'n', SPIECE_UNDERLINE + 'in', SPIECE_UNDERLINE + '', '<unk>', '2', '0', '0', '0', ',', SPIECE_UNDERLINE + 'and', SPIECE_UNDERLINE + 'this', SPIECE_UNDERLINE + 'is', SPIECE_UNDERLINE + 'f', 'al', 's', '<unk>', '.', ] , ) @cached_property def lowercase_ ( self : Union[str, Any] ): return BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base' ) @slow def lowercase_ ( self : List[Any] ): a : List[str] = 'Hello World!' a : Union[str, Any] = [65, 1_85_36, 22_60, 1_01, 66] self.assertListEqual(__snake_case , self.big_tokenizer.encode(__snake_case ) ) @slow def lowercase_ ( self : List[Any] ): a : int = ( 'This is a very long text with a lot of weird characters, such as: . , ~ ? ( ) " [ ] ! : - . Also we will' ' add words that should not exsist and be tokenized to <unk>, such as saoneuhaoesuth' ) # fmt: off a : int = [65, 8_71, 4_19, 3_58, 9_46, 9_91, 25_21, 4_52, 3_58, 13_57, 3_87, 77_51, 35_36, 1_12, 9_85, 4_56, 1_26, 8_65, 9_38, 54_00, 57_34, 4_58, 13_68, 4_67, 7_86, 24_62, 52_46, 11_59, 6_33, 8_65, 45_19, 4_57, 5_82, 8_52, 25_57, 4_27, 9_16, 5_08, 4_05, 3_43_24, 4_97, 3_91, 4_08, 1_13_42, 12_44, 3_85, 1_00, 9_38, 9_85, 4_56, 5_74, 3_62, 1_25_97, 32_00, 31_29, 11_72, 66] # noqa: E231 # fmt: on self.assertListEqual(__snake_case , self.big_tokenizer.encode(__snake_case ) ) @require_torch @slow def lowercase_ ( self : List[Any] ): import torch from transformers import BigBirdConfig, BigBirdModel # Build sequence a : Union[str, Any] = list(self.big_tokenizer.get_vocab().keys() )[:10] a : Dict = ' '.join(__snake_case ) a : str = self.big_tokenizer.encode_plus(__snake_case , return_tensors='pt' , return_token_type_ids=__snake_case ) a : Optional[int] = self.big_tokenizer.batch_encode_plus( [sequence + ' ' + sequence] , return_tensors='pt' , return_token_type_ids=__snake_case ) a : Optional[Any] = BigBirdConfig(attention_type='original_full' ) a : int = BigBirdModel(__snake_case ) assert model.get_input_embeddings().weight.shape[0] >= self.big_tokenizer.vocab_size with torch.no_grad(): model(**__snake_case ) model(**__snake_case ) @slow def lowercase_ ( self : Tuple ): a : Union[str, Any] = BigBirdTokenizer.from_pretrained('google/bigbird-roberta-base' ) a : Any = tokenizer.decode(tokenizer('Paris is the [MASK].' ).input_ids ) self.assertTrue(decoded_text == '[CLS] Paris is the[MASK].[SEP]' ) @slow def lowercase_ ( self : List[Any] ): # fmt: off a : Optional[Any] = {'input_ids': [[65, 3_92_86, 4_58, 3_63_35, 20_01, 4_56, 1_30_73, 1_32_66, 4_55, 1_13, 77_46, 17_41, 1_11_57, 3_91, 1_30_73, 1_32_66, 4_55, 1_13, 39_67, 3_54_12, 1_13, 49_36, 1_09, 38_70, 23_77, 1_13, 3_00_84, 4_57_20, 4_58, 1_34, 1_74_96, 1_12, 5_03, 1_16_72, 1_13, 1_18, 1_12, 56_65, 1_33_47, 3_86_87, 1_12, 14_96, 3_13_89, 1_12, 32_68, 4_72_64, 1_34, 9_62, 1_12, 1_63_77, 80_35, 2_31_30, 4_30, 1_21_69, 1_55_18, 2_85_92, 4_58, 1_46, 4_16_97, 1_09, 3_91, 1_21_69, 1_55_18, 1_66_89, 4_58, 1_46, 4_13_58, 1_09, 4_52, 7_26, 40_34, 1_11, 7_63, 3_54_12, 50_82, 3_88, 19_03, 1_11, 90_51, 3_91, 28_70, 4_89_18, 19_00, 11_23, 5_50, 9_98, 1_12, 95_86, 1_59_85, 4_55, 3_91, 4_10, 2_29_55, 3_76_36, 1_14, 66], [65, 4_48, 1_74_96, 4_19, 36_63, 3_85, 7_63, 1_13, 2_75_33, 28_70, 32_83, 1_30_43, 16_39, 2_47_13, 5_23, 6_56, 2_40_13, 1_85_50, 25_21, 5_17, 2_70_14, 2_12_44, 4_20, 12_12, 14_65, 3_91, 9_27, 48_33, 3_88, 5_78, 1_17_86, 1_14, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [65, 4_84, 21_69, 76_87, 2_19_32, 1_81_46, 7_26, 3_63, 1_70_32, 33_91, 1_14, 66, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]} # noqa: E501 # fmt: on self.tokenizer_integration_test_util( expected_encoding=__snake_case , model_name='google/bigbird-roberta-base' , revision='215c99f1600e06f83acce68422f2035b2b5c3510' , )
297
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase: Any = logging.get_logger(__name__) lowerCAmelCase: Any = {'vocab_file': 'vocab.txt'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } lowerCAmelCase: str = { 'openbmb/cpm-ant-10b': 1_0_2_4, } def lowerCamelCase__ ( _A ): a : Union[str, Any] = collections.OrderedDict() with open(_A , 'r' , encoding='utf-8' ) as reader: a : int = reader.readlines() for index, token in enumerate(_A ): a : int = token.rstrip('\n' ) a : List[Any] = index return vocab class a__( lowerCamelCase__ ): def __init__( self : Dict , __snake_case : Any , __snake_case : Dict="<unk>" , __snake_case : str=2_00 ): a : List[Any] = vocab a : Any = unk_token a : List[str] = max_input_chars_per_word def lowercase_ ( self : Optional[int] , __snake_case : Union[str, Any] ): a : Optional[Any] = list(__snake_case ) if len(__snake_case ) > self.max_input_chars_per_word: return [self.unk_token] a : Any = 0 a : Optional[Any] = [] while start < len(__snake_case ): a : Optional[int] = len(__snake_case ) a : str = None while start < end: a : Optional[Any] = ''.join(chars[start:end] ) if substr in self.vocab: a : List[str] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(__snake_case ) a : List[str] = end return sub_tokens class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = False def __init__( self : Any , __snake_case : str , __snake_case : Tuple="<d>" , __snake_case : List[str]="</d>" , __snake_case : Dict="<s>" , __snake_case : List[Any]="</s>" , __snake_case : int="<pad>" , __snake_case : Any="<unk>" , __snake_case : List[str]="</n>" , __snake_case : int="</_>" , __snake_case : Optional[Any]="left" , **__snake_case : Dict , ): requires_backends(self , ['jieba'] ) super().__init__( bod_token=__snake_case , eod_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , pad_token=__snake_case , unk_token=__snake_case , line_token=__snake_case , space_token=__snake_case , padding_side=__snake_case , **__snake_case , ) a : Union[str, Any] = bod_token a : Any = eod_token a : List[str] = load_vocab(__snake_case ) a : Optional[int] = self.encoder[space_token] a : str = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] a : str = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) a : Tuple = {v: k for k, v in self.encoder.items()} a : List[str] = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def lowercase_ ( self : Optional[int] ): return self.encoder[self.bod_token] @property def lowercase_ ( self : Dict ): return self.encoder[self.eod_token] @property def lowercase_ ( self : Any ): return self.encoder["\n"] @property def lowercase_ ( self : Tuple ): return len(self.encoder ) def lowercase_ ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def lowercase_ ( self : Union[str, Any] , __snake_case : List[str] ): a : List[str] = [] for x in jieba.cut(__snake_case , cut_all=__snake_case ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(__snake_case ) ) return output_tokens def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[Any] , **__snake_case : Optional[Any] ): a : Optional[int] = [i for i in token_ids if i >= 0] a : Any = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(__snake_case , **__snake_case ) def lowercase_ ( self : Optional[int] , __snake_case : int ): return token in self.encoder def lowercase_ ( self : int , __snake_case : List[str] ): return "".join(__snake_case ) def lowercase_ ( self : List[str] , __snake_case : Union[str, Any] ): return self.encoder.get(__snake_case , self.encoder.get(self.unk_token ) ) def lowercase_ ( self : Tuple , __snake_case : List[str] ): return self.decoder.get(__snake_case , self.unk_token ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] = None ): if os.path.isdir(__snake_case ): a : Optional[int] = os.path.join( __snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: a : int = (filename_prefix + '-' if filename_prefix else '') + save_directory a : Any = 0 if " " in self.encoder: a : Union[str, Any] = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: a : Tuple = self.encoder['\n'] del self.encoder["\n"] a : Dict = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) with open(__snake_case , 'w' , encoding='utf-8' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ' Please check that the vocabulary is not corrupted!' ) a : List[Any] = token_index writer.write(token + '\n' ) index += 1 return (vocab_file,) def lowercase_ ( self : Union[str, Any] , __snake_case : List[int] , __snake_case : List[int] = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowercase_ ( self : Dict , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) if token_ids_a is not None: return [1] + ([0] * len(__snake_case )) + [1] + ([0] * len(__snake_case )) return [1] + ([0] * len(__snake_case ))
297
1
'''simple docstring''' import json from typing import TYPE_CHECKING, List, Optional, Tuple from tokenizers import pre_tokenizers from ...tokenization_utils_base import BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_gpta import GPTaTokenizer if TYPE_CHECKING: from transformers.pipelines.conversational import Conversation lowerCAmelCase: Optional[int] = logging.get_logger(__name__) lowerCAmelCase: List[str] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/vocab.json', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/vocab.json', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/vocab.json', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/vocab.json', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/vocab.json', }, 'merges_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/merges.txt', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/merges.txt', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/merges.txt', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/merges.txt', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/merges.txt', }, 'tokenizer_file': { 'gpt2': 'https://huggingface.co/gpt2/resolve/main/tokenizer.json', 'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/tokenizer.json', 'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/tokenizer.json', 'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/tokenizer.json', 'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/tokenizer.json', }, } lowerCAmelCase: List[Any] = { 'gpt2': 1_0_2_4, 'gpt2-medium': 1_0_2_4, 'gpt2-large': 1_0_2_4, 'gpt2-xl': 1_0_2_4, 'distilgpt2': 1_0_2_4, } class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = GPTaTokenizer def __init__( self : int , __snake_case : Optional[int]=None , __snake_case : Optional[Any]=None , __snake_case : int=None , __snake_case : Dict="<|endoftext|>" , __snake_case : Union[str, Any]="<|endoftext|>" , __snake_case : Any="<|endoftext|>" , __snake_case : str=False , **__snake_case : Optional[Any] , ): super().__init__( __snake_case , __snake_case , tokenizer_file=__snake_case , unk_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , add_prefix_space=__snake_case , **__snake_case , ) a : Optional[Any] = kwargs.pop('add_bos_token' , __snake_case ) a : Optional[Any] = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : Optional[Any] = getattr(__snake_case , pre_tok_state.pop('type' ) ) a : Tuple = add_prefix_space a : List[Any] = pre_tok_class(**__snake_case ) a : Dict = add_prefix_space def lowercase_ ( self : Dict , *__snake_case : List[str] , **__snake_case : int ): a : Any = kwargs.get('is_split_into_words' , __snake_case ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._batch_encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Optional[Any] , *__snake_case : Dict , **__snake_case : Any ): a : List[Any] = kwargs.get('is_split_into_words' , __snake_case ) assert self.add_prefix_space or not is_split_into_words, ( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ "to use it with pretokenized inputs." ) return super()._encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] = None ): a : Any = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case ) def lowercase_ ( self : str , __snake_case : "Conversation" ): a : Optional[int] = [] for is_user, text in conversation.iter_texts(): input_ids.extend(self.encode(__snake_case , add_special_tokens=__snake_case ) + [self.eos_token_id] ) if len(__snake_case ) > self.model_max_length: a : Any = input_ids[-self.model_max_length :] return input_ids
297
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class a__( unittest.TestCase ): @slow def lowercase_ ( self : List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[int] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = TFAutoModel.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModel.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Union[str, Any] = TFAutoModelForPreTraining.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = AutoModelForPreTraining.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Union[str, Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForCausalLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Any = TFAutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForCausalLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[str] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[int] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Optional[int] = TFAutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = AutoModelForMaskedLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = TFAutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : str = AutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForSequenceClassification.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSequenceClassification.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : int = TFAutoModelForQuestionAnswering.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModelForQuestionAnswering.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowercase_ ( self : Tuple ): a : List[Any] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[int] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) def lowercase_ ( self : Any ): a : int = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[Any] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 )
297
1
'''simple docstring''' import tempfile import unittest import numpy as np import transformers from transformers import GPTaTokenizer, GPTJConfig, is_flax_available, is_torch_available from transformers.testing_utils import is_pt_flax_cross_test, require_flax, tooslow from ...generation.test_flax_utils import FlaxGenerationTesterMixin from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask if is_flax_available(): import jax import jax.numpy as jnp from transformers.modeling_flax_pytorch_utils import ( convert_pytorch_state_dict_to_flax, load_flax_weights_in_pytorch_model, ) from transformers.models.gptj.modeling_flax_gptj import FlaxGPTJForCausalLM, FlaxGPTJModel if is_torch_available(): import torch class a__: def __init__( self : List[str] , __snake_case : Optional[Any] , __snake_case : Any=14 , __snake_case : Optional[Any]=7 , __snake_case : Any=True , __snake_case : Union[str, Any]=True , __snake_case : int=False , __snake_case : int=True , __snake_case : Optional[Any]=99 , __snake_case : Tuple=32 , __snake_case : Any=4 , __snake_case : List[str]=4 , __snake_case : Union[str, Any]=4 , __snake_case : int=37 , __snake_case : Dict="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : Optional[int]=0.1 , __snake_case : Dict=5_12 , __snake_case : Any=0.02 , ): a : List[str] = parent a : Dict = batch_size a : List[str] = seq_length a : Tuple = is_training a : List[Any] = use_input_mask a : Optional[Any] = use_token_type_ids a : Optional[int] = use_labels a : str = vocab_size a : Optional[Any] = hidden_size a : int = rotary_dim a : str = num_hidden_layers a : int = num_attention_heads a : str = intermediate_size a : int = hidden_act a : Tuple = hidden_dropout_prob a : List[Any] = attention_probs_dropout_prob a : Any = max_position_embeddings a : Optional[int] = initializer_range a : str = None a : int = vocab_size - 1 a : Tuple = vocab_size - 1 a : Union[str, Any] = vocab_size - 1 def lowercase_ ( self : Tuple ): a : int = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Optional[Any] = None if self.use_input_mask: a : List[str] = random_attention_mask([self.batch_size, self.seq_length] ) a : Tuple = GPTJConfig( vocab_size=self.vocab_size , n_embd=self.hidden_size , n_layer=self.num_hidden_layers , n_head=self.num_attention_heads , n_positions=self.max_position_embeddings , use_cache=__snake_case , bos_token_id=self.bos_token_id , eos_token_id=self.eos_token_id , pad_token_id=self.pad_token_id , rotary_dim=self.rotary_dim , ) return (config, input_ids, input_mask) def lowercase_ ( self : Dict ): a : Any = self.prepare_config_and_inputs() a , a , a : Tuple = config_and_inputs a : Tuple = {'input_ids': input_ids, 'attention_mask': attention_mask} return config, inputs_dict def lowercase_ ( self : Any , __snake_case : Union[str, Any] , __snake_case : Tuple , __snake_case : int , __snake_case : Any ): a : Dict = 20 a : Union[str, Any] = model_class_name(__snake_case ) a : Union[str, Any] = model.init_cache(input_ids.shape[0] , __snake_case ) a : Optional[Any] = jnp.ones((input_ids.shape[0], max_decoder_length) , dtype='i4' ) a : Tuple = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) a : Optional[Any] = model( input_ids[:, :-1] , attention_mask=__snake_case , past_key_values=__snake_case , position_ids=__snake_case , ) a : List[Any] = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) a : List[str] = model( input_ids[:, -1:] , attention_mask=__snake_case , past_key_values=outputs_cache.past_key_values , position_ids=__snake_case , ) a : List[str] = model(__snake_case ) a : Optional[int] = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) def lowercase_ ( self : str , __snake_case : Any , __snake_case : List[Any] , __snake_case : str , __snake_case : List[str] ): a : int = 20 a : Tuple = model_class_name(__snake_case ) a : Union[str, Any] = jnp.concatenate( [attention_mask, jnp.zeros((attention_mask.shape[0], max_decoder_length - attention_mask.shape[1]) )] , axis=-1 , ) a : Any = model.init_cache(input_ids.shape[0] , __snake_case ) a : int = jnp.broadcast_to( jnp.arange(input_ids.shape[-1] - 1 )[None, :] , (input_ids.shape[0], input_ids.shape[-1] - 1) ) a : Optional[Any] = model( input_ids[:, :-1] , attention_mask=__snake_case , past_key_values=__snake_case , position_ids=__snake_case , ) a : Dict = jnp.array(input_ids.shape[0] * [[input_ids.shape[-1] - 1]] , dtype='i4' ) a : Optional[int] = model( input_ids[:, -1:] , past_key_values=outputs_cache.past_key_values , attention_mask=__snake_case , position_ids=__snake_case , ) a : Union[str, Any] = model(__snake_case , attention_mask=__snake_case ) a : Any = np.max(np.abs((outputs_cache_next[0][:, -1, :5] - outputs[0][:, -1, :5]) ) ) self.parent.assertTrue(diff < 1e-3 , msg=F"""Max diff is {diff}""" ) @require_flax class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = (FlaxGPTJModel, FlaxGPTJForCausalLM) if is_flax_available() else () lowercase__ = (FlaxGPTJForCausalLM,) if is_flax_available() else () def lowercase_ ( self : Dict ): a : Tuple = FlaxGPTJModelTester(self ) def lowercase_ ( self : List[Any] ): for model_class_name in self.all_model_classes: a , a , a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward(__snake_case , __snake_case , __snake_case , __snake_case ) def lowercase_ ( self : Optional[Any] ): for model_class_name in self.all_model_classes: a , a , a : List[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.check_use_cache_forward_with_attn_mask( __snake_case , __snake_case , __snake_case , __snake_case ) @tooslow def lowercase_ ( self : Union[str, Any] ): a : Optional[Any] = GPTaTokenizer.from_pretrained('gpt2' , pad_token='<|endoftext|>' , padding_side='left' ) a : int = tokenizer(['Hello this is a long string', 'Hey'] , return_tensors='np' , padding=__snake_case , truncation=__snake_case ) a : Tuple = FlaxGPTJForCausalLM.from_pretrained('EleutherAI/gpt-j-6B' ) a : List[Any] = False a : int = model.config.eos_token_id a : Tuple = jax.jit(model.generate ) a : int = jit_generate( inputs['input_ids'] , attention_mask=inputs['attention_mask'] , pad_token_id=tokenizer.pad_token_id ).sequences a : int = tokenizer.batch_decode(__snake_case , skip_special_tokens=__snake_case ) a : Tuple = [ 'Hello this is a long string of text.\n\nI\'m trying to get the text of the', 'Hey, I\'m a little late to the party. I\'m going to', ] self.assertListEqual(__snake_case , __snake_case ) @is_pt_flax_cross_test def lowercase_ ( self : List[Any] ): a , a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs a : Optional[Any] = self._prepare_for_class(__snake_case , __snake_case ) a : Tuple = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class a : int = model_class.__name__[4:] # Skip the "Flax" at the beginning a : int = getattr(__snake_case , __snake_case ) a , a : Optional[int] = pt_inputs['input_ids'].shape a : Optional[int] = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__snake_case ): a : Tuple = 0 a : str = 1 a : Tuple = 0 a : Union[str, Any] = 1 a : Any = pt_model_class(__snake_case ).eval() a : List[Any] = model_class(__snake_case , dtype=jnp.floataa ) a : Dict = convert_pytorch_state_dict_to_flax(pt_model.state_dict() , __snake_case ) a : str = fx_state with torch.no_grad(): a : Tuple = pt_model(**__snake_case ).to_tuple() a : Tuple = fx_model(**__snake_case ).to_tuple() self.assertEqual(len(__snake_case ) , len(__snake_case ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(__snake_case , __snake_case ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: pt_model.save_pretrained(__snake_case ) a : Union[str, Any] = model_class.from_pretrained(__snake_case , from_pt=__snake_case ) a : Optional[int] = fx_model_loaded(**__snake_case ).to_tuple() self.assertEqual( len(__snake_case ) , len(__snake_case ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output_loaded, pt_output in zip(__snake_case , __snake_case ): self.assert_almost_equals(fx_output_loaded[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @is_pt_flax_cross_test def lowercase_ ( self : Dict ): a , a : Tuple = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: with self.subTest(model_class.__name__ ): # prepare inputs a : Optional[Any] = self._prepare_for_class(__snake_case , __snake_case ) a : Dict = {k: torch.tensor(v.tolist() ) for k, v in prepared_inputs_dict.items()} # load corresponding PyTorch class a : int = model_class.__name__[4:] # Skip the "Flax" at the beginning a : Union[str, Any] = getattr(__snake_case , __snake_case ) a : List[str] = pt_model_class(__snake_case ).eval() a : Dict = model_class(__snake_case , dtype=jnp.floataa ) a : Optional[int] = load_flax_weights_in_pytorch_model(__snake_case , fx_model.params ) a , a : List[str] = pt_inputs['input_ids'].shape a : Dict = np.random.randint(0 , seq_length - 1 , size=(batch_size,) ) for batch_idx, start_index in enumerate(__snake_case ): a : List[str] = 0 a : str = 1 a : Optional[Any] = 0 a : Optional[Any] = 1 # make sure weights are tied in PyTorch pt_model.tie_weights() with torch.no_grad(): a : List[Any] = pt_model(**__snake_case ).to_tuple() a : Optional[Any] = fx_model(**__snake_case ).to_tuple() self.assertEqual(len(__snake_case ) , len(__snake_case ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(__snake_case , __snake_case ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) with tempfile.TemporaryDirectory() as tmpdirname: fx_model.save_pretrained(__snake_case ) a : Any = pt_model_class.from_pretrained(__snake_case , from_flax=__snake_case ) with torch.no_grad(): a : Any = pt_model_loaded(**__snake_case ).to_tuple() self.assertEqual( len(__snake_case ) , len(__snake_case ) , 'Output lengths differ between Flax and PyTorch' ) for fx_output, pt_output in zip(__snake_case , __snake_case ): self.assert_almost_equals(fx_output[:, -1] , pt_output[:, -1].numpy() , 4e-2 ) @tooslow def lowercase_ ( self : int ): for model_class_name in self.all_model_classes: a : str = model_class_name.from_pretrained('EleutherAI/gpt-j-6B' ) a : Dict = model(np.ones((1, 1) ) ) self.assertIsNotNone(__snake_case )
297
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase: List[Any] = logging.get_logger(__name__) lowerCAmelCase: List[Any] = { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """roberta""" def __init__( self : Tuple , __snake_case : List[str]=5_02_65 , __snake_case : int=7_68 , __snake_case : Union[str, Any]=12 , __snake_case : Dict=12 , __snake_case : Tuple=30_72 , __snake_case : Optional[Any]="gelu" , __snake_case : str=0.1 , __snake_case : Any=0.1 , __snake_case : str=5_12 , __snake_case : int=2 , __snake_case : Any=0.02 , __snake_case : int=1e-1_2 , __snake_case : str=1 , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=2 , __snake_case : Optional[int]="absolute" , __snake_case : Union[str, Any]=True , __snake_case : Union[str, Any]=None , **__snake_case : str , ): super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) a : List[str] = vocab_size a : str = hidden_size a : Tuple = num_hidden_layers a : Dict = num_attention_heads a : List[Any] = hidden_act a : str = intermediate_size a : Union[str, Any] = hidden_dropout_prob a : Optional[Any] = attention_probs_dropout_prob a : Any = max_position_embeddings a : Optional[int] = type_vocab_size a : str = initializer_range a : List[Any] = layer_norm_eps a : Optional[int] = position_embedding_type a : Dict = use_cache a : Any = classifier_dropout class a__( lowerCamelCase__ ): @property def lowercase_ ( self : int ): if self.task == "multiple-choice": a : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a : str = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
297
1
'''simple docstring''' import unittest from pathlib import Path from tempfile import TemporaryDirectory from transformers import AutoConfig, TFGPTaLMHeadModel, is_keras_nlp_available, is_tf_available from transformers.models.gpta.tokenization_gpta import GPTaTokenizer from transformers.testing_utils import require_keras_nlp, require_tf, slow if is_tf_available(): import tensorflow as tf if is_keras_nlp_available(): from transformers.models.gpta import TFGPTaTokenizer lowerCAmelCase: Dict = ['gpt2'] lowerCAmelCase: Tuple = 'gpt2' if is_tf_available(): class a__( tf.Module ): def __init__( self : Optional[Any] , __snake_case : int ): super().__init__() a : str = tokenizer a : Any = AutoConfig.from_pretrained(__snake_case ) a : Union[str, Any] = TFGPTaLMHeadModel.from_config(__snake_case ) @tf.function(input_signature=(tf.TensorSpec((None,) , tf.string , name='text' ),) ) def lowercase_ ( self : Any , __snake_case : Union[str, Any] ): a : Union[str, Any] = self.tokenizer(__snake_case ) a : Tuple = tokenized['input_ids'].to_tensor() a : Optional[int] = tf.cast(input_ids_dense > 0 , tf.intaa ) # input_mask = tf.reshape(input_mask, [-1, MAX_SEQ_LEN]) a : str = self.model(input_ids=__snake_case , attention_mask=__snake_case )['logits'] return outputs @require_tf @require_keras_nlp class a__( unittest.TestCase ): def lowercase_ ( self : str ): super().setUp() a : Union[str, Any] = [GPTaTokenizer.from_pretrained(__snake_case ) for checkpoint in (TOKENIZER_CHECKPOINTS)] a : str = [TFGPTaTokenizer.from_pretrained(__snake_case ) for checkpoint in TOKENIZER_CHECKPOINTS] assert len(self.tokenizers ) == len(self.tf_tokenizers ) a : List[Any] = [ 'This is a straightforward English test sentence.', 'This one has some weird characters\rto\nsee\r\nif those\u00E9break things.', 'Now we\'re going to add some Chinese: 一 二 三 一二三', 'And some much more rare Chinese: 齉 堃 齉堃', 'Je vais aussi écrire en français pour tester les accents', 'Classical Irish also has some unusual characters, so in they go: Gaelaċ, ꝼ', ] a : Union[str, Any] = list(zip(self.test_sentences , self.test_sentences[::-1] ) ) def lowercase_ ( self : List[Any] ): for tokenizer, tf_tokenizer in zip(self.tokenizers , self.tf_tokenizers ): for test_inputs in self.test_sentences: a : str = tokenizer([test_inputs] , return_tensors='tf' ) a : List[str] = tf_tokenizer([test_inputs] ) for key in python_outputs.keys(): # convert them to numpy to avoid messing with ragged tensors a : List[str] = python_outputs[key].numpy() a : List[Any] = tf_outputs[key].numpy() self.assertTrue(tf.reduce_all(python_outputs_values.shape == tf_outputs_values.shape ) ) self.assertTrue(tf.reduce_all(tf.cast(__snake_case , tf.intaa ) == tf_outputs_values ) ) @slow def lowercase_ ( self : List[Any] ): for tf_tokenizer in self.tf_tokenizers: a : Optional[int] = tf.function(__snake_case ) for test_inputs in self.test_sentences: a : str = tf.constant(__snake_case ) a : Any = compiled_tokenizer(__snake_case ) a : Dict = tf_tokenizer(__snake_case ) for key in eager_outputs.keys(): self.assertTrue(tf.reduce_all(eager_outputs[key] == compiled_outputs[key] ) ) @slow def lowercase_ ( self : int ): for tf_tokenizer in self.tf_tokenizers: a : Optional[Any] = ModelToSave(tokenizer=__snake_case ) a : List[str] = tf.convert_to_tensor([self.test_sentences[0]] ) a : str = model.serving(__snake_case ) # Build model with some sample inputs with TemporaryDirectory() as tempdir: a : int = Path(__snake_case ) / 'saved.model' tf.saved_model.save(__snake_case , __snake_case , signatures={'serving_default': model.serving} ) a : str = tf.saved_model.load(__snake_case ) a : Optional[int] = loaded_model.signatures['serving_default'](__snake_case )['output_0'] # We may see small differences because the loaded model is compiled, so we need an epsilon for the test self.assertTrue(tf.reduce_all(out == loaded_output ) ) @slow def lowercase_ ( self : str ): for tf_tokenizer in self.tf_tokenizers: a : Any = tf.convert_to_tensor([self.test_sentences[0]] ) a : List[str] = tf_tokenizer(__snake_case ) # Build model with some sample inputs a : List[str] = tf_tokenizer.get_config() a : Tuple = TFGPTaTokenizer.from_config(__snake_case ) a : Tuple = model_from_config(__snake_case ) for key in from_config_output.keys(): self.assertTrue(tf.reduce_all(from_config_output[key] == out[key] ) ) @slow def lowercase_ ( self : Optional[Any] ): for tf_tokenizer in self.tf_tokenizers: # for the test to run a : List[Any] = 12_31_23 for max_length in [3, 5, 10_24]: a : Optional[Any] = tf.convert_to_tensor([self.test_sentences[0]] ) a : List[str] = tf_tokenizer(__snake_case , max_length=__snake_case ) a : List[str] = out['input_ids'].numpy().shape[1] assert out_length == max_length
297
'''simple docstring''' def lowerCamelCase__ ( _A ): return 10 - x * x def lowerCamelCase__ ( _A , _A ): # Bolzano theory in order to find if there is a root between a and b if equation(_A ) * equation(_A ) >= 0: raise ValueError('Wrong space!' ) a : Tuple = a while (b - a) >= 0.01: # Find middle point a : Tuple = (a + b) / 2 # Check if middle point is root if equation(_A ) == 0.0: break # Decide the side to repeat the steps if equation(_A ) * equation(_A ) < 0: a : List[str] = c else: a : Tuple = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
297
1
'''simple docstring''' import warnings from functools import wraps from typing import Callable def lowerCamelCase__ ( _A ): @wraps(_A ) def _inner_fn(*_A , **_A ): warnings.warn( (f"""'{fn.__name__}' is experimental and might be subject to breaking changes in the future.""") , _A , ) return fn(*_A , **_A ) return _inner_fn
297
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.esm.modeling_esmfold import EsmForProteinFolding class a__: def __init__( self : str , __snake_case : Union[str, Any] , __snake_case : List[str]=13 , __snake_case : Tuple=7 , __snake_case : Optional[Any]=False , __snake_case : Dict=True , __snake_case : List[Any]=False , __snake_case : Optional[int]=False , __snake_case : Optional[Any]=19 , __snake_case : Any=32 , __snake_case : Union[str, Any]=5 , __snake_case : Union[str, Any]=4 , __snake_case : int=37 , __snake_case : Union[str, Any]="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : List[str]=0.1 , __snake_case : int=5_12 , __snake_case : int=16 , __snake_case : Tuple=2 , __snake_case : str=0.02 , __snake_case : str=3 , __snake_case : Dict=4 , __snake_case : List[Any]=None , ): a : Tuple = parent a : List[str] = batch_size a : Optional[Any] = seq_length a : Tuple = is_training a : Optional[Any] = use_input_mask a : List[Any] = use_token_type_ids a : List[Any] = use_labels a : int = vocab_size a : Union[str, Any] = hidden_size a : Any = num_hidden_layers a : List[str] = num_attention_heads a : int = intermediate_size a : str = hidden_act a : Tuple = hidden_dropout_prob a : Union[str, Any] = attention_probs_dropout_prob a : List[str] = max_position_embeddings a : Any = type_vocab_size a : List[str] = type_sequence_label_size a : Union[str, Any] = initializer_range a : Optional[int] = num_labels a : Optional[Any] = num_choices a : Optional[int] = scope def lowercase_ ( self : List[Any] ): a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Dict = None if self.use_input_mask: a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a : Optional[Any] = None a : Optional[int] = None a : Dict = None if self.use_labels: a : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) a : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self : List[Any] ): a : Any = EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , is_folding_model=__snake_case , esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False} , ) return config def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : str , __snake_case : Optional[Any] , __snake_case : List[Any] , __snake_case : str , __snake_case : Any ): a : Tuple = EsmForProteinFolding(config=__snake_case ).float() model.to(__snake_case ) model.eval() a : Dict = model(__snake_case , attention_mask=__snake_case ) a : Union[str, Any] = model(__snake_case ) a : List[Any] = model(__snake_case ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def lowercase_ ( self : Optional[Any] ): a : Tuple = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : Optional[Any] = config_and_inputs a : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = False lowercase__ = (EsmForProteinFolding,) if is_torch_available() else () lowercase__ = () lowercase__ = {} if is_torch_available() else {} lowercase__ = False def lowercase_ ( self : int ): a : Tuple = EsmFoldModelTester(self ) a : Any = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase_ ( self : List[str] ): self.config_tester.run_common_tests() def lowercase_ ( self : Union[str, Any] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) @unittest.skip('Does not support attention outputs' ) def lowercase_ ( self : str ): pass @unittest.skip def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support passing input embeds!' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMfold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold only has one output format.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality' ) def lowercase_ ( self : Tuple ): pass @unittest.skip('ESMFold does not support input chunking.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t support data parallel.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowercase_ ( self : Union[str, Any] ): pass @require_torch class a__( lowerCamelCase__ ): @slow def lowercase_ ( self : Optional[int] ): a : Optional[Any] = EsmForProteinFolding.from_pretrained('facebook/esmfold_v1' ).float() model.eval() a : int = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) a : Any = model(__snake_case )['positions'] a : Dict = torch.tensor([2.5828, 0.7993, -10.9334] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , __snake_case , atol=1e-4 ) )
297
1
'''simple docstring''' import torch from torch import nn from transformers import CLIPPreTrainedModel, CLIPVisionModel from ...models.attention import BasicTransformerBlock from ...utils import logging lowerCAmelCase: Optional[Any] = logging.get_logger(__name__) # pylint: disable=invalid-name class a__( lowerCamelCase__ ): def __init__( self : Any , __snake_case : int , __snake_case : List[str]=7_68 ): super().__init__(__snake_case ) a : Dict = proj_size a : Optional[Any] = CLIPVisionModel(__snake_case ) a : Optional[Any] = PaintByExampleMapper(__snake_case ) a : List[str] = nn.LayerNorm(config.hidden_size ) a : Optional[int] = nn.Linear(config.hidden_size , self.proj_size ) # uncondition for scaling a : Dict = nn.Parameter(torch.randn((1, 1, self.proj_size) ) ) def lowercase_ ( self : Optional[int] , __snake_case : Any , __snake_case : Optional[int]=False ): a : int = self.model(pixel_values=__snake_case ) a : Dict = clip_output.pooler_output a : Union[str, Any] = self.mapper(latent_states[:, None] ) a : int = self.final_layer_norm(__snake_case ) a : Union[str, Any] = self.proj_out(__snake_case ) if return_uncond_vector: return latent_states, self.uncond_vector return latent_states class a__( nn.Module ): def __init__( self : int , __snake_case : Optional[int] ): super().__init__() a : Union[str, Any] = (config.num_hidden_layers + 1) // 5 a : int = config.hidden_size a : Any = 1 a : Optional[Any] = nn.ModuleList( [ BasicTransformerBlock(__snake_case , __snake_case , __snake_case , activation_fn='gelu' , attention_bias=__snake_case ) for _ in range(__snake_case ) ] ) def lowercase_ ( self : Any , __snake_case : int ): for block in self.blocks: a : Tuple = block(__snake_case ) return hidden_states
297
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class a__( nn.Module ): def __init__( self : Any , __snake_case : int = 16 , __snake_case : int = 88 , __snake_case : Optional[int] = None , __snake_case : int = 1 , __snake_case : float = 0.0 , __snake_case : int = 32 , __snake_case : Optional[int] = None , __snake_case : bool = False , __snake_case : Optional[int] = None , __snake_case : Optional[int] = None , __snake_case : str = "geglu" , __snake_case : Optional[int] = None , ): super().__init__() a : Optional[int] = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__snake_case , attention_head_dim=__snake_case , in_channels=__snake_case , num_layers=__snake_case , dropout=__snake_case , norm_num_groups=__snake_case , cross_attention_dim=__snake_case , attention_bias=__snake_case , sample_size=__snake_case , num_vector_embeds=__snake_case , activation_fn=__snake_case , num_embeds_ada_norm=__snake_case , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference a : Union[str, Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` a : Tuple = [77, 2_57] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` a : Any = [1, 0] def lowercase_ ( self : str , __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any]=None , __snake_case : int=None , __snake_case : Dict=None , __snake_case : bool = True , ): a : Dict = hidden_states a : Tuple = [] a : Optional[int] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens a : Union[str, Any] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] a : Tuple = self.transformer_index_for_condition[i] a : Union[str, Any] = self.transformers[transformer_index]( __snake_case , encoder_hidden_states=__snake_case , timestep=__snake_case , cross_attention_kwargs=__snake_case , return_dict=__snake_case , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] a : Optional[Any] = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) a : int = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__snake_case )
297
1
'''simple docstring''' import itertools import json import linecache import os import pickle import re import socket import string from collections import Counter from logging import getLogger from pathlib import Path from typing import Callable, Dict, Iterable, List import git import torch from torch.utils.data import Dataset from transformers import BartTokenizer, RagTokenizer, TaTokenizer def lowerCamelCase__ ( _A , _A , _A , _A , _A=True , _A="pt" ): a : List[Any] = {'add_prefix_space': True} if isinstance(_A , _A ) and not line.startswith(' ' ) else {} a : Tuple = padding_side return tokenizer( [line] , max_length=_A , padding='max_length' if pad_to_max_length else None , truncation=_A , return_tensors=_A , add_special_tokens=_A , **_A , ) def lowerCamelCase__ ( _A , _A , _A=None , ): a : Union[str, Any] = input_ids.ne(_A ).any(dim=0 ) if attention_mask is None: return input_ids[:, keep_column_mask] else: return (input_ids[:, keep_column_mask], attention_mask[:, keep_column_mask]) class a__( lowerCamelCase__ ): def __init__( self : int , __snake_case : str , __snake_case : Optional[int] , __snake_case : List[str] , __snake_case : int , __snake_case : Optional[Any]="train" , __snake_case : List[str]=None , __snake_case : Dict=None , __snake_case : Optional[Any]=None , __snake_case : str="" , ): super().__init__() a : Any = Path(__snake_case ).joinpath(type_path + '.source' ) a : List[str] = Path(__snake_case ).joinpath(type_path + '.target' ) a : Any = self.get_char_lens(self.src_file ) a : Dict = max_source_length a : Any = max_target_length assert min(self.src_lens ) > 0, F"""found empty line in {self.src_file}""" a : Optional[int] = tokenizer a : int = prefix if n_obs is not None: a : Optional[int] = self.src_lens[:n_obs] a : List[Any] = src_lang a : Optional[Any] = tgt_lang def __len__( self : Tuple ): return len(self.src_lens ) def __getitem__( self : Any , __snake_case : Union[str, Any] ): a : Dict = index + 1 # linecache starts at 1 a : Tuple = self.prefix + linecache.getline(str(self.src_file ) , __snake_case ).rstrip('\n' ) a : Dict = linecache.getline(str(self.tgt_file ) , __snake_case ).rstrip('\n' ) assert source_line, F"""empty source line for index {index}""" assert tgt_line, F"""empty tgt line for index {index}""" # Need to add eos token manually for T5 if isinstance(self.tokenizer , __snake_case ): source_line += self.tokenizer.eos_token tgt_line += self.tokenizer.eos_token # Pad source and target to the right a : str = ( self.tokenizer.question_encoder if isinstance(self.tokenizer , __snake_case ) else self.tokenizer ) a : int = self.tokenizer.generator if isinstance(self.tokenizer , __snake_case ) else self.tokenizer a : Optional[int] = encode_line(__snake_case , __snake_case , self.max_source_length , 'right' ) a : Optional[int] = encode_line(__snake_case , __snake_case , self.max_target_length , 'right' ) a : Union[str, Any] = source_inputs['input_ids'].squeeze() a : str = target_inputs['input_ids'].squeeze() a : List[str] = source_inputs['attention_mask'].squeeze() return { "input_ids": source_ids, "attention_mask": src_mask, "decoder_input_ids": target_ids, } @staticmethod def lowercase_ ( __snake_case : List[str] ): return [len(__snake_case ) for x in Path(__snake_case ).open().readlines()] def lowercase_ ( self : int , __snake_case : Tuple ): a : Dict = torch.stack([x['input_ids'] for x in batch] ) a : str = torch.stack([x['attention_mask'] for x in batch] ) a : Union[str, Any] = torch.stack([x['decoder_input_ids'] for x in batch] ) a : int = ( self.tokenizer.generator.pad_token_id if isinstance(self.tokenizer , __snake_case ) else self.tokenizer.pad_token_id ) a : Optional[int] = ( self.tokenizer.question_encoder.pad_token_id if isinstance(self.tokenizer , __snake_case ) else self.tokenizer.pad_token_id ) a : Optional[int] = trim_batch(__snake_case , __snake_case ) a , a : str = trim_batch(__snake_case , __snake_case , attention_mask=__snake_case ) a : str = { 'input_ids': source_ids, 'attention_mask': source_mask, 'decoder_input_ids': y, } return batch lowerCAmelCase: Dict = getLogger(__name__) def lowerCamelCase__ ( _A ): return list(itertools.chain.from_iterable(_A ) ) def lowerCamelCase__ ( _A ): a : List[str] = get_git_info() save_json(_A , os.path.join(_A , 'git_log.json' ) ) def lowerCamelCase__ ( _A , _A , _A=4 , **_A ): with open(_A , 'w' ) as f: json.dump(_A , _A , indent=_A , **_A ) def lowerCamelCase__ ( _A ): with open(_A ) as f: return json.load(_A ) def lowerCamelCase__ ( ): a : Any = git.Repo(search_parent_directories=_A ) a : Union[str, Any] = { 'repo_id': str(_A ), 'repo_sha': str(repo.head.object.hexsha ), 'repo_branch': str(repo.active_branch ), 'hostname': str(socket.gethostname() ), } return repo_infos def lowerCamelCase__ ( _A , _A ): return list(map(_A , _A ) ) def lowerCamelCase__ ( _A , _A ): with open(_A , 'wb' ) as f: return pickle.dump(_A , _A ) def lowerCamelCase__ ( _A ): def remove_articles(_A ): return re.sub(r'\b(a|an|the)\b' , ' ' , _A ) def white_space_fix(_A ): return " ".join(text.split() ) def remove_punc(_A ): a : List[Any] = set(string.punctuation ) return "".join(ch for ch in text if ch not in exclude ) def lower(_A ): return text.lower() return white_space_fix(remove_articles(remove_punc(lower(_A ) ) ) ) def lowerCamelCase__ ( _A , _A ): a : Optional[Any] = normalize_answer(_A ).split() a : Any = normalize_answer(_A ).split() a : Union[str, Any] = Counter(_A ) & Counter(_A ) a : Optional[int] = sum(common.values() ) if num_same == 0: return 0 a : str = 1.0 * num_same / len(_A ) a : str = 1.0 * num_same / len(_A ) a : Optional[int] = (2 * precision * recall) / (precision + recall) return fa def lowerCamelCase__ ( _A , _A ): return normalize_answer(_A ) == normalize_answer(_A ) def lowerCamelCase__ ( _A , _A ): assert len(_A ) == len(_A ) a : List[str] = 0 for hypo, pred in zip(_A , _A ): em += exact_match_score(_A , _A ) if len(_A ) > 0: em /= len(_A ) return {"em": em} def lowerCamelCase__ ( _A ): return model_prefix.startswith('rag' ) def lowerCamelCase__ ( _A , _A , _A ): a : Any = {p: p for p in extra_params} # T5 models don't have `dropout` param, they have `dropout_rate` instead a : Optional[Any] = 'dropout_rate' for p in extra_params: if getattr(_A , _A , _A ): if not hasattr(_A , _A ) and not hasattr(_A , equivalent_param[p] ): logger.info('config doesn\'t have a `{}` attribute'.format(_A ) ) delattr(_A , _A ) continue a : int = p if hasattr(_A , _A ) else equivalent_param[p] setattr(_A , _A , getattr(_A , _A ) ) delattr(_A , _A ) return hparams, config
297
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase: Union[str, Any] = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[Any] = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Any = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
'''simple docstring''' from copy import deepcopy class a__: def __init__( self : Union[str, Any] , __snake_case : list[int] | None = None , __snake_case : int | None = None ): if arr is None and size is not None: a : List[str] = size a : List[Any] = [0] * size elif arr is not None: self.init(__snake_case ) else: raise ValueError('Either arr or size must be specified' ) def lowercase_ ( self : str , __snake_case : list[int] ): a : List[Any] = len(__snake_case ) a : Optional[Any] = deepcopy(__snake_case ) for i in range(1 , self.size ): a : List[Any] = self.next_(__snake_case ) if j < self.size: self.tree[j] += self.tree[i] def lowercase_ ( self : List[str] ): a : Any = self.tree[:] for i in range(self.size - 1 , 0 , -1 ): a : str = self.next_(__snake_case ) if j < self.size: arr[j] -= arr[i] return arr @staticmethod def lowercase_ ( __snake_case : int ): return index + (index & (-index)) @staticmethod def lowercase_ ( __snake_case : int ): return index - (index & (-index)) def lowercase_ ( self : Union[str, Any] , __snake_case : int , __snake_case : int ): if index == 0: self.tree[0] += value return while index < self.size: self.tree[index] += value a : Union[str, Any] = self.next_(__snake_case ) def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int ): self.add(__snake_case , value - self.get(__snake_case ) ) def lowercase_ ( self : Dict , __snake_case : int ): if right == 0: return 0 a : Any = self.tree[0] right -= 1 # make right inclusive while right > 0: result += self.tree[right] a : List[str] = self.prev(__snake_case ) return result def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int ): return self.prefix(__snake_case ) - self.prefix(__snake_case ) def lowercase_ ( self : Any , __snake_case : int ): return self.query(__snake_case , index + 1 ) def lowercase_ ( self : Optional[Any] , __snake_case : int ): value -= self.tree[0] if value < 0: return -1 a : Tuple = 1 # Largest power of 2 <= size while j * 2 < self.size: j *= 2 a : List[str] = 0 while j > 0: if i + j < self.size and self.tree[i + j] <= value: value -= self.tree[i + j] i += j j //= 2 return i if __name__ == "__main__": import doctest doctest.testmod()
297
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase: str = { 'configuration_mgp_str': ['MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MgpstrConfig'], 'processing_mgp_str': ['MgpstrProcessor'], 'tokenization_mgp_str': ['MgpstrTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Optional[Any] = [ 'MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST', 'MgpstrModel', 'MgpstrPreTrainedModel', 'MgpstrForSceneTextRecognition', ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys lowerCAmelCase: Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
'''simple docstring''' from typing import Optional, Tuple, Union import flax import flax.linen as nn import jax import jax.numpy as jnp from flax.core.frozen_dict import FrozenDict from ..configuration_utils import ConfigMixin, flax_register_to_config from ..utils import BaseOutput from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps from .modeling_flax_utils import FlaxModelMixin from .unet_ad_blocks_flax import ( FlaxCrossAttnDownBlockaD, FlaxDownBlockaD, FlaxUNetMidBlockaDCrossAttn, ) @flax.struct.dataclass class a__( lowerCamelCase__ ): lowercase__ = 42 lowercase__ = 42 class a__( nn.Module ): lowercase__ = 42 lowercase__ = (16, 32, 96, 2_56) lowercase__ = jnp.floataa def lowercase_ ( self : List[str] ): a : Optional[Any] = nn.Conv( self.block_out_channels[0] , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) a : Union[str, Any] = [] for i in range(len(self.block_out_channels ) - 1 ): a : Optional[int] = self.block_out_channels[i] a : str = self.block_out_channels[i + 1] a : Any = nn.Conv( __snake_case , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__snake_case ) a : List[Any] = nn.Conv( __snake_case , kernel_size=(3, 3) , strides=(2, 2) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) blocks.append(__snake_case ) a : Tuple = blocks a : Optional[Any] = nn.Conv( self.conditioning_embedding_channels , kernel_size=(3, 3) , padding=((1, 1), (1, 1)) , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : Union[str, Any] , __snake_case : Optional[int] ): a : int = self.conv_in(__snake_case ) a : int = nn.silu(__snake_case ) for block in self.blocks: a : List[Any] = block(__snake_case ) a : Dict = nn.silu(__snake_case ) a : Any = self.conv_out(__snake_case ) return embedding @flax_register_to_config class a__( nn.Module , lowerCamelCase__ , lowerCamelCase__ ): lowercase__ = 32 lowercase__ = 4 lowercase__ = ( "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D", ) lowercase__ = False lowercase__ = (3_20, 6_40, 12_80, 12_80) lowercase__ = 2 lowercase__ = 8 lowercase__ = None lowercase__ = 12_80 lowercase__ = 0.0 lowercase__ = False lowercase__ = jnp.floataa lowercase__ = True lowercase__ = 0 lowercase__ = "rgb" lowercase__ = (16, 32, 96, 2_56) def lowercase_ ( self : List[str] , __snake_case : jax.random.KeyArray ): # init input tensors a : str = (1, self.in_channels, self.sample_size, self.sample_size) a : Dict = jnp.zeros(__snake_case , dtype=jnp.floataa ) a : str = jnp.ones((1,) , dtype=jnp.intaa ) a : str = jnp.zeros((1, 1, self.cross_attention_dim) , dtype=jnp.floataa ) a : Any = (1, 3, self.sample_size * 8, self.sample_size * 8) a : Any = jnp.zeros(__snake_case , dtype=jnp.floataa ) a , a : int = jax.random.split(__snake_case ) a : Optional[Any] = {'params': params_rng, 'dropout': dropout_rng} return self.init(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case )["params"] def lowercase_ ( self : Optional[Any] ): a : Dict = self.block_out_channels a : Tuple = block_out_channels[0] * 4 # If `num_attention_heads` is not defined (which is the case for most models) # it will default to `attention_head_dim`. This looks weird upon first reading it and it is. # The reason for this behavior is to correct for incorrectly named variables that were introduced # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking # which is why we correct for the naming here. a : List[str] = self.num_attention_heads or self.attention_head_dim # input a : Union[str, Any] = nn.Conv( block_out_channels[0] , kernel_size=(3, 3) , strides=(1, 1) , padding=((1, 1), (1, 1)) , dtype=self.dtype , ) # time a : Dict = FlaxTimesteps( block_out_channels[0] , flip_sin_to_cos=self.flip_sin_to_cos , freq_shift=self.config.freq_shift ) a : Union[str, Any] = FlaxTimestepEmbedding(__snake_case , dtype=self.dtype ) a : str = FlaxControlNetConditioningEmbedding( conditioning_embedding_channels=block_out_channels[0] , block_out_channels=self.conditioning_embedding_out_channels , ) a : Union[str, Any] = self.only_cross_attention if isinstance(__snake_case , __snake_case ): a : List[Any] = (only_cross_attention,) * len(self.down_block_types ) if isinstance(__snake_case , __snake_case ): a : Optional[Any] = (num_attention_heads,) * len(self.down_block_types ) # down a : Tuple = [] a : List[Any] = [] a : int = block_out_channels[0] a : Optional[Any] = nn.Conv( __snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__snake_case ) for i, down_block_type in enumerate(self.down_block_types ): a : Union[str, Any] = output_channel a : Any = block_out_channels[i] a : Any = i == len(__snake_case ) - 1 if down_block_type == "CrossAttnDownBlock2D": a : List[str] = FlaxCrossAttnDownBlockaD( in_channels=__snake_case , out_channels=__snake_case , dropout=self.dropout , num_layers=self.layers_per_block , num_attention_heads=num_attention_heads[i] , add_downsample=not is_final_block , use_linear_projection=self.use_linear_projection , only_cross_attention=only_cross_attention[i] , dtype=self.dtype , ) else: a : List[str] = FlaxDownBlockaD( in_channels=__snake_case , out_channels=__snake_case , dropout=self.dropout , num_layers=self.layers_per_block , add_downsample=not is_final_block , dtype=self.dtype , ) down_blocks.append(__snake_case ) for _ in range(self.layers_per_block ): a : List[Any] = nn.Conv( __snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__snake_case ) if not is_final_block: a : Tuple = nn.Conv( __snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) controlnet_down_blocks.append(__snake_case ) a : int = down_blocks a : int = controlnet_down_blocks # mid a : Optional[Any] = block_out_channels[-1] a : List[Any] = FlaxUNetMidBlockaDCrossAttn( in_channels=__snake_case , dropout=self.dropout , num_attention_heads=num_attention_heads[-1] , use_linear_projection=self.use_linear_projection , dtype=self.dtype , ) a : int = nn.Conv( __snake_case , kernel_size=(1, 1) , padding='VALID' , kernel_init=nn.initializers.zeros_init() , bias_init=nn.initializers.zeros_init() , dtype=self.dtype , ) def __call__( self : str , __snake_case : Optional[int] , __snake_case : Union[str, Any] , __snake_case : Optional[int] , __snake_case : List[str] , __snake_case : float = 1.0 , __snake_case : bool = True , __snake_case : bool = False , ): a : Union[str, Any] = self.controlnet_conditioning_channel_order if channel_order == "bgr": a : Union[str, Any] = jnp.flip(__snake_case , axis=1 ) # 1. time if not isinstance(__snake_case , jnp.ndarray ): a : int = jnp.array([timesteps] , dtype=jnp.intaa ) elif isinstance(__snake_case , jnp.ndarray ) and len(timesteps.shape ) == 0: a : Any = timesteps.astype(dtype=jnp.floataa ) a : str = jnp.expand_dims(__snake_case , 0 ) a : Optional[Any] = self.time_proj(__snake_case ) a : Tuple = self.time_embedding(__snake_case ) # 2. pre-process a : Union[str, Any] = jnp.transpose(__snake_case , (0, 2, 3, 1) ) a : Optional[int] = self.conv_in(__snake_case ) a : List[str] = jnp.transpose(__snake_case , (0, 2, 3, 1) ) a : Any = self.controlnet_cond_embedding(__snake_case ) sample += controlnet_cond # 3. down a : List[str] = (sample,) for down_block in self.down_blocks: if isinstance(__snake_case , __snake_case ): a , a : Dict = down_block(__snake_case , __snake_case , __snake_case , deterministic=not train ) else: a , a : Union[str, Any] = down_block(__snake_case , __snake_case , deterministic=not train ) down_block_res_samples += res_samples # 4. mid a : List[Any] = self.mid_block(__snake_case , __snake_case , __snake_case , deterministic=not train ) # 5. contronet blocks a : List[str] = () for down_block_res_sample, controlnet_block in zip(__snake_case , self.controlnet_down_blocks ): a : List[str] = controlnet_block(__snake_case ) controlnet_down_block_res_samples += (down_block_res_sample,) a : Union[str, Any] = controlnet_down_block_res_samples a : str = self.controlnet_mid_block(__snake_case ) # 6. scaling a : Union[str, Any] = [sample * conditioning_scale for sample in down_block_res_samples] mid_block_res_sample *= conditioning_scale if not return_dict: return (down_block_res_samples, mid_block_res_sample) return FlaxControlNetOutput( down_block_res_samples=__snake_case , mid_block_res_sample=__snake_case )
297
'''simple docstring''' import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer lowerCAmelCase: Dict = logging.get_logger(__name__) lowerCAmelCase: str = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json', }, 'merges_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt', }, 'tokenizer_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json', }, } lowerCAmelCase: str = { 'allenai/led-base-16384': 1_6_3_8_4, } class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = LEDTokenizer lowercase__ = ["""input_ids""", """attention_mask"""] def __init__( self : List[Any] , __snake_case : Optional[Any]=None , __snake_case : List[str]=None , __snake_case : Tuple=None , __snake_case : Dict="replace" , __snake_case : int="<s>" , __snake_case : Any="</s>" , __snake_case : Optional[Any]="</s>" , __snake_case : Optional[Any]="<s>" , __snake_case : Optional[Any]="<unk>" , __snake_case : List[str]="<pad>" , __snake_case : int="<mask>" , __snake_case : int=False , __snake_case : str=True , **__snake_case : Tuple , ): super().__init__( __snake_case , __snake_case , tokenizer_file=__snake_case , errors=__snake_case , bos_token=__snake_case , eos_token=__snake_case , sep_token=__snake_case , cls_token=__snake_case , unk_token=__snake_case , pad_token=__snake_case , mask_token=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case , **__snake_case , ) a : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : List[Any] = getattr(__snake_case , pre_tok_state.pop('type' ) ) a : Optional[Any] = add_prefix_space a : Optional[Any] = pre_tok_class(**__snake_case ) a : Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` a : Dict = 'post_processor' a : int = getattr(self.backend_tokenizer , __snake_case , __snake_case ) if tokenizer_component_instance: a : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a : Any = tuple(state['sep'] ) if "cls" in state: a : Any = tuple(state['cls'] ) a : Optional[Any] = False if state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : Any = add_prefix_space a : Optional[Any] = True if state.get('trim_offsets' , __snake_case ) != trim_offsets: a : List[Any] = trim_offsets a : Union[str, Any] = True if changes_to_apply: a : int = getattr(__snake_case , state.pop('type' ) ) a : List[Any] = component_class(**__snake_case ) setattr(self.backend_tokenizer , __snake_case , __snake_case ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def lowercase_ ( self : Dict ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def lowercase_ ( self : Dict , __snake_case : List[str] ): a : Tuple = AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else value a : Optional[int] = value def lowercase_ ( self : Optional[Any] , *__snake_case : Any , **__snake_case : Union[str, Any] ): a : Dict = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Union[str, Any] , *__snake_case : Optional[int] , **__snake_case : List[str] ): a : Optional[int] = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Dict , __snake_case : str , __snake_case : Optional[str] = None ): a : Union[str, Any] = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : int=None ): a : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase_ ( self : Optional[int] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : int = [self.sep_token_id] a : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase_ ( self : List[str] , __snake_case : Union[Dict[str, EncodedInput], BatchEncoding] , __snake_case : Optional[int] = None , __snake_case : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __snake_case : Optional[int] = None , __snake_case : Optional[bool] = None , ): a : Optional[Any] = super()._pad( encoded_inputs=__snake_case , max_length=__snake_case , padding_strategy=__snake_case , pad_to_multiple_of=__snake_case , return_attention_mask=__snake_case , ) # Load from model defaults if return_attention_mask is None: a : str = 'attention_mask' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: a : Any = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. a : Union[str, Any] = len(encoded_inputs['global_attention_mask'] ) != len(__snake_case ) if needs_to_be_padded: a : str = len(__snake_case ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` a : Dict = ( encoded_inputs['global_attention_mask'] + [-1] * difference ) elif self.padding_side == "left": a : Union[str, Any] = [-1] * difference + encoded_inputs[ 'global_attention_mask' ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
297
1
'''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, ) lowerCAmelCase: str = logging.getLogger(__name__) @dataclass(frozen=lowerCamelCase__ ) class a__: lowercase__ = 42 lowercase__ = 42 lowercase__ = None lowercase__ = None lowercase__ = None @dataclass(frozen=lowerCamelCase__ ) class a__: lowercase__ = 42 lowercase__ = None lowercase__ = None lowercase__ = None lowercase__ = None if is_torch_available(): import torch from torch.utils.data import Dataset class a__( lowerCamelCase__ ): lowercase__ = 42 def __init__( self : Union[str, Any] , __snake_case : str , __snake_case : PreTrainedTokenizer , __snake_case : str , __snake_case : Optional[int] = None , __snake_case : Tuple=False , __snake_case : bool = False , ): a : Optional[Any] = hans_processors[task]() a : List[str] = os.path.join( __snake_case , 'cached_{}_{}_{}_{}'.format( 'dev' if evaluate else 'train' , tokenizer.__class__.__name__ , str(__snake_case ) , __snake_case , ) , ) a : List[str] = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) a , a : List[Any] = label_list[2], label_list[1] a : List[str] = label_list # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. a : Dict = 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}""" ) a : List[Any] = torch.load(__snake_case ) else: logger.info(F"""Creating features from dataset file at {data_dir}""" ) a : Optional[Any] = ( processor.get_dev_examples(__snake_case ) if evaluate else processor.get_train_examples(__snake_case ) ) logger.info('Training examples: %s' , len(__snake_case ) ) a : Optional[int] = 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[Any] ): return len(self.features ) def __getitem__( self : Optional[int] , __snake_case : List[str] ): return self.features[i] def lowercase_ ( self : Optional[int] ): return self.label_list if is_tf_available(): import tensorflow as tf class a__: lowercase__ = 42 def __init__( self : str , __snake_case : str , __snake_case : PreTrainedTokenizer , __snake_case : str , __snake_case : Optional[int] = 1_28 , __snake_case : Optional[Any]=False , __snake_case : bool = False , ): a : Union[str, Any] = hans_processors[task]() a : List[str] = processor.get_labels() if tokenizer.__class__ in ( RobertaTokenizer, RobertaTokenizerFast, XLMRobertaTokenizer, BartTokenizer, BartTokenizerFast, ): # HACK(label indices are swapped in RoBERTa pretrained model) a , a : Dict = label_list[2], label_list[1] a : Any = label_list a : Optional[int] = processor.get_dev_examples(__snake_case ) if evaluate else processor.get_train_examples(__snake_case ) a : List[Any] = 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, ) a : Dict = 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 : str ): return self.dataset def __len__( self : int ): return len(self.features ) def __getitem__( self : Optional[Any] , __snake_case : Optional[int] ): return self.features[i] def lowercase_ ( self : Union[str, Any] ): return self.label_list class a__( lowerCamelCase__ ): def lowercase_ ( self : List[Any] , __snake_case : Union[str, Any] ): return self._create_examples(self._read_tsv(os.path.join(__snake_case , 'heuristics_train_set.txt' ) ) , 'train' ) def lowercase_ ( self : List[Any] , __snake_case : Any ): return self._create_examples(self._read_tsv(os.path.join(__snake_case , 'heuristics_evaluation_set.txt' ) ) , 'dev' ) def lowercase_ ( self : Union[str, Any] ): return ["contradiction", "entailment", "neutral"] def lowercase_ ( self : Dict , __snake_case : Tuple , __snake_case : Tuple ): a : Union[str, Any] = [] for i, line in enumerate(__snake_case ): if i == 0: continue a : Optional[Any] = '%s-%s' % (set_type, line[0]) a : Dict = line[5] a : str = line[6] a : Union[str, Any] = line[7][2:] if line[7].startswith('ex' ) else line[7] a : Optional[Any] = 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 lowerCamelCase__ ( _A , _A , _A , _A , ): a : Optional[int] = {label: i for i, label in enumerate(_A )} a : List[Any] = [] for ex_index, example in tqdm.tqdm(enumerate(_A ) , desc='convert examples to features' ): if ex_index % 1_0000 == 0: logger.info('Writing example %d' % (ex_index) ) a : Dict = tokenizer( example.text_a , example.text_b , add_special_tokens=_A , max_length=_A , padding='max_length' , truncation=_A , return_overflowing_tokens=_A , ) a : List[Any] = label_map[example.label] if example.label in label_map else 0 a : Optional[int] = int(example.pairID ) features.append(InputFeatures(**_A , label=_A , pairID=_A ) ) for i, example in enumerate(examples[:5] ): logger.info('*** Example ***' ) logger.info(f"""guid: {example}""" ) logger.info(f"""features: {features[i]}""" ) return features lowerCAmelCase: List[Any] = { 'hans': 3, } lowerCAmelCase: Dict = { 'hans': HansProcessor, }
297
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class a__: def __init__( self : Tuple ): a : Optional[int] = '' a : Optional[Any] = '' a : str = [] a : int = 0 a : str = 2_56 a : Union[str, Any] = 0 a : Any = 0 a : Optional[int] = 0 a : List[str] = 0 def lowercase_ ( self : str , __snake_case : str ): a : Any = cva.imread(__snake_case , 0 ) a : Optional[Any] = copy.deepcopy(self.img ) a , a , a : int = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label='x' ) a : Optional[int] = np.sum(__snake_case ) for i in range(len(__snake_case ) ): a : Optional[Any] = x[i] / self.k self.sk += prk a : str = (self.L - 1) * self.sk if self.rem != 0: a : Optional[int] = int(last % last ) a : int = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__snake_case ) a : str = int(np.ma.count(self.img ) / self.img[1].size ) a : Optional[int] = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a : Any = self.img[j][i] if num != self.last_list[num]: a : str = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def lowercase_ ( self : Dict ): plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def lowercase_ ( self : List[Any] ): cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": lowerCAmelCase: Optional[Any] = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') lowerCAmelCase: Tuple = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
297
1
'''simple docstring''' from typing import List, Optional, Tuple, Union import torch from ...utils import logging, randn_tensor from ..pipeline_utils import AudioPipelineOutput, DiffusionPipeline lowerCAmelCase: Tuple = logging.get_logger(__name__) # pylint: disable=invalid-name class a__( lowerCamelCase__ ): def __init__( self : Tuple , __snake_case : List[str] , __snake_case : Union[str, Any] ): super().__init__() self.register_modules(unet=__snake_case , scheduler=__snake_case ) @torch.no_grad() def __call__( self : List[Any] , __snake_case : int = 1 , __snake_case : int = 1_00 , __snake_case : Optional[Union[torch.Generator, List[torch.Generator]]] = None , __snake_case : Optional[float] = None , __snake_case : bool = True , ): if audio_length_in_s is None: a : List[str] = self.unet.config.sample_size / self.unet.config.sample_rate a : Any = audio_length_in_s * self.unet.config.sample_rate a : Any = 2 ** len(self.unet.up_blocks ) if sample_size < 3 * down_scale_factor: raise ValueError( F"""{audio_length_in_s} is too small. Make sure it's bigger or equal to""" F""" {3 * down_scale_factor / self.unet.config.sample_rate}.""" ) a : Union[str, Any] = int(__snake_case ) if sample_size % down_scale_factor != 0: a : Any = ( (audio_length_in_s * self.unet.config.sample_rate) // down_scale_factor + 1 ) * down_scale_factor logger.info( F"""{audio_length_in_s} is increased to {sample_size / self.unet.config.sample_rate} so that it can be handled""" F""" by the model. It will be cut to {original_sample_size / self.unet.config.sample_rate} after the denoising""" ' process.' ) a : Optional[Any] = int(__snake_case ) a : Optional[Any] = next(iter(self.unet.parameters() ) ).dtype a : Dict = (batch_size, self.unet.config.in_channels, sample_size) if isinstance(__snake_case , __snake_case ) and len(__snake_case ) != batch_size: raise ValueError( F"""You have passed a list of generators of length {len(__snake_case )}, but requested an effective batch""" F""" size of {batch_size}. Make sure the batch size matches the length of the generators.""" ) a : int = randn_tensor(__snake_case , generator=__snake_case , device=self.device , dtype=__snake_case ) # set step values self.scheduler.set_timesteps(__snake_case , device=audio.device ) a : Tuple = self.scheduler.timesteps.to(__snake_case ) for t in self.progress_bar(self.scheduler.timesteps ): # 1. predict noise model_output a : List[Any] = self.unet(__snake_case , __snake_case ).sample # 2. compute previous image: x_t -> t_t-1 a : Optional[int] = self.scheduler.step(__snake_case , __snake_case , __snake_case ).prev_sample a : Union[str, Any] = audio.clamp(-1 , 1 ).float().cpu().numpy() a : Optional[Any] = audio[:, :, :original_sample_size] if not return_dict: return (audio,) return AudioPipelineOutput(audios=__snake_case )
297
'''simple docstring''' import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class a__: def __init__( self : List[Any] , __snake_case : Union[str, Any] ): if isinstance(__snake_case , __snake_case ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden a : str = deepcopy(__snake_case ) elif os.path.exists(__snake_case ): with io.open(__snake_case , 'r' , encoding='utf-8' ) as f: a : Optional[Any] = json.load(__snake_case ) else: try: a : Any = baseaa.urlsafe_baadecode(__snake_case ).decode('utf-8' ) a : Union[str, Any] = json.loads(__snake_case ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) a : List[str] = config self.set_stage_and_offload() def lowercase_ ( self : List[str] ): # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. a : Dict = self.get_value('zero_optimization.stage' , -1 ) # offload a : str = False if self.is_zeroa() or self.is_zeroa(): a : Union[str, Any] = set(['cpu', 'nvme'] ) a : Optional[Any] = set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: a : List[str] = True def lowercase_ ( self : Optional[Any] , __snake_case : Optional[Any] ): a : str = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) a : Dict = nodes.pop() for node in nodes: a : List[Any] = config.get(__snake_case ) if config is None: return None, ds_key return config, ds_key def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] , __snake_case : Any=None ): a , a : List[Any] = self.find_config_node(__snake_case ) if config is None: return default return config.get(__snake_case , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Any] , __snake_case : List[str]=False ): a : Optional[Any] = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) for node in nodes: a : str = config a : Dict = config.get(__snake_case ) if config is None: if must_exist: raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] ): a : Union[str, Any] = self.get_value(__snake_case ) return False if value is None else bool(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str ): a : Optional[Any] = self.get_value(__snake_case ) return False if value is None else not bool(__snake_case ) def lowercase_ ( self : Optional[Any] ): return self._stage == 2 def lowercase_ ( self : Union[str, Any] ): return self._stage == 3 def lowercase_ ( self : str ): return self._offload class a__: def __init__( self : Tuple , __snake_case : str ): a : Optional[Any] = engine def lowercase_ ( self : Union[str, Any] , __snake_case : str , **__snake_case : Tuple ): # runs backpropagation and handles mixed precision self.engine.backward(__snake_case , **__snake_case ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : List[str] ): super().__init__(__snake_case , device_placement=__snake_case , scaler=__snake_case ) a : Optional[Any] = hasattr(self.optimizer , 'overflow' ) def lowercase_ ( self : Dict , __snake_case : Dict=None ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def lowercase_ ( self : Optional[Any] ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def lowercase_ ( self : Tuple ): if self.__has_overflow__: return self.optimizer.overflow return False class a__( lowerCamelCase__ ): def __init__( self : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any] ): super().__init__(__snake_case , __snake_case ) def lowercase_ ( self : Any ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class a__: def __init__( self : List[Any] , __snake_case : str , __snake_case : Dict=0.001 , __snake_case : Union[str, Any]=0 , **__snake_case : List[Any] ): a : Optional[Any] = params a : str = lr a : List[str] = weight_decay a : str = kwargs class a__: def __init__( self : str , __snake_case : Optional[Any] , __snake_case : List[str]=None , __snake_case : Tuple=0 , **__snake_case : Any ): a : Union[str, Any] = optimizer a : Any = total_num_steps a : List[str] = warmup_num_steps a : int = kwargs
297
1
'''simple docstring''' import numpy as np # Importing the Keras libraries and packages import tensorflow as tf from tensorflow.keras import layers, models if __name__ == "__main__": # Initialising the CNN # (Sequential- Building the model layer by layer) lowerCAmelCase: Optional[Any] = models.Sequential() # Step 1 - Convolution # Here 64,64 is the length & breadth of dataset images and 3 is for the RGB channel # (3,3) is the kernel size (filter matrix) classifier.add( layers.ConvaD(3_2, (3, 3), input_shape=(6_4, 6_4, 3), activation='relu') ) # Step 2 - Pooling classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Adding a second convolutional layer classifier.add(layers.ConvaD(3_2, (3, 3), activation='relu')) classifier.add(layers.MaxPoolingaD(pool_size=(2, 2))) # Step 3 - Flattening classifier.add(layers.Flatten()) # Step 4 - Full connection classifier.add(layers.Dense(units=1_2_8, activation='relu')) classifier.add(layers.Dense(units=1, activation='sigmoid')) # Compiling the CNN classifier.compile( optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'] ) # Part 2 - Fitting the CNN to the images # Load Trained model weights # from keras.models import load_model # regressor=load_model('cnn.h5') lowerCAmelCase: int = tf.keras.preprocessing.image.ImageDataGenerator( rescale=1.0 / 2_5_5, shear_range=0.2, zoom_range=0.2, horizontal_flip=True ) lowerCAmelCase: Tuple = tf.keras.preprocessing.image.ImageDataGenerator(rescale=1.0 / 2_5_5) lowerCAmelCase: Dict = train_datagen.flow_from_directory( 'dataset/training_set', target_size=(6_4, 6_4), batch_size=3_2, class_mode='binary' ) lowerCAmelCase: Tuple = test_datagen.flow_from_directory( 'dataset/test_set', target_size=(6_4, 6_4), batch_size=3_2, class_mode='binary' ) classifier.fit_generator( training_set, steps_per_epoch=5, epochs=3_0, validation_data=test_set ) classifier.save('cnn.h5') # Part 3 - Making new predictions lowerCAmelCase: Dict = tf.keras.preprocessing.image.load_img( 'dataset/single_prediction/image.png', target_size=(6_4, 6_4) ) lowerCAmelCase: Tuple = tf.keras.preprocessing.image.img_to_array(test_image) lowerCAmelCase: Any = np.expand_dims(test_image, axis=0) lowerCAmelCase: Any = classifier.predict(test_image) # training_set.class_indices if result[0][0] == 0: lowerCAmelCase: Tuple = 'Normal' if result[0][0] == 1: lowerCAmelCase: str = 'Abnormality detected'
297
'''simple docstring''' import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) lowerCAmelCase: int = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class a__( unittest.TestCase ): def lowercase_ ( self : int , __snake_case : str , __snake_case : bool , __snake_case : str = None , __snake_case : list = None ): a : Optional[int] = None a : Tuple = os.path.abspath(os.path.join('examples' , 'by_feature' ) ) a : List[str] = os.path.abspath('examples' ) for item in os.listdir(__snake_case ): if item not in EXCLUDE_EXAMPLES: a : int = os.path.join(__snake_case , __snake_case ) if os.path.isfile(__snake_case ) and ".py" in item_path: with self.subTest( tested_script=__snake_case , feature_script=__snake_case , tested_section='main()' if parser_only else 'training_function()' , ): a : List[Any] = compare_against_test( os.path.join(__snake_case , __snake_case ) , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = '\n'.join(__snake_case ) if special_strings is not None: for string in special_strings: a : Union[str, Any] = diff.replace(__snake_case , '' ) self.assertEqual(__snake_case , '' ) def lowercase_ ( self : Optional[Any] ): self.one_complete_example('complete_nlp_example.py' , __snake_case ) self.one_complete_example('complete_nlp_example.py' , __snake_case ) def lowercase_ ( self : Any ): a : Dict = os.path.abspath(os.path.join('examples' , 'cv_example.py' ) ) a : int = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , __snake_case , __snake_case , __snake_case ) self.one_complete_example('complete_cv_example.py' , __snake_case , __snake_case , __snake_case ) @mock.patch.dict(os.environ , {"""TESTING_MOCKED_DATALOADERS""": """1"""} ) class a__( lowerCamelCase__ ): lowercase__ = False @classmethod def lowercase_ ( cls : Optional[int] ): super().setUpClass() a : List[str] = tempfile.mkdtemp() a : Tuple = os.path.join(cls._tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) a : Optional[int] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def lowercase_ ( cls : Optional[int] ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def lowercase_ ( self : Tuple ): a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0' ) ) ) def lowercase_ ( self : Dict ): a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} """.split() a : int = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2' ) ) ) def lowercase_ ( self : Any ): a : Tuple = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0" )} """.split() a : int = run_command(self._launch_args + testargs , return_stdout=__snake_case ) self.assertNotIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) def lowercase_ ( self : int ): a : Optional[int] = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2" )} """.split() a : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=__snake_case ) if torch.cuda.is_available(): a : Any = torch.cuda.device_count() else: a : str = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) else: self.assertIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) @slow def lowercase_ ( self : Tuple ): a : Tuple = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'} ): a : Any = run_command(self._launch_args + testargs , return_stdout=__snake_case ) a : Optional[Any] = re.findall('({.+})' , __snake_case ) a : str = [r for r in results if 'accuracy' in r][-1] a : str = ast.literal_eval(__snake_case ) self.assertGreaterEqual(results['accuracy'] , 0.75 ) def lowercase_ ( self : Optional[int] ): a : int = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def lowercase_ ( self : Optional[int] ): with tempfile.TemporaryDirectory() as tmpdir: a : Optional[Any] = F""" examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(__snake_case , 'tracking' ) ) ) def lowercase_ ( self : List[str] ): a : Optional[Any] = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs ) def lowercase_ ( self : int ): a : Optional[Any] = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs )
297
1
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class a__( unittest.TestCase ): @slow def lowercase_ ( self : List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[int] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = TFAutoModel.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModel.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Union[str, Any] = TFAutoModelForPreTraining.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = AutoModelForPreTraining.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Union[str, Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForCausalLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Any = TFAutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForCausalLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[str] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[int] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Optional[int] = TFAutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = AutoModelForMaskedLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = TFAutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : str = AutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForSequenceClassification.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSequenceClassification.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : int = TFAutoModelForQuestionAnswering.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModelForQuestionAnswering.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowercase_ ( self : Tuple ): a : List[Any] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[int] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) def lowercase_ ( self : Any ): a : int = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[Any] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 )
297
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList lowerCAmelCase: List[str] = ['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif'] class a__( lowerCamelCase__ ): def __init__( self : Any , __snake_case : List[str] , __snake_case : Union[str, Any] , __snake_case : List[Any]=None , __snake_case : Optional[Any]=1 ): a : Union[str, Any] = tokenizer a : Union[str, Any] = dataset a : Any = len(__snake_case ) if n_tasks is None else n_tasks a : List[str] = n_copies def __iter__( self : str ): a : List[Any] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['prompt'].strip() ) a : Dict = self.tokenizer(__snake_case , padding=__snake_case , return_tensors='pt' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class a__( lowerCamelCase__ ): def __init__( self : Union[str, Any] , __snake_case : int , __snake_case : Optional[Any] , __snake_case : str ): a : Dict = start_length a : Dict = eof_strings a : str = tokenizer def __call__( self : Optional[Any] , __snake_case : Optional[Any] , __snake_case : Any , **__snake_case : Union[str, Any] ): a : int = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) a : Optional[int] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(__snake_case ) def lowerCamelCase__ ( _A ): a : Optional[Any] = re.split('(%s)' % '|'.join(_A ) , _A ) # last string should be "" return "".join(string_list[:-2] ) def lowerCamelCase__ ( _A , _A , _A , _A , _A , _A=20 , **_A ): a : Optional[Any] = defaultdict(_A ) # dict of list of generated tokens for step, batch in tqdm(enumerate(_A ) ): with torch.no_grad(): a : Optional[Any] = batch['ids'].shape[-1] a : Optional[Any] = accelerator.unwrap_model(_A ).generate( input_ids=batch['ids'][:, : batch['input_len']] , num_return_sequences=_A , **_A ) # each task is generated batch_size times a : Tuple = batch['task_id'].repeat(_A ) a : List[Any] = accelerator.pad_across_processes( _A , dim=1 , pad_index=tokenizer.pad_token_id ) a , a : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) a : List[str] = generated_tokens.cpu().numpy() a : int = generated_tasks.cpu().numpy() for task, generated_tokens in zip(_A , _A ): gen_token_dict[task].append(_A ) a : Any = [[] for _ in range(_A )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: a : Optional[int] = tokenizer.decode(_A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) code_gens[task].append(remove_last_block(_A ) ) return code_gens def lowerCamelCase__ ( ): # Setup configuration a : Dict = HfArgumentParser(_A ) a : Any = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric a : List[Any] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing a : int = 'false' if args.num_workers is None: a : Dict = multiprocessing.cpu_count() # Use dataset load to feed to accelerate a : List[Any] = Accelerator() set_seed(args.seed , device_specific=_A ) # Load model and tokenizer a : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) a : str = tokenizer.eos_token a : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings a : Optional[Any] = { 'do_sample': args.do_sample, 'temperature': args.temperature, 'max_new_tokens': args.max_new_tokens, 'top_p': args.top_p, 'top_k': args.top_k, 'stopping_criteria': StoppingCriteriaList([EndOfFunctionCriteria(0 , _A , _A )] ), } # Load evaluation dataset and metric a : Optional[int] = load_dataset('openai_humaneval' ) a : Optional[Any] = load_metric('code_eval' ) a : Optional[int] = args.num_tasks if args.num_tasks is not None else len(human_eval['test'] ) a : Optional[Any] = args.n_samples // args.batch_size a : Any = TokenizedDataset(_A , human_eval['test'] , n_copies=_A , n_tasks=_A ) # do not confuse args.batch_size, which is actually the num_return_sequences a : int = DataLoader(_A , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: a : int = code_eval_metric.compute(references=[''] , predictions=[['']] ) except ValueError as exception: print( 'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`' ' flag to enable code evaluation.' ) raise exception a , a : int = accelerator.prepare(_A , _A ) a : int = complete_code( _A , _A , _A , _A , n_tasks=_A , batch_size=args.batch_size , **_A , ) if accelerator.is_main_process: a : List[str] = [] for task in tqdm(range(_A ) ): a : int = human_eval['test'][task]['test'] a : int = f"""check({human_eval["test"][task]["entry_point"]})""" references.append('\n' + test_func + '\n' + entry_point ) # Evaluate completions with "code_eval" metric a , a : Tuple = code_eval_metric.compute( references=_A , predictions=_A , num_workers=args.num_workers ) print(f"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , 'w' ) as fp: json.dump(_A , _A ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
297
1
'''simple docstring''' import baseaa def lowerCamelCase__ ( _A ): return baseaa.aaaencode(string.encode('utf-8' ) ) def lowerCamelCase__ ( _A ): return baseaa.aaadecode(_A ).decode('utf-8' ) if __name__ == "__main__": import doctest doctest.testmod()
297
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( _A , _A , _A ): if isinstance(_A , torch.Tensor ): return image elif isinstance(_A , PIL.Image.Image ): a : Any = [image] if isinstance(image[0] , PIL.Image.Image ): a : List[str] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] a : int = np.concatenate(_A , axis=0 ) a : int = np.array(_A ).astype(np.floataa ) / 255.0 a : str = image.transpose(0 , 3 , 1 , 2 ) a : str = 2.0 * image - 1.0 a : Optional[int] = torch.from_numpy(_A ) elif isinstance(image[0] , torch.Tensor ): a : Optional[Any] = torch.cat(_A , dim=0 ) return image def lowerCamelCase__ ( _A , _A , _A , _A=0.9995 ): if not isinstance(_A , np.ndarray ): a : Dict = True a : Optional[Any] = va.device a : Optional[int] = va.cpu().numpy() a : Union[str, Any] = va.cpu().numpy() a : Any = np.sum(va * va / (np.linalg.norm(_A ) * np.linalg.norm(_A )) ) if np.abs(_A ) > DOT_THRESHOLD: a : Any = (1 - t) * va + t * va else: a : Any = np.arccos(_A ) a : Tuple = np.sin(_A ) a : Optional[Any] = theta_a * t a : List[Any] = np.sin(_A ) a : Dict = np.sin(theta_a - theta_t ) / sin_theta_a a : int = sin_theta_t / sin_theta_a a : Any = sa * va + sa * va if inputs_are_torch: a : Dict = torch.from_numpy(_A ).to(_A ) return va def lowerCamelCase__ ( _A , _A ): a : Optional[int] = F.normalize(_A , dim=-1 ) a : str = F.normalize(_A , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( _A , _A ): for param in model.parameters(): a : int = value class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : AutoencoderKL , __snake_case : CLIPTextModel , __snake_case : CLIPModel , __snake_case : CLIPTokenizer , __snake_case : UNetaDConditionModel , __snake_case : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , __snake_case : CLIPFeatureExtractor , __snake_case : List[str]=None , __snake_case : List[str]=None , __snake_case : List[Any]=None , ): super().__init__() self.register_modules( vae=__snake_case , text_encoder=__snake_case , clip_model=__snake_case , tokenizer=__snake_case , unet=__snake_case , scheduler=__snake_case , feature_extractor=__snake_case , coca_model=__snake_case , coca_tokenizer=__snake_case , coca_transform=__snake_case , ) a : Optional[Any] = ( feature_extractor.size if isinstance(feature_extractor.size , __snake_case ) else feature_extractor.size['shortest_edge'] ) a : Optional[int] = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , __snake_case ) set_requires_grad(self.clip_model , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory a : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__snake_case ) def lowercase_ ( self : Union[str, Any] ): self.enable_attention_slicing(__snake_case ) def lowercase_ ( self : Optional[Any] ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : Tuple ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : int ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : Union[str, Any] ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : int , __snake_case : Dict , __snake_case : str , __snake_case : Optional[int] ): # get the original timestep using init_timestep a : Optional[Any] = min(int(num_inference_steps * strength ) , __snake_case ) a : Union[str, Any] = max(num_inference_steps - init_timestep , 0 ) a : List[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase_ ( self : Dict , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Any , __snake_case : Optional[Any]=None ): if not isinstance(__snake_case , torch.Tensor ): raise ValueError(F"""`image` has to be of type `torch.Tensor` but is {type(__snake_case )}""" ) a : Optional[Any] = image.to(device=__snake_case , dtype=__snake_case ) if isinstance(__snake_case , __snake_case ): a : Optional[int] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__snake_case ) ] a : Optional[Any] = torch.cat(__snake_case , dim=0 ) else: a : Union[str, Any] = self.vae.encode(__snake_case ).latent_dist.sample(__snake_case ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : List[str] = 0.18215 * init_latents a : str = init_latents.repeat_interleave(__snake_case , dim=0 ) a : Dict = randn_tensor(init_latents.shape , generator=__snake_case , device=__snake_case , dtype=__snake_case ) # get latents a : Dict = self.scheduler.add_noise(__snake_case , __snake_case , __snake_case ) a : int = init_latents return latents def lowercase_ ( self : List[str] , __snake_case : Dict ): a : List[Any] = self.coca_transform(__snake_case ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): a : Optional[Any] = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) a : Union[str, Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('<end_of_text>' )[0].replace('<start_of_text>' , '' ).rstrip(' .,' ) def lowercase_ ( self : Tuple , __snake_case : Any , __snake_case : Optional[Any] ): a : List[Any] = self.feature_extractor.preprocess(__snake_case ) a : Optional[Any] = torch.from_numpy(clip_image_input['pixel_values'][0] ).unsqueeze(0 ).to(self.device ).half() a : int = self.clip_model.get_image_features(__snake_case ) a : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : Tuple = image_embeddings_clip.repeat_interleave(__snake_case , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowercase_ ( self : Tuple , __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : List[Any] , ): a : Optional[Any] = latents.detach().requires_grad_() a : List[Any] = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : Any = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): a : int = self.scheduler.alphas_cumprod[timestep] a : Any = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf a : List[str] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 a : Tuple = torch.sqrt(__snake_case ) a : str = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , __snake_case ): a : List[Any] = self.scheduler.sigmas[index] a : Optional[int] = latents - sigma * noise_pred else: raise ValueError(F"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Union[str, Any] = 1 / 0.18215 * sample a : str = self.vae.decode(__snake_case ).sample a : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) a : Tuple = transforms.Resize(self.feature_extractor_size )(__snake_case ) a : List[str] = self.normalize(__snake_case ).to(latents.dtype ) a : List[str] = self.clip_model.get_image_features(__snake_case ) a : Tuple = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : int = spherical_dist_loss(__snake_case , __snake_case ).mean() * clip_guidance_scale a : List[str] = -torch.autograd.grad(__snake_case , __snake_case )[0] if isinstance(self.scheduler , __snake_case ): a : List[Any] = latents.detach() + grads * (sigma**2) a : Optional[int] = noise_pred_original else: a : List[Any] = noise_pred_original - torch.sqrt(__snake_case ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Optional[int] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Optional[str] = None , __snake_case : Optional[str] = None , __snake_case : Optional[int] = 5_12 , __snake_case : Optional[int] = 5_12 , __snake_case : float = 0.6 , __snake_case : Optional[int] = 50 , __snake_case : Optional[float] = 7.5 , __snake_case : Optional[int] = 1 , __snake_case : float = 0.0 , __snake_case : Optional[float] = 1_00 , __snake_case : Optional[torch.Generator] = None , __snake_case : Optional[str] = "pil" , __snake_case : bool = True , __snake_case : float = 0.8 , __snake_case : float = 0.1 , __snake_case : float = 0.1 , ): if isinstance(__snake_case , __snake_case ) and len(__snake_case ) != batch_size: raise ValueError(F"""You have passed {batch_size} batch_size, but only {len(__snake_case )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(__snake_case , torch.Generator ) and batch_size > 1: a : Dict = [generator] + [None] * (batch_size - 1) a : Any = [ ('model', self.coca_model is None), ('tokenizer', self.coca_tokenizer is None), ('transform', self.coca_transform is None), ] a : List[str] = [x[0] for x in coca_is_none if x[1]] a : List[str] = ', '.join(__snake_case ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(__snake_case ): raise ValueError( F"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" F"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : int = self.get_image_description(__snake_case ) if style_prompt is None: if len(__snake_case ): raise ValueError( F"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" F""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : Union[str, Any] = self.get_image_description(__snake_case ) # get prompt text embeddings for content and style a : Optional[Any] = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] a : Dict = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] a : Any = slerp(__snake_case , __snake_case , __snake_case ) # duplicate text embeddings for each generation per prompt a : Optional[Any] = text_embeddings.repeat_interleave(__snake_case , dim=0 ) # set timesteps a : int = 'offset' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) a : Any = {} if accepts_offset: a : Optional[Any] = 1 self.scheduler.set_timesteps(__snake_case , **__snake_case ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) a , a : Tuple = self.get_timesteps(__snake_case , __snake_case , self.device ) a : Optional[int] = timesteps[:1].repeat(__snake_case ) # Preprocess image a : Optional[Any] = preprocess(__snake_case , __snake_case , __snake_case ) a : List[Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : str = preprocess(__snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : Union[str, Any] = slerp(__snake_case , __snake_case , __snake_case ) if clip_guidance_scale > 0: a : Dict = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : int = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : List[str] = slerp( __snake_case , __snake_case , __snake_case ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. a : int = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: a : Any = content_text_input.input_ids.shape[-1] a : List[Any] = self.tokenizer([''] , padding='max_length' , max_length=__snake_case , return_tensors='pt' ) a : List[str] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt a : Dict = uncond_embeddings.repeat_interleave(__snake_case , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a : Any = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. a : List[str] = (batch_size, self.unet.config.in_channels, height // 8, width // 8) a : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps a : int = torch.randn(__snake_case , generator=__snake_case , device='cpu' , dtype=__snake_case ).to( self.device ) else: a : Optional[int] = torch.randn(__snake_case , generator=__snake_case , device=self.device , dtype=__snake_case ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) a : List[str] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler a : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a : Optional[Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a : Union[str, Any] = {} if accepts_eta: a : List[str] = eta # check if the scheduler accepts generator a : List[Any] = 'generator' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: a : Any = generator with self.progress_bar(total=__snake_case ): for i, t in enumerate(__snake_case ): # expand the latents if we are doing classifier free guidance a : Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a : Dict = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : List[Any] = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample # perform classifier free guidance if do_classifier_free_guidance: a , a : List[str] = noise_pred.chunk(2 ) a : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: a : Optional[Any] = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) a , a : Union[str, Any] = self.cond_fn( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ) # compute the previous noisy sample x_t -> x_t-1 a : Any = self.scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Tuple = 1 / 0.18215 * latents a : Optional[int] = self.vae.decode(__snake_case ).sample a : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) a : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a : str = self.numpy_to_pil(__snake_case ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=__snake_case , nsfw_content_detected=__snake_case )
297
1
'''simple docstring''' import os import time from dataclasses import dataclass, field from enum import Enum from typing import Dict, List, Optional, Union import torch from filelock import FileLock from torch.utils.data import Dataset from ...models.auto.modeling_auto import MODEL_FOR_QUESTION_ANSWERING_MAPPING from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging from ..processors.squad import SquadFeatures, SquadVaProcessor, SquadVaProcessor, squad_convert_examples_to_features lowerCAmelCase: str = logging.get_logger(__name__) lowerCAmelCase: List[Any] = list(MODEL_FOR_QUESTION_ANSWERING_MAPPING.keys()) lowerCAmelCase: Optional[int] = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) @dataclass class a__: lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """Model type selected in the list: """ + """, """.join(lowerCamelCase__ )} ) lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """The input data dir. Should contain the .json files for the SQuAD task."""} ) lowercase__ = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) lowercase__ = field( default=1_28 , metadata={"""help""": """When splitting up a long document into chunks, how much stride to take between chunks."""} , ) lowercase__ = field( default=64 , metadata={ """help""": ( """The maximum number of tokens for the question. Questions longer than this will """ """be truncated to this length.""" ) } , ) lowercase__ = field( default=30 , metadata={ """help""": ( """The maximum length of an answer that can be generated. This is needed because the start """ """and end predictions are not conditioned on one another.""" ) } , ) lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """If true, the SQuAD examples contain some that do not have an answer."""} ) lowercase__ = field( default=0.0 , metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""} ) lowercase__ = field( default=20 , metadata={"""help""": """If null_score - best_non_null is greater than the threshold predict null."""} ) lowercase__ = field( default=0 , metadata={ """help""": ( """language id of input for language-specific xlm models (see""" """ tokenization_xlm.PRETRAINED_INIT_CONFIGURATION)""" ) } , ) lowercase__ = field(default=1 , metadata={"""help""": """multiple threads for converting example to features"""} ) class a__( lowerCamelCase__ ): lowercase__ = """train""" lowercase__ = """dev""" class a__( lowerCamelCase__ ): lowercase__ = 42 lowercase__ = 42 lowercase__ = 42 lowercase__ = 42 def __init__( self : Any , __snake_case : SquadDataTrainingArguments , __snake_case : PreTrainedTokenizer , __snake_case : Optional[int] = None , __snake_case : Union[str, Split] = Split.train , __snake_case : Optional[bool] = False , __snake_case : Optional[str] = None , __snake_case : Optional[str] = "pt" , ): a : Any = args a : Dict = is_language_sensitive a : Dict = SquadVaProcessor() if args.version_2_with_negative else SquadVaProcessor() if isinstance(__snake_case , __snake_case ): try: a : Optional[Any] = Split[mode] except KeyError: raise KeyError('mode is not a valid split name' ) a : str = mode # Load data features from cache or dataset file a : Union[str, Any] = 'v2' if args.version_2_with_negative else 'v1' a : Optional[int] = os.path.join( cache_dir if cache_dir is not None else args.data_dir , F"""cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{version_tag}""" , ) # Make sure only the first process in distributed training processes the dataset, # and the others will use the cache. a : Optional[int] = cached_features_file + '.lock' with FileLock(__snake_case ): if os.path.exists(__snake_case ) and not args.overwrite_cache: a : List[Any] = time.time() a : str = torch.load(__snake_case ) # Legacy cache files have only features, while new cache files # will have dataset and examples also. a : int = self.old_features['features'] a : str = self.old_features.get('dataset' , __snake_case ) a : Any = self.old_features.get('examples' , __snake_case ) logger.info( F"""Loading features from cached file {cached_features_file} [took %.3f s]""" , time.time() - start ) if self.dataset is None or self.examples is None: logger.warning( F"""Deleting cached file {cached_features_file} will allow dataset and examples to be cached in""" ' future run' ) else: if mode == Split.dev: a : Optional[int] = self.processor.get_dev_examples(args.data_dir ) else: a : Dict = self.processor.get_train_examples(args.data_dir ) a , a : int = squad_convert_examples_to_features( examples=self.examples , tokenizer=__snake_case , max_seq_length=args.max_seq_length , doc_stride=args.doc_stride , max_query_length=args.max_query_length , is_training=mode == Split.train , threads=args.threads , return_dataset=__snake_case , ) a : int = time.time() torch.save( {'features': self.features, 'dataset': self.dataset, 'examples': self.examples} , __snake_case , ) # ^ This seems to take a lot of time so I want to investigate why and how we can improve. logger.info( F"""Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]""" ) def __len__( self : Dict ): return len(self.features ) def __getitem__( self : Tuple , __snake_case : List[Any] ): # Convert to Tensors and build dataset a : Dict = self.features[i] a : Tuple = torch.tensor(feature.input_ids , dtype=torch.long ) a : Optional[Any] = torch.tensor(feature.attention_mask , dtype=torch.long ) a : List[Any] = torch.tensor(feature.token_type_ids , dtype=torch.long ) a : Tuple = torch.tensor(feature.cls_index , dtype=torch.long ) a : int = torch.tensor(feature.p_mask , dtype=torch.float ) a : int = torch.tensor(feature.is_impossible , dtype=torch.float ) a : Union[str, Any] = { 'input_ids': input_ids, 'attention_mask': attention_mask, 'token_type_ids': token_type_ids, } if self.args.model_type in ["xlm", "roberta", "distilbert", "camembert"]: del inputs["token_type_ids"] if self.args.model_type in ["xlnet", "xlm"]: inputs.update({'cls_index': cls_index, 'p_mask': p_mask} ) if self.args.version_2_with_negative: inputs.update({'is_impossible': is_impossible} ) if self.is_language_sensitive: inputs.update({'langs': (torch.ones(input_ids.shape , dtype=torch.intaa ) * self.args.lang_id)} ) if self.mode == Split.train: a : Dict = torch.tensor(feature.start_position , dtype=torch.long ) a : Any = torch.tensor(feature.end_position , dtype=torch.long ) inputs.update({'start_positions': start_positions, 'end_positions': end_positions} ) return inputs
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A , _A , _A , _A , ): a : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: a : Union[str, Any] = 1 - (matter_density + radiation_density + dark_energy) a : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) a : int = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation lowerCAmelCase: Optional[Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
297
1
'''simple docstring''' from typing import Dict, List, Optional, Union import numpy as np from ...image_processing_utils import BaseImageProcessor, BatchFeature, get_size_dict from ...image_transforms import rescale, resize, to_channel_dimension_format from ...image_utils import ( ChannelDimension, ImageInput, PILImageResampling, make_list_of_images, to_numpy_array, valid_images, ) from ...utils import TensorType, is_vision_available, logging if is_vision_available(): import PIL lowerCAmelCase: Optional[int] = logging.get_logger(__name__) def lowerCamelCase__ ( _A , _A ): a : Any = b.T a : Any = np.sum(np.square(_A ) , axis=1 ) a : Tuple = np.sum(np.square(_A ) , axis=0 ) a : Tuple = np.matmul(_A , _A ) a : str = aa[:, None] - 2 * ab + ba[None, :] return d def lowerCamelCase__ ( _A , _A ): a : Dict = x.reshape(-1 , 3 ) a : int = squared_euclidean_distance(_A , _A ) return np.argmin(_A , axis=1 ) class a__( lowerCamelCase__ ): lowercase__ = ["""pixel_values"""] def __init__( self : Any , __snake_case : Optional[Union[List[List[int]], np.ndarray]] = None , __snake_case : bool = True , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = PILImageResampling.BILINEAR , __snake_case : bool = True , __snake_case : bool = True , **__snake_case : List[str] , ): super().__init__(**__snake_case ) a : Optional[int] = size if size is not None else {'height': 2_56, 'width': 2_56} a : Union[str, Any] = get_size_dict(__snake_case ) a : Union[str, Any] = np.array(__snake_case ) if clusters is not None else None a : Union[str, Any] = do_resize a : Any = size a : Tuple = resample a : int = do_normalize a : List[Any] = do_color_quantize def lowercase_ ( self : Any , __snake_case : np.ndarray , __snake_case : Dict[str, int] , __snake_case : PILImageResampling = PILImageResampling.BILINEAR , __snake_case : Optional[Union[str, ChannelDimension]] = None , **__snake_case : Any , ): a : Union[str, Any] = get_size_dict(__snake_case ) if "height" not in size or "width" not in size: raise ValueError(F"""Size dictionary must contain both height and width keys. Got {size.keys()}""" ) return resize( __snake_case , size=(size['height'], size['width']) , resample=__snake_case , data_format=__snake_case , **__snake_case ) def lowercase_ ( self : List[Any] , __snake_case : np.ndarray , __snake_case : Optional[Union[str, ChannelDimension]] = None , ): a : List[Any] = rescale(image=__snake_case , scale=1 / 127.5 , data_format=__snake_case ) a : Any = image - 1 return image def lowercase_ ( self : Dict , __snake_case : ImageInput , __snake_case : bool = None , __snake_case : Dict[str, int] = None , __snake_case : PILImageResampling = None , __snake_case : bool = None , __snake_case : Optional[bool] = None , __snake_case : Optional[Union[List[List[int]], np.ndarray]] = None , __snake_case : Optional[Union[str, TensorType]] = None , __snake_case : Optional[Union[str, ChannelDimension]] = ChannelDimension.FIRST , **__snake_case : Optional[int] , ): a : List[str] = do_resize if do_resize is not None else self.do_resize a : List[Any] = size if size is not None else self.size a : List[str] = get_size_dict(__snake_case ) a : Dict = resample if resample is not None else self.resample a : str = do_normalize if do_normalize is not None else self.do_normalize a : Optional[Any] = do_color_quantize if do_color_quantize is not None else self.do_color_quantize a : Optional[Any] = clusters if clusters is not None else self.clusters a : Any = np.array(__snake_case ) a : List[Any] = make_list_of_images(__snake_case ) if not valid_images(__snake_case ): raise ValueError( 'Invalid image type. Must be of type PIL.Image.Image, numpy.ndarray, ' 'torch.Tensor, tf.Tensor or jax.ndarray.' ) if do_resize and size is None or resample is None: raise ValueError('Size and resample must be specified if do_resize is True.' ) if do_color_quantize and clusters is None: raise ValueError('Clusters must be specified if do_color_quantize is True.' ) # All transformations expect numpy arrays. a : List[Any] = [to_numpy_array(__snake_case ) for image in images] if do_resize: a : Optional[int] = [self.resize(image=__snake_case , size=__snake_case , resample=__snake_case ) for image in images] if do_normalize: a : str = [self.normalize(image=__snake_case ) for image in images] if do_color_quantize: a : Dict = [to_channel_dimension_format(__snake_case , ChannelDimension.LAST ) for image in images] # color quantize from (batch_size, height, width, 3) to (batch_size, height, width) a : List[Any] = np.array(__snake_case ) a : int = color_quantize(__snake_case , __snake_case ).reshape(images.shape[:-1] ) # flatten to (batch_size, height*width) a : str = images.shape[0] a : Dict = images.reshape(__snake_case , -1 ) # We need to convert back to a list of images to keep consistent behaviour across processors. a : List[str] = list(__snake_case ) else: a : Optional[int] = [to_channel_dimension_format(__snake_case , __snake_case ) for image in images] a : int = {'input_ids': images} return BatchFeature(data=__snake_case , tensor_type=__snake_case )
297
'''simple docstring''' from __future__ import annotations import math class a__: def __init__( self : List[str] , __snake_case : int ): a : str = size # approximate the overall size of segment tree with given value a : Optional[int] = [0 for i in range(0 , 4 * size )] # create array to store lazy update a : Any = [0 for i in range(0 , 4 * size )] a : Dict = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowercase_ ( self : int , __snake_case : int ): return idx * 2 def lowercase_ ( self : Dict , __snake_case : int ): return idx * 2 + 1 def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : list[int] ): if left_element == right_element: a : Tuple = a[left_element - 1] else: a : Tuple = (left_element + right_element) // 2 self.build(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case ) self.build(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case ) a : Union[str, Any] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : int = self.lazy[idx] a : Union[str, Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : int = self.lazy[idx] a : Tuple = True a : Optional[Any] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: a : int = val if left_element != right_element: a : int = val a : Dict = val a : List[str] = True a : List[str] = True return True a : Tuple = (left_element + right_element) // 2 self.update(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) self.update(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case , __snake_case ) a : Optional[int] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) return True def lowercase_ ( self : Union[str, Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : str = self.lazy[idx] a : Optional[Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : Union[str, Any] = self.lazy[idx] a : Dict = True a : int = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] a : Dict = (left_element + right_element) // 2 a : Optional[int] = self.query(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.query(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case ) return max(__snake_case , __snake_case ) def __str__( self : Any ): return str([self.query(1 , 1 , self.size , __snake_case , __snake_case ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] lowerCAmelCase: int = 1_5 lowerCAmelCase: Optional[int] = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
297
1
'''simple docstring''' from .imports import is_rich_available if is_rich_available(): from rich.traceback import install install(show_locals=False) else: raise ModuleNotFoundError('To use the rich extension, install rich with `pip install rich`')
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A ): while second != 0: a : Union[str, Any] = first & second first ^= second a : Tuple = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase: Optional[int] = int(input('Enter the first number: ').strip()) lowerCAmelCase: Union[str, Any] = int(input('Enter the second number: ').strip()) print(F"{add(first, second) = }")
297
1
'''simple docstring''' from __future__ import annotations from decimal import Decimal from math import * # noqa: F403 from sympy import diff def lowerCamelCase__ ( _A , _A , _A = 10**-10 ): a : Any = a while True: a : List[str] = Decimal(_A ) - ( Decimal(eval(_A ) ) / Decimal(eval(str(diff(_A ) ) ) ) # noqa: S307 ) # This number dictates the accuracy of the answer if abs(eval(_A ) ) < precision: # noqa: S307 return float(_A ) # Let's Execute if __name__ == "__main__": # Find root of trigonometric function # Find value of pi print(F"The root of sin(x) = 0 is {newton_raphson('sin(x)', 2)}") # Find root of polynomial print(F"The root of x**2 - 5*x + 2 = 0 is {newton_raphson('x**2 - 5*x + 2', 0.4)}") # Find Square Root of 5 print(F"The root of log(x) - 1 = 0 is {newton_raphson('log(x) - 1', 2)}") # Exponential Roots print(F"The root of exp(x) - 1 = 0 is {newton_raphson('exp(x) - 1', 0)}")
297
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ ( _A , _A ): assert isinstance(_A , _A ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Optional[int] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , keep_in_memory=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Tuple = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Dict = features.copy() if features else default_expected_features a : Union[str, Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Tuple = tmp_path / 'cache' a : Optional[Any] = {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} a : Optional[int] = features.copy() if features else default_expected_features a : Dict = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Optional[int] = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCamelCase__ ( _A , _A ): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} a : Dict = {'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} a : int = features.copy() a : List[Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Dict = tmp_path / 'cache' a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[str] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , split=_A ).read() _check_json_dataset(_A , _A ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def lowerCamelCase__ ( _A , _A , _A ): if issubclass(_A , _A ): a : Optional[int] = jsonl_path elif issubclass(_A , _A ): a : Optional[int] = [jsonl_path] a : List[str] = tmp_path / 'cache' a : Dict = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) def lowerCamelCase__ ( _A , _A , _A=("train",) ): assert isinstance(_A , _A ) for split in splits: a : str = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : Any = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : int = JsonDatasetReader({'train': jsonl_path} , cache_dir=_A , keep_in_memory=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[Any] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = features.copy() if features else default_expected_features a : Any = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : List[str] = JsonDatasetReader({'train': jsonl_path} , features=_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): if split: a : Any = {split: jsonl_path} else: a : List[Any] = 'train' a : List[str] = {'train': jsonl_path, 'test': jsonl_path} a : List[Any] = tmp_path / 'cache' a : str = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase__ ( _A ): return json.load(_A ) def lowerCamelCase__ ( _A ): return [json.loads(_A ) for line in buffer] class a__: @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : Tuple , __snake_case : int , __snake_case : Optional[int] , __snake_case : Any ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case ).write() buffer.seek(0 ) a : List[str] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Tuple , __snake_case : Tuple , __snake_case : Any , __snake_case : Any , __snake_case : List[str] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : List[Any] , __snake_case : Any , __snake_case : Optional[int] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : List[Any] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Optional[int] , __snake_case : Any , __snake_case : str , __snake_case : int , __snake_case : List[Any] , __snake_case : Dict ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 def lowercase_ ( self : List[str] , __snake_case : str ): with pytest.raises(__snake_case ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def lowercase_ ( self : Tuple , __snake_case : Dict , __snake_case : List[Any] , __snake_case : int , __snake_case : List[str] , __snake_case : Optional[int] ): a : Tuple = tmp_path_factory.mktemp('data' ) / F"""test.json.{extension}""" a : List[Any] = str(shared_datadir / F"""test_file.json.{extension}""" ) JsonDatasetWriter(__snake_case , __snake_case , compression=__snake_case ).write() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() assert exported_content == original_content
297
1
'''simple docstring''' import copy import tempfile import unittest from transformers import MaMaaaConfig, is_torch_available from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow, torch_device from transformers.utils import cached_property from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import MaMaaaForConditionalGeneration, MaMaaaModel, MaMaaaTokenizer from transformers.models.mam_aaa.modeling_mam_aaa import MaMaaaDecoder, MaMaaaEncoder def lowerCamelCase__ ( _A , _A , _A , _A=None , _A=None , _A=None , _A=None , _A=None , ): if attention_mask is None: a : Optional[Any] = input_ids.ne(config.pad_token_id ) if decoder_attention_mask is None: a : str = decoder_input_ids.ne(config.pad_token_id ) if head_mask is None: a : str = torch.ones(config.encoder_layers , config.encoder_attention_heads , device=_A ) if decoder_head_mask is None: a : Optional[int] = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=_A ) if cross_attn_head_mask is None: a : Union[str, Any] = torch.ones(config.decoder_layers , config.decoder_attention_heads , device=_A ) return { "input_ids": input_ids, "decoder_input_ids": decoder_input_ids, "attention_mask": attention_mask, "decoder_attention_mask": attention_mask, "head_mask": head_mask, "decoder_head_mask": decoder_head_mask, "cross_attn_head_mask": cross_attn_head_mask, } class a__: def __init__( self : Dict , __snake_case : Dict , __snake_case : Optional[Any]=13 , __snake_case : int=7 , __snake_case : Optional[int]=True , __snake_case : Union[str, Any]=False , __snake_case : List[Any]=99 , __snake_case : Tuple=16 , __snake_case : Any=2 , __snake_case : Union[str, Any]=4 , __snake_case : Dict=4 , __snake_case : Tuple="relu" , __snake_case : Optional[int]=0.1 , __snake_case : int=0.1 , __snake_case : int=0.0 , __snake_case : List[str]=0.0 , __snake_case : List[str]=20 , __snake_case : Optional[Any]=2 , __snake_case : Tuple=1 , __snake_case : Optional[Any]=0 , ): a : List[str] = parent a : Optional[Any] = batch_size a : List[Any] = seq_length a : Dict = is_training a : Union[str, Any] = use_labels a : Optional[Any] = vocab_size a : Optional[int] = hidden_size a : Tuple = num_hidden_layers a : List[Any] = num_attention_heads a : Tuple = intermediate_size a : Dict = hidden_act a : Optional[int] = hidden_dropout_prob a : List[Any] = attention_probs_dropout_prob a : int = encoder_layerdrop a : Union[str, Any] = decoder_layerdrop a : Optional[int] = max_position_embeddings a : Dict = eos_token_id a : Dict = pad_token_id a : Tuple = bos_token_id def lowercase_ ( self : Dict ): a : List[str] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Dict = self.eos_token_id # Eos Token a : Union[str, Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) # we need to clamp the input ids here to avoid having pad token in between # this is because for M2M100 the position_ids are prepared such that # all pad tokens have pos id = 2 and rest are between 2..seq_length # and the seq_length here is seq_length - num_pad_tokens # but when using past, there is no way of knowing if the past input ids had # pad tokens in them, which results in incorrect seq_lenth and which in turn results in # position_ids being off by num_pad_tokens in past input a : List[str] = input_ids.clamp(self.pad_token_id + 1 ) a : Union[str, Any] = decoder_input_ids.clamp(self.pad_token_id + 1 ) a : Union[str, Any] = self.get_config() a : int = prepare_mam_aaa_inputs_dict(__snake_case , __snake_case , __snake_case ) return config, inputs_dict def lowercase_ ( self : Union[str, Any] ): return MaMaaaConfig( vocab_size=self.vocab_size , d_model=self.hidden_size , encoder_layers=self.num_hidden_layers , decoder_layers=self.num_hidden_layers , encoder_attention_heads=self.num_attention_heads , decoder_attention_heads=self.num_attention_heads , encoder_ffn_dim=self.intermediate_size , decoder_ffn_dim=self.intermediate_size , dropout=self.hidden_dropout_prob , attention_dropout=self.attention_probs_dropout_prob , encoder_layerdrop=self.encoder_layerdrop , decoder_layerdrop=self.decoder_layerdrop , max_position_embeddings=self.max_position_embeddings , eos_token_id=self.eos_token_id , bos_token_id=self.bos_token_id , pad_token_id=self.pad_token_id , ) def lowercase_ ( self : Optional[Any] ): a , a : List[Any] = self.prepare_config_and_inputs() return config, inputs_dict def lowercase_ ( self : List[Any] , __snake_case : Union[str, Any] , __snake_case : Tuple ): a : Union[str, Any] = MaMaaaModel(config=__snake_case ).get_decoder().to(__snake_case ).eval() a : List[str] = inputs_dict['input_ids'] a : Any = inputs_dict['attention_mask'] a : List[str] = inputs_dict['head_mask'] # first forward pass a : Optional[Any] = model(__snake_case , attention_mask=__snake_case , head_mask=__snake_case , use_cache=__snake_case ) a , a : Union[str, Any] = outputs.to_tuple() # create hypothetical multiple next token and extent to next_input_ids a : Dict = ids_tensor((self.batch_size, 3) , config.vocab_size ) a : List[str] = ids_tensor((self.batch_size, 3) , 2 ) # append to next input_ids and a : Dict = torch.cat([input_ids, next_tokens] , dim=-1 ) a : Tuple = torch.cat([attention_mask, next_attn_mask] , dim=-1 ) a : Tuple = model(__snake_case , attention_mask=__snake_case )['last_hidden_state'] a : Tuple = model(__snake_case , attention_mask=__snake_case , past_key_values=__snake_case )[ 'last_hidden_state' ] # select random slice a : Union[str, Any] = ids_tensor((1,) , output_from_past.shape[-1] ).item() a : Any = output_from_no_past[:, -3:, random_slice_idx].detach() a : Dict = output_from_past[:, :, random_slice_idx].detach() self.parent.assertTrue(output_from_past_slice.shape[1] == next_tokens.shape[1] ) # test that outputs are equal for slice self.parent.assertTrue(torch.allclose(__snake_case , __snake_case , atol=1e-2 ) ) def lowercase_ ( self : Dict , __snake_case : List[Any] , __snake_case : Optional[int] ): a : int = MaMaaaModel(config=__snake_case ).to(__snake_case ).eval() a : Union[str, Any] = model(**__snake_case ) a : Union[str, Any] = outputs.encoder_last_hidden_state a : List[str] = outputs.last_hidden_state with tempfile.TemporaryDirectory() as tmpdirname: a : Optional[int] = model.get_encoder() encoder.save_pretrained(__snake_case ) a : Union[str, Any] = MaMaaaEncoder.from_pretrained(__snake_case ).to(__snake_case ) a : List[str] = encoder(inputs_dict['input_ids'] , attention_mask=inputs_dict['attention_mask'] )[ 0 ] self.parent.assertTrue((encoder_last_hidden_state_a - encoder_last_hidden_state).abs().max().item() < 1e-3 ) with tempfile.TemporaryDirectory() as tmpdirname: a : Tuple = model.get_decoder() decoder.save_pretrained(__snake_case ) a : Any = MaMaaaDecoder.from_pretrained(__snake_case ).to(__snake_case ) a : Optional[Any] = decoder( input_ids=inputs_dict['decoder_input_ids'] , attention_mask=inputs_dict['decoder_attention_mask'] , encoder_hidden_states=__snake_case , encoder_attention_mask=inputs_dict['attention_mask'] , )[0] self.parent.assertTrue((last_hidden_state_a - last_hidden_state).abs().max().item() < 1e-3 ) @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = ( ( MaMaaaModel, MaMaaaForConditionalGeneration, ) if is_torch_available() else () ) lowercase__ = (MaMaaaForConditionalGeneration,) if is_torch_available() else () lowercase__ = ( { """conversational""": MaMaaaForConditionalGeneration, """feature-extraction""": MaMaaaModel, """summarization""": MaMaaaForConditionalGeneration, """text2text-generation""": MaMaaaForConditionalGeneration, """translation""": MaMaaaForConditionalGeneration, } if is_torch_available() else {} ) lowercase__ = True lowercase__ = True lowercase__ = False lowercase__ = False def lowercase_ ( self : Optional[Any] , __snake_case : Dict , __snake_case : str , __snake_case : Any , __snake_case : List[Any] , __snake_case : Any ): if pipeline_test_casse_name == "TranslationPipelineTests": # Get `ValueError: Translation requires a `src_lang` and a `tgt_lang` for this model`. # `M2M100Config` was never used in pipeline tests: cannot create a simple tokenizer. return True return False def lowercase_ ( self : List[Any] ): a : int = MaMaaaModelTester(self ) a : List[Any] = ConfigTester(self , config_class=__snake_case ) def lowercase_ ( self : Any ): self.config_tester.run_common_tests() def lowercase_ ( self : List[str] ): a , a : int = self.model_tester.prepare_config_and_inputs() for model_class in self.all_model_classes: a : Any = model_class(__snake_case ) with tempfile.TemporaryDirectory() as tmpdirname: model.save_pretrained(__snake_case ) a , a : Optional[Any] = model_class.from_pretrained(__snake_case , output_loading_info=__snake_case ) self.assertEqual(info['missing_keys'] , [] ) def lowercase_ ( self : Optional[Any] ): a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_decoder_model_past_large_inputs(*__snake_case ) def lowercase_ ( self : Optional[Any] ): a : Dict = self.model_tester.prepare_config_and_inputs_for_common() self.model_tester.check_encoder_decoder_model_standalone(*__snake_case ) def lowercase_ ( self : Optional[int] ): a , a : Optional[int] = self.model_tester.prepare_config_and_inputs_for_common() for model_class in (MaMaaaModel, MaMaaaForConditionalGeneration): a : str = model_class(__snake_case ) model.to(__snake_case ) model.eval() a : Tuple = copy.deepcopy(self._prepare_for_class(__snake_case , __snake_case ) ) if not self.is_encoder_decoder: a : Dict = inputs['input_ids'] del inputs["input_ids"] else: a : int = inputs['input_ids'] a : str = inputs.get('decoder_input_ids' , __snake_case ) del inputs["input_ids"] inputs.pop('decoder_input_ids' , __snake_case ) a : str = model.get_input_embeddings() if not self.is_encoder_decoder: a : Optional[int] = wte(__snake_case ) else: a : Optional[Any] = wte(__snake_case ) a : List[str] = wte(__snake_case ) with torch.no_grad(): model(**__snake_case )[0] def lowercase_ ( self : Optional[Any] ): a , a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() a : Optional[int] = input_dict['input_ids'] a : Any = input_ids.ne(1 ).to(__snake_case ) a : Dict = MaMaaaForConditionalGeneration(__snake_case ).eval().to(__snake_case ) if torch_device == "cuda": model.half() model.generate(__snake_case , attention_mask=__snake_case ) model.generate(num_beams=4 , do_sample=__snake_case , early_stopping=__snake_case , num_return_sequences=3 ) def lowerCamelCase__ ( _A ): return torch.tensor(_A , dtype=torch.long , device=_A ) lowerCAmelCase: Any = 1e-4 @require_torch @require_sentencepiece @require_tokenizers @slow class a__( unittest.TestCase ): @cached_property def lowercase_ ( self : List[Any] ): return MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M' ) def lowercase_ ( self : Union[str, Any] ): a : List[Any] = MaMaaaModel.from_pretrained('facebook/m2m100_418M' ).to(__snake_case ) a : Union[str, Any] = _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]] ) a : str = _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]] ) a : Optional[Any] = prepare_mam_aaa_inputs_dict(model.config , __snake_case , __snake_case ) with torch.no_grad(): a : Tuple = model(**__snake_case )[0] a : Tuple = torch.Size((1, 11, 10_24) ) self.assertEqual(output.shape , __snake_case ) # change to expected output here a : Optional[Any] = torch.tensor( [[-0.7780, -0.1676, 0.1038], [-6.7556, -1.3992, 0.0567], [-7.5383, -0.5920, -0.2779]] , device=__snake_case ) self.assertTrue(torch.allclose(output[:, :3, :3] , __snake_case , atol=__snake_case ) ) def lowercase_ ( self : str ): a : Dict = MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M' ).to(__snake_case ) # change to intended input a : str = _long_tensor([[12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38, 2]] ) a : Any = _long_tensor([[2, 12_80_28, 98, 12, 3_05_27, 27_32, 1_59, 77_55, 6_19_04, 3_91_44, 38]] ) a : Any = prepare_mam_aaa_inputs_dict(model.config , __snake_case , __snake_case ) with torch.no_grad(): a : Tuple = model(**__snake_case )[0] a : int = torch.Size((1, 11, model.config.vocab_size) ) self.assertEqual(output.shape , __snake_case ) # change to expected output here a : Tuple = torch.tensor( [[-1.0448, -1.0411, 3.7992], [-3.2191, -3.2386, -1.3451], [-3.6210, -3.5993, 0.4925]] , device=__snake_case ) self.assertTrue(torch.allclose(output[:, :3, :3] , __snake_case , atol=__snake_case ) ) def lowercase_ ( self : int ): a : Dict = MaMaaaForConditionalGeneration.from_pretrained('facebook/m2m100_418M' ).to(__snake_case ) a : Tuple = MaMaaaTokenizer.from_pretrained('facebook/m2m100_418M' , src_lang='fr' , tgt_lang='en' ) a : Any = [ 'L\'affaire NSA souligne l\'absence totale de débat sur le renseignement', 'Selon moi, il y a deux niveaux de réponse de la part du gouvernement français.', 'Lorsque François Hollande téléphone à Barack Obama ou quand le ministre des affaires étrangères Laurent' ' Fabius convoque l\'ambassadeur des Etats-Unis, ils réagissent à une vraie découverte, qui est celle de' ' l\'ampleur de la surveillance américaine sur l\'ensemble des communications en France.', ] # The below article tests that we don't add any hypotheses outside of the top n_beams a : List[str] = tokenizer(__snake_case , padding=__snake_case , return_tensors='pt' ) a : Tuple = model.generate( input_ids=dct['input_ids'].to(__snake_case ) , attention_mask=dct['attention_mask'].to(__snake_case ) , num_beams=5 , forced_bos_token_id=tokenizer.get_lang_id('en' ) , ) a : int = [ 'The NSA case highlights the total absence of intelligence debate', 'I think there are two levels of response from the French government.', 'When François Hollande calls Barack Obama or when Foreign Minister Laurent Fabius calls the U.S.' ' Ambassador, they respond to a real discovery, which is that of the scale of U.S. surveillance on all' ' communications in France.', ] a : Optional[Any] = tokenizer.batch_decode( hypotheses_batch.tolist() , clean_up_tokenization_spaces=__snake_case , skip_special_tokens=__snake_case ) assert generated == expected_en
297
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCamelCase__ ( _A = "laptop" ): a : Any = f"""https://www.amazon.in/laptop/s?k={product}""" a : Tuple = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5', } a : Any = BeautifulSoup(requests.get(_A , headers=_A ).text ) # Initialize a Pandas dataframe with the column titles a : Any = DataFrame( columns=[ 'Product Title', 'Product Link', 'Current Price of the product', 'Product Rating', 'MRP of the product', 'Discount', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( 'div' , attrs={'class': 's-result-item', 'data-component-type': 's-search-result'} , ) , soup.find_all('div' , attrs={'class': 'a-row a-size-base a-color-base'} ) , ): try: a : Optional[int] = item.ha.text a : str = 'https://www.amazon.in/' + item.ha.a['href'] a : List[str] = item.find('span' , attrs={'class': 'a-offscreen'} ).text try: a : Optional[Any] = item.find('span' , attrs={'class': 'a-icon-alt'} ).text except AttributeError: a : Union[str, Any] = 'Not available' try: a : str = ( '₹' + item.find( 'span' , attrs={'class': 'a-price a-text-price'} ).text.split('₹' )[1] ) except AttributeError: a : int = '' try: a : Union[str, Any] = float( ( ( float(product_mrp.strip('₹' ).replace(',' , '' ) ) - float(product_price.strip('₹' ).replace(',' , '' ) ) ) / float(product_mrp.strip('₹' ).replace(',' , '' ) ) ) * 100 ) except ValueError: a : Any = float('nan' ) except AttributeError: pass a : Any = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] a : Any = ' ' a : List[str] = ' ' data_frame.index += 1 return data_frame if __name__ == "__main__": lowerCAmelCase: str = 'headphones' get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
297
1
'''simple docstring''' from __future__ import annotations def lowerCamelCase__ ( _A ): a : Optional[Any] = str(_A ) return len(_A ) == 9 and set(_A ) == set('123456789' ) def lowerCamelCase__ ( ): for base_num in range(9999 , 4999 , -1 ): a : Optional[int] = 10_0002 * base_num if is_9_pandigital(_A ): return candidate for base_num in range(333 , 99 , -1 ): a : Tuple = 100_2003 * base_num if is_9_pandigital(_A ): return candidate return None if __name__ == "__main__": print(F"{solution() = }")
297
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = StableUnCLIPImgaImgPipeline lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase__ = frozenset([] ) def lowercase_ ( self : int ): a : Dict = 32 a : str = embedder_hidden_size # image encoding components a : List[Any] = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) a : Dict = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=__snake_case , projection_dim=__snake_case , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) a : Dict = StableUnCLIPImageNormalizer(embedding_dim=__snake_case ) a : Optional[int] = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) a : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) a : Tuple = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__snake_case , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) a : Union[str, Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__snake_case , layers_per_block=1 , upcast_attention=__snake_case , use_linear_projection=__snake_case , ) torch.manual_seed(0 ) a : List[Any] = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.00085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=__snake_case , steps_offset=1 , ) torch.manual_seed(0 ) a : List[str] = AutoencoderKL() a : str = { # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def lowercase_ ( self : Tuple , __snake_case : List[str] , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=True ): if str(__snake_case ).startswith('mps' ): a : Tuple = torch.manual_seed(__snake_case ) else: a : List[Any] = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) a : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__snake_case ) ).to(__snake_case ) if pil_image: a : Optional[Any] = input_image * 0.5 + 0.5 a : Optional[Any] = input_image.clamp(0 , 1 ) a : Dict = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() a : int = DiffusionPipeline.numpy_to_pil(__snake_case )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def lowercase_ ( self : Optional[Any] ): a : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a : Union[str, Any] = self.get_dummy_components() a : Any = StableUnCLIPImgaImgPipeline(**__snake_case ) a : Tuple = sd_pipe.to(__snake_case ) sd_pipe.set_progress_bar_config(disable=__snake_case ) a : Union[str, Any] = self.get_dummy_inputs(__snake_case ) inputs.update({'image_embeds': None} ) a : str = sd_pipe(**__snake_case ).images a : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) a : Optional[int] = np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase_ ( self : List[str] ): a : int = torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=__snake_case ) def lowercase_ ( self : int ): a : Optional[int] = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=__snake_case ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def lowercase_ ( self : Dict ): self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__snake_case ) @slow @require_torch_gpu class a__( unittest.TestCase ): def lowercase_ ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Optional[Any] ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Union[str, Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) a : Optional[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = torch.Generator(device='cpu' ).manual_seed(0 ) a : Optional[int] = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Optional[int] ): a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) a : Union[str, Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a : str = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Any ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) a : Optional[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = pipe( __snake_case , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) a : int = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
297
1
'''simple docstring''' import json from typing import List, Optional, Tuple from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import logging from .tokenization_mvp import MvpTokenizer lowerCAmelCase: str = logging.get_logger(__name__) lowerCAmelCase: Optional[int] = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} # See all MVP models at https://huggingface.co/models?filter=mvp lowerCAmelCase: str = { 'vocab_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/vocab.json', }, 'added_tokens.json': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/added_tokens.json', }, 'merges_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/merges.txt', }, 'tokenizer_file': { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/tokenizer.json', }, } lowerCAmelCase: Union[str, Any] = { 'RUCAIBox/mvp': 1_0_2_4, } class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = MvpTokenizer def __init__( self : List[str] , __snake_case : Optional[Any]=None , __snake_case : Any=None , __snake_case : Optional[int]=None , __snake_case : List[str]="replace" , __snake_case : Tuple="<s>" , __snake_case : List[Any]="</s>" , __snake_case : str="</s>" , __snake_case : List[str]="<s>" , __snake_case : Union[str, Any]="<unk>" , __snake_case : Any="<pad>" , __snake_case : List[Any]="<mask>" , __snake_case : Any=False , __snake_case : int=True , **__snake_case : List[str] , ): super().__init__( __snake_case , __snake_case , tokenizer_file=__snake_case , errors=__snake_case , bos_token=__snake_case , eos_token=__snake_case , sep_token=__snake_case , cls_token=__snake_case , unk_token=__snake_case , pad_token=__snake_case , mask_token=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case , **__snake_case , ) a : Any = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : Any = getattr(__snake_case , pre_tok_state.pop('type' ) ) a : int = add_prefix_space a : Any = pre_tok_class(**__snake_case ) a : Dict = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` a : Dict = 'post_processor' a : Dict = getattr(self.backend_tokenizer , __snake_case , __snake_case ) if tokenizer_component_instance: a : Optional[int] = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a : List[Any] = tuple(state['sep'] ) if "cls" in state: a : Dict = tuple(state['cls'] ) a : Optional[Any] = False if state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : List[Any] = add_prefix_space a : Dict = True if state.get('trim_offsets' , __snake_case ) != trim_offsets: a : Union[str, Any] = trim_offsets a : Optional[Any] = True if changes_to_apply: a : str = getattr(__snake_case , state.pop('type' ) ) a : Tuple = component_class(**__snake_case ) setattr(self.backend_tokenizer , __snake_case , __snake_case ) @property def lowercase_ ( self : List[str] ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def lowercase_ ( self : Dict , __snake_case : int ): a : List[str] = AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else value a : str = value def lowercase_ ( self : Tuple , *__snake_case : List[Any] , **__snake_case : Optional[int] ): a : Dict = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Optional[int] , *__snake_case : Optional[int] , **__snake_case : Optional[int] ): a : Optional[int] = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : List[Any] , __snake_case : str , __snake_case : Optional[str] = None ): a : Optional[int] = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case ) def lowercase_ ( self : List[Any] , __snake_case : Optional[Any] , __snake_case : List[str]=None ): a : List[str] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase_ ( self : Optional[int] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : Any = [self.sep_token_id] a : Any = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0]
297
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowerCAmelCase: Union[str, Any] = logging.get_logger(__name__) lowerCAmelCase: List[str] = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """t5""" lowercase__ = ["""past_key_values"""] lowercase__ = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : Union[str, Any] , __snake_case : int=3_21_28 , __snake_case : str=5_12 , __snake_case : Dict=64 , __snake_case : Optional[int]=20_48 , __snake_case : Tuple=6 , __snake_case : Any=None , __snake_case : Optional[int]=8 , __snake_case : str=32 , __snake_case : Union[str, Any]=1_28 , __snake_case : Optional[int]=0.1 , __snake_case : Dict=1e-6 , __snake_case : int=1.0 , __snake_case : Optional[int]="relu" , __snake_case : Any=True , __snake_case : List[str]=True , __snake_case : Union[str, Any]=0 , __snake_case : Dict=1 , **__snake_case : Optional[int] , ): a : Optional[int] = vocab_size a : Dict = d_model a : Union[str, Any] = d_kv a : Dict = d_ff a : Tuple = num_layers a : Dict = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a : int = num_heads a : str = relative_attention_num_buckets a : List[Any] = relative_attention_max_distance a : int = dropout_rate a : Tuple = layer_norm_epsilon a : str = initializer_factor a : List[Any] = feed_forward_proj a : Union[str, Any] = use_cache a : List[str] = self.feed_forward_proj.split('-' ) a : int = act_info[-1] a : Union[str, Any] = act_info[0] == 'gated' if len(__snake_case ) > 1 and act_info[0] != "gated" or len(__snake_case ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a : Optional[Any] = 'gelu_new' super().__init__( pad_token_id=__snake_case , eos_token_id=__snake_case , is_encoder_decoder=__snake_case , **__snake_case , ) class a__( lowerCamelCase__ ): @property def lowercase_ ( self : Optional[int] ): a : Dict = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: a : Dict = 'past_encoder_sequence + sequence' a : Dict = {0: 'batch'} a : Any = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: a : Optional[Any] = {0: 'batch', 1: 'decoder_sequence'} a : List[str] = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__snake_case , direction='inputs' ) return common_inputs @property def lowercase_ ( self : List[Any] ): return 13
297
1
'''simple docstring''' import argparse import os.path as osp import re import torch from safetensors.torch import load_file, save_file # =================# # UNet Conversion # # =================# lowerCAmelCase: Tuple = [ # (stable-diffusion, HF Diffusers) ('time_embed.0.weight', 'time_embedding.linear_1.weight'), ('time_embed.0.bias', 'time_embedding.linear_1.bias'), ('time_embed.2.weight', 'time_embedding.linear_2.weight'), ('time_embed.2.bias', 'time_embedding.linear_2.bias'), ('input_blocks.0.0.weight', 'conv_in.weight'), ('input_blocks.0.0.bias', 'conv_in.bias'), ('out.0.weight', 'conv_norm_out.weight'), ('out.0.bias', 'conv_norm_out.bias'), ('out.2.weight', 'conv_out.weight'), ('out.2.bias', 'conv_out.bias'), ] lowerCAmelCase: Any = [ # (stable-diffusion, HF Diffusers) ('in_layers.0', 'norm1'), ('in_layers.2', 'conv1'), ('out_layers.0', 'norm2'), ('out_layers.3', 'conv2'), ('emb_layers.1', 'time_emb_proj'), ('skip_connection', 'conv_shortcut'), ] lowerCAmelCase: int = [] # hardcoded number of downblocks and resnets/attentions... # would need smarter logic for other networks. for i in range(4): # loop over downblocks/upblocks for j in range(2): # loop over resnets/attentions for downblocks lowerCAmelCase: List[str] = F"down_blocks.{i}.resnets.{j}." lowerCAmelCase: List[str] = F"input_blocks.{3*i + j + 1}.0." unet_conversion_map_layer.append((sd_down_res_prefix, hf_down_res_prefix)) if i < 3: # no attention layers in down_blocks.3 lowerCAmelCase: Optional[Any] = F"down_blocks.{i}.attentions.{j}." lowerCAmelCase: Any = F"input_blocks.{3*i + j + 1}.1." unet_conversion_map_layer.append((sd_down_atn_prefix, hf_down_atn_prefix)) for j in range(3): # loop over resnets/attentions for upblocks lowerCAmelCase: Optional[int] = F"up_blocks.{i}.resnets.{j}." lowerCAmelCase: Optional[int] = F"output_blocks.{3*i + j}.0." unet_conversion_map_layer.append((sd_up_res_prefix, hf_up_res_prefix)) if i > 0: # no attention layers in up_blocks.0 lowerCAmelCase: List[Any] = F"up_blocks.{i}.attentions.{j}." lowerCAmelCase: Optional[Any] = F"output_blocks.{3*i + j}.1." unet_conversion_map_layer.append((sd_up_atn_prefix, hf_up_atn_prefix)) if i < 3: # no downsample in down_blocks.3 lowerCAmelCase: Dict = F"down_blocks.{i}.downsamplers.0.conv." lowerCAmelCase: Tuple = F"input_blocks.{3*(i+1)}.0.op." unet_conversion_map_layer.append((sd_downsample_prefix, hf_downsample_prefix)) # no upsample in up_blocks.3 lowerCAmelCase: Union[str, Any] = F"up_blocks.{i}.upsamplers.0." lowerCAmelCase: Optional[int] = F"output_blocks.{3*i + 2}.{1 if i == 0 else 2}." unet_conversion_map_layer.append((sd_upsample_prefix, hf_upsample_prefix)) lowerCAmelCase: Dict = 'mid_block.attentions.0.' lowerCAmelCase: List[Any] = 'middle_block.1.' unet_conversion_map_layer.append((sd_mid_atn_prefix, hf_mid_atn_prefix)) for j in range(2): lowerCAmelCase: Union[str, Any] = F"mid_block.resnets.{j}." lowerCAmelCase: Optional[Any] = F"middle_block.{2*j}." unet_conversion_map_layer.append((sd_mid_res_prefix, hf_mid_res_prefix)) def lowerCamelCase__ ( _A ): # buyer beware: this is a *brittle* function, # and correct output requires that all of these pieces interact in # the exact order in which I have arranged them. a : Optional[int] = {k: k for k in unet_state_dict.keys()} for sd_name, hf_name in unet_conversion_map: a : Tuple = sd_name for k, v in mapping.items(): if "resnets" in k: for sd_part, hf_part in unet_conversion_map_resnet: a : Dict = v.replace(_A , _A ) a : List[str] = v for k, v in mapping.items(): for sd_part, hf_part in unet_conversion_map_layer: a : str = v.replace(_A , _A ) a : Any = v a : str = {v: unet_state_dict[k] for k, v in mapping.items()} return new_state_dict # ================# # VAE Conversion # # ================# lowerCAmelCase: Tuple = [ # (stable-diffusion, HF Diffusers) ('nin_shortcut', 'conv_shortcut'), ('norm_out', 'conv_norm_out'), ('mid.attn_1.', 'mid_block.attentions.0.'), ] for i in range(4): # down_blocks have two resnets for j in range(2): lowerCAmelCase: Dict = F"encoder.down_blocks.{i}.resnets.{j}." lowerCAmelCase: int = F"encoder.down.{i}.block.{j}." vae_conversion_map.append((sd_down_prefix, hf_down_prefix)) if i < 3: lowerCAmelCase: str = F"down_blocks.{i}.downsamplers.0." lowerCAmelCase: Dict = F"down.{i}.downsample." vae_conversion_map.append((sd_downsample_prefix, hf_downsample_prefix)) lowerCAmelCase: Dict = F"up_blocks.{i}.upsamplers.0." lowerCAmelCase: Dict = F"up.{3-i}.upsample." vae_conversion_map.append((sd_upsample_prefix, hf_upsample_prefix)) # up_blocks have three resnets # also, up blocks in hf are numbered in reverse from sd for j in range(3): lowerCAmelCase: Tuple = F"decoder.up_blocks.{i}.resnets.{j}." lowerCAmelCase: Dict = F"decoder.up.{3-i}.block.{j}." vae_conversion_map.append((sd_up_prefix, hf_up_prefix)) # this part accounts for mid blocks in both the encoder and the decoder for i in range(2): lowerCAmelCase: Optional[Any] = F"mid_block.resnets.{i}." lowerCAmelCase: List[str] = F"mid.block_{i+1}." vae_conversion_map.append((sd_mid_res_prefix, hf_mid_res_prefix)) lowerCAmelCase: int = [ # (stable-diffusion, HF Diffusers) ('norm.', 'group_norm.'), ('q.', 'query.'), ('k.', 'key.'), ('v.', 'value.'), ('proj_out.', 'proj_attn.'), ] def lowerCamelCase__ ( _A ): # convert HF linear weights to SD conv2d weights return w.reshape(*w.shape , 1 , 1 ) def lowerCamelCase__ ( _A ): a : int = {k: k for k in vae_state_dict.keys()} for k, v in mapping.items(): for sd_part, hf_part in vae_conversion_map: a : List[Any] = v.replace(_A , _A ) a : Any = v for k, v in mapping.items(): if "attentions" in k: for sd_part, hf_part in vae_conversion_map_attn: a : Optional[Any] = v.replace(_A , _A ) a : Dict = v a : str = {v: vae_state_dict[k] for k, v in mapping.items()} a : List[Any] = ['q', 'k', 'v', 'proj_out'] for k, v in new_state_dict.items(): for weight_name in weights_to_convert: if f"""mid.attn_1.{weight_name}.weight""" in k: print(f"""Reshaping {k} for SD format""" ) a : int = reshape_weight_for_sd(_A ) return new_state_dict # =========================# # Text Encoder Conversion # # =========================# lowerCAmelCase: str = [ # (stable-diffusion, HF Diffusers) ('resblocks.', 'text_model.encoder.layers.'), ('ln_1', 'layer_norm1'), ('ln_2', 'layer_norm2'), ('.c_fc.', '.fc1.'), ('.c_proj.', '.fc2.'), ('.attn', '.self_attn'), ('ln_final.', 'transformer.text_model.final_layer_norm.'), ('token_embedding.weight', 'transformer.text_model.embeddings.token_embedding.weight'), ('positional_embedding', 'transformer.text_model.embeddings.position_embedding.weight'), ] lowerCAmelCase: Dict = {re.escape(x[1]): x[0] for x in textenc_conversion_lst} lowerCAmelCase: Optional[int] = re.compile('|'.join(protected.keys())) # Ordering is from https://github.com/pytorch/pytorch/blob/master/test/cpp/api/modules.cpp lowerCAmelCase: Any = {'q': 0, 'k': 1, 'v': 2} def lowerCamelCase__ ( _A ): a : List[str] = {} a : Optional[Any] = {} a : int = {} for k, v in text_enc_dict.items(): if ( k.endswith('.self_attn.q_proj.weight' ) or k.endswith('.self_attn.k_proj.weight' ) or k.endswith('.self_attn.v_proj.weight' ) ): a : Optional[Any] = k[: -len('.q_proj.weight' )] a : int = k[-len('q_proj.weight' )] if k_pre not in capture_qkv_weight: a : List[Any] = [None, None, None] a : Dict = v continue if ( k.endswith('.self_attn.q_proj.bias' ) or k.endswith('.self_attn.k_proj.bias' ) or k.endswith('.self_attn.v_proj.bias' ) ): a : Tuple = k[: -len('.q_proj.bias' )] a : int = k[-len('q_proj.bias' )] if k_pre not in capture_qkv_bias: a : Optional[int] = [None, None, None] a : Optional[Any] = v continue a : str = textenc_pattern.sub(lambda _A : protected[re.escape(m.group(0 ) )] , _A ) a : Dict = v for k_pre, tensors in capture_qkv_weight.items(): if None in tensors: raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing' ) a : Optional[Any] = textenc_pattern.sub(lambda _A : protected[re.escape(m.group(0 ) )] , _A ) a : Optional[int] = torch.cat(_A ) for k_pre, tensors in capture_qkv_bias.items(): if None in tensors: raise Exception('CORRUPTED MODEL: one of the q-k-v values for the text encoder was missing' ) a : Optional[Any] = textenc_pattern.sub(lambda _A : protected[re.escape(m.group(0 ) )] , _A ) a : Tuple = torch.cat(_A ) return new_state_dict def lowerCamelCase__ ( _A ): return text_enc_dict if __name__ == "__main__": lowerCAmelCase: Dict = argparse.ArgumentParser() parser.add_argument('--model_path', default=None, type=str, required=True, help='Path to the model to convert.') parser.add_argument('--checkpoint_path', default=None, type=str, required=True, help='Path to the output model.') parser.add_argument('--half', action='store_true', help='Save weights in half precision.') parser.add_argument( '--use_safetensors', action='store_true', help='Save weights use safetensors, default is ckpt.' ) lowerCAmelCase: Optional[Any] = parser.parse_args() assert args.model_path is not None, "Must provide a model path!" assert args.checkpoint_path is not None, "Must provide a checkpoint path!" # Path for safetensors lowerCAmelCase: Any = osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.safetensors') lowerCAmelCase: Union[str, Any] = osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.safetensors') lowerCAmelCase: List[Any] = osp.join(args.model_path, 'text_encoder', 'model.safetensors') # Load models from safetensors if it exists, if it doesn't pytorch if osp.exists(unet_path): lowerCAmelCase: Any = load_file(unet_path, device='cpu') else: lowerCAmelCase: Tuple = osp.join(args.model_path, 'unet', 'diffusion_pytorch_model.bin') lowerCAmelCase: List[Any] = torch.load(unet_path, map_location='cpu') if osp.exists(vae_path): lowerCAmelCase: List[str] = load_file(vae_path, device='cpu') else: lowerCAmelCase: Union[str, Any] = osp.join(args.model_path, 'vae', 'diffusion_pytorch_model.bin') lowerCAmelCase: Optional[Any] = torch.load(vae_path, map_location='cpu') if osp.exists(text_enc_path): lowerCAmelCase: Any = load_file(text_enc_path, device='cpu') else: lowerCAmelCase: List[Any] = osp.join(args.model_path, 'text_encoder', 'pytorch_model.bin') lowerCAmelCase: List[str] = torch.load(text_enc_path, map_location='cpu') # Convert the UNet model lowerCAmelCase: List[Any] = convert_unet_state_dict(unet_state_dict) lowerCAmelCase: int = {'model.diffusion_model.' + k: v for k, v in unet_state_dict.items()} # Convert the VAE model lowerCAmelCase: str = convert_vae_state_dict(vae_state_dict) lowerCAmelCase: Tuple = {'first_stage_model.' + k: v for k, v in vae_state_dict.items()} # Easiest way to identify v2.0 model seems to be that the text encoder (OpenCLIP) is deeper lowerCAmelCase: int = 'text_model.encoder.layers.22.layer_norm2.bias' in text_enc_dict if is_vaa_model: # Need to add the tag 'transformer' in advance so we can knock it out from the final layer-norm lowerCAmelCase: Optional[Any] = {'transformer.' + k: v for k, v in text_enc_dict.items()} lowerCAmelCase: Union[str, Any] = convert_text_enc_state_dict_vaa(text_enc_dict) lowerCAmelCase: Any = {'cond_stage_model.model.' + k: v for k, v in text_enc_dict.items()} else: lowerCAmelCase: List[Any] = convert_text_enc_state_dict(text_enc_dict) lowerCAmelCase: Dict = {'cond_stage_model.transformer.' + k: v for k, v in text_enc_dict.items()} # Put together new checkpoint lowerCAmelCase: Tuple = {**unet_state_dict, **vae_state_dict, **text_enc_dict} if args.half: lowerCAmelCase: List[Any] = {k: v.half() for k, v in state_dict.items()} if args.use_safetensors: save_file(state_dict, args.checkpoint_path) else: lowerCAmelCase: str = {'state_dict': state_dict} torch.save(state_dict, args.checkpoint_path)
297
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def lowerCamelCase__ ( _A , _A ): if inductance <= 0: raise ValueError('Inductance cannot be 0 or negative' ) elif capacitance <= 0: raise ValueError('Capacitance cannot be 0 or negative' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
297
1
'''simple docstring''' from pathlib import PurePosixPath from typing import Optional import fsspec from fsspec import AbstractFileSystem from huggingface_hub.hf_api import DatasetInfo from ..utils.file_utils import get_authentication_headers_for_url from ..utils.hub import hf_hub_url class a__( lowerCamelCase__ ): lowercase__ = """""" lowercase__ = """hf-legacy""" # "hf://"" is reserved for hffs def __init__( self : Dict , __snake_case : Optional[DatasetInfo] = None , __snake_case : Optional[str] = None , **__snake_case : Optional[int] , ): super().__init__(self , **__snake_case ) a : Tuple = repo_info a : str = token a : Any = None def lowercase_ ( self : List[Any] ): if self.dir_cache is None: a : Any = {} for hf_file in self.repo_info.siblings: # TODO(QL): add sizes a : Dict = { 'name': hf_file.rfilename, 'size': None, 'type': 'file', } self.dir_cache.update( { str(__snake_case ): {'name': str(__snake_case ), 'size': None, 'type': 'directory'} for d in list(PurePosixPath(hf_file.rfilename ).parents )[:-1] } ) def lowercase_ ( self : List[Any] , __snake_case : str , __snake_case : str = "rb" , **__snake_case : List[str] , ): if not isinstance(self.repo_info , __snake_case ): raise NotImplementedError(F"""Open is only implemented for dataset repositories, but got {self.repo_info}""" ) a : Optional[int] = hf_hub_url(self.repo_info.id , __snake_case , revision=self.repo_info.sha ) return fsspec.open( __snake_case , mode=__snake_case , headers=get_authentication_headers_for_url(__snake_case , use_auth_token=self.token ) , client_kwargs={'trust_env': True} , ).open() def lowercase_ ( self : Optional[int] , __snake_case : List[Any] , **__snake_case : Any ): self._get_dirs() a : Any = self._strip_protocol(__snake_case ) if path in self.dir_cache: return self.dir_cache[path] else: raise FileNotFoundError(__snake_case ) def lowercase_ ( self : Optional[Any] , __snake_case : Tuple , __snake_case : List[str]=False , **__snake_case : Any ): self._get_dirs() a : Optional[Any] = PurePosixPath(path.strip('/' ) ) a : List[str] = {} for p, f in self.dir_cache.items(): a : Union[str, Any] = PurePosixPath(p.strip('/' ) ) a : List[str] = p.parent if root == path: a : int = f a : Optional[int] = list(paths.values() ) if detail: return out else: return sorted(f['name'] for f in out )
297
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase: Any = logging.get_logger(__name__) lowerCAmelCase: Any = {'vocab_file': 'vocab.txt'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } lowerCAmelCase: str = { 'openbmb/cpm-ant-10b': 1_0_2_4, } def lowerCamelCase__ ( _A ): a : Union[str, Any] = collections.OrderedDict() with open(_A , 'r' , encoding='utf-8' ) as reader: a : int = reader.readlines() for index, token in enumerate(_A ): a : int = token.rstrip('\n' ) a : List[Any] = index return vocab class a__( lowerCamelCase__ ): def __init__( self : Dict , __snake_case : Any , __snake_case : Dict="<unk>" , __snake_case : str=2_00 ): a : List[Any] = vocab a : Any = unk_token a : List[str] = max_input_chars_per_word def lowercase_ ( self : Optional[int] , __snake_case : Union[str, Any] ): a : Optional[Any] = list(__snake_case ) if len(__snake_case ) > self.max_input_chars_per_word: return [self.unk_token] a : Any = 0 a : Optional[Any] = [] while start < len(__snake_case ): a : Optional[int] = len(__snake_case ) a : str = None while start < end: a : Optional[Any] = ''.join(chars[start:end] ) if substr in self.vocab: a : List[str] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(__snake_case ) a : List[str] = end return sub_tokens class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = False def __init__( self : Any , __snake_case : str , __snake_case : Tuple="<d>" , __snake_case : List[str]="</d>" , __snake_case : Dict="<s>" , __snake_case : List[Any]="</s>" , __snake_case : int="<pad>" , __snake_case : Any="<unk>" , __snake_case : List[str]="</n>" , __snake_case : int="</_>" , __snake_case : Optional[Any]="left" , **__snake_case : Dict , ): requires_backends(self , ['jieba'] ) super().__init__( bod_token=__snake_case , eod_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , pad_token=__snake_case , unk_token=__snake_case , line_token=__snake_case , space_token=__snake_case , padding_side=__snake_case , **__snake_case , ) a : Union[str, Any] = bod_token a : Any = eod_token a : List[str] = load_vocab(__snake_case ) a : Optional[int] = self.encoder[space_token] a : str = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] a : str = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) a : Tuple = {v: k for k, v in self.encoder.items()} a : List[str] = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def lowercase_ ( self : Optional[int] ): return self.encoder[self.bod_token] @property def lowercase_ ( self : Dict ): return self.encoder[self.eod_token] @property def lowercase_ ( self : Any ): return self.encoder["\n"] @property def lowercase_ ( self : Tuple ): return len(self.encoder ) def lowercase_ ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def lowercase_ ( self : Union[str, Any] , __snake_case : List[str] ): a : List[str] = [] for x in jieba.cut(__snake_case , cut_all=__snake_case ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(__snake_case ) ) return output_tokens def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[Any] , **__snake_case : Optional[Any] ): a : Optional[int] = [i for i in token_ids if i >= 0] a : Any = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(__snake_case , **__snake_case ) def lowercase_ ( self : Optional[int] , __snake_case : int ): return token in self.encoder def lowercase_ ( self : int , __snake_case : List[str] ): return "".join(__snake_case ) def lowercase_ ( self : List[str] , __snake_case : Union[str, Any] ): return self.encoder.get(__snake_case , self.encoder.get(self.unk_token ) ) def lowercase_ ( self : Tuple , __snake_case : List[str] ): return self.decoder.get(__snake_case , self.unk_token ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] = None ): if os.path.isdir(__snake_case ): a : Optional[int] = os.path.join( __snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: a : int = (filename_prefix + '-' if filename_prefix else '') + save_directory a : Any = 0 if " " in self.encoder: a : Union[str, Any] = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: a : Tuple = self.encoder['\n'] del self.encoder["\n"] a : Dict = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) with open(__snake_case , 'w' , encoding='utf-8' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ' Please check that the vocabulary is not corrupted!' ) a : List[Any] = token_index writer.write(token + '\n' ) index += 1 return (vocab_file,) def lowercase_ ( self : Union[str, Any] , __snake_case : List[int] , __snake_case : List[int] = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowercase_ ( self : Dict , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) if token_ids_a is not None: return [1] + ([0] * len(__snake_case )) + [1] + ([0] * len(__snake_case )) return [1] + ([0] * len(__snake_case ))
297
1
'''simple docstring''' import argparse import os import evaluate import torch from datasets import load_dataset from torch.optim import AdamW from torch.utils.data import DataLoader from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed from accelerate import Accelerator, DistributedType ######################################################################## # This is a fully working simple example to use Accelerate, # specifically showcasing the experiment tracking capability, # and builds off the `nlp_example.py` script. # # This example trains a Bert base model on GLUE MRPC # in any of the following settings (with the same script): # - single CPU or single GPU # - multi GPUS (using PyTorch distributed mode) # - (multi) TPUs # - fp16 (mixed-precision) or fp32 (normal precision) # # To help focus on the differences in the code, building `DataLoaders` # was refactored into its own function. # New additions from the base script can be found quickly by # looking for the # New Code # tags # # To run it in each of these various modes, follow the instructions # in the readme for examples: # https://github.com/huggingface/accelerate/tree/main/examples # ######################################################################## lowerCAmelCase: Optional[Any] = 1_6 lowerCAmelCase: List[str] = 3_2 def lowerCamelCase__ ( _A , _A = 16 ): a : Any = AutoTokenizer.from_pretrained('bert-base-cased' ) a : Tuple = load_dataset('glue' , 'mrpc' ) def tokenize_function(_A ): # max_length=None => use the model max length (it's actually the default) a : Optional[int] = tokenizer(examples['sentence1'] , examples['sentence2'] , truncation=_A , max_length=_A ) return outputs # Apply the method we just defined to all the examples in all the splits of the dataset # starting with the main process first: with accelerator.main_process_first(): a : List[Any] = datasets.map( _A , batched=_A , remove_columns=['idx', 'sentence1', 'sentence2'] , ) # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the # transformers library a : int = tokenized_datasets.rename_column('label' , 'labels' ) def collate_fn(_A ): # On TPU it's best to pad everything to the same length or training will be very slow. a : Union[str, Any] = 128 if accelerator.distributed_type == DistributedType.TPU else None # When using mixed precision we want round multiples of 8/16 if accelerator.mixed_precision == "fp8": a : str = 16 elif accelerator.mixed_precision != "no": a : Dict = 8 else: a : Optional[Any] = None return tokenizer.pad( _A , padding='longest' , max_length=_A , pad_to_multiple_of=_A , return_tensors='pt' , ) # Instantiate dataloaders. a : List[str] = DataLoader( tokenized_datasets['train'] , shuffle=_A , collate_fn=_A , batch_size=_A ) a : Tuple = DataLoader( tokenized_datasets['validation'] , shuffle=_A , collate_fn=_A , batch_size=_A ) return train_dataloader, eval_dataloader # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS', None) == "1": from accelerate.test_utils.training import mocked_dataloaders lowerCAmelCase: Dict = mocked_dataloaders # noqa: F811 def lowerCamelCase__ ( _A , _A ): # For testing only if os.environ.get('TESTING_MOCKED_DATALOADERS' , _A ) == "1": a : Union[str, Any] = 2 # Initialize Accelerator # New Code # # We pass in "all" to `log_with` to grab all available trackers in the environment # Note: If using a custom `Tracker` class, should be passed in here such as: # >>> log_with = ["all", MyCustomTrackerClassInstance()] if args.with_tracking: a : Optional[Any] = Accelerator( cpu=args.cpu , mixed_precision=args.mixed_precision , log_with='all' , project_dir=args.project_dir ) else: a : Tuple = Accelerator(cpu=args.cpu , mixed_precision=args.mixed_precision ) # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs a : Dict = config['lr'] a : Dict = int(config['num_epochs'] ) a : Optional[Any] = int(config['seed'] ) a : str = int(config['batch_size'] ) set_seed(_A ) a , a : Optional[Any] = get_dataloaders(_A , _A ) a : Optional[int] = evaluate.load('glue' , 'mrpc' ) # If the batch size is too big we use gradient accumulation a : Tuple = 1 if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU: a : Any = batch_size // MAX_GPU_BATCH_SIZE a : List[Any] = MAX_GPU_BATCH_SIZE # Instantiate the model (we build the model here so that the seed also control new weights initialization) a : Optional[Any] = AutoModelForSequenceClassification.from_pretrained('bert-base-cased' , return_dict=_A ) # We could avoid this line since the accelerator is set with `device_placement=True` (default value). # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). a : Dict = model.to(accelerator.device ) # Instantiate optimizer a : Optional[Any] = AdamW(params=model.parameters() , lr=_A ) # Instantiate scheduler a : List[str] = get_linear_schedule_with_warmup( optimizer=_A , num_warmup_steps=100 , num_training_steps=(len(_A ) * num_epochs) // gradient_accumulation_steps , ) # Prepare everything # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the # prepare method. a , a , a , a , a : Optional[int] = accelerator.prepare( _A , _A , _A , _A , _A ) # New Code # # We need to initialize the trackers we use. Overall configurations can also be stored if args.with_tracking: a : Optional[int] = os.path.split(_A )[-1].split('.' )[0] accelerator.init_trackers(_A , _A ) # Now we train the model for epoch in range(_A ): model.train() # New Code # # For our tracking example, we will log the total loss of each epoch if args.with_tracking: a : Optional[int] = 0 for step, batch in enumerate(_A ): # We could avoid this line since we set the accelerator with `device_placement=True`. batch.to(accelerator.device ) a : Union[str, Any] = model(**_A ) a : str = outputs.loss # New Code # if args.with_tracking: total_loss += loss.detach().float() a : List[str] = loss / gradient_accumulation_steps accelerator.backward(_A ) if step % gradient_accumulation_steps == 0: optimizer.step() lr_scheduler.step() optimizer.zero_grad() model.eval() for step, batch in enumerate(_A ): # We could avoid this line since we set the accelerator with `device_placement=True` (the default). batch.to(accelerator.device ) with torch.no_grad(): a : Dict = model(**_A ) a : Optional[Any] = outputs.logits.argmax(dim=-1 ) a , a : List[Any] = accelerator.gather_for_metrics((predictions, batch['labels']) ) metric.add_batch( predictions=_A , references=_A , ) a : Optional[int] = metric.compute() # Use accelerator.print to print only on the main process. accelerator.print(f"""epoch {epoch}:""" , _A ) # New Code # # To actually log, we call `Accelerator.log` # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` if args.with_tracking: accelerator.log( { 'accuracy': eval_metric['accuracy'], 'f1': eval_metric['f1'], 'train_loss': total_loss.item() / len(_A ), 'epoch': epoch, } , step=_A , ) # New Code # # When a run is finished, you should call `accelerator.end_training()` # to close all of the open trackers if args.with_tracking: accelerator.end_training() def lowerCamelCase__ ( ): a : List[str] = argparse.ArgumentParser(description='Simple example of training script.' ) parser.add_argument( '--mixed_precision' , type=_A , default=_A , choices=['no', 'fp16', 'bf16', 'fp8'] , help='Whether to use mixed precision. Choose' 'between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10.' 'and an Nvidia Ampere GPU.' , ) parser.add_argument('--cpu' , action='store_true' , help='If passed, will train on the CPU.' ) parser.add_argument( '--with_tracking' , action='store_true' , help='Whether to load in all available experiment trackers from the environment and use them for logging.' , ) parser.add_argument( '--project_dir' , type=_A , default='logs' , help='Location on where to store experiment tracking logs` and relevent project information' , ) a : int = parser.parse_args() a : Optional[Any] = {'lr': 2E-5, 'num_epochs': 3, 'seed': 42, 'batch_size': 16} training_function(_A , _A ) if __name__ == "__main__": main()
297
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class a__( unittest.TestCase ): @slow def lowercase_ ( self : List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[int] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = TFAutoModel.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModel.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Union[str, Any] = TFAutoModelForPreTraining.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = AutoModelForPreTraining.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Union[str, Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForCausalLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Any = TFAutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForCausalLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[str] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[int] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Optional[int] = TFAutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = AutoModelForMaskedLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = TFAutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : str = AutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForSequenceClassification.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSequenceClassification.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : int = TFAutoModelForQuestionAnswering.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModelForQuestionAnswering.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowercase_ ( self : Tuple ): a : List[Any] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[int] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) def lowercase_ ( self : Any ): a : int = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[Any] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 )
297
1
'''simple docstring''' from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase: List[str] = logging.get_logger(__name__) lowerCAmelCase: Dict = {'openai-gpt': 'https://huggingface.co/openai-gpt/resolve/main/config.json'} class a__( lowerCamelCase__ ): lowercase__ = """openai-gpt""" lowercase__ = { """max_position_embeddings""": """n_positions""", """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Tuple , __snake_case : Any=4_04_78 , __snake_case : List[str]=5_12 , __snake_case : List[Any]=7_68 , __snake_case : Optional[int]=12 , __snake_case : Dict=12 , __snake_case : List[Any]="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : List[str]=0.1 , __snake_case : List[Any]=0.1 , __snake_case : List[str]=1e-5 , __snake_case : int=0.02 , __snake_case : List[Any]="cls_index" , __snake_case : Any=True , __snake_case : Union[str, Any]=None , __snake_case : Dict=True , __snake_case : Union[str, Any]=0.1 , **__snake_case : Tuple , ): a : List[str] = vocab_size a : Any = n_positions a : Optional[int] = n_embd a : Tuple = n_layer a : Union[str, Any] = n_head a : List[str] = afn a : List[str] = resid_pdrop a : Tuple = embd_pdrop a : int = attn_pdrop a : List[Any] = layer_norm_epsilon a : Tuple = initializer_range a : Optional[int] = summary_type a : Union[str, Any] = summary_use_proj a : Optional[int] = summary_activation a : Tuple = summary_first_dropout a : List[Any] = summary_proj_to_labels super().__init__(**__snake_case )
297
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase: List[Any] = logging.get_logger(__name__) lowerCAmelCase: List[Any] = { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """roberta""" def __init__( self : Tuple , __snake_case : List[str]=5_02_65 , __snake_case : int=7_68 , __snake_case : Union[str, Any]=12 , __snake_case : Dict=12 , __snake_case : Tuple=30_72 , __snake_case : Optional[Any]="gelu" , __snake_case : str=0.1 , __snake_case : Any=0.1 , __snake_case : str=5_12 , __snake_case : int=2 , __snake_case : Any=0.02 , __snake_case : int=1e-1_2 , __snake_case : str=1 , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=2 , __snake_case : Optional[int]="absolute" , __snake_case : Union[str, Any]=True , __snake_case : Union[str, Any]=None , **__snake_case : str , ): super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) a : List[str] = vocab_size a : str = hidden_size a : Tuple = num_hidden_layers a : Dict = num_attention_heads a : List[Any] = hidden_act a : str = intermediate_size a : Union[str, Any] = hidden_dropout_prob a : Optional[Any] = attention_probs_dropout_prob a : Any = max_position_embeddings a : Optional[int] = type_vocab_size a : str = initializer_range a : List[Any] = layer_norm_eps a : Optional[int] = position_embedding_type a : Dict = use_cache a : Any = classifier_dropout class a__( lowerCamelCase__ ): @property def lowercase_ ( self : int ): if self.task == "multiple-choice": a : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a : str = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
297
1
'''simple docstring''' def lowerCamelCase__ ( _A = 1000 ): a , a : Optional[int] = 1, 1 a : Optional[int] = 2 while True: a : Tuple = 0 a : Any = fa + fa a , a : Union[str, Any] = fa, f index += 1 for _ in str(_A ): i += 1 if i == n: break return index if __name__ == "__main__": print(solution(int(str(input()).strip())))
297
'''simple docstring''' def lowerCamelCase__ ( _A ): return 10 - x * x def lowerCamelCase__ ( _A , _A ): # Bolzano theory in order to find if there is a root between a and b if equation(_A ) * equation(_A ) >= 0: raise ValueError('Wrong space!' ) a : Tuple = a while (b - a) >= 0.01: # Find middle point a : Tuple = (a + b) / 2 # Check if middle point is root if equation(_A ) == 0.0: break # Decide the side to repeat the steps if equation(_A ) * equation(_A ) < 0: a : List[str] = c else: a : Tuple = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
297
1
'''simple docstring''' import unittest from pathlib import Path from tempfile import NamedTemporaryFile, TemporaryDirectory from transformers import BertConfig, BertTokenizerFast, FeatureExtractionPipeline from transformers.convert_graph_to_onnx import ( convert, ensure_valid_input, generate_identified_filename, infer_shapes, quantize, ) from transformers.testing_utils import require_tf, require_tokenizers, require_torch, slow class a__: def lowercase_ ( self : str , __snake_case : Optional[int] , __snake_case : Optional[Any] , __snake_case : int ): return None class a__: def lowercase_ ( self : Union[str, Any] , __snake_case : Dict , __snake_case : str , __snake_case : int , __snake_case : List[Any] ): return None class a__( unittest.TestCase ): lowercase__ = [ # (model_name, model_kwargs) ("""bert-base-cased""", {}), ("""gpt2""", {"""use_cache""": False}), # We don't support exporting GPT2 past keys anymore ] @require_tf @slow def lowercase_ ( self : List[str] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__snake_case , 'tf' , 12 , **__snake_case ) @require_torch @slow def lowercase_ ( self : Dict ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: self._test_export(__snake_case , 'pt' , 12 , **__snake_case ) @require_torch @slow def lowercase_ ( self : Optional[int] ): from transformers import BertModel a : Tuple = ['[UNK]', '[SEP]', '[CLS]', '[PAD]', '[MASK]', 'some', 'other', 'words'] with NamedTemporaryFile(mode='w+t' ) as vocab_file: vocab_file.write('\n'.join(__snake_case ) ) vocab_file.flush() a : Optional[int] = BertTokenizerFast(vocab_file.name ) with TemporaryDirectory() as bert_save_dir: a : Tuple = BertModel(BertConfig(vocab_size=len(__snake_case ) ) ) model.save_pretrained(__snake_case ) self._test_export(__snake_case , 'pt' , 12 , __snake_case ) @require_tf @slow def lowercase_ ( self : Union[str, Any] ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: a : Optional[Any] = self._test_export(__snake_case , 'tf' , 12 , **__snake_case ) a : Optional[Any] = quantize(Path(__snake_case ) ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__snake_case ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) @require_torch @slow def lowercase_ ( self : Dict ): for model, model_kwargs in OnnxExportTestCase.MODEL_TO_TEST: a : Optional[int] = self._test_export(__snake_case , 'pt' , 12 , **__snake_case ) a : Dict = quantize(__snake_case ) # Ensure the actual quantized model is not bigger than the original one if quantized_path.stat().st_size >= Path(__snake_case ).stat().st_size: self.fail('Quantized model is bigger than initial ONNX model' ) def lowercase_ ( self : str , __snake_case : Tuple , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : int=None , **__snake_case : List[Any] ): try: # Compute path with TemporaryDirectory() as tempdir: a : Optional[int] = Path(__snake_case ).joinpath('model.onnx' ) # Remove folder if exists if path.parent.exists(): path.parent.rmdir() # Export convert(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case , **__snake_case ) return path except Exception as e: self.fail(__snake_case ) @require_torch @require_tokenizers @slow def lowercase_ ( self : Optional[Any] ): from transformers import BertModel a : str = BertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) a : Optional[Any] = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(__snake_case , __snake_case , 'pt' ) @require_tf @require_tokenizers @slow def lowercase_ ( self : Optional[Any] ): from transformers import TFBertModel a : Union[str, Any] = TFBertModel(BertConfig.from_pretrained('lysandre/tiny-bert-random' ) ) a : Union[str, Any] = BertTokenizerFast.from_pretrained('lysandre/tiny-bert-random' ) self._test_infer_dynamic_axis(__snake_case , __snake_case , 'tf' ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : Optional[Any] , __snake_case : str ): a : Optional[int] = FeatureExtractionPipeline(__snake_case , __snake_case ) a : List[Any] = ['input_ids', 'token_type_ids', 'attention_mask', 'output_0', 'output_1'] a , a , a , a : List[Any] = infer_shapes(__snake_case , __snake_case ) # Assert all variables are present self.assertEqual(len(__snake_case ) , len(__snake_case ) ) self.assertTrue(all(var_name in shapes for var_name in variable_names ) ) self.assertSequenceEqual(variable_names[:3] , __snake_case ) self.assertSequenceEqual(variable_names[3:] , __snake_case ) # Assert inputs are {0: batch, 1: sequence} for var_name in ["input_ids", "token_type_ids", "attention_mask"]: self.assertDictEqual(shapes[var_name] , {0: 'batch', 1: 'sequence'} ) # Assert outputs are {0: batch, 1: sequence} and {0: batch} self.assertDictEqual(shapes['output_0'] , {0: 'batch', 1: 'sequence'} ) self.assertDictEqual(shapes['output_1'] , {0: 'batch'} ) def lowercase_ ( self : Tuple ): a : Optional[Any] = ['input_ids', 'attention_mask', 'token_type_ids'] a : str = {'input_ids': [1, 2, 3, 4], 'attention_mask': [0, 0, 0, 0], 'token_type_ids': [1, 1, 1, 1]} a , a : Union[str, Any] = ensure_valid_input(FuncContiguousArgs() , __snake_case , __snake_case ) # Should have exactly the same number of args (all are valid) self.assertEqual(len(__snake_case ) , 3 ) # Should have exactly the same input names self.assertEqual(set(__snake_case ) , set(__snake_case ) ) # Parameter should be reordered according to their respective place in the function: # (input_ids, token_type_ids, attention_mask) self.assertEqual(__snake_case , (tokens['input_ids'], tokens['token_type_ids'], tokens['attention_mask']) ) # Generated args are interleaved with another args (for instance parameter "past" in GPT2) a , a : Union[str, Any] = ensure_valid_input(FuncNonContiguousArgs() , __snake_case , __snake_case ) # Should have exactly the one arg (all before the one not provided "some_other_args") self.assertEqual(len(__snake_case ) , 1 ) self.assertEqual(len(__snake_case ) , 1 ) # Should have only "input_ids" self.assertEqual(inputs_args[0] , tokens['input_ids'] ) self.assertEqual(ordered_input_names[0] , 'input_ids' ) def lowercase_ ( self : Tuple ): a : Optional[int] = generate_identified_filename(Path('/home/something/my_fake_model.onnx' ) , '-test' ) self.assertEqual('/home/something/my_fake_model-test.onnx' , generated.as_posix() )
297
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.esm.modeling_esmfold import EsmForProteinFolding class a__: def __init__( self : str , __snake_case : Union[str, Any] , __snake_case : List[str]=13 , __snake_case : Tuple=7 , __snake_case : Optional[Any]=False , __snake_case : Dict=True , __snake_case : List[Any]=False , __snake_case : Optional[int]=False , __snake_case : Optional[Any]=19 , __snake_case : Any=32 , __snake_case : Union[str, Any]=5 , __snake_case : Union[str, Any]=4 , __snake_case : int=37 , __snake_case : Union[str, Any]="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : List[str]=0.1 , __snake_case : int=5_12 , __snake_case : int=16 , __snake_case : Tuple=2 , __snake_case : str=0.02 , __snake_case : str=3 , __snake_case : Dict=4 , __snake_case : List[Any]=None , ): a : Tuple = parent a : List[str] = batch_size a : Optional[Any] = seq_length a : Tuple = is_training a : Optional[Any] = use_input_mask a : List[Any] = use_token_type_ids a : List[Any] = use_labels a : int = vocab_size a : Union[str, Any] = hidden_size a : Any = num_hidden_layers a : List[str] = num_attention_heads a : int = intermediate_size a : str = hidden_act a : Tuple = hidden_dropout_prob a : Union[str, Any] = attention_probs_dropout_prob a : List[str] = max_position_embeddings a : Any = type_vocab_size a : List[str] = type_sequence_label_size a : Union[str, Any] = initializer_range a : Optional[int] = num_labels a : Optional[Any] = num_choices a : Optional[int] = scope def lowercase_ ( self : List[Any] ): a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Dict = None if self.use_input_mask: a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a : Optional[Any] = None a : Optional[int] = None a : Dict = None if self.use_labels: a : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) a : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self : List[Any] ): a : Any = EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , is_folding_model=__snake_case , esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False} , ) return config def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : str , __snake_case : Optional[Any] , __snake_case : List[Any] , __snake_case : str , __snake_case : Any ): a : Tuple = EsmForProteinFolding(config=__snake_case ).float() model.to(__snake_case ) model.eval() a : Dict = model(__snake_case , attention_mask=__snake_case ) a : Union[str, Any] = model(__snake_case ) a : List[Any] = model(__snake_case ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def lowercase_ ( self : Optional[Any] ): a : Tuple = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : Optional[Any] = config_and_inputs a : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = False lowercase__ = (EsmForProteinFolding,) if is_torch_available() else () lowercase__ = () lowercase__ = {} if is_torch_available() else {} lowercase__ = False def lowercase_ ( self : int ): a : Tuple = EsmFoldModelTester(self ) a : Any = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase_ ( self : List[str] ): self.config_tester.run_common_tests() def lowercase_ ( self : Union[str, Any] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) @unittest.skip('Does not support attention outputs' ) def lowercase_ ( self : str ): pass @unittest.skip def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support passing input embeds!' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMfold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold only has one output format.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality' ) def lowercase_ ( self : Tuple ): pass @unittest.skip('ESMFold does not support input chunking.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t support data parallel.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowercase_ ( self : Union[str, Any] ): pass @require_torch class a__( lowerCamelCase__ ): @slow def lowercase_ ( self : Optional[int] ): a : Optional[Any] = EsmForProteinFolding.from_pretrained('facebook/esmfold_v1' ).float() model.eval() a : int = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) a : Any = model(__snake_case )['positions'] a : Dict = torch.tensor([2.5828, 0.7993, -10.9334] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , __snake_case , atol=1e-4 ) )
297
1
'''simple docstring''' def lowerCamelCase__ ( _A ): return sum(i for i in range(1 , number // 2 + 1 ) if number % i == 0 ) == number if __name__ == "__main__": print('Program to check whether a number is a Perfect number or not...') lowerCAmelCase: List[Any] = int(input('Enter number: ').strip()) print(F"{number} is {'' if perfect(number) else 'not '}a Perfect Number.")
297
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class a__( nn.Module ): def __init__( self : Any , __snake_case : int = 16 , __snake_case : int = 88 , __snake_case : Optional[int] = None , __snake_case : int = 1 , __snake_case : float = 0.0 , __snake_case : int = 32 , __snake_case : Optional[int] = None , __snake_case : bool = False , __snake_case : Optional[int] = None , __snake_case : Optional[int] = None , __snake_case : str = "geglu" , __snake_case : Optional[int] = None , ): super().__init__() a : Optional[int] = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__snake_case , attention_head_dim=__snake_case , in_channels=__snake_case , num_layers=__snake_case , dropout=__snake_case , norm_num_groups=__snake_case , cross_attention_dim=__snake_case , attention_bias=__snake_case , sample_size=__snake_case , num_vector_embeds=__snake_case , activation_fn=__snake_case , num_embeds_ada_norm=__snake_case , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference a : Union[str, Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` a : Tuple = [77, 2_57] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` a : Any = [1, 0] def lowercase_ ( self : str , __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any]=None , __snake_case : int=None , __snake_case : Dict=None , __snake_case : bool = True , ): a : Dict = hidden_states a : Tuple = [] a : Optional[int] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens a : Union[str, Any] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] a : Tuple = self.transformer_index_for_condition[i] a : Union[str, Any] = self.transformers[transformer_index]( __snake_case , encoder_hidden_states=__snake_case , timestep=__snake_case , cross_attention_kwargs=__snake_case , return_dict=__snake_case , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] a : Optional[Any] = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) a : int = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__snake_case )
297
1
'''simple docstring''' def lowerCamelCase__ ( _A ): if any(not isinstance(_A , _A ) or x < 0 for x in sequence ): raise TypeError('Sequence must be list of non-negative integers' ) for _ in range(len(_A ) ): for i, (rod_upper, rod_lower) in enumerate(zip(_A , sequence[1:] ) ): if rod_upper > rod_lower: sequence[i] -= rod_upper - rod_lower sequence[i + 1] += rod_upper - rod_lower return sequence if __name__ == "__main__": assert bead_sort([5, 4, 3, 2, 1]) == [1, 2, 3, 4, 5] assert bead_sort([7, 9, 4, 3, 5]) == [3, 4, 5, 7, 9]
297
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase: Union[str, Any] = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[Any] = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Any = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
'''simple docstring''' import argparse import pathlib import fairseq import torch from fairseq.models.roberta import RobertaModel as FairseqRobertaModel from fairseq.modules import TransformerSentenceEncoderLayer from packaging import version from transformers import XLMRobertaConfig, XLMRobertaXLForMaskedLM, XLMRobertaXLForSequenceClassification from transformers.models.bert.modeling_bert import ( BertIntermediate, BertLayer, BertOutput, BertSelfAttention, BertSelfOutput, ) from transformers.models.roberta.modeling_roberta import RobertaAttention from transformers.utils import logging if version.parse(fairseq.__version__) < version.parse('1.0.0a'): raise Exception('requires fairseq >= 1.0.0a') logging.set_verbosity_info() lowerCAmelCase: int = logging.get_logger(__name__) lowerCAmelCase: Union[str, Any] = 'Hello world! cécé herlolip' def lowerCamelCase__ ( _A , _A , _A ): a : Tuple = FairseqRobertaModel.from_pretrained(_A ) roberta.eval() # disable dropout a : Tuple = roberta.model.encoder.sentence_encoder a : Tuple = XLMRobertaConfig( vocab_size=roberta_sent_encoder.embed_tokens.num_embeddings , hidden_size=roberta.cfg.model.encoder_embed_dim , num_hidden_layers=roberta.cfg.model.encoder_layers , num_attention_heads=roberta.cfg.model.encoder_attention_heads , intermediate_size=roberta.cfg.model.encoder_ffn_embed_dim , max_position_embeddings=514 , type_vocab_size=1 , layer_norm_eps=1E-5 , ) if classification_head: a : Dict = roberta.model.classification_heads['mnli'].out_proj.weight.shape[0] print('Our RoBERTa config:' , _A ) a : List[str] = XLMRobertaXLForSequenceClassification(_A ) if classification_head else XLMRobertaXLForMaskedLM(_A ) model.eval() # Now let's copy all the weights. # Embeddings a : Union[str, Any] = roberta_sent_encoder.embed_tokens.weight a : Dict = roberta_sent_encoder.embed_positions.weight a : Tuple = torch.zeros_like( model.roberta.embeddings.token_type_embeddings.weight ) # just zero them out b/c RoBERTa doesn't use them. a : Union[str, Any] = roberta_sent_encoder.layer_norm.weight a : Union[str, Any] = roberta_sent_encoder.layer_norm.bias for i in range(config.num_hidden_layers ): # Encoder: start of layer a : BertLayer = model.roberta.encoder.layer[i] a : TransformerSentenceEncoderLayer = roberta_sent_encoder.layers[i] a : RobertaAttention = layer.attention a : Tuple = roberta_layer.self_attn_layer_norm.weight a : Union[str, Any] = roberta_layer.self_attn_layer_norm.bias # self attention a : BertSelfAttention = layer.attention.self assert ( roberta_layer.self_attn.k_proj.weight.data.shape == roberta_layer.self_attn.q_proj.weight.data.shape == roberta_layer.self_attn.v_proj.weight.data.shape == torch.Size((config.hidden_size, config.hidden_size) ) ) a : Union[str, Any] = roberta_layer.self_attn.q_proj.weight a : Union[str, Any] = roberta_layer.self_attn.q_proj.bias a : Union[str, Any] = roberta_layer.self_attn.k_proj.weight a : Dict = roberta_layer.self_attn.k_proj.bias a : List[Any] = roberta_layer.self_attn.v_proj.weight a : Union[str, Any] = roberta_layer.self_attn.v_proj.bias # self-attention output a : BertSelfOutput = layer.attention.output assert self_output.dense.weight.shape == roberta_layer.self_attn.out_proj.weight.shape a : Dict = roberta_layer.self_attn.out_proj.weight a : str = roberta_layer.self_attn.out_proj.bias # this one is final layer norm a : List[str] = roberta_layer.final_layer_norm.weight a : Tuple = roberta_layer.final_layer_norm.bias # intermediate a : BertIntermediate = layer.intermediate assert intermediate.dense.weight.shape == roberta_layer.fca.weight.shape a : List[Any] = roberta_layer.fca.weight a : List[str] = roberta_layer.fca.bias # output a : BertOutput = layer.output assert bert_output.dense.weight.shape == roberta_layer.fca.weight.shape a : str = roberta_layer.fca.weight a : Dict = roberta_layer.fca.bias # end of layer if classification_head: a : List[str] = roberta.model.classification_heads['mnli'].dense.weight a : Any = roberta.model.classification_heads['mnli'].dense.bias a : Dict = roberta.model.classification_heads['mnli'].out_proj.weight a : Any = roberta.model.classification_heads['mnli'].out_proj.bias else: # LM Head a : Optional[int] = roberta.model.encoder.lm_head.dense.weight a : Dict = roberta.model.encoder.lm_head.dense.bias a : Dict = roberta.model.encoder.lm_head.layer_norm.weight a : str = roberta.model.encoder.lm_head.layer_norm.bias a : Optional[int] = roberta.model.encoder.lm_head.weight a : Union[str, Any] = roberta.model.encoder.lm_head.bias # Let's check that we get the same results. a : torch.Tensor = roberta.encode(_A ).unsqueeze(0 ) # batch of size 1 a : Union[str, Any] = model(_A )[0] if classification_head: a : List[str] = roberta.model.classification_heads['mnli'](roberta.extract_features(_A ) ) else: a : int = roberta.model(_A )[0] print(our_output.shape , their_output.shape ) a : Optional[Any] = torch.max(torch.abs(our_output - their_output ) ).item() print(f"""max_absolute_diff = {max_absolute_diff}""" ) # ~ 1e-7 a : List[Any] = torch.allclose(_A , _A , atol=1E-3 ) print('Do both models output the same tensors?' , '🔥' if success else '💩' ) if not success: raise Exception('Something went wRoNg' ) pathlib.Path(_A ).mkdir(parents=_A , exist_ok=_A ) print(f"""Saving model to {pytorch_dump_folder_path}""" ) model.save_pretrained(_A ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--roberta_checkpoint_path', default=None, type=str, required=True, help='Path the official PyTorch dump.' ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, required=True, help='Path to the output PyTorch model.' ) parser.add_argument( '--classification_head', action='store_true', help='Whether to convert a final classification head.' ) lowerCAmelCase: List[str] = parser.parse_args() convert_xlm_roberta_xl_checkpoint_to_pytorch( args.roberta_checkpoint_path, args.pytorch_dump_folder_path, args.classification_head )
297
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase: str = { 'configuration_mgp_str': ['MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MgpstrConfig'], 'processing_mgp_str': ['MgpstrProcessor'], 'tokenization_mgp_str': ['MgpstrTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Optional[Any] = [ 'MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST', 'MgpstrModel', 'MgpstrPreTrainedModel', 'MgpstrForSceneTextRecognition', ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys lowerCAmelCase: Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
'''simple docstring''' from unittest import TestCase from datasets import Sequence, Value from datasets.arrow_dataset import Dataset class a__( lowerCamelCase__ ): def lowercase_ ( self : Optional[int] ): return [ {"col_1": 3, "col_2": "a"}, {"col_1": 2, "col_2": "b"}, {"col_1": 1, "col_2": "c"}, {"col_1": 0, "col_2": "d"}, ] def lowercase_ ( self : Optional[Any] ): a : Any = {'col_1': [3, 2, 1, 0], 'col_2': ['a', 'b', 'c', 'd']} return Dataset.from_dict(__snake_case ) def lowercase_ ( self : str ): a : Optional[Any] = self._create_example_records() a : str = Dataset.from_list(__snake_case ) self.assertListEqual(dset.column_names , ['col_1', 'col_2'] ) for i, r in enumerate(__snake_case ): self.assertDictEqual(__snake_case , example_records[i] ) def lowercase_ ( self : str ): a : Any = self._create_example_records() a : Dict = Dataset.from_list(__snake_case ) a : Tuple = Dataset.from_dict({k: [r[k] for r in example_records] for k in example_records[0]} ) self.assertEqual(dset.info , dset_from_dict.info ) def lowercase_ ( self : Tuple ): # checks what happens with missing columns a : str = [{'col_1': 1}, {'col_2': 'x'}] a : int = Dataset.from_list(__snake_case ) self.assertDictEqual(dset[0] , {'col_1': 1} ) self.assertDictEqual(dset[1] , {'col_1': None} ) # NB: first record is used for columns def lowercase_ ( self : Optional[Any] ): # checks if the type can be inferred from the second record a : Tuple = [{'col_1': []}, {'col_1': [1, 2]}] a : List[Any] = Dataset.from_list(__snake_case ) self.assertEqual(dset.info.features['col_1'] , Sequence(Value('int64' ) ) ) def lowercase_ ( self : Union[str, Any] ): a : Dict = Dataset.from_list([] ) self.assertEqual(len(__snake_case ) , 0 ) self.assertListEqual(dset.column_names , [] )
297
'''simple docstring''' import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer lowerCAmelCase: Dict = logging.get_logger(__name__) lowerCAmelCase: str = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json', }, 'merges_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt', }, 'tokenizer_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json', }, } lowerCAmelCase: str = { 'allenai/led-base-16384': 1_6_3_8_4, } class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = LEDTokenizer lowercase__ = ["""input_ids""", """attention_mask"""] def __init__( self : List[Any] , __snake_case : Optional[Any]=None , __snake_case : List[str]=None , __snake_case : Tuple=None , __snake_case : Dict="replace" , __snake_case : int="<s>" , __snake_case : Any="</s>" , __snake_case : Optional[Any]="</s>" , __snake_case : Optional[Any]="<s>" , __snake_case : Optional[Any]="<unk>" , __snake_case : List[str]="<pad>" , __snake_case : int="<mask>" , __snake_case : int=False , __snake_case : str=True , **__snake_case : Tuple , ): super().__init__( __snake_case , __snake_case , tokenizer_file=__snake_case , errors=__snake_case , bos_token=__snake_case , eos_token=__snake_case , sep_token=__snake_case , cls_token=__snake_case , unk_token=__snake_case , pad_token=__snake_case , mask_token=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case , **__snake_case , ) a : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : List[Any] = getattr(__snake_case , pre_tok_state.pop('type' ) ) a : Optional[Any] = add_prefix_space a : Optional[Any] = pre_tok_class(**__snake_case ) a : Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` a : Dict = 'post_processor' a : int = getattr(self.backend_tokenizer , __snake_case , __snake_case ) if tokenizer_component_instance: a : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a : Any = tuple(state['sep'] ) if "cls" in state: a : Any = tuple(state['cls'] ) a : Optional[Any] = False if state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : Any = add_prefix_space a : Optional[Any] = True if state.get('trim_offsets' , __snake_case ) != trim_offsets: a : List[Any] = trim_offsets a : Union[str, Any] = True if changes_to_apply: a : int = getattr(__snake_case , state.pop('type' ) ) a : List[Any] = component_class(**__snake_case ) setattr(self.backend_tokenizer , __snake_case , __snake_case ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def lowercase_ ( self : Dict ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def lowercase_ ( self : Dict , __snake_case : List[str] ): a : Tuple = AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else value a : Optional[int] = value def lowercase_ ( self : Optional[Any] , *__snake_case : Any , **__snake_case : Union[str, Any] ): a : Dict = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Union[str, Any] , *__snake_case : Optional[int] , **__snake_case : List[str] ): a : Optional[int] = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Dict , __snake_case : str , __snake_case : Optional[str] = None ): a : Union[str, Any] = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : int=None ): a : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase_ ( self : Optional[int] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : int = [self.sep_token_id] a : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase_ ( self : List[str] , __snake_case : Union[Dict[str, EncodedInput], BatchEncoding] , __snake_case : Optional[int] = None , __snake_case : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __snake_case : Optional[int] = None , __snake_case : Optional[bool] = None , ): a : Optional[Any] = super()._pad( encoded_inputs=__snake_case , max_length=__snake_case , padding_strategy=__snake_case , pad_to_multiple_of=__snake_case , return_attention_mask=__snake_case , ) # Load from model defaults if return_attention_mask is None: a : str = 'attention_mask' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: a : Any = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. a : Union[str, Any] = len(encoded_inputs['global_attention_mask'] ) != len(__snake_case ) if needs_to_be_padded: a : str = len(__snake_case ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` a : Dict = ( encoded_inputs['global_attention_mask'] + [-1] * difference ) elif self.padding_side == "left": a : Union[str, Any] = [-1] * difference + encoded_inputs[ 'global_attention_mask' ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
297
1
'''simple docstring''' import warnings from ...configuration_utils import PretrainedConfig from ...utils import logging lowerCAmelCase: str = logging.get_logger(__name__) lowerCAmelCase: Dict = { 'RUCAIBox/mvp': 'https://huggingface.co/RUCAIBox/mvp/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """mvp""" lowercase__ = ["""past_key_values"""] lowercase__ = {"""num_attention_heads""": """encoder_attention_heads""", """hidden_size""": """d_model"""} def __init__( self : Optional[int] , __snake_case : Optional[Any]=5_02_67 , __snake_case : Any=10_24 , __snake_case : Optional[int]=12 , __snake_case : List[str]=40_96 , __snake_case : int=16 , __snake_case : List[Any]=12 , __snake_case : int=40_96 , __snake_case : List[Any]=16 , __snake_case : int=0.0 , __snake_case : int=0.0 , __snake_case : str="gelu" , __snake_case : int=10_24 , __snake_case : Optional[Any]=0.1 , __snake_case : str=0.0 , __snake_case : Tuple=0.0 , __snake_case : str=0.02 , __snake_case : List[Any]=0.0 , __snake_case : Optional[int]=False , __snake_case : List[Any]=True , __snake_case : Any=1 , __snake_case : Any=0 , __snake_case : str=2 , __snake_case : int=True , __snake_case : Any=2 , __snake_case : Any=2 , __snake_case : str=False , __snake_case : Any=1_00 , __snake_case : List[Any]=8_00 , **__snake_case : Union[str, Any] , ): a : str = vocab_size a : Any = max_position_embeddings a : Optional[Any] = d_model a : List[str] = encoder_ffn_dim a : Optional[Any] = encoder_layers a : Tuple = encoder_attention_heads a : Tuple = decoder_ffn_dim a : List[str] = decoder_layers a : Dict = decoder_attention_heads a : Union[str, Any] = dropout a : List[Any] = attention_dropout a : Union[str, Any] = activation_dropout a : Optional[Any] = activation_function a : Optional[Any] = init_std a : Union[str, Any] = encoder_layerdrop a : Optional[int] = decoder_layerdrop a : str = classifier_dropout a : str = use_cache a : int = encoder_layers a : Any = scale_embedding # scale factor will be sqrt(d_model) if True a : Union[str, Any] = use_prompt a : int = prompt_length a : int = prompt_mid_dim super().__init__( pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , is_encoder_decoder=__snake_case , decoder_start_token_id=__snake_case , forced_eos_token_id=__snake_case , **__snake_case , ) if self.forced_bos_token_id is None and kwargs.get('force_bos_token_to_be_generated' , __snake_case ): a : List[Any] = self.bos_token_id warnings.warn( F"""Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. """ 'The config can simply be saved and uploaded again to be fixed.' )
297
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class a__: def __init__( self : Tuple ): a : Optional[int] = '' a : Optional[Any] = '' a : str = [] a : int = 0 a : str = 2_56 a : Union[str, Any] = 0 a : Any = 0 a : Optional[int] = 0 a : List[str] = 0 def lowercase_ ( self : str , __snake_case : str ): a : Any = cva.imread(__snake_case , 0 ) a : Optional[Any] = copy.deepcopy(self.img ) a , a , a : int = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label='x' ) a : Optional[int] = np.sum(__snake_case ) for i in range(len(__snake_case ) ): a : Optional[Any] = x[i] / self.k self.sk += prk a : str = (self.L - 1) * self.sk if self.rem != 0: a : Optional[int] = int(last % last ) a : int = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__snake_case ) a : str = int(np.ma.count(self.img ) / self.img[1].size ) a : Optional[int] = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a : Any = self.img[j][i] if num != self.last_list[num]: a : str = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def lowercase_ ( self : Dict ): plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def lowercase_ ( self : List[Any] ): cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": lowerCAmelCase: Optional[Any] = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') lowerCAmelCase: Tuple = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
297
1
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.esm.modeling_esmfold import EsmForProteinFolding class a__: def __init__( self : str , __snake_case : Union[str, Any] , __snake_case : List[str]=13 , __snake_case : Tuple=7 , __snake_case : Optional[Any]=False , __snake_case : Dict=True , __snake_case : List[Any]=False , __snake_case : Optional[int]=False , __snake_case : Optional[Any]=19 , __snake_case : Any=32 , __snake_case : Union[str, Any]=5 , __snake_case : Union[str, Any]=4 , __snake_case : int=37 , __snake_case : Union[str, Any]="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : List[str]=0.1 , __snake_case : int=5_12 , __snake_case : int=16 , __snake_case : Tuple=2 , __snake_case : str=0.02 , __snake_case : str=3 , __snake_case : Dict=4 , __snake_case : List[Any]=None , ): a : Tuple = parent a : List[str] = batch_size a : Optional[Any] = seq_length a : Tuple = is_training a : Optional[Any] = use_input_mask a : List[Any] = use_token_type_ids a : List[Any] = use_labels a : int = vocab_size a : Union[str, Any] = hidden_size a : Any = num_hidden_layers a : List[str] = num_attention_heads a : int = intermediate_size a : str = hidden_act a : Tuple = hidden_dropout_prob a : Union[str, Any] = attention_probs_dropout_prob a : List[str] = max_position_embeddings a : Any = type_vocab_size a : List[str] = type_sequence_label_size a : Union[str, Any] = initializer_range a : Optional[int] = num_labels a : Optional[Any] = num_choices a : Optional[int] = scope def lowercase_ ( self : List[Any] ): a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Dict = None if self.use_input_mask: a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a : Optional[Any] = None a : Optional[int] = None a : Dict = None if self.use_labels: a : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) a : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self : List[Any] ): a : Any = EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , is_folding_model=__snake_case , esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False} , ) return config def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : str , __snake_case : Optional[Any] , __snake_case : List[Any] , __snake_case : str , __snake_case : Any ): a : Tuple = EsmForProteinFolding(config=__snake_case ).float() model.to(__snake_case ) model.eval() a : Dict = model(__snake_case , attention_mask=__snake_case ) a : Union[str, Any] = model(__snake_case ) a : List[Any] = model(__snake_case ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def lowercase_ ( self : Optional[Any] ): a : Tuple = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : Optional[Any] = config_and_inputs a : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = False lowercase__ = (EsmForProteinFolding,) if is_torch_available() else () lowercase__ = () lowercase__ = {} if is_torch_available() else {} lowercase__ = False def lowercase_ ( self : int ): a : Tuple = EsmFoldModelTester(self ) a : Any = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase_ ( self : List[str] ): self.config_tester.run_common_tests() def lowercase_ ( self : Union[str, Any] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) @unittest.skip('Does not support attention outputs' ) def lowercase_ ( self : str ): pass @unittest.skip def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support passing input embeds!' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMfold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold only has one output format.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality' ) def lowercase_ ( self : Tuple ): pass @unittest.skip('ESMFold does not support input chunking.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t support data parallel.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowercase_ ( self : Union[str, Any] ): pass @require_torch class a__( lowerCamelCase__ ): @slow def lowercase_ ( self : Optional[int] ): a : Optional[Any] = EsmForProteinFolding.from_pretrained('facebook/esmfold_v1' ).float() model.eval() a : int = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) a : Any = model(__snake_case )['positions'] a : Dict = torch.tensor([2.5828, 0.7993, -10.9334] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , __snake_case , atol=1e-4 ) )
297
'''simple docstring''' import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class a__: def __init__( self : List[Any] , __snake_case : Union[str, Any] ): if isinstance(__snake_case , __snake_case ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden a : str = deepcopy(__snake_case ) elif os.path.exists(__snake_case ): with io.open(__snake_case , 'r' , encoding='utf-8' ) as f: a : Optional[Any] = json.load(__snake_case ) else: try: a : Any = baseaa.urlsafe_baadecode(__snake_case ).decode('utf-8' ) a : Union[str, Any] = json.loads(__snake_case ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) a : List[str] = config self.set_stage_and_offload() def lowercase_ ( self : List[str] ): # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. a : Dict = self.get_value('zero_optimization.stage' , -1 ) # offload a : str = False if self.is_zeroa() or self.is_zeroa(): a : Union[str, Any] = set(['cpu', 'nvme'] ) a : Optional[Any] = set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: a : List[str] = True def lowercase_ ( self : Optional[Any] , __snake_case : Optional[Any] ): a : str = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) a : Dict = nodes.pop() for node in nodes: a : List[Any] = config.get(__snake_case ) if config is None: return None, ds_key return config, ds_key def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] , __snake_case : Any=None ): a , a : List[Any] = self.find_config_node(__snake_case ) if config is None: return default return config.get(__snake_case , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Any] , __snake_case : List[str]=False ): a : Optional[Any] = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) for node in nodes: a : str = config a : Dict = config.get(__snake_case ) if config is None: if must_exist: raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] ): a : Union[str, Any] = self.get_value(__snake_case ) return False if value is None else bool(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str ): a : Optional[Any] = self.get_value(__snake_case ) return False if value is None else not bool(__snake_case ) def lowercase_ ( self : Optional[Any] ): return self._stage == 2 def lowercase_ ( self : Union[str, Any] ): return self._stage == 3 def lowercase_ ( self : str ): return self._offload class a__: def __init__( self : Tuple , __snake_case : str ): a : Optional[Any] = engine def lowercase_ ( self : Union[str, Any] , __snake_case : str , **__snake_case : Tuple ): # runs backpropagation and handles mixed precision self.engine.backward(__snake_case , **__snake_case ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : List[str] ): super().__init__(__snake_case , device_placement=__snake_case , scaler=__snake_case ) a : Optional[Any] = hasattr(self.optimizer , 'overflow' ) def lowercase_ ( self : Dict , __snake_case : Dict=None ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def lowercase_ ( self : Optional[Any] ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def lowercase_ ( self : Tuple ): if self.__has_overflow__: return self.optimizer.overflow return False class a__( lowerCamelCase__ ): def __init__( self : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any] ): super().__init__(__snake_case , __snake_case ) def lowercase_ ( self : Any ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class a__: def __init__( self : List[Any] , __snake_case : str , __snake_case : Dict=0.001 , __snake_case : Union[str, Any]=0 , **__snake_case : List[Any] ): a : Optional[Any] = params a : str = lr a : List[str] = weight_decay a : str = kwargs class a__: def __init__( self : str , __snake_case : Optional[Any] , __snake_case : List[str]=None , __snake_case : Tuple=0 , **__snake_case : Any ): a : Union[str, Any] = optimizer a : Any = total_num_steps a : List[str] = warmup_num_steps a : int = kwargs
297
1
'''simple docstring''' def lowerCamelCase__ ( _A , _A ): while second != 0: a : Union[str, Any] = first & second first ^= second a : Tuple = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase: Optional[int] = int(input('Enter the first number: ').strip()) lowerCAmelCase: Union[str, Any] = int(input('Enter the second number: ').strip()) print(F"{add(first, second) = }")
297
'''simple docstring''' import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) lowerCAmelCase: int = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class a__( unittest.TestCase ): def lowercase_ ( self : int , __snake_case : str , __snake_case : bool , __snake_case : str = None , __snake_case : list = None ): a : Optional[int] = None a : Tuple = os.path.abspath(os.path.join('examples' , 'by_feature' ) ) a : List[str] = os.path.abspath('examples' ) for item in os.listdir(__snake_case ): if item not in EXCLUDE_EXAMPLES: a : int = os.path.join(__snake_case , __snake_case ) if os.path.isfile(__snake_case ) and ".py" in item_path: with self.subTest( tested_script=__snake_case , feature_script=__snake_case , tested_section='main()' if parser_only else 'training_function()' , ): a : List[Any] = compare_against_test( os.path.join(__snake_case , __snake_case ) , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = '\n'.join(__snake_case ) if special_strings is not None: for string in special_strings: a : Union[str, Any] = diff.replace(__snake_case , '' ) self.assertEqual(__snake_case , '' ) def lowercase_ ( self : Optional[Any] ): self.one_complete_example('complete_nlp_example.py' , __snake_case ) self.one_complete_example('complete_nlp_example.py' , __snake_case ) def lowercase_ ( self : Any ): a : Dict = os.path.abspath(os.path.join('examples' , 'cv_example.py' ) ) a : int = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , __snake_case , __snake_case , __snake_case ) self.one_complete_example('complete_cv_example.py' , __snake_case , __snake_case , __snake_case ) @mock.patch.dict(os.environ , {"""TESTING_MOCKED_DATALOADERS""": """1"""} ) class a__( lowerCamelCase__ ): lowercase__ = False @classmethod def lowercase_ ( cls : Optional[int] ): super().setUpClass() a : List[str] = tempfile.mkdtemp() a : Tuple = os.path.join(cls._tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) a : Optional[int] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def lowercase_ ( cls : Optional[int] ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def lowercase_ ( self : Tuple ): a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0' ) ) ) def lowercase_ ( self : Dict ): a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} """.split() a : int = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2' ) ) ) def lowercase_ ( self : Any ): a : Tuple = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0" )} """.split() a : int = run_command(self._launch_args + testargs , return_stdout=__snake_case ) self.assertNotIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) def lowercase_ ( self : int ): a : Optional[int] = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2" )} """.split() a : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=__snake_case ) if torch.cuda.is_available(): a : Any = torch.cuda.device_count() else: a : str = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) else: self.assertIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) @slow def lowercase_ ( self : Tuple ): a : Tuple = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'} ): a : Any = run_command(self._launch_args + testargs , return_stdout=__snake_case ) a : Optional[Any] = re.findall('({.+})' , __snake_case ) a : str = [r for r in results if 'accuracy' in r][-1] a : str = ast.literal_eval(__snake_case ) self.assertGreaterEqual(results['accuracy'] , 0.75 ) def lowercase_ ( self : Optional[int] ): a : int = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def lowercase_ ( self : Optional[int] ): with tempfile.TemporaryDirectory() as tmpdir: a : Optional[Any] = F""" examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(__snake_case , 'tracking' ) ) ) def lowercase_ ( self : List[str] ): a : Optional[Any] = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs ) def lowercase_ ( self : int ): a : Optional[Any] = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs )
297
1
'''simple docstring''' import gc import unittest import numpy as np import torch from diffusers import ( AudioDiffusionPipeline, AutoencoderKL, DDIMScheduler, DDPMScheduler, DiffusionPipeline, Mel, UNetaDConditionModel, UNetaDModel, ) from diffusers.utils import slow, torch_device from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu enable_full_determinism() class a__( unittest.TestCase ): def lowercase_ ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() @property def lowercase_ ( self : Optional[int] ): torch.manual_seed(0 ) a : Any = UNetaDModel( sample_size=(32, 64) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return model @property def lowercase_ ( self : Union[str, Any] ): torch.manual_seed(0 ) a : Any = UNetaDConditionModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , cross_attention_dim=10 , ) return model @property def lowercase_ ( self : Dict ): torch.manual_seed(0 ) a : Any = AutoencoderKL( sample_size=(1_28, 64) , in_channels=1 , out_channels=1 , latent_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=('DownEncoderBlock2D', 'DownEncoderBlock2D') , up_block_types=('UpDecoderBlock2D', 'UpDecoderBlock2D') , ) a : List[str] = UNetaDModel( sample_size=(64, 32) , in_channels=1 , out_channels=1 , layers_per_block=2 , block_out_channels=(1_28, 1_28) , down_block_types=('AttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'AttnUpBlock2D') , ) return vqvae, unet @slow def lowercase_ ( self : Optional[int] ): a : int = 'cpu' # ensure determinism for the device-dependent torch.Generator a : Optional[Any] = Mel( x_res=self.dummy_unet.config.sample_size[1] , y_res=self.dummy_unet.config.sample_size[0] , ) a : List[Any] = DDPMScheduler() a : Optional[int] = AudioDiffusionPipeline(vqvae=__snake_case , unet=self.dummy_unet , mel=__snake_case , scheduler=__snake_case ) a : int = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) a : List[str] = torch.Generator(device=__snake_case ).manual_seed(42 ) a : List[Any] = pipe(generator=__snake_case , steps=4 ) a : Union[str, Any] = output.audios[0] a : Optional[int] = output.images[0] a : Union[str, Any] = torch.Generator(device=__snake_case ).manual_seed(42 ) a : int = pipe(generator=__snake_case , steps=4 , return_dict=__snake_case ) a : str = output[0][0] assert audio.shape == (1, (self.dummy_unet.config.sample_size[1] - 1) * mel.hop_length) assert ( image.height == self.dummy_unet.config.sample_size[0] and image.width == self.dummy_unet.config.sample_size[1] ) a : Dict = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] a : Dict = np.frombuffer(image_from_tuple.tobytes() , dtype='uint8' )[:10] a : Union[str, Any] = np.array([69, 2_55, 2_55, 2_55, 0, 0, 77, 1_81, 12, 1_27] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 assert np.abs(image_from_tuple_slice.flatten() - expected_slice ).max() == 0 a : Dict = Mel( x_res=self.dummy_vqvae_and_unet[0].config.sample_size[1] , y_res=self.dummy_vqvae_and_unet[0].config.sample_size[0] , ) a : List[Any] = DDIMScheduler() a : Any = self.dummy_vqvae_and_unet a : Tuple = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=dummy_vqvae_and_unet[1] , mel=__snake_case , scheduler=__snake_case ) a : Tuple = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) np.random.seed(0 ) a : List[Any] = np.random.uniform(-1 , 1 , ((dummy_vqvae_and_unet[0].config.sample_size[1] - 1) * mel.hop_length,) ) a : Optional[int] = torch.Generator(device=__snake_case ).manual_seed(42 ) a : List[str] = pipe(raw_audio=__snake_case , generator=__snake_case , start_step=5 , steps=10 ) a : int = output.images[0] assert ( image.height == self.dummy_vqvae_and_unet[0].config.sample_size[0] and image.width == self.dummy_vqvae_and_unet[0].config.sample_size[1] ) a : Union[str, Any] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] a : Optional[Any] = np.array([1_20, 1_17, 1_10, 1_09, 1_38, 1_67, 1_38, 1_48, 1_32, 1_21] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 a : Any = self.dummy_unet_condition a : str = AudioDiffusionPipeline( vqvae=self.dummy_vqvae_and_unet[0] , unet=__snake_case , mel=__snake_case , scheduler=__snake_case ) a : Any = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) np.random.seed(0 ) a : Dict = torch.rand((1, 1, 10) ) a : str = pipe(generator=__snake_case , encoding=__snake_case ) a : str = output.images[0] a : List[str] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] a : Optional[Any] = np.array([1_07, 1_03, 1_20, 1_27, 1_42, 1_22, 1_13, 1_22, 97, 1_11] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0 @slow @require_torch_gpu class a__( unittest.TestCase ): def lowercase_ ( self : List[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Dict ): a : List[str] = torch_device a : List[str] = DiffusionPipeline.from_pretrained('teticio/audio-diffusion-ddim-256' ) a : Optional[int] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) a : int = torch.Generator(device=__snake_case ).manual_seed(42 ) a : Optional[Any] = pipe(generator=__snake_case ) a : Tuple = output.audios[0] a : Union[str, Any] = output.images[0] assert audio.shape == (1, (pipe.unet.config.sample_size[1] - 1) * pipe.mel.hop_length) assert image.height == pipe.unet.config.sample_size[0] and image.width == pipe.unet.config.sample_size[1] a : List[Any] = np.frombuffer(image.tobytes() , dtype='uint8' )[:10] a : int = np.array([1_51, 1_67, 1_54, 1_44, 1_22, 1_34, 1_21, 1_05, 70, 26] ) assert np.abs(image_slice.flatten() - expected_slice ).max() == 0
297
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList lowerCAmelCase: List[str] = ['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif'] class a__( lowerCamelCase__ ): def __init__( self : Any , __snake_case : List[str] , __snake_case : Union[str, Any] , __snake_case : List[Any]=None , __snake_case : Optional[Any]=1 ): a : Union[str, Any] = tokenizer a : Union[str, Any] = dataset a : Any = len(__snake_case ) if n_tasks is None else n_tasks a : List[str] = n_copies def __iter__( self : str ): a : List[Any] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['prompt'].strip() ) a : Dict = self.tokenizer(__snake_case , padding=__snake_case , return_tensors='pt' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class a__( lowerCamelCase__ ): def __init__( self : Union[str, Any] , __snake_case : int , __snake_case : Optional[Any] , __snake_case : str ): a : Dict = start_length a : Dict = eof_strings a : str = tokenizer def __call__( self : Optional[Any] , __snake_case : Optional[Any] , __snake_case : Any , **__snake_case : Union[str, Any] ): a : int = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) a : Optional[int] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(__snake_case ) def lowerCamelCase__ ( _A ): a : Optional[Any] = re.split('(%s)' % '|'.join(_A ) , _A ) # last string should be "" return "".join(string_list[:-2] ) def lowerCamelCase__ ( _A , _A , _A , _A , _A , _A=20 , **_A ): a : Optional[Any] = defaultdict(_A ) # dict of list of generated tokens for step, batch in tqdm(enumerate(_A ) ): with torch.no_grad(): a : Optional[Any] = batch['ids'].shape[-1] a : Optional[Any] = accelerator.unwrap_model(_A ).generate( input_ids=batch['ids'][:, : batch['input_len']] , num_return_sequences=_A , **_A ) # each task is generated batch_size times a : Tuple = batch['task_id'].repeat(_A ) a : List[Any] = accelerator.pad_across_processes( _A , dim=1 , pad_index=tokenizer.pad_token_id ) a , a : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) a : List[str] = generated_tokens.cpu().numpy() a : int = generated_tasks.cpu().numpy() for task, generated_tokens in zip(_A , _A ): gen_token_dict[task].append(_A ) a : Any = [[] for _ in range(_A )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: a : Optional[int] = tokenizer.decode(_A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) code_gens[task].append(remove_last_block(_A ) ) return code_gens def lowerCamelCase__ ( ): # Setup configuration a : Dict = HfArgumentParser(_A ) a : Any = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric a : List[Any] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing a : int = 'false' if args.num_workers is None: a : Dict = multiprocessing.cpu_count() # Use dataset load to feed to accelerate a : List[Any] = Accelerator() set_seed(args.seed , device_specific=_A ) # Load model and tokenizer a : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) a : str = tokenizer.eos_token a : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings a : Optional[Any] = { 'do_sample': args.do_sample, 'temperature': args.temperature, 'max_new_tokens': args.max_new_tokens, 'top_p': args.top_p, 'top_k': args.top_k, 'stopping_criteria': StoppingCriteriaList([EndOfFunctionCriteria(0 , _A , _A )] ), } # Load evaluation dataset and metric a : Optional[int] = load_dataset('openai_humaneval' ) a : Optional[Any] = load_metric('code_eval' ) a : Optional[int] = args.num_tasks if args.num_tasks is not None else len(human_eval['test'] ) a : Optional[Any] = args.n_samples // args.batch_size a : Any = TokenizedDataset(_A , human_eval['test'] , n_copies=_A , n_tasks=_A ) # do not confuse args.batch_size, which is actually the num_return_sequences a : int = DataLoader(_A , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: a : int = code_eval_metric.compute(references=[''] , predictions=[['']] ) except ValueError as exception: print( 'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`' ' flag to enable code evaluation.' ) raise exception a , a : int = accelerator.prepare(_A , _A ) a : int = complete_code( _A , _A , _A , _A , n_tasks=_A , batch_size=args.batch_size , **_A , ) if accelerator.is_main_process: a : List[str] = [] for task in tqdm(range(_A ) ): a : int = human_eval['test'][task]['test'] a : int = f"""check({human_eval["test"][task]["entry_point"]})""" references.append('\n' + test_func + '\n' + entry_point ) # Evaluate completions with "code_eval" metric a , a : Tuple = code_eval_metric.compute( references=_A , predictions=_A , num_workers=args.num_workers ) print(f"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , 'w' ) as fp: json.dump(_A , _A ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
297
1
'''simple docstring''' import inspect import unittest from transformers import DecisionTransformerConfig, is_torch_available from transformers.testing_utils import require_torch, slow, torch_device from ...generation.test_utils import GenerationTesterMixin from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers import DecisionTransformerModel from transformers.models.decision_transformer.modeling_decision_transformer import ( DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST, ) class a__: def __init__( self : Dict , __snake_case : str , __snake_case : List[str]=13 , __snake_case : List[Any]=7 , __snake_case : Union[str, Any]=6 , __snake_case : List[str]=17 , __snake_case : Any=23 , __snake_case : Optional[int]=11 , __snake_case : int=True , ): a : List[str] = parent a : List[Any] = batch_size a : Dict = seq_length a : Tuple = act_dim a : Any = state_dim a : Dict = hidden_size a : Dict = max_length a : Dict = is_training def lowercase_ ( self : Optional[Any] ): a : Any = floats_tensor((self.batch_size, self.seq_length, self.state_dim) ) a : List[Any] = floats_tensor((self.batch_size, self.seq_length, self.act_dim) ) a : List[Any] = floats_tensor((self.batch_size, self.seq_length, 1) ) a : Tuple = floats_tensor((self.batch_size, self.seq_length, 1) ) a : List[str] = ids_tensor((self.batch_size, self.seq_length) , vocab_size=10_00 ) a : Tuple = random_attention_mask((self.batch_size, self.seq_length) ) a : Dict = self.get_config() return ( config, states, actions, rewards, returns_to_go, timesteps, attention_mask, ) def lowercase_ ( self : Optional[int] ): return DecisionTransformerConfig( batch_size=self.batch_size , seq_length=self.seq_length , act_dim=self.act_dim , state_dim=self.state_dim , hidden_size=self.hidden_size , max_length=self.max_length , ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : List[str] , __snake_case : List[str] , __snake_case : Tuple , __snake_case : List[Any] , __snake_case : List[str] , __snake_case : Any , ): a : List[str] = DecisionTransformerModel(config=__snake_case ) model.to(__snake_case ) model.eval() a : Any = model(__snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) self.parent.assertEqual(result.state_preds.shape , states.shape ) self.parent.assertEqual(result.action_preds.shape , actions.shape ) self.parent.assertEqual(result.return_preds.shape , returns_to_go.shape ) self.parent.assertEqual( result.last_hidden_state.shape , (self.batch_size, self.seq_length * 3, self.hidden_size) ) # seq length *3 as there are 3 modelities: states, returns and actions def lowercase_ ( self : Optional[int] ): a : Dict = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : int = config_and_inputs a : Optional[Any] = { 'states': states, 'actions': actions, 'rewards': rewards, 'returns_to_go': returns_to_go, 'timesteps': timesteps, 'attention_mask': attention_mask, } return config, inputs_dict @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = (DecisionTransformerModel,) if is_torch_available() else () lowercase__ = () lowercase__ = {"""feature-extraction""": DecisionTransformerModel} if is_torch_available() else {} # Ignoring of a failing test from GenerationTesterMixin, as the model does not use inputs_ids lowercase__ = False # Ignoring of a failing tests from ModelTesterMixin, as the model does not implement these features lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False lowercase__ = False def lowercase_ ( self : Tuple ): a : Optional[Any] = DecisionTransformerModelTester(self ) a : Dict = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase_ ( self : int ): self.config_tester.run_common_tests() def lowercase_ ( self : List[Any] ): a : Optional[Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) @slow def lowercase_ ( self : Optional[Any] ): for model_name in DECISION_TRANSFORMER_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Union[str, Any] = DecisionTransformerModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) def lowercase_ ( self : Union[str, Any] ): a , a : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : int = model_class(__snake_case ) a : Optional[int] = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a : Tuple = [*signature.parameters.keys()] a : Dict = [ 'states', 'actions', 'rewards', 'returns_to_go', 'timesteps', 'attention_mask', ] self.assertListEqual(arg_names[: len(__snake_case )] , __snake_case ) @require_torch class a__( unittest.TestCase ): @slow def lowercase_ ( self : List[str] ): a : Tuple = 2 # number of steps of autoregressive prediction we will perform a : List[str] = 10 # defined by the RL environment, may be normalized a : Union[str, Any] = DecisionTransformerModel.from_pretrained('edbeeching/decision-transformer-gym-hopper-expert' ) a : Any = model.to(__snake_case ) a : List[Any] = model.config torch.manual_seed(0 ) a : Union[str, Any] = torch.randn(1 , 1 , config.state_dim ).to(device=__snake_case , dtype=torch.floataa ) # env.reset() a : Optional[Any] = torch.tensor( [[0.242793, -0.28693074, 0.8742613], [0.67815274, -0.08101085, -0.12952147]] , device=__snake_case ) a : Optional[Any] = torch.tensor(__snake_case , device=__snake_case , dtype=torch.floataa ).reshape(1 , 1 , 1 ) a : Tuple = state a : List[str] = torch.zeros(1 , 0 , config.act_dim , device=__snake_case , dtype=torch.floataa ) a : Any = torch.zeros(1 , 0 , device=__snake_case , dtype=torch.floataa ) a : Tuple = torch.tensor(0 , device=__snake_case , dtype=torch.long ).reshape(1 , 1 ) for step in range(__snake_case ): a : List[Any] = torch.cat([actions, torch.zeros(1 , 1 , config.act_dim , device=__snake_case )] , dim=1 ) a : List[Any] = torch.cat([rewards, torch.zeros(1 , 1 , device=__snake_case )] , dim=1 ) a : Any = torch.ones(1 , states.shape[1] ).to(dtype=torch.long , device=states.device ) with torch.no_grad(): a , a , a : List[str] = model( states=__snake_case , actions=__snake_case , rewards=__snake_case , returns_to_go=__snake_case , timesteps=__snake_case , attention_mask=__snake_case , return_dict=__snake_case , ) self.assertEqual(action_pred.shape , actions.shape ) self.assertTrue(torch.allclose(action_pred[0, -1] , expected_outputs[step] , atol=1e-4 ) ) a , a , a , a : List[str] = ( # env.step(action) torch.randn(1 , 1 , config.state_dim ).to(device=__snake_case , dtype=torch.floataa ), 1.0, False, {}, ) a : List[Any] = action_pred[0, -1] a : Dict = torch.cat([states, state] , dim=1 ) a : List[Any] = returns_to_go[0, -1] - reward a : Tuple = torch.cat([returns_to_go, pred_return.reshape(1 , 1 , 1 )] , dim=1 ) a : List[str] = torch.cat( [timesteps, torch.ones((1, 1) , device=__snake_case , dtype=torch.long ) * (step + 1)] , dim=1 )
297
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( _A , _A , _A ): if isinstance(_A , torch.Tensor ): return image elif isinstance(_A , PIL.Image.Image ): a : Any = [image] if isinstance(image[0] , PIL.Image.Image ): a : List[str] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] a : int = np.concatenate(_A , axis=0 ) a : int = np.array(_A ).astype(np.floataa ) / 255.0 a : str = image.transpose(0 , 3 , 1 , 2 ) a : str = 2.0 * image - 1.0 a : Optional[int] = torch.from_numpy(_A ) elif isinstance(image[0] , torch.Tensor ): a : Optional[Any] = torch.cat(_A , dim=0 ) return image def lowerCamelCase__ ( _A , _A , _A , _A=0.9995 ): if not isinstance(_A , np.ndarray ): a : Dict = True a : Optional[Any] = va.device a : Optional[int] = va.cpu().numpy() a : Union[str, Any] = va.cpu().numpy() a : Any = np.sum(va * va / (np.linalg.norm(_A ) * np.linalg.norm(_A )) ) if np.abs(_A ) > DOT_THRESHOLD: a : Any = (1 - t) * va + t * va else: a : Any = np.arccos(_A ) a : Tuple = np.sin(_A ) a : Optional[Any] = theta_a * t a : List[Any] = np.sin(_A ) a : Dict = np.sin(theta_a - theta_t ) / sin_theta_a a : int = sin_theta_t / sin_theta_a a : Any = sa * va + sa * va if inputs_are_torch: a : Dict = torch.from_numpy(_A ).to(_A ) return va def lowerCamelCase__ ( _A , _A ): a : Optional[int] = F.normalize(_A , dim=-1 ) a : str = F.normalize(_A , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( _A , _A ): for param in model.parameters(): a : int = value class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : AutoencoderKL , __snake_case : CLIPTextModel , __snake_case : CLIPModel , __snake_case : CLIPTokenizer , __snake_case : UNetaDConditionModel , __snake_case : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , __snake_case : CLIPFeatureExtractor , __snake_case : List[str]=None , __snake_case : List[str]=None , __snake_case : List[Any]=None , ): super().__init__() self.register_modules( vae=__snake_case , text_encoder=__snake_case , clip_model=__snake_case , tokenizer=__snake_case , unet=__snake_case , scheduler=__snake_case , feature_extractor=__snake_case , coca_model=__snake_case , coca_tokenizer=__snake_case , coca_transform=__snake_case , ) a : Optional[Any] = ( feature_extractor.size if isinstance(feature_extractor.size , __snake_case ) else feature_extractor.size['shortest_edge'] ) a : Optional[int] = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , __snake_case ) set_requires_grad(self.clip_model , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory a : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__snake_case ) def lowercase_ ( self : Union[str, Any] ): self.enable_attention_slicing(__snake_case ) def lowercase_ ( self : Optional[Any] ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : Tuple ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : int ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : Union[str, Any] ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : int , __snake_case : Dict , __snake_case : str , __snake_case : Optional[int] ): # get the original timestep using init_timestep a : Optional[Any] = min(int(num_inference_steps * strength ) , __snake_case ) a : Union[str, Any] = max(num_inference_steps - init_timestep , 0 ) a : List[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase_ ( self : Dict , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Any , __snake_case : Optional[Any]=None ): if not isinstance(__snake_case , torch.Tensor ): raise ValueError(F"""`image` has to be of type `torch.Tensor` but is {type(__snake_case )}""" ) a : Optional[Any] = image.to(device=__snake_case , dtype=__snake_case ) if isinstance(__snake_case , __snake_case ): a : Optional[int] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__snake_case ) ] a : Optional[Any] = torch.cat(__snake_case , dim=0 ) else: a : Union[str, Any] = self.vae.encode(__snake_case ).latent_dist.sample(__snake_case ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : List[str] = 0.18215 * init_latents a : str = init_latents.repeat_interleave(__snake_case , dim=0 ) a : Dict = randn_tensor(init_latents.shape , generator=__snake_case , device=__snake_case , dtype=__snake_case ) # get latents a : Dict = self.scheduler.add_noise(__snake_case , __snake_case , __snake_case ) a : int = init_latents return latents def lowercase_ ( self : List[str] , __snake_case : Dict ): a : List[Any] = self.coca_transform(__snake_case ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): a : Optional[Any] = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) a : Union[str, Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('<end_of_text>' )[0].replace('<start_of_text>' , '' ).rstrip(' .,' ) def lowercase_ ( self : Tuple , __snake_case : Any , __snake_case : Optional[Any] ): a : List[Any] = self.feature_extractor.preprocess(__snake_case ) a : Optional[Any] = torch.from_numpy(clip_image_input['pixel_values'][0] ).unsqueeze(0 ).to(self.device ).half() a : int = self.clip_model.get_image_features(__snake_case ) a : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : Tuple = image_embeddings_clip.repeat_interleave(__snake_case , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowercase_ ( self : Tuple , __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : List[Any] , ): a : Optional[Any] = latents.detach().requires_grad_() a : List[Any] = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : Any = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): a : int = self.scheduler.alphas_cumprod[timestep] a : Any = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf a : List[str] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 a : Tuple = torch.sqrt(__snake_case ) a : str = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , __snake_case ): a : List[Any] = self.scheduler.sigmas[index] a : Optional[int] = latents - sigma * noise_pred else: raise ValueError(F"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Union[str, Any] = 1 / 0.18215 * sample a : str = self.vae.decode(__snake_case ).sample a : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) a : Tuple = transforms.Resize(self.feature_extractor_size )(__snake_case ) a : List[str] = self.normalize(__snake_case ).to(latents.dtype ) a : List[str] = self.clip_model.get_image_features(__snake_case ) a : Tuple = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : int = spherical_dist_loss(__snake_case , __snake_case ).mean() * clip_guidance_scale a : List[str] = -torch.autograd.grad(__snake_case , __snake_case )[0] if isinstance(self.scheduler , __snake_case ): a : List[Any] = latents.detach() + grads * (sigma**2) a : Optional[int] = noise_pred_original else: a : List[Any] = noise_pred_original - torch.sqrt(__snake_case ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Optional[int] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Optional[str] = None , __snake_case : Optional[str] = None , __snake_case : Optional[int] = 5_12 , __snake_case : Optional[int] = 5_12 , __snake_case : float = 0.6 , __snake_case : Optional[int] = 50 , __snake_case : Optional[float] = 7.5 , __snake_case : Optional[int] = 1 , __snake_case : float = 0.0 , __snake_case : Optional[float] = 1_00 , __snake_case : Optional[torch.Generator] = None , __snake_case : Optional[str] = "pil" , __snake_case : bool = True , __snake_case : float = 0.8 , __snake_case : float = 0.1 , __snake_case : float = 0.1 , ): if isinstance(__snake_case , __snake_case ) and len(__snake_case ) != batch_size: raise ValueError(F"""You have passed {batch_size} batch_size, but only {len(__snake_case )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(__snake_case , torch.Generator ) and batch_size > 1: a : Dict = [generator] + [None] * (batch_size - 1) a : Any = [ ('model', self.coca_model is None), ('tokenizer', self.coca_tokenizer is None), ('transform', self.coca_transform is None), ] a : List[str] = [x[0] for x in coca_is_none if x[1]] a : List[str] = ', '.join(__snake_case ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(__snake_case ): raise ValueError( F"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" F"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : int = self.get_image_description(__snake_case ) if style_prompt is None: if len(__snake_case ): raise ValueError( F"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" F""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : Union[str, Any] = self.get_image_description(__snake_case ) # get prompt text embeddings for content and style a : Optional[Any] = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] a : Dict = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] a : Any = slerp(__snake_case , __snake_case , __snake_case ) # duplicate text embeddings for each generation per prompt a : Optional[Any] = text_embeddings.repeat_interleave(__snake_case , dim=0 ) # set timesteps a : int = 'offset' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) a : Any = {} if accepts_offset: a : Optional[Any] = 1 self.scheduler.set_timesteps(__snake_case , **__snake_case ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) a , a : Tuple = self.get_timesteps(__snake_case , __snake_case , self.device ) a : Optional[int] = timesteps[:1].repeat(__snake_case ) # Preprocess image a : Optional[Any] = preprocess(__snake_case , __snake_case , __snake_case ) a : List[Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : str = preprocess(__snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : Union[str, Any] = slerp(__snake_case , __snake_case , __snake_case ) if clip_guidance_scale > 0: a : Dict = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : int = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : List[str] = slerp( __snake_case , __snake_case , __snake_case ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. a : int = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: a : Any = content_text_input.input_ids.shape[-1] a : List[Any] = self.tokenizer([''] , padding='max_length' , max_length=__snake_case , return_tensors='pt' ) a : List[str] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt a : Dict = uncond_embeddings.repeat_interleave(__snake_case , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a : Any = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. a : List[str] = (batch_size, self.unet.config.in_channels, height // 8, width // 8) a : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps a : int = torch.randn(__snake_case , generator=__snake_case , device='cpu' , dtype=__snake_case ).to( self.device ) else: a : Optional[int] = torch.randn(__snake_case , generator=__snake_case , device=self.device , dtype=__snake_case ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) a : List[str] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler a : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a : Optional[Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a : Union[str, Any] = {} if accepts_eta: a : List[str] = eta # check if the scheduler accepts generator a : List[Any] = 'generator' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: a : Any = generator with self.progress_bar(total=__snake_case ): for i, t in enumerate(__snake_case ): # expand the latents if we are doing classifier free guidance a : Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a : Dict = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : List[Any] = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample # perform classifier free guidance if do_classifier_free_guidance: a , a : List[str] = noise_pred.chunk(2 ) a : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: a : Optional[Any] = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) a , a : Union[str, Any] = self.cond_fn( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ) # compute the previous noisy sample x_t -> x_t-1 a : Any = self.scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Tuple = 1 / 0.18215 * latents a : Optional[int] = self.vae.decode(__snake_case ).sample a : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) a : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a : str = self.numpy_to_pil(__snake_case ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=__snake_case , nsfw_content_detected=__snake_case )
297
1
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class a__( nn.Module ): def __init__( self : Any , __snake_case : int = 16 , __snake_case : int = 88 , __snake_case : Optional[int] = None , __snake_case : int = 1 , __snake_case : float = 0.0 , __snake_case : int = 32 , __snake_case : Optional[int] = None , __snake_case : bool = False , __snake_case : Optional[int] = None , __snake_case : Optional[int] = None , __snake_case : str = "geglu" , __snake_case : Optional[int] = None , ): super().__init__() a : Optional[int] = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__snake_case , attention_head_dim=__snake_case , in_channels=__snake_case , num_layers=__snake_case , dropout=__snake_case , norm_num_groups=__snake_case , cross_attention_dim=__snake_case , attention_bias=__snake_case , sample_size=__snake_case , num_vector_embeds=__snake_case , activation_fn=__snake_case , num_embeds_ada_norm=__snake_case , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference a : Union[str, Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` a : Tuple = [77, 2_57] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` a : Any = [1, 0] def lowercase_ ( self : str , __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any]=None , __snake_case : int=None , __snake_case : Dict=None , __snake_case : bool = True , ): a : Dict = hidden_states a : Tuple = [] a : Optional[int] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens a : Union[str, Any] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] a : Tuple = self.transformer_index_for_condition[i] a : Union[str, Any] = self.transformers[transformer_index]( __snake_case , encoder_hidden_states=__snake_case , timestep=__snake_case , cross_attention_kwargs=__snake_case , return_dict=__snake_case , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] a : Optional[Any] = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) a : int = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__snake_case )
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A , _A , _A , _A , ): a : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: a : Union[str, Any] = 1 - (matter_density + radiation_density + dark_energy) a : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) a : int = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation lowerCAmelCase: Optional[Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
297
1
'''simple docstring''' 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 lowerCAmelCase: Optional[Any] = logging.get_logger(__name__) # General docstring lowerCAmelCase: str = 'RegNetConfig' # Base docstring lowerCAmelCase: str = 'facebook/regnet-y-040' lowerCAmelCase: Optional[int] = [1, 1_0_8_8, 7, 7] # Image classification docstring lowerCAmelCase: Union[str, Any] = 'facebook/regnet-y-040' lowerCAmelCase: Any = 'tabby, tabby cat' lowerCAmelCase: Union[str, Any] = [ 'facebook/regnet-y-040', # See all regnet models at https://huggingface.co/models?filter=regnet ] class a__( tf.keras.layers.Layer ): def __init__( self : Optional[Any] , __snake_case : int , __snake_case : int = 3 , __snake_case : int = 1 , __snake_case : int = 1 , __snake_case : Optional[str] = "relu" , **__snake_case : Optional[int] , ): super().__init__(**__snake_case ) # The padding and conv has been verified in # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb a : Optional[Any] = tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 ) a : Dict = tf.keras.layers.ConvaD( filters=__snake_case , kernel_size=__snake_case , strides=__snake_case , padding='VALID' , groups=__snake_case , use_bias=__snake_case , name='convolution' , ) a : Any = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='normalization' ) a : Union[str, Any] = ACTaFN[activation] if activation is not None else tf.identity def lowercase_ ( self : int , __snake_case : Tuple ): a : Optional[Any] = self.convolution(self.padding(__snake_case ) ) a : Dict = self.normalization(__snake_case ) a : Tuple = self.activation(__snake_case ) return hidden_state class a__( tf.keras.layers.Layer ): def __init__( self : Optional[int] , __snake_case : RegNetConfig , **__snake_case : Dict ): super().__init__(**__snake_case ) a : int = config.num_channels a : List[str] = TFRegNetConvLayer( out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='embedder' , ) def lowercase_ ( self : int , __snake_case : str ): a : Tuple = shape_list(__snake_case )[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 : List[str] = tf.transpose(__snake_case , perm=(0, 2, 3, 1) ) a : Tuple = self.embedder(__snake_case ) return hidden_state class a__( tf.keras.layers.Layer ): def __init__( self : Optional[int] , __snake_case : int , __snake_case : int = 2 , **__snake_case : Optional[int] ): super().__init__(**__snake_case ) a : List[str] = tf.keras.layers.ConvaD( filters=__snake_case , kernel_size=1 , strides=__snake_case , use_bias=__snake_case , name='convolution' ) a : List[Any] = tf.keras.layers.BatchNormalization(epsilon=1e-5 , momentum=0.9 , name='normalization' ) def lowercase_ ( self : Dict , __snake_case : tf.Tensor , __snake_case : bool = False ): return self.normalization(self.convolution(__snake_case ) , training=__snake_case ) class a__( tf.keras.layers.Layer ): def __init__( self : Any , __snake_case : int , __snake_case : int , **__snake_case : List[str] ): super().__init__(**__snake_case ) a : Optional[int] = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__snake_case , name='pooler' ) a : str = [ tf.keras.layers.ConvaD(filters=__snake_case , kernel_size=1 , activation='relu' , name='attention.0' ), tf.keras.layers.ConvaD(filters=__snake_case , kernel_size=1 , activation='sigmoid' , name='attention.2' ), ] def lowercase_ ( self : Dict , __snake_case : Optional[int] ): # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels] a : Union[str, Any] = self.pooler(__snake_case ) for layer_module in self.attention: a : Optional[int] = layer_module(__snake_case ) a : Optional[int] = hidden_state * pooled return hidden_state class a__( tf.keras.layers.Layer ): def __init__( self : Any , __snake_case : RegNetConfig , __snake_case : int , __snake_case : int , __snake_case : int = 1 , **__snake_case : str ): super().__init__(**__snake_case ) a : str = in_channels != out_channels or stride != 1 a : Optional[Any] = max(1 , out_channels // config.groups_width ) a : List[Any] = ( TFRegNetShortCut(__snake_case , stride=__snake_case , 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 : Any = [ TFRegNetConvLayer(__snake_case , kernel_size=1 , activation=config.hidden_act , name='layer.0' ), TFRegNetConvLayer( __snake_case , stride=__snake_case , groups=__snake_case , activation=config.hidden_act , name='layer.1' ), TFRegNetConvLayer(__snake_case , kernel_size=1 , activation=__snake_case , name='layer.2' ), ] a : Tuple = ACTaFN[config.hidden_act] def lowercase_ ( self : Tuple , __snake_case : Union[str, Any] ): a : Optional[int] = hidden_state for layer_module in self.layers: a : Optional[int] = layer_module(__snake_case ) a : Union[str, Any] = self.shortcut(__snake_case ) hidden_state += residual a : List[Any] = self.activation(__snake_case ) return hidden_state class a__( tf.keras.layers.Layer ): def __init__( self : List[str] , __snake_case : RegNetConfig , __snake_case : int , __snake_case : int , __snake_case : int = 1 , **__snake_case : str ): super().__init__(**__snake_case ) a : Dict = in_channels != out_channels or stride != 1 a : Tuple = max(1 , out_channels // config.groups_width ) a : List[Any] = ( TFRegNetShortCut(__snake_case , stride=__snake_case , name='shortcut' ) if should_apply_shortcut else tf.keras.layers.Activation('linear' , name='shortcut' ) ) a : List[Any] = [ TFRegNetConvLayer(__snake_case , kernel_size=1 , activation=config.hidden_act , name='layer.0' ), TFRegNetConvLayer( __snake_case , stride=__snake_case , groups=__snake_case , activation=config.hidden_act , name='layer.1' ), TFRegNetSELayer(__snake_case , reduced_channels=int(round(in_channels / 4 ) ) , name='layer.2' ), TFRegNetConvLayer(__snake_case , kernel_size=1 , activation=__snake_case , name='layer.3' ), ] a : Optional[int] = ACTaFN[config.hidden_act] def lowercase_ ( self : int , __snake_case : Union[str, Any] ): a : List[str] = hidden_state for layer_module in self.layers: a : Any = layer_module(__snake_case ) a : List[str] = self.shortcut(__snake_case ) hidden_state += residual a : Tuple = self.activation(__snake_case ) return hidden_state class a__( tf.keras.layers.Layer ): def __init__( self : Optional[Any] , __snake_case : RegNetConfig , __snake_case : int , __snake_case : int , __snake_case : int = 2 , __snake_case : int = 2 , **__snake_case : List[Any] ): super().__init__(**__snake_case ) a : Optional[Any] = TFRegNetXLayer if config.layer_type == 'x' else TFRegNetYLayer a : Any = [ # downsampling is done in the first layer with stride of 2 layer(__snake_case , __snake_case , __snake_case , stride=__snake_case , name='layers.0' ), *[layer(__snake_case , __snake_case , __snake_case , name=F"""layers.{i+1}""" ) for i in range(depth - 1 )], ] def lowercase_ ( self : Dict , __snake_case : int ): for layer_module in self.layers: a : int = layer_module(__snake_case ) return hidden_state class a__( tf.keras.layers.Layer ): def __init__( self : List[Any] , __snake_case : RegNetConfig , **__snake_case : Tuple ): super().__init__(**__snake_case ) a : int = [] # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input self.stages.append( TFRegNetStage( __snake_case , 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 : List[str] = zip(config.hidden_sizes , config.hidden_sizes[1:] ) for i, ((in_channels, out_channels), depth) in enumerate(zip(__snake_case , config.depths[1:] ) ): self.stages.append(TFRegNetStage(__snake_case , __snake_case , __snake_case , depth=__snake_case , name=F"""stages.{i+1}""" ) ) def lowercase_ ( self : int , __snake_case : tf.Tensor , __snake_case : bool = False , __snake_case : bool = True ): a : Any = () if output_hidden_states else None for stage_module in self.stages: if output_hidden_states: a : int = hidden_states + (hidden_state,) a : Tuple = stage_module(__snake_case ) if output_hidden_states: a : Any = 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=__snake_case , hidden_states=__snake_case ) @keras_serializable class a__( tf.keras.layers.Layer ): lowercase__ = RegNetConfig def __init__( self : Optional[Any] , __snake_case : Tuple , **__snake_case : List[Any] ): super().__init__(**__snake_case ) a : List[str] = config a : Tuple = TFRegNetEmbeddings(__snake_case , name='embedder' ) a : Dict = TFRegNetEncoder(__snake_case , name='encoder' ) a : str = tf.keras.layers.GlobalAveragePoolingaD(keepdims=__snake_case , name='pooler' ) @unpack_inputs def lowercase_ ( self : List[str] , __snake_case : tf.Tensor , __snake_case : Optional[bool] = None , __snake_case : Optional[bool] = None , __snake_case : bool = False , ): a : List[str] = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a : Union[str, Any] = return_dict if return_dict is not None else self.config.use_return_dict a : Dict = self.embedder(__snake_case , training=__snake_case ) a : str = self.encoder( __snake_case , output_hidden_states=__snake_case , return_dict=__snake_case , training=__snake_case ) a : Dict = encoder_outputs[0] a : Tuple = self.pooler(__snake_case ) # Change to NCHW output format have uniformity in the modules a : List[Any] = tf.transpose(__snake_case , perm=(0, 3, 1, 2) ) a : Dict = tf.transpose(__snake_case , perm=(0, 3, 1, 2) ) # Change the other hidden state outputs to NCHW as well if output_hidden_states: a : Tuple = tuple([tf.transpose(__snake_case , 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=__snake_case , pooler_output=__snake_case , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , ) class a__( lowerCamelCase__ ): lowercase__ = RegNetConfig lowercase__ = """regnet""" lowercase__ = """pixel_values""" @property def lowercase_ ( self : int ): return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24) , dtype=tf.floataa )} lowerCAmelCase: List[Any] = 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' lowerCAmelCase: 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.""" , lowerCamelCase__ , ) class a__( lowerCamelCase__ ): def __init__( self : Dict , __snake_case : RegNetConfig , *__snake_case : Dict , **__snake_case : Union[str, Any] ): super().__init__(__snake_case , *__snake_case , **__snake_case ) a : List[Any] = TFRegNetMainLayer(__snake_case , name='regnet' ) @unpack_inputs @add_start_docstrings_to_model_forward(__snake_case ) @add_code_sample_docstrings( checkpoint=_CHECKPOINT_FOR_DOC , output_type=__snake_case , config_class=_CONFIG_FOR_DOC , modality='vision' , expected_output=_EXPECTED_OUTPUT_SHAPE , ) def lowercase_ ( self : str , __snake_case : tf.Tensor , __snake_case : Optional[bool] = None , __snake_case : Optional[bool] = None , __snake_case : List[str]=False , ): a : Any = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a : str = return_dict if return_dict is not None else self.config.use_return_dict a : List[Any] = self.regnet( pixel_values=__snake_case , output_hidden_states=__snake_case , return_dict=__snake_case , training=__snake_case , ) 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( """ RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for ImageNet. """ , lowerCamelCase__ , ) class a__( lowerCamelCase__ , lowerCamelCase__ ): def __init__( self : Any , __snake_case : RegNetConfig , *__snake_case : List[Any] , **__snake_case : int ): super().__init__(__snake_case , *__snake_case , **__snake_case ) a : Dict = config.num_labels a : Dict = TFRegNetMainLayer(__snake_case , name='regnet' ) # classification head a : List[str] = [ 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(__snake_case ) @add_code_sample_docstrings( checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__snake_case , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , ) def lowercase_ ( self : Union[str, Any] , __snake_case : tf.Tensor = None , __snake_case : tf.Tensor = None , __snake_case : bool = None , __snake_case : bool = None , __snake_case : str=False , ): a : Dict = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) a : int = return_dict if return_dict is not None else self.config.use_return_dict a : List[Any] = self.regnet( __snake_case , output_hidden_states=__snake_case , return_dict=__snake_case , training=__snake_case ) a : str = outputs.pooler_output if return_dict else outputs[1] a : int = self.classifier[0](__snake_case ) a : str = self.classifier[1](__snake_case ) a : List[str] = None if labels is None else self.hf_compute_loss(labels=__snake_case , logits=__snake_case ) if not return_dict: a : Optional[int] = (logits,) + outputs[2:] return ((loss,) + output) if loss is not None else output return TFSequenceClassifierOutput(loss=__snake_case , logits=__snake_case , hidden_states=outputs.hidden_states )
297
'''simple docstring''' from __future__ import annotations import math class a__: def __init__( self : List[str] , __snake_case : int ): a : str = size # approximate the overall size of segment tree with given value a : Optional[int] = [0 for i in range(0 , 4 * size )] # create array to store lazy update a : Any = [0 for i in range(0 , 4 * size )] a : Dict = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowercase_ ( self : int , __snake_case : int ): return idx * 2 def lowercase_ ( self : Dict , __snake_case : int ): return idx * 2 + 1 def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : list[int] ): if left_element == right_element: a : Tuple = a[left_element - 1] else: a : Tuple = (left_element + right_element) // 2 self.build(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case ) self.build(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case ) a : Union[str, Any] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : int = self.lazy[idx] a : Union[str, Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : int = self.lazy[idx] a : Tuple = True a : Optional[Any] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: a : int = val if left_element != right_element: a : int = val a : Dict = val a : List[str] = True a : List[str] = True return True a : Tuple = (left_element + right_element) // 2 self.update(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) self.update(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case , __snake_case ) a : Optional[int] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) return True def lowercase_ ( self : Union[str, Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : str = self.lazy[idx] a : Optional[Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : Union[str, Any] = self.lazy[idx] a : Dict = True a : int = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] a : Dict = (left_element + right_element) // 2 a : Optional[int] = self.query(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.query(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case ) return max(__snake_case , __snake_case ) def __str__( self : Any ): return str([self.query(1 , 1 , self.size , __snake_case , __snake_case ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] lowerCAmelCase: int = 1_5 lowerCAmelCase: Optional[int] = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
297
1
'''simple docstring''' import argparse import json from pathlib import Path import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinvaConfig, SwinvaForImageClassification def lowerCamelCase__ ( _A ): a : Optional[int] = SwinvaConfig() a : Any = swinva_name.split('_' ) a : Optional[int] = name_split[1] if "to" in name_split[3]: a : List[Any] = int(name_split[3][-3:] ) else: a : List[Any] = int(name_split[3] ) if "to" in name_split[2]: a : Optional[Any] = int(name_split[2][-2:] ) else: a : Tuple = int(name_split[2][6:] ) if model_size == "tiny": a : List[str] = 96 a : int = (2, 2, 6, 2) a : str = (3, 6, 12, 24) elif model_size == "small": a : Union[str, Any] = 96 a : List[Any] = (2, 2, 18, 2) a : str = (3, 6, 12, 24) elif model_size == "base": a : Any = 128 a : Union[str, Any] = (2, 2, 18, 2) a : Optional[Any] = (4, 8, 16, 32) else: a : Union[str, Any] = 192 a : List[Any] = (2, 2, 18, 2) a : List[Any] = (6, 12, 24, 48) if "to" in swinva_name: a : Optional[Any] = (12, 12, 12, 6) if ("22k" in swinva_name) and ("to" not in swinva_name): a : Any = 2_1841 a : Tuple = 'huggingface/label-files' a : Optional[int] = 'imagenet-22k-id2label.json' a : List[Any] = json.load(open(hf_hub_download(_A , _A , repo_type='dataset' ) , 'r' ) ) a : Optional[int] = {int(_A ): v for k, v in idalabel.items()} a : Union[str, Any] = idalabel a : Optional[Any] = {v: k for k, v in idalabel.items()} else: a : Tuple = 1000 a : Optional[Any] = 'huggingface/label-files' a : Optional[Any] = 'imagenet-1k-id2label.json' a : List[Any] = json.load(open(hf_hub_download(_A , _A , repo_type='dataset' ) , 'r' ) ) a : Tuple = {int(_A ): v for k, v in idalabel.items()} a : List[str] = idalabel a : Optional[int] = {v: k for k, v in idalabel.items()} a : Tuple = img_size a : Tuple = num_classes a : Optional[Any] = embed_dim a : Optional[Any] = depths a : int = num_heads a : Union[str, Any] = window_size return config def lowerCamelCase__ ( _A ): if "patch_embed.proj" in name: a : Optional[Any] = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: a : str = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: a : List[Any] = 'encoder.' + name if "attn.proj" in name: a : str = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: a : List[str] = name.replace('attn' , 'attention.self' ) if "norm1" in name: a : Union[str, Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: a : Dict = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: a : Optional[Any] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: a : List[str] = name.replace('mlp.fc2' , 'output.dense' ) if "q_bias" in name: a : List[str] = name.replace('q_bias' , 'query.bias' ) if "k_bias" in name: a : Optional[int] = name.replace('k_bias' , 'key.bias' ) if "v_bias" in name: a : Tuple = name.replace('v_bias' , 'value.bias' ) if "cpb_mlp" in name: a : Optional[Any] = name.replace('cpb_mlp' , 'continuous_position_bias_mlp' ) if name == "norm.weight": a : Tuple = 'layernorm.weight' if name == "norm.bias": a : Dict = 'layernorm.bias' if "head" in name: a : str = name.replace('head' , 'classifier' ) else: a : List[str] = 'swinv2.' + name return name def lowerCamelCase__ ( _A , _A ): for key in orig_state_dict.copy().keys(): a : int = orig_state_dict.pop(_A ) if "mask" in key: continue elif "qkv" in key: a : str = key.split('.' ) a : Any = int(key_split[1] ) a : Any = int(key_split[3] ) a : Optional[Any] = model.swinva.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a : List[str] = val[:dim, :] a : str = val[dim : dim * 2, :] a : str = val[-dim:, :] else: a : str = val[:dim] a : int = val[ dim : dim * 2 ] a : List[str] = val[-dim:] else: a : Union[str, Any] = val return orig_state_dict def lowerCamelCase__ ( _A , _A ): a : Any = timm.create_model(_A , pretrained=_A ) timm_model.eval() a : str = get_swinva_config(_A ) a : Optional[Any] = SwinvaForImageClassification(_A ) model.eval() a : Any = convert_state_dict(timm_model.state_dict() , _A ) model.load_state_dict(_A ) a : Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' a : List[str] = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swinva_name.replace('_' , '-' ) ) ) a : Any = Image.open(requests.get(_A , stream=_A ).raw ) a : Any = image_processor(images=_A , return_tensors='pt' ) a : Optional[Any] = timm_model(inputs['pixel_values'] ) a : int = model(**_A ).logits assert torch.allclose(_A , _A , atol=1E-3 ) print(f"""Saving model {swinva_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_A ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_A ) model.push_to_hub( repo_path_or_name=Path(_A , _A ) , organization='nandwalritik' , commit_message='Add model' , ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swinv2_name', default='swinv2_tiny_patch4_window8_256', type=str, help='Name of the Swinv2 timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowerCAmelCase: Optional[Any] = parser.parse_args() convert_swinva_checkpoint(args.swinva_name, args.pytorch_dump_folder_path)
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A ): while second != 0: a : Union[str, Any] = first & second first ^= second a : Tuple = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase: Optional[int] = int(input('Enter the first number: ').strip()) lowerCAmelCase: Union[str, Any] = int(input('Enter the second number: ').strip()) print(F"{add(first, second) = }")
297
1
'''simple docstring''' import argparse import json import requests import timm import torch from huggingface_hub import hf_hub_download from PIL import Image from transformers import AutoImageProcessor, SwinConfig, SwinForImageClassification def lowerCamelCase__ ( _A ): a : Dict = SwinConfig() a : Optional[Any] = swin_name.split('_' ) a : Dict = name_split[1] a : Any = int(name_split[4] ) a : List[Any] = int(name_split[3][-1] ) if model_size == "tiny": a : Optional[Any] = 96 a : int = (2, 2, 6, 2) a : int = (3, 6, 12, 24) elif model_size == "small": a : Union[str, Any] = 96 a : str = (2, 2, 18, 2) a : Optional[int] = (3, 6, 12, 24) elif model_size == "base": a : Dict = 128 a : Dict = (2, 2, 18, 2) a : Tuple = (4, 8, 16, 32) else: a : Optional[Any] = 192 a : List[str] = (2, 2, 18, 2) a : Tuple = (6, 12, 24, 48) if "in22k" in swin_name: a : int = 2_1841 else: a : Optional[Any] = 1000 a : Union[str, Any] = 'huggingface/label-files' a : List[Any] = 'imagenet-1k-id2label.json' a : Optional[Any] = json.load(open(hf_hub_download(_A , _A , repo_type='dataset' ) , 'r' ) ) a : int = {int(_A ): v for k, v in idalabel.items()} a : Optional[int] = idalabel a : Any = {v: k for k, v in idalabel.items()} a : Any = img_size a : Any = num_classes a : int = embed_dim a : Dict = depths a : str = num_heads a : Tuple = window_size return config def lowerCamelCase__ ( _A ): if "patch_embed.proj" in name: a : Union[str, Any] = name.replace('patch_embed.proj' , 'embeddings.patch_embeddings.projection' ) if "patch_embed.norm" in name: a : Union[str, Any] = name.replace('patch_embed.norm' , 'embeddings.norm' ) if "layers" in name: a : Tuple = 'encoder.' + name if "attn.proj" in name: a : Optional[int] = name.replace('attn.proj' , 'attention.output.dense' ) if "attn" in name: a : Union[str, Any] = name.replace('attn' , 'attention.self' ) if "norm1" in name: a : Optional[Any] = name.replace('norm1' , 'layernorm_before' ) if "norm2" in name: a : Optional[int] = name.replace('norm2' , 'layernorm_after' ) if "mlp.fc1" in name: a : Optional[int] = name.replace('mlp.fc1' , 'intermediate.dense' ) if "mlp.fc2" in name: a : Dict = name.replace('mlp.fc2' , 'output.dense' ) if name == "norm.weight": a : Optional[Any] = 'layernorm.weight' if name == "norm.bias": a : Tuple = 'layernorm.bias' if "head" in name: a : str = name.replace('head' , 'classifier' ) else: a : Tuple = 'swin.' + name return name def lowerCamelCase__ ( _A , _A ): for key in orig_state_dict.copy().keys(): a : Union[str, Any] = orig_state_dict.pop(_A ) if "mask" in key: continue elif "qkv" in key: a : List[str] = key.split('.' ) a : Union[str, Any] = int(key_split[1] ) a : Union[str, Any] = int(key_split[3] ) a : Optional[int] = model.swin.encoder.layers[layer_num].blocks[block_num].attention.self.all_head_size if "weight" in key: a : str = val[:dim, :] a : Dict = val[ dim : dim * 2, : ] a : Union[str, Any] = val[-dim:, :] else: a : Any = val[ :dim ] a : Dict = val[ dim : dim * 2 ] a : Optional[int] = val[ -dim: ] else: a : Dict = val return orig_state_dict def lowerCamelCase__ ( _A , _A ): a : List[str] = timm.create_model(_A , pretrained=_A ) timm_model.eval() a : Tuple = get_swin_config(_A ) a : Dict = SwinForImageClassification(_A ) model.eval() a : Any = convert_state_dict(timm_model.state_dict() , _A ) model.load_state_dict(_A ) a : Union[str, Any] = 'http://images.cocodataset.org/val2017/000000039769.jpg' a : Tuple = AutoImageProcessor.from_pretrained('microsoft/{}'.format(swin_name.replace('_' , '-' ) ) ) a : str = Image.open(requests.get(_A , stream=_A ).raw ) a : List[Any] = image_processor(images=_A , return_tensors='pt' ) a : List[Any] = timm_model(inputs['pixel_values'] ) a : Optional[int] = model(**_A ).logits assert torch.allclose(_A , _A , atol=1E-3 ) print(f"""Saving model {swin_name} to {pytorch_dump_folder_path}""" ) model.save_pretrained(_A ) print(f"""Saving image processor to {pytorch_dump_folder_path}""" ) image_processor.save_pretrained(_A ) if __name__ == "__main__": lowerCAmelCase: Union[str, Any] = argparse.ArgumentParser() # Required parameters parser.add_argument( '--swin_name', default='swin_tiny_patch4_window7_224', type=str, help='Name of the Swin timm model you\'d like to convert.', ) parser.add_argument( '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.' ) lowerCAmelCase: Dict = parser.parse_args() convert_swin_checkpoint(args.swin_name, args.pytorch_dump_folder_path)
297
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ ( _A , _A ): assert isinstance(_A , _A ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Optional[int] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , keep_in_memory=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Tuple = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Dict = features.copy() if features else default_expected_features a : Union[str, Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Tuple = tmp_path / 'cache' a : Optional[Any] = {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} a : Optional[int] = features.copy() if features else default_expected_features a : Dict = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Optional[int] = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCamelCase__ ( _A , _A ): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} a : Dict = {'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} a : int = features.copy() a : List[Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Dict = tmp_path / 'cache' a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[str] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , split=_A ).read() _check_json_dataset(_A , _A ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def lowerCamelCase__ ( _A , _A , _A ): if issubclass(_A , _A ): a : Optional[int] = jsonl_path elif issubclass(_A , _A ): a : Optional[int] = [jsonl_path] a : List[str] = tmp_path / 'cache' a : Dict = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) def lowerCamelCase__ ( _A , _A , _A=("train",) ): assert isinstance(_A , _A ) for split in splits: a : str = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : Any = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : int = JsonDatasetReader({'train': jsonl_path} , cache_dir=_A , keep_in_memory=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[Any] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = features.copy() if features else default_expected_features a : Any = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : List[str] = JsonDatasetReader({'train': jsonl_path} , features=_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): if split: a : Any = {split: jsonl_path} else: a : List[Any] = 'train' a : List[str] = {'train': jsonl_path, 'test': jsonl_path} a : List[Any] = tmp_path / 'cache' a : str = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase__ ( _A ): return json.load(_A ) def lowerCamelCase__ ( _A ): return [json.loads(_A ) for line in buffer] class a__: @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : Tuple , __snake_case : int , __snake_case : Optional[int] , __snake_case : Any ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case ).write() buffer.seek(0 ) a : List[str] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Tuple , __snake_case : Tuple , __snake_case : Any , __snake_case : Any , __snake_case : List[str] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : List[Any] , __snake_case : Any , __snake_case : Optional[int] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : List[Any] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Optional[int] , __snake_case : Any , __snake_case : str , __snake_case : int , __snake_case : List[Any] , __snake_case : Dict ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 def lowercase_ ( self : List[str] , __snake_case : str ): with pytest.raises(__snake_case ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def lowercase_ ( self : Tuple , __snake_case : Dict , __snake_case : List[Any] , __snake_case : int , __snake_case : List[str] , __snake_case : Optional[int] ): a : Tuple = tmp_path_factory.mktemp('data' ) / F"""test.json.{extension}""" a : List[Any] = str(shared_datadir / F"""test_file.json.{extension}""" ) JsonDatasetWriter(__snake_case , __snake_case , compression=__snake_case ).write() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() assert exported_content == original_content
297
1
'''simple docstring''' from datasets.utils.patching import _PatchedModuleObj, patch_submodule from . import _test_patching def lowerCamelCase__ ( ): import os as original_os from os import path as original_path from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join a : Optional[Any] = '__test_patch_submodule_mock__' with patch_submodule(_test_patching , 'os.path.join' , _A ): # Every way to access os.path.join must be patched, and the rest must stay untouched # check os.path.join assert isinstance(_test_patching.os , _PatchedModuleObj ) assert isinstance(_test_patching.os.path , _PatchedModuleObj ) assert _test_patching.os.path.join is mock # check path.join assert isinstance(_test_patching.path , _PatchedModuleObj ) assert _test_patching.path.join is mock # check join assert _test_patching.join is mock # check that the other attributes are untouched assert _test_patching.os.rename is original_rename assert _test_patching.path.dirname is original_dirname assert _test_patching.os.path.dirname is original_dirname # Even renamed modules or objects must be patched # check renamed_os.path.join assert isinstance(_test_patching.renamed_os , _PatchedModuleObj ) assert isinstance(_test_patching.renamed_os.path , _PatchedModuleObj ) assert _test_patching.renamed_os.path.join is mock # check renamed_path.join assert isinstance(_test_patching.renamed_path , _PatchedModuleObj ) assert _test_patching.renamed_path.join is mock # check renamed_join assert _test_patching.renamed_join is mock # check that the other attributes are untouched assert _test_patching.renamed_os.rename is original_rename assert _test_patching.renamed_path.dirname is original_dirname assert _test_patching.renamed_os.path.dirname is original_dirname # check that everthing is back to normal when the patch is over assert _test_patching.os is original_os assert _test_patching.path is original_path assert _test_patching.join is original_join assert _test_patching.renamed_os is original_os assert _test_patching.renamed_path is original_path assert _test_patching.renamed_join is original_join def lowerCamelCase__ ( ): assert _test_patching.open is open a : Optional[int] = '__test_patch_submodule_builtin_mock__' # _test_patching has "open" in its globals assert _test_patching.open is open with patch_submodule(_test_patching , 'open' , _A ): assert _test_patching.open is mock # check that everthing is back to normal when the patch is over assert _test_patching.open is open def lowerCamelCase__ ( ): # pandas.read_csv is not present in _test_patching a : str = '__test_patch_submodule_missing_mock__' with patch_submodule(_test_patching , 'pandas.read_csv' , _A ): pass def lowerCamelCase__ ( ): # builtin should always be mocked even if they're not in the globals # in case they're loaded at one point a : Optional[int] = '__test_patch_submodule_missing_builtin_mock__' # _test_patching doesn't have "len" in its globals assert getattr(_test_patching , 'len' , _A ) is None with patch_submodule(_test_patching , 'len' , _A ): assert _test_patching.len is mock assert _test_patching.len is len def lowerCamelCase__ ( ): a : Optional[int] = '__test_patch_submodule_start_and_stop_mock__' a : List[str] = patch_submodule(_test_patching , 'open' , _A ) assert _test_patching.open is open patch.start() assert _test_patching.open is mock patch.stop() assert _test_patching.open is open def lowerCamelCase__ ( ): from os import rename as original_rename from os.path import dirname as original_dirname from os.path import join as original_join a : Optional[int] = '__test_patch_submodule_successive_join__' a : Tuple = '__test_patch_submodule_successive_dirname__' a : Optional[Any] = '__test_patch_submodule_successive_rename__' assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename with patch_submodule(_test_patching , 'os.path.join' , _A ): with patch_submodule(_test_patching , 'os.rename' , _A ): with patch_submodule(_test_patching , 'os.path.dirname' , _A ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename # try another order with patch_submodule(_test_patching , 'os.rename' , _A ): with patch_submodule(_test_patching , 'os.path.join' , _A ): with patch_submodule(_test_patching , 'os.path.dirname' , _A ): assert _test_patching.os.path.join is mock_join assert _test_patching.os.path.dirname is mock_dirname assert _test_patching.os.rename is mock_rename assert _test_patching.os.path.join is original_join assert _test_patching.os.path.dirname is original_dirname assert _test_patching.os.rename is original_rename def lowerCamelCase__ ( ): a : List[Any] = '__test_patch_submodule_doesnt_exist_mock__' with patch_submodule(_test_patching , '__module_that_doesn_exist__.__attribute_that_doesn_exist__' , _A ): pass with patch_submodule(_test_patching , 'os.__attribute_that_doesn_exist__' , _A ): pass
297
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCamelCase__ ( _A = "laptop" ): a : Any = f"""https://www.amazon.in/laptop/s?k={product}""" a : Tuple = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5', } a : Any = BeautifulSoup(requests.get(_A , headers=_A ).text ) # Initialize a Pandas dataframe with the column titles a : Any = DataFrame( columns=[ 'Product Title', 'Product Link', 'Current Price of the product', 'Product Rating', 'MRP of the product', 'Discount', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( 'div' , attrs={'class': 's-result-item', 'data-component-type': 's-search-result'} , ) , soup.find_all('div' , attrs={'class': 'a-row a-size-base a-color-base'} ) , ): try: a : Optional[int] = item.ha.text a : str = 'https://www.amazon.in/' + item.ha.a['href'] a : List[str] = item.find('span' , attrs={'class': 'a-offscreen'} ).text try: a : Optional[Any] = item.find('span' , attrs={'class': 'a-icon-alt'} ).text except AttributeError: a : Union[str, Any] = 'Not available' try: a : str = ( '₹' + item.find( 'span' , attrs={'class': 'a-price a-text-price'} ).text.split('₹' )[1] ) except AttributeError: a : int = '' try: a : Union[str, Any] = float( ( ( float(product_mrp.strip('₹' ).replace(',' , '' ) ) - float(product_price.strip('₹' ).replace(',' , '' ) ) ) / float(product_mrp.strip('₹' ).replace(',' , '' ) ) ) * 100 ) except ValueError: a : Any = float('nan' ) except AttributeError: pass a : Any = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] a : Any = ' ' a : List[str] = ' ' data_frame.index += 1 return data_frame if __name__ == "__main__": lowerCAmelCase: str = 'headphones' get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
297
1
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase: Any = logging.get_logger(__name__) lowerCAmelCase: Any = {'vocab_file': 'vocab.txt'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } lowerCAmelCase: str = { 'openbmb/cpm-ant-10b': 1_0_2_4, } def lowerCamelCase__ ( _A ): a : Union[str, Any] = collections.OrderedDict() with open(_A , 'r' , encoding='utf-8' ) as reader: a : int = reader.readlines() for index, token in enumerate(_A ): a : int = token.rstrip('\n' ) a : List[Any] = index return vocab class a__( lowerCamelCase__ ): def __init__( self : Dict , __snake_case : Any , __snake_case : Dict="<unk>" , __snake_case : str=2_00 ): a : List[Any] = vocab a : Any = unk_token a : List[str] = max_input_chars_per_word def lowercase_ ( self : Optional[int] , __snake_case : Union[str, Any] ): a : Optional[Any] = list(__snake_case ) if len(__snake_case ) > self.max_input_chars_per_word: return [self.unk_token] a : Any = 0 a : Optional[Any] = [] while start < len(__snake_case ): a : Optional[int] = len(__snake_case ) a : str = None while start < end: a : Optional[Any] = ''.join(chars[start:end] ) if substr in self.vocab: a : List[str] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(__snake_case ) a : List[str] = end return sub_tokens class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = False def __init__( self : Any , __snake_case : str , __snake_case : Tuple="<d>" , __snake_case : List[str]="</d>" , __snake_case : Dict="<s>" , __snake_case : List[Any]="</s>" , __snake_case : int="<pad>" , __snake_case : Any="<unk>" , __snake_case : List[str]="</n>" , __snake_case : int="</_>" , __snake_case : Optional[Any]="left" , **__snake_case : Dict , ): requires_backends(self , ['jieba'] ) super().__init__( bod_token=__snake_case , eod_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , pad_token=__snake_case , unk_token=__snake_case , line_token=__snake_case , space_token=__snake_case , padding_side=__snake_case , **__snake_case , ) a : Union[str, Any] = bod_token a : Any = eod_token a : List[str] = load_vocab(__snake_case ) a : Optional[int] = self.encoder[space_token] a : str = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] a : str = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) a : Tuple = {v: k for k, v in self.encoder.items()} a : List[str] = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def lowercase_ ( self : Optional[int] ): return self.encoder[self.bod_token] @property def lowercase_ ( self : Dict ): return self.encoder[self.eod_token] @property def lowercase_ ( self : Any ): return self.encoder["\n"] @property def lowercase_ ( self : Tuple ): return len(self.encoder ) def lowercase_ ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def lowercase_ ( self : Union[str, Any] , __snake_case : List[str] ): a : List[str] = [] for x in jieba.cut(__snake_case , cut_all=__snake_case ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(__snake_case ) ) return output_tokens def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[Any] , **__snake_case : Optional[Any] ): a : Optional[int] = [i for i in token_ids if i >= 0] a : Any = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(__snake_case , **__snake_case ) def lowercase_ ( self : Optional[int] , __snake_case : int ): return token in self.encoder def lowercase_ ( self : int , __snake_case : List[str] ): return "".join(__snake_case ) def lowercase_ ( self : List[str] , __snake_case : Union[str, Any] ): return self.encoder.get(__snake_case , self.encoder.get(self.unk_token ) ) def lowercase_ ( self : Tuple , __snake_case : List[str] ): return self.decoder.get(__snake_case , self.unk_token ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] = None ): if os.path.isdir(__snake_case ): a : Optional[int] = os.path.join( __snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: a : int = (filename_prefix + '-' if filename_prefix else '') + save_directory a : Any = 0 if " " in self.encoder: a : Union[str, Any] = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: a : Tuple = self.encoder['\n'] del self.encoder["\n"] a : Dict = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) with open(__snake_case , 'w' , encoding='utf-8' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ' Please check that the vocabulary is not corrupted!' ) a : List[Any] = token_index writer.write(token + '\n' ) index += 1 return (vocab_file,) def lowercase_ ( self : Union[str, Any] , __snake_case : List[int] , __snake_case : List[int] = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowercase_ ( self : Dict , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) if token_ids_a is not None: return [1] + ([0] * len(__snake_case )) + [1] + ([0] * len(__snake_case )) return [1] + ([0] * len(__snake_case ))
297
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = StableUnCLIPImgaImgPipeline lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase__ = frozenset([] ) def lowercase_ ( self : int ): a : Dict = 32 a : str = embedder_hidden_size # image encoding components a : List[Any] = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) a : Dict = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=__snake_case , projection_dim=__snake_case , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) a : Dict = StableUnCLIPImageNormalizer(embedding_dim=__snake_case ) a : Optional[int] = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) a : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) a : Tuple = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__snake_case , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) a : Union[str, Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__snake_case , layers_per_block=1 , upcast_attention=__snake_case , use_linear_projection=__snake_case , ) torch.manual_seed(0 ) a : List[Any] = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.00085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=__snake_case , steps_offset=1 , ) torch.manual_seed(0 ) a : List[str] = AutoencoderKL() a : str = { # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def lowercase_ ( self : Tuple , __snake_case : List[str] , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=True ): if str(__snake_case ).startswith('mps' ): a : Tuple = torch.manual_seed(__snake_case ) else: a : List[Any] = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) a : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__snake_case ) ).to(__snake_case ) if pil_image: a : Optional[Any] = input_image * 0.5 + 0.5 a : Optional[Any] = input_image.clamp(0 , 1 ) a : Dict = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() a : int = DiffusionPipeline.numpy_to_pil(__snake_case )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def lowercase_ ( self : Optional[Any] ): a : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a : Union[str, Any] = self.get_dummy_components() a : Any = StableUnCLIPImgaImgPipeline(**__snake_case ) a : Tuple = sd_pipe.to(__snake_case ) sd_pipe.set_progress_bar_config(disable=__snake_case ) a : Union[str, Any] = self.get_dummy_inputs(__snake_case ) inputs.update({'image_embeds': None} ) a : str = sd_pipe(**__snake_case ).images a : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) a : Optional[int] = np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase_ ( self : List[str] ): a : int = torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=__snake_case ) def lowercase_ ( self : int ): a : Optional[int] = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=__snake_case ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def lowercase_ ( self : Dict ): self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__snake_case ) @slow @require_torch_gpu class a__( unittest.TestCase ): def lowercase_ ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Optional[Any] ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Union[str, Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) a : Optional[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = torch.Generator(device='cpu' ).manual_seed(0 ) a : Optional[int] = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Optional[int] ): a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) a : Union[str, Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a : str = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Any ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) a : Optional[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = pipe( __snake_case , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) a : int = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
297
1
'''simple docstring''' import os lowerCAmelCase: Any = {'I': 1, 'V': 5, 'X': 1_0, 'L': 5_0, 'C': 1_0_0, 'D': 5_0_0, 'M': 1_0_0_0} def lowerCamelCase__ ( _A ): a : Optional[Any] = 0 a : Optional[int] = 0 while index < len(_A ) - 1: a : Any = SYMBOLS[numerals[index]] a : Union[str, Any] = SYMBOLS[numerals[index + 1]] if current_value < next_value: total_value -= current_value else: total_value += current_value index += 1 total_value += SYMBOLS[numerals[index]] return total_value def lowerCamelCase__ ( _A ): a : str = '' a : Union[str, Any] = num // 1000 numerals += m_count * "M" num %= 1000 a : int = num // 100 if c_count == 9: numerals += "CM" c_count -= 9 elif c_count == 4: numerals += "CD" c_count -= 4 if c_count >= 5: numerals += "D" c_count -= 5 numerals += c_count * "C" num %= 100 a : Union[str, Any] = num // 10 if x_count == 9: numerals += "XC" x_count -= 9 elif x_count == 4: numerals += "XL" x_count -= 4 if x_count >= 5: numerals += "L" x_count -= 5 numerals += x_count * "X" num %= 10 if num == 9: numerals += "IX" num -= 9 elif num == 4: numerals += "IV" num -= 4 if num >= 5: numerals += "V" num -= 5 numerals += num * "I" return numerals def lowerCamelCase__ ( _A = "/p089_roman.txt" ): a : Optional[int] = 0 with open(os.path.dirname(_A ) + roman_numerals_filename ) as filea: a : Tuple = filea.readlines() for line in lines: a : Dict = line.strip() a : Tuple = parse_roman_numerals(_A ) a : int = generate_roman_numerals(_A ) savings += len(_A ) - len(_A ) return savings if __name__ == "__main__": print(F"{solution() = }")
297
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowerCAmelCase: Union[str, Any] = logging.get_logger(__name__) lowerCAmelCase: List[str] = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """t5""" lowercase__ = ["""past_key_values"""] lowercase__ = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : Union[str, Any] , __snake_case : int=3_21_28 , __snake_case : str=5_12 , __snake_case : Dict=64 , __snake_case : Optional[int]=20_48 , __snake_case : Tuple=6 , __snake_case : Any=None , __snake_case : Optional[int]=8 , __snake_case : str=32 , __snake_case : Union[str, Any]=1_28 , __snake_case : Optional[int]=0.1 , __snake_case : Dict=1e-6 , __snake_case : int=1.0 , __snake_case : Optional[int]="relu" , __snake_case : Any=True , __snake_case : List[str]=True , __snake_case : Union[str, Any]=0 , __snake_case : Dict=1 , **__snake_case : Optional[int] , ): a : Optional[int] = vocab_size a : Dict = d_model a : Union[str, Any] = d_kv a : Dict = d_ff a : Tuple = num_layers a : Dict = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a : int = num_heads a : str = relative_attention_num_buckets a : List[Any] = relative_attention_max_distance a : int = dropout_rate a : Tuple = layer_norm_epsilon a : str = initializer_factor a : List[Any] = feed_forward_proj a : Union[str, Any] = use_cache a : List[str] = self.feed_forward_proj.split('-' ) a : int = act_info[-1] a : Union[str, Any] = act_info[0] == 'gated' if len(__snake_case ) > 1 and act_info[0] != "gated" or len(__snake_case ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a : Optional[Any] = 'gelu_new' super().__init__( pad_token_id=__snake_case , eos_token_id=__snake_case , is_encoder_decoder=__snake_case , **__snake_case , ) class a__( lowerCamelCase__ ): @property def lowercase_ ( self : Optional[int] ): a : Dict = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: a : Dict = 'past_encoder_sequence + sequence' a : Dict = {0: 'batch'} a : Any = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: a : Optional[Any] = {0: 'batch', 1: 'decoder_sequence'} a : List[str] = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__snake_case , direction='inputs' ) return common_inputs @property def lowercase_ ( self : List[Any] ): return 13
297
1
'''simple docstring''' import json import pathlib import unittest import numpy as np from transformers.testing_utils import require_torch, require_vision, slow from transformers.utils import is_torch_available, is_vision_available from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs if is_torch_available(): import torch if is_vision_available(): from PIL import Image from transformers import YolosImageProcessor class a__( unittest.TestCase ): def __init__( self : int , __snake_case : str , __snake_case : Dict=7 , __snake_case : int=3 , __snake_case : int=30 , __snake_case : Dict=4_00 , __snake_case : Optional[Any]=True , __snake_case : List[str]=None , __snake_case : Union[str, Any]=True , __snake_case : List[Any]=[0.5, 0.5, 0.5] , __snake_case : Union[str, Any]=[0.5, 0.5, 0.5] , __snake_case : List[Any]=True , __snake_case : List[Any]=1 / 2_55 , __snake_case : Any=True , ): # by setting size["longest_edge"] > max_resolution we're effectively not testing this :p a : Tuple = size if size is not None else {'shortest_edge': 18, 'longest_edge': 13_33} a : str = parent a : Any = batch_size a : Any = num_channels a : Optional[Any] = min_resolution a : Tuple = max_resolution a : str = do_resize a : List[str] = size a : List[str] = do_normalize a : List[Any] = image_mean a : Tuple = image_std a : Optional[Any] = do_rescale a : Any = rescale_factor a : int = do_pad def lowercase_ ( self : Optional[Any] ): return { "do_resize": self.do_resize, "size": self.size, "do_normalize": self.do_normalize, "image_mean": self.image_mean, "image_std": self.image_std, "do_rescale": self.do_rescale, "rescale_factor": self.rescale_factor, "do_pad": self.do_pad, } def lowercase_ ( self : List[str] , __snake_case : str , __snake_case : Tuple=False ): if not batched: a : List[Any] = image_inputs[0] if isinstance(__snake_case , Image.Image ): a , a : Dict = image.size else: a , a : Union[str, Any] = image.shape[1], image.shape[2] if w < h: a : Optional[Any] = int(self.size['shortest_edge'] * h / w ) a : Optional[int] = self.size['shortest_edge'] elif w > h: a : List[str] = self.size['shortest_edge'] a : Tuple = int(self.size['shortest_edge'] * w / h ) else: a : Any = self.size['shortest_edge'] a : str = self.size['shortest_edge'] else: a : str = [] for image in image_inputs: a , a : int = self.get_expected_values([image] ) expected_values.append((expected_height, expected_width) ) a : Tuple = max(__snake_case , key=lambda __snake_case : item[0] )[0] a : Tuple = max(__snake_case , key=lambda __snake_case : item[1] )[1] return expected_height, expected_width @require_torch @require_vision class a__( lowerCamelCase__ , unittest.TestCase ): lowercase__ = YolosImageProcessor if is_vision_available() else None def lowercase_ ( self : Optional[Any] ): a : Dict = YolosImageProcessingTester(self ) @property def lowercase_ ( self : Dict ): return self.image_processor_tester.prepare_image_processor_dict() def lowercase_ ( self : List[str] ): a : str = self.image_processing_class(**self.image_processor_dict ) self.assertTrue(hasattr(__snake_case , 'image_mean' ) ) self.assertTrue(hasattr(__snake_case , 'image_std' ) ) self.assertTrue(hasattr(__snake_case , 'do_normalize' ) ) self.assertTrue(hasattr(__snake_case , 'do_resize' ) ) self.assertTrue(hasattr(__snake_case , 'size' ) ) def lowercase_ ( self : Dict ): a : Union[str, Any] = self.image_processing_class.from_dict(self.image_processor_dict ) self.assertEqual(image_processor.size , {'shortest_edge': 18, 'longest_edge': 13_33} ) self.assertEqual(image_processor.do_pad , __snake_case ) a : str = self.image_processing_class.from_dict( self.image_processor_dict , size=42 , max_size=84 , pad_and_return_pixel_mask=__snake_case ) self.assertEqual(image_processor.size , {'shortest_edge': 42, 'longest_edge': 84} ) self.assertEqual(image_processor.do_pad , __snake_case ) def lowercase_ ( self : List[str] ): pass def lowercase_ ( self : List[Any] ): # Initialize image_processing a : Union[str, Any] = self.image_processing_class(**self.image_processor_dict ) # create random PIL images a : Union[str, Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , Image.Image ) # Test not batched input a : Any = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values a , a : Optional[int] = self.image_processor_tester.get_expected_values(__snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a , a : Union[str, Any] = self.image_processor_tester.get_expected_values(__snake_case , batched=__snake_case ) a : Dict = image_processing(__snake_case , return_tensors='pt' ).pixel_values self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowercase_ ( self : Any ): # Initialize image_processing a : Any = self.image_processing_class(**self.image_processor_dict ) # create random numpy tensors a : str = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , numpify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , np.ndarray ) # Test not batched input a : str = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values a , a : Any = self.image_processor_tester.get_expected_values(__snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a : str = image_processing(__snake_case , return_tensors='pt' ).pixel_values a , a : Tuple = self.image_processor_tester.get_expected_values(__snake_case , batched=__snake_case ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowercase_ ( self : Optional[int] ): # Initialize image_processing a : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) # create random PyTorch tensors a : List[Any] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , torchify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , torch.Tensor ) # Test not batched input a : List[str] = image_processing(image_inputs[0] , return_tensors='pt' ).pixel_values a , a : List[str] = self.image_processor_tester.get_expected_values(__snake_case ) self.assertEqual( encoded_images.shape , (1, self.image_processor_tester.num_channels, expected_height, expected_width) , ) # Test batched a : Optional[int] = image_processing(__snake_case , return_tensors='pt' ).pixel_values a , a : Any = self.image_processor_tester.get_expected_values(__snake_case , batched=__snake_case ) self.assertEqual( encoded_images.shape , ( self.image_processor_tester.batch_size, self.image_processor_tester.num_channels, expected_height, expected_width, ) , ) def lowercase_ ( self : Optional[int] ): # Initialize image_processings a : Optional[Any] = self.image_processing_class(**self.image_processor_dict ) a : Tuple = self.image_processing_class(do_resize=__snake_case , do_normalize=__snake_case , do_rescale=__snake_case ) # create random PyTorch tensors a : Optional[int] = prepare_image_inputs(self.image_processor_tester , equal_resolution=__snake_case , torchify=__snake_case ) for image in image_inputs: self.assertIsInstance(__snake_case , torch.Tensor ) # Test whether the method "pad" and calling the image processor return the same tensors a : str = image_processing_a.pad(__snake_case , return_tensors='pt' ) a : Optional[Any] = image_processing_a(__snake_case , return_tensors='pt' ) self.assertTrue( torch.allclose(encoded_images_with_method['pixel_values'] , encoded_images['pixel_values'] , atol=1e-4 ) ) @slow def lowercase_ ( self : Union[str, Any] ): # prepare image and target a : Optional[Any] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_annotations.txt' , 'r' ) as f: a : int = json.loads(f.read() ) a : Tuple = {'image_id': 3_97_69, 'annotations': target} # encode them a : str = YolosImageProcessor.from_pretrained('hustvl/yolos-small' ) a : Optional[Any] = image_processing(images=__snake_case , annotations=__snake_case , return_tensors='pt' ) # verify pixel values a : Dict = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , __snake_case ) a : Optional[int] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __snake_case , atol=1e-4 ) ) # verify area a : Union[str, Any] = torch.tensor([5887.9600, 11250.2061, 489353.8438, 837122.7500, 147967.5156, 165732.3438] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __snake_case ) ) # verify boxes a : Optional[Any] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , __snake_case ) a : Any = torch.tensor([0.5503, 0.2765, 0.0604, 0.2215] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __snake_case , atol=1e-3 ) ) # verify image_id a : Any = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __snake_case ) ) # verify is_crowd a : List[str] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __snake_case ) ) # verify class_labels a : Union[str, Any] = torch.tensor([75, 75, 63, 65, 17, 17] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __snake_case ) ) # verify orig_size a : Any = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __snake_case ) ) # verify size a : List[str] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __snake_case ) ) @slow def lowercase_ ( self : List[str] ): # prepare image, target and masks_path a : Optional[int] = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) with open('./tests/fixtures/tests_samples/COCO/coco_panoptic_annotations.txt' , 'r' ) as f: a : List[str] = json.loads(f.read() ) a : Union[str, Any] = {'file_name': '000000039769.png', 'image_id': 3_97_69, 'segments_info': target} a : List[str] = pathlib.Path('./tests/fixtures/tests_samples/COCO/coco_panoptic' ) # encode them a : Union[str, Any] = YolosImageProcessor(format='coco_panoptic' ) a : int = image_processing(images=__snake_case , annotations=__snake_case , masks_path=__snake_case , return_tensors='pt' ) # verify pixel values a : int = torch.Size([1, 3, 8_00, 10_66] ) self.assertEqual(encoding['pixel_values'].shape , __snake_case ) a : Optional[Any] = torch.tensor([0.2796, 0.3138, 0.3481] ) self.assertTrue(torch.allclose(encoding['pixel_values'][0, 0, 0, :3] , __snake_case , atol=1e-4 ) ) # verify area a : List[Any] = torch.tensor([147979.6875, 165527.0469, 484638.5938, 11292.9375, 5879.6562, 7634.1147] ) self.assertTrue(torch.allclose(encoding['labels'][0]['area'] , __snake_case ) ) # verify boxes a : List[Any] = torch.Size([6, 4] ) self.assertEqual(encoding['labels'][0]['boxes'].shape , __snake_case ) a : Dict = torch.tensor([0.2625, 0.5437, 0.4688, 0.8625] ) self.assertTrue(torch.allclose(encoding['labels'][0]['boxes'][0] , __snake_case , atol=1e-3 ) ) # verify image_id a : str = torch.tensor([3_97_69] ) self.assertTrue(torch.allclose(encoding['labels'][0]['image_id'] , __snake_case ) ) # verify is_crowd a : Optional[Any] = torch.tensor([0, 0, 0, 0, 0, 0] ) self.assertTrue(torch.allclose(encoding['labels'][0]['iscrowd'] , __snake_case ) ) # verify class_labels a : Optional[int] = torch.tensor([17, 17, 63, 75, 75, 93] ) self.assertTrue(torch.allclose(encoding['labels'][0]['class_labels'] , __snake_case ) ) # verify masks a : Dict = 82_28_73 self.assertEqual(encoding['labels'][0]['masks'].sum().item() , __snake_case ) # verify orig_size a : int = torch.tensor([4_80, 6_40] ) self.assertTrue(torch.allclose(encoding['labels'][0]['orig_size'] , __snake_case ) ) # verify size a : Optional[int] = torch.tensor([8_00, 10_66] ) self.assertTrue(torch.allclose(encoding['labels'][0]['size'] , __snake_case ) )
297
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def lowerCamelCase__ ( _A , _A ): if inductance <= 0: raise ValueError('Inductance cannot be 0 or negative' ) elif capacitance <= 0: raise ValueError('Capacitance cannot be 0 or negative' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
297
1
'''simple docstring''' # 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 lowerCAmelCase: Dict = TypeVar('T') class a__( Generic[T] ): def __init__( self : str , __snake_case : bool = True ): a : dict[T, list[T]] = {} # dictionary of lists a : Any = directed def lowercase_ ( self : str , __snake_case : T , __snake_case : 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(__snake_case ) self.adj_list[destination_vertex].append(__snake_case ) # 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(__snake_case ) a : Dict = [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(__snake_case ) a : List[str] = [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 : Optional[int] = [destination_vertex] a : List[Any] = [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(__snake_case ) # 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(__snake_case ) a : List[Any] = [] # 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 : Optional[Any] = [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 : int = [destination_vertex] a : str = [] return self def __repr__( self : int ): return pformat(self.adj_list )
297
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase: Any = logging.get_logger(__name__) lowerCAmelCase: Any = {'vocab_file': 'vocab.txt'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } lowerCAmelCase: str = { 'openbmb/cpm-ant-10b': 1_0_2_4, } def lowerCamelCase__ ( _A ): a : Union[str, Any] = collections.OrderedDict() with open(_A , 'r' , encoding='utf-8' ) as reader: a : int = reader.readlines() for index, token in enumerate(_A ): a : int = token.rstrip('\n' ) a : List[Any] = index return vocab class a__( lowerCamelCase__ ): def __init__( self : Dict , __snake_case : Any , __snake_case : Dict="<unk>" , __snake_case : str=2_00 ): a : List[Any] = vocab a : Any = unk_token a : List[str] = max_input_chars_per_word def lowercase_ ( self : Optional[int] , __snake_case : Union[str, Any] ): a : Optional[Any] = list(__snake_case ) if len(__snake_case ) > self.max_input_chars_per_word: return [self.unk_token] a : Any = 0 a : Optional[Any] = [] while start < len(__snake_case ): a : Optional[int] = len(__snake_case ) a : str = None while start < end: a : Optional[Any] = ''.join(chars[start:end] ) if substr in self.vocab: a : List[str] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(__snake_case ) a : List[str] = end return sub_tokens class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = False def __init__( self : Any , __snake_case : str , __snake_case : Tuple="<d>" , __snake_case : List[str]="</d>" , __snake_case : Dict="<s>" , __snake_case : List[Any]="</s>" , __snake_case : int="<pad>" , __snake_case : Any="<unk>" , __snake_case : List[str]="</n>" , __snake_case : int="</_>" , __snake_case : Optional[Any]="left" , **__snake_case : Dict , ): requires_backends(self , ['jieba'] ) super().__init__( bod_token=__snake_case , eod_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , pad_token=__snake_case , unk_token=__snake_case , line_token=__snake_case , space_token=__snake_case , padding_side=__snake_case , **__snake_case , ) a : Union[str, Any] = bod_token a : Any = eod_token a : List[str] = load_vocab(__snake_case ) a : Optional[int] = self.encoder[space_token] a : str = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] a : str = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) a : Tuple = {v: k for k, v in self.encoder.items()} a : List[str] = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def lowercase_ ( self : Optional[int] ): return self.encoder[self.bod_token] @property def lowercase_ ( self : Dict ): return self.encoder[self.eod_token] @property def lowercase_ ( self : Any ): return self.encoder["\n"] @property def lowercase_ ( self : Tuple ): return len(self.encoder ) def lowercase_ ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def lowercase_ ( self : Union[str, Any] , __snake_case : List[str] ): a : List[str] = [] for x in jieba.cut(__snake_case , cut_all=__snake_case ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(__snake_case ) ) return output_tokens def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[Any] , **__snake_case : Optional[Any] ): a : Optional[int] = [i for i in token_ids if i >= 0] a : Any = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(__snake_case , **__snake_case ) def lowercase_ ( self : Optional[int] , __snake_case : int ): return token in self.encoder def lowercase_ ( self : int , __snake_case : List[str] ): return "".join(__snake_case ) def lowercase_ ( self : List[str] , __snake_case : Union[str, Any] ): return self.encoder.get(__snake_case , self.encoder.get(self.unk_token ) ) def lowercase_ ( self : Tuple , __snake_case : List[str] ): return self.decoder.get(__snake_case , self.unk_token ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] = None ): if os.path.isdir(__snake_case ): a : Optional[int] = os.path.join( __snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: a : int = (filename_prefix + '-' if filename_prefix else '') + save_directory a : Any = 0 if " " in self.encoder: a : Union[str, Any] = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: a : Tuple = self.encoder['\n'] del self.encoder["\n"] a : Dict = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) with open(__snake_case , 'w' , encoding='utf-8' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ' Please check that the vocabulary is not corrupted!' ) a : List[Any] = token_index writer.write(token + '\n' ) index += 1 return (vocab_file,) def lowercase_ ( self : Union[str, Any] , __snake_case : List[int] , __snake_case : List[int] = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowercase_ ( self : Dict , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) if token_ids_a is not None: return [1] + ([0] * len(__snake_case )) + [1] + ([0] * len(__snake_case )) return [1] + ([0] * len(__snake_case ))
297
1
'''simple docstring''' import os import textwrap import pyarrow as pa import pytest from datasets import ClassLabel, Features, Image from datasets.packaged_modules.csv.csv import Csv from ..utils import require_pil @pytest.fixture def lowerCamelCase__ ( _A ): a : List[str] = tmp_path / 'file.csv' a : List[Any] = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20\n ' ) with open(_A , 'w' ) as f: f.write(_A ) return str(_A ) @pytest.fixture def lowerCamelCase__ ( _A ): a : Optional[int] = tmp_path / 'malformed_file.csv' a : str = textwrap.dedent( '\\n header1,header2\n 1,2\n 10,20,\n ' ) with open(_A , 'w' ) as f: f.write(_A ) return str(_A ) @pytest.fixture def lowerCamelCase__ ( _A , _A ): a : Tuple = tmp_path / 'csv_with_image.csv' a : List[str] = textwrap.dedent( f"""\ image {image_file} """ ) with open(_A , 'w' ) as f: f.write(_A ) return str(_A ) @pytest.fixture def lowerCamelCase__ ( _A ): a : int = tmp_path / 'csv_with_label.csv' a : str = textwrap.dedent( '\\n label\n good\n bad\n good\n ' ) with open(_A , 'w' ) as f: f.write(_A ) return str(_A ) @pytest.fixture def lowerCamelCase__ ( _A ): a : str = tmp_path / 'csv_with_int_list.csv' a : List[Any] = textwrap.dedent( '\\n int_list\n 1 2 3\n 4 5 6\n 7 8 9\n ' ) with open(_A , 'w' ) as f: f.write(_A ) return str(_A ) def lowerCamelCase__ ( _A , _A , _A ): a : int = Csv() a : Tuple = csv._generate_tables([[csv_file, malformed_csv_file]] ) with pytest.raises(_A , match='Error tokenizing data' ): for _ in generator: pass assert any( record.levelname == 'ERROR' and 'Failed to read file' in record.message and os.path.basename(_A ) in record.message for record in caplog.records ) @require_pil def lowerCamelCase__ ( _A ): with open(_A , encoding='utf-8' ) as f: a : Optional[Any] = f.read().splitlines()[1] a : Dict = Csv(encoding='utf-8' , features=Features({'image': Image()} ) ) a : Dict = csv._generate_tables([[csv_file_with_image]] ) a : int = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('image' ).type == Image()() a : List[Any] = pa_table.to_pydict()['image'] assert generated_content == [{"path": image_file, "bytes": None}] def lowerCamelCase__ ( _A ): with open(_A , encoding='utf-8' ) as f: a : List[Any] = f.read().splitlines()[1:] a : Dict = Csv(encoding='utf-8' , features=Features({'label': ClassLabel(names=['good', 'bad'] )} ) ) a : Tuple = csv._generate_tables([[csv_file_with_label]] ) a : Tuple = pa.concat_tables([table for _, table in generator] ) assert pa_table.schema.field('label' ).type == ClassLabel(names=['good', 'bad'] )() a : Dict = pa_table.to_pydict()['label'] assert generated_content == [ClassLabel(names=['good', 'bad'] ).straint(_A ) for label in labels] def lowerCamelCase__ ( _A ): a : List[str] = Csv(encoding='utf-8' , sep=',' , converters={'int_list': lambda _A : [int(_A ) for i in x.split()]} ) a : Optional[Any] = csv._generate_tables([[csv_file_with_int_list]] ) a : Dict = pa.concat_tables([table for _, table in generator] ) assert pa.types.is_list(pa_table.schema.field('int_list' ).type ) a : Union[str, Any] = pa_table.to_pydict()['int_list'] assert generated_content == [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
297
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class a__( unittest.TestCase ): @slow def lowercase_ ( self : List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[int] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = TFAutoModel.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModel.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Union[str, Any] = TFAutoModelForPreTraining.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = AutoModelForPreTraining.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Union[str, Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForCausalLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Any = TFAutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForCausalLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[str] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[int] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Optional[int] = TFAutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = AutoModelForMaskedLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = TFAutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : str = AutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForSequenceClassification.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSequenceClassification.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : int = TFAutoModelForQuestionAnswering.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModelForQuestionAnswering.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowercase_ ( self : Tuple ): a : List[Any] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[int] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) def lowercase_ ( self : Any ): a : int = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[Any] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 )
297
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase: Union[str, Any] = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[Any] = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Any = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase: List[Any] = logging.get_logger(__name__) lowerCAmelCase: List[Any] = { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """roberta""" def __init__( self : Tuple , __snake_case : List[str]=5_02_65 , __snake_case : int=7_68 , __snake_case : Union[str, Any]=12 , __snake_case : Dict=12 , __snake_case : Tuple=30_72 , __snake_case : Optional[Any]="gelu" , __snake_case : str=0.1 , __snake_case : Any=0.1 , __snake_case : str=5_12 , __snake_case : int=2 , __snake_case : Any=0.02 , __snake_case : int=1e-1_2 , __snake_case : str=1 , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=2 , __snake_case : Optional[int]="absolute" , __snake_case : Union[str, Any]=True , __snake_case : Union[str, Any]=None , **__snake_case : str , ): super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) a : List[str] = vocab_size a : str = hidden_size a : Tuple = num_hidden_layers a : Dict = num_attention_heads a : List[Any] = hidden_act a : str = intermediate_size a : Union[str, Any] = hidden_dropout_prob a : Optional[Any] = attention_probs_dropout_prob a : Any = max_position_embeddings a : Optional[int] = type_vocab_size a : str = initializer_range a : List[Any] = layer_norm_eps a : Optional[int] = position_embedding_type a : Dict = use_cache a : Any = classifier_dropout class a__( lowerCamelCase__ ): @property def lowercase_ ( self : int ): if self.task == "multiple-choice": a : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a : str = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
297
1
'''simple docstring''' import random import sys import numpy as np from matplotlib import pyplot as plt from matplotlib.colors import ListedColormap lowerCAmelCase: List[str] = 'Usage of script: script_name <size_of_canvas:int>' lowerCAmelCase: Optional[int] = [0] * 1_0_0 + [1] * 1_0 random.shuffle(choice) def lowerCamelCase__ ( _A ): a : Dict = [[False for i in range(_A )] for j in range(_A )] return canvas def lowerCamelCase__ ( _A ): for i, row in enumerate(_A ): for j, _ in enumerate(_A ): a : int = bool(random.getrandbits(1 ) ) def lowerCamelCase__ ( _A ): a : Tuple = np.array(_A ) a : int = np.array(create_canvas(current_canvas.shape[0] ) ) for r, row in enumerate(_A ): for c, pt in enumerate(_A ): a : Tuple = __judge_point( _A , current_canvas[r - 1 : r + 2, c - 1 : c + 2] ) a : Tuple = next_gen_canvas del next_gen_canvas # cleaning memory as we move on. a : list[list[bool]] = current_canvas.tolist() return return_canvas def lowerCamelCase__ ( _A , _A ): a : Dict = 0 a : List[str] = 0 # finding dead or alive neighbours count. for i in neighbours: for status in i: if status: alive += 1 else: dead += 1 # handling duplicate entry for focus pt. if pt: alive -= 1 else: dead -= 1 # running the rules of game here. a : int = pt if pt: if alive < 2: a : Union[str, Any] = False elif alive == 2 or alive == 3: a : Optional[Any] = True elif alive > 3: a : Tuple = False else: if alive == 3: a : Any = True return state if __name__ == "__main__": if len(sys.argv) != 2: raise Exception(usage_doc) lowerCAmelCase: Dict = int(sys.argv[1]) # main working structure of this module. lowerCAmelCase: List[Any] = create_canvas(canvas_size) seed(c) lowerCAmelCase , lowerCAmelCase: Any = plt.subplots() fig.show() lowerCAmelCase: str = ListedColormap(['w', 'k']) try: while True: lowerCAmelCase: Dict = run(c) ax.matshow(c, cmap=cmap) fig.canvas.draw() ax.cla() except KeyboardInterrupt: # do nothing. pass
297
'''simple docstring''' def lowerCamelCase__ ( _A ): return 10 - x * x def lowerCamelCase__ ( _A , _A ): # Bolzano theory in order to find if there is a root between a and b if equation(_A ) * equation(_A ) >= 0: raise ValueError('Wrong space!' ) a : Tuple = a while (b - a) >= 0.01: # Find middle point a : Tuple = (a + b) / 2 # Check if middle point is root if equation(_A ) == 0.0: break # Decide the side to repeat the steps if equation(_A ) * equation(_A ) < 0: a : List[str] = c else: a : Tuple = c return c if __name__ == "__main__": import doctest doctest.testmod() print(bisection(-2, 5)) print(bisection(0, 6))
297
1
'''simple docstring''' # this script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: # python ./utils/get_modified_files.py utils src tests examples # # it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered # since the output of this script is fed into Makefile commands it doesn't print a newline after the results import re import subprocess import sys lowerCAmelCase: Optional[Any] = subprocess.check_output('git merge-base main HEAD'.split()).decode('utf-8') lowerCAmelCase: Tuple = ( subprocess.check_output(F"git diff --diff-filter=d --name-only {fork_point_sha}".split()).decode('utf-8').split() ) lowerCAmelCase: Any = '|'.join(sys.argv[1:]) lowerCAmelCase: Any = re.compile(rF"^({joined_dirs}).*?\.py$") lowerCAmelCase: Dict = [x for x in modified_files if regex.match(x)] print(' '.join(relevant_modified_files), end='')
297
'''simple docstring''' import unittest from transformers import EsmConfig, is_torch_available from transformers.testing_utils import TestCasePlus, require_torch, slow, torch_device from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from transformers.models.esm.modeling_esmfold import EsmForProteinFolding class a__: def __init__( self : str , __snake_case : Union[str, Any] , __snake_case : List[str]=13 , __snake_case : Tuple=7 , __snake_case : Optional[Any]=False , __snake_case : Dict=True , __snake_case : List[Any]=False , __snake_case : Optional[int]=False , __snake_case : Optional[Any]=19 , __snake_case : Any=32 , __snake_case : Union[str, Any]=5 , __snake_case : Union[str, Any]=4 , __snake_case : int=37 , __snake_case : Union[str, Any]="gelu" , __snake_case : Optional[Any]=0.1 , __snake_case : List[str]=0.1 , __snake_case : int=5_12 , __snake_case : int=16 , __snake_case : Tuple=2 , __snake_case : str=0.02 , __snake_case : str=3 , __snake_case : Dict=4 , __snake_case : List[Any]=None , ): a : Tuple = parent a : List[str] = batch_size a : Optional[Any] = seq_length a : Tuple = is_training a : Optional[Any] = use_input_mask a : List[Any] = use_token_type_ids a : List[Any] = use_labels a : int = vocab_size a : Union[str, Any] = hidden_size a : Any = num_hidden_layers a : List[str] = num_attention_heads a : int = intermediate_size a : str = hidden_act a : Tuple = hidden_dropout_prob a : Union[str, Any] = attention_probs_dropout_prob a : List[str] = max_position_embeddings a : Any = type_vocab_size a : List[str] = type_sequence_label_size a : Union[str, Any] = initializer_range a : Optional[int] = num_labels a : Optional[Any] = num_choices a : Optional[int] = scope def lowercase_ ( self : List[Any] ): a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.vocab_size ) a : Dict = None if self.use_input_mask: a : Optional[Any] = random_attention_mask([self.batch_size, self.seq_length] ) a : Optional[Any] = None a : Optional[int] = None a : Dict = None if self.use_labels: a : Dict = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : List[Any] = ids_tensor([self.batch_size, self.seq_length] , self.num_labels ) a : List[str] = ids_tensor([self.batch_size] , self.num_choices ) a : Dict = self.get_config() return config, input_ids, input_mask, sequence_labels, token_labels, choice_labels def lowercase_ ( self : List[Any] ): a : Any = EsmConfig( vocab_size=33 , hidden_size=self.hidden_size , pad_token_id=1 , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , max_position_embeddings=self.max_position_embeddings , type_vocab_size=self.type_vocab_size , initializer_range=self.initializer_range , is_folding_model=__snake_case , esmfold_config={'trunk': {'num_blocks': 2}, 'fp16_esm': False} , ) return config def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : str , __snake_case : Optional[Any] , __snake_case : List[Any] , __snake_case : str , __snake_case : Any ): a : Tuple = EsmForProteinFolding(config=__snake_case ).float() model.to(__snake_case ) model.eval() a : Dict = model(__snake_case , attention_mask=__snake_case ) a : Union[str, Any] = model(__snake_case ) a : List[Any] = model(__snake_case ) self.parent.assertEqual(result.positions.shape , (8, self.batch_size, self.seq_length, 14, 3) ) self.parent.assertEqual(result.angles.shape , (8, self.batch_size, self.seq_length, 7, 2) ) def lowercase_ ( self : Optional[Any] ): a : Tuple = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ( a ) , ) : Optional[Any] = config_and_inputs a : Optional[int] = {'input_ids': input_ids, 'attention_mask': input_mask} return config, inputs_dict @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = False lowercase__ = (EsmForProteinFolding,) if is_torch_available() else () lowercase__ = () lowercase__ = {} if is_torch_available() else {} lowercase__ = False def lowercase_ ( self : int ): a : Tuple = EsmFoldModelTester(self ) a : Any = ConfigTester(self , config_class=__snake_case , hidden_size=37 ) def lowercase_ ( self : List[str] ): self.config_tester.run_common_tests() def lowercase_ ( self : Union[str, Any] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) @unittest.skip('Does not support attention outputs' ) def lowercase_ ( self : str ): pass @unittest.skip def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Optional[int] ): pass @unittest.skip('Esm does not support embedding resizing' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support passing input embeds!' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold does not support head pruning.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMfold does not output hidden states in the normal way.' ) def lowercase_ ( self : int ): pass @unittest.skip('ESMFold only has one output format.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('This test doesn\'t work for ESMFold and doesn\'t test core functionality' ) def lowercase_ ( self : Tuple ): pass @unittest.skip('ESMFold does not support input chunking.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t respect you and it certainly doesn\'t respect your initialization arguments.' ) def lowercase_ ( self : List[Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Union[str, Any] ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : Any ): pass @unittest.skip('ESMFold doesn\'t support torchscript compilation.' ) def lowercase_ ( self : List[str] ): pass @unittest.skip('ESMFold doesn\'t support data parallel.' ) def lowercase_ ( self : Dict ): pass @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.' ) def lowercase_ ( self : Union[str, Any] ): pass @require_torch class a__( lowerCamelCase__ ): @slow def lowercase_ ( self : Optional[int] ): a : Optional[Any] = EsmForProteinFolding.from_pretrained('facebook/esmfold_v1' ).float() model.eval() a : int = torch.tensor([[0, 6, 4, 13, 5, 4, 16, 12, 11, 7, 2]] ) a : Any = model(__snake_case )['positions'] a : Dict = torch.tensor([2.5828, 0.7993, -10.9334] , dtype=torch.floataa ) self.assertTrue(torch.allclose(position_outputs[0, 0, 0, 0] , __snake_case , atol=1e-4 ) )
297
1
'''simple docstring''' from ....configuration_utils import PretrainedConfig from ....utils import logging lowerCAmelCase: Optional[int] = logging.get_logger(__name__) lowerCAmelCase: Dict = { 'CarlCochet/trajectory-transformer-halfcheetah-medium-v2': ( 'https://huggingface.co/CarlCochet/trajectory-transformer-halfcheetah-medium-v2/resolve/main/config.json' ), # See all TrajectoryTransformer models at https://huggingface.co/models?filter=trajectory_transformer } class a__( lowerCamelCase__ ): lowercase__ = """trajectory_transformer""" lowercase__ = ["""past_key_values"""] lowercase__ = { """hidden_size""": """n_embd""", """num_attention_heads""": """n_head""", """num_hidden_layers""": """n_layer""", } def __init__( self : Optional[int] , __snake_case : List[str]=1_00 , __snake_case : Tuple=5 , __snake_case : Any=1 , __snake_case : Any=1 , __snake_case : Optional[Any]=2_49 , __snake_case : Tuple=6 , __snake_case : str=17 , __snake_case : Any=25 , __snake_case : Optional[int]=4 , __snake_case : Tuple=4 , __snake_case : List[Any]=1_28 , __snake_case : Dict=0.1 , __snake_case : List[str]=0.1 , __snake_case : Union[str, Any]=0.1 , __snake_case : List[str]=0.0006 , __snake_case : str=5_12 , __snake_case : Optional[int]=0.02 , __snake_case : Any=1e-1_2 , __snake_case : Optional[int]=1 , __snake_case : str=True , __snake_case : Optional[Any]=1 , __snake_case : List[str]=5_02_56 , __snake_case : Optional[int]=5_02_56 , **__snake_case : str , ): a : Union[str, Any] = vocab_size a : Tuple = action_weight a : Any = reward_weight a : Optional[int] = value_weight a : List[str] = max_position_embeddings a : List[str] = block_size a : Any = action_dim a : Optional[Any] = observation_dim a : Dict = transition_dim a : List[Any] = learning_rate a : Union[str, Any] = n_layer a : str = n_head a : Tuple = n_embd a : Any = embd_pdrop a : List[str] = attn_pdrop a : Optional[int] = resid_pdrop a : str = initializer_range a : Optional[int] = layer_norm_eps a : Tuple = kaiming_initializer_range a : List[str] = use_cache super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case )
297
'''simple docstring''' from typing import Optional from torch import nn from .transformer_ad import TransformeraDModel, TransformeraDModelOutput class a__( nn.Module ): def __init__( self : Any , __snake_case : int = 16 , __snake_case : int = 88 , __snake_case : Optional[int] = None , __snake_case : int = 1 , __snake_case : float = 0.0 , __snake_case : int = 32 , __snake_case : Optional[int] = None , __snake_case : bool = False , __snake_case : Optional[int] = None , __snake_case : Optional[int] = None , __snake_case : str = "geglu" , __snake_case : Optional[int] = None , ): super().__init__() a : Optional[int] = nn.ModuleList( [ TransformeraDModel( num_attention_heads=__snake_case , attention_head_dim=__snake_case , in_channels=__snake_case , num_layers=__snake_case , dropout=__snake_case , norm_num_groups=__snake_case , cross_attention_dim=__snake_case , attention_bias=__snake_case , sample_size=__snake_case , num_vector_embeds=__snake_case , activation_fn=__snake_case , num_embeds_ada_norm=__snake_case , ) for _ in range(2 ) ] ) # Variables that can be set by a pipeline: # The ratio of transformer1 to transformer2's output states to be combined during inference a : Union[str, Any] = 0.5 # The shape of `encoder_hidden_states` is expected to be # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)` a : Tuple = [77, 2_57] # Which transformer to use to encode which condition. # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])` a : Any = [1, 0] def lowercase_ ( self : str , __snake_case : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any]=None , __snake_case : int=None , __snake_case : Dict=None , __snake_case : bool = True , ): a : Dict = hidden_states a : Tuple = [] a : Optional[int] = 0 # attention_mask is not used yet for i in range(2 ): # for each of the two transformers, pass the corresponding condition tokens a : Union[str, Any] = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]] a : Tuple = self.transformer_index_for_condition[i] a : Union[str, Any] = self.transformers[transformer_index]( __snake_case , encoder_hidden_states=__snake_case , timestep=__snake_case , cross_attention_kwargs=__snake_case , return_dict=__snake_case , )[0] encoded_states.append(encoded_state - input_states ) tokens_start += self.condition_lengths[i] a : Optional[Any] = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio) a : int = output_states + input_states if not return_dict: return (output_states,) return TransformeraDModelOutput(sample=__snake_case )
297
1
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCamelCase__ ( _A = "laptop" ): a : Any = f"""https://www.amazon.in/laptop/s?k={product}""" a : Tuple = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5', } a : Any = BeautifulSoup(requests.get(_A , headers=_A ).text ) # Initialize a Pandas dataframe with the column titles a : Any = DataFrame( columns=[ 'Product Title', 'Product Link', 'Current Price of the product', 'Product Rating', 'MRP of the product', 'Discount', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( 'div' , attrs={'class': 's-result-item', 'data-component-type': 's-search-result'} , ) , soup.find_all('div' , attrs={'class': 'a-row a-size-base a-color-base'} ) , ): try: a : Optional[int] = item.ha.text a : str = 'https://www.amazon.in/' + item.ha.a['href'] a : List[str] = item.find('span' , attrs={'class': 'a-offscreen'} ).text try: a : Optional[Any] = item.find('span' , attrs={'class': 'a-icon-alt'} ).text except AttributeError: a : Union[str, Any] = 'Not available' try: a : str = ( '₹' + item.find( 'span' , attrs={'class': 'a-price a-text-price'} ).text.split('₹' )[1] ) except AttributeError: a : int = '' try: a : Union[str, Any] = float( ( ( float(product_mrp.strip('₹' ).replace(',' , '' ) ) - float(product_price.strip('₹' ).replace(',' , '' ) ) ) / float(product_mrp.strip('₹' ).replace(',' , '' ) ) ) * 100 ) except ValueError: a : Any = float('nan' ) except AttributeError: pass a : Any = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] a : Any = ' ' a : List[str] = ' ' data_frame.index += 1 return data_frame if __name__ == "__main__": lowerCAmelCase: str = 'headphones' get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
297
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_sentencepiece_available, is_torch_available, ) lowerCAmelCase: Union[str, Any] = { 'configuration_speecht5': [ 'SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP', 'SpeechT5Config', 'SpeechT5HifiGanConfig', ], 'feature_extraction_speecht5': ['SpeechT5FeatureExtractor'], 'processing_speecht5': ['SpeechT5Processor'], } try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[Any] = ['SpeechT5Tokenizer'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Any = [ 'SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST', 'SpeechT5ForSpeechToText', 'SpeechT5ForSpeechToSpeech', 'SpeechT5ForTextToSpeech', 'SpeechT5Model', 'SpeechT5PreTrainedModel', 'SpeechT5HifiGan', ] if TYPE_CHECKING: from .configuration_speechta import ( SPEECHT5_PRETRAINED_CONFIG_ARCHIVE_MAP, SPEECHT5_PRETRAINED_HIFIGAN_CONFIG_ARCHIVE_MAP, SpeechTaConfig, SpeechTaHifiGanConfig, ) from .feature_extraction_speechta import SpeechTaFeatureExtractor from .processing_speechta import SpeechTaProcessor try: if not is_sentencepiece_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .tokenization_speechta import SpeechTaTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_speechta import ( SPEECHT5_PRETRAINED_MODEL_ARCHIVE_LIST, SpeechTaForSpeechToSpeech, SpeechTaForSpeechToText, SpeechTaForTextToSpeech, SpeechTaHifiGan, SpeechTaModel, SpeechTaPreTrainedModel, ) else: import sys lowerCAmelCase: Any = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
'''simple docstring''' from __future__ import annotations def lowerCamelCase__ ( _A , _A , _A , _A ): a : Union[str, Any] = [] a , a : Optional[Any] = input_list[low:mid], input_list[mid : high + 1] while left and right: result.append((left if left[0] <= right[0] else right).pop(0 ) ) a : Dict = result + left + right return input_list def lowerCamelCase__ ( _A ): if len(_A ) <= 1: return input_list a : Optional[Any] = list(_A ) # iteration for two-way merging a : int = 2 while p <= len(_A ): # getting low, high and middle value for merge-sort of single list for i in range(0 , len(_A ) , _A ): a : List[str] = i a : int = i + p - 1 a : List[Any] = (low + high + 1) // 2 a : Union[str, Any] = merge(_A , _A , _A , _A ) # final merge of last two parts if p * 2 >= len(_A ): a : Any = i a : Any = merge(_A , 0 , _A , len(_A ) - 1 ) break p *= 2 return input_list if __name__ == "__main__": lowerCAmelCase: Optional[Any] = input('Enter numbers separated by a comma:\n').strip() if user_input == "": lowerCAmelCase: Tuple = [] else: lowerCAmelCase: List[str] = [int(item.strip()) for item in user_input.split(',')] print(iter_merge_sort(unsorted))
297
'''simple docstring''' # Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available lowerCAmelCase: str = { 'configuration_mgp_str': ['MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP', 'MgpstrConfig'], 'processing_mgp_str': ['MgpstrProcessor'], 'tokenization_mgp_str': ['MgpstrTokenizer'], } try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Optional[Any] = [ 'MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST', 'MgpstrModel', 'MgpstrPreTrainedModel', 'MgpstrForSceneTextRecognition', ] if TYPE_CHECKING: from .configuration_mgp_str import MGP_STR_PRETRAINED_CONFIG_ARCHIVE_MAP, MgpstrConfig from .processing_mgp_str import MgpstrProcessor from .tokenization_mgp_str import MgpstrTokenizer try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_mgp_str import ( MGP_STR_PRETRAINED_MODEL_ARCHIVE_LIST, MgpstrForSceneTextRecognition, MgpstrModel, MgpstrPreTrainedModel, ) else: import sys lowerCAmelCase: Optional[Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
1
'''simple docstring''' from __future__ import annotations def lowerCamelCase__ ( _A , _A ): a : list[list[int]] = [] create_all_state(1 , _A , _A , [] , _A ) return result def lowerCamelCase__ ( _A , _A , _A , _A , _A , ): if level == 0: total_list.append(current_list[:] ) return for i in range(_A , total_number - level + 2 ): current_list.append(_A ) create_all_state(i + 1 , _A , level - 1 , _A , _A ) current_list.pop() def lowerCamelCase__ ( _A ): for i in total_list: print(*_A ) if __name__ == "__main__": lowerCAmelCase: int = 4 lowerCAmelCase: int = 2 lowerCAmelCase: Optional[Any] = generate_all_combinations(n, k) print_all_state(total_list)
297
'''simple docstring''' import json from typing import Dict, List, Optional, Tuple, Union from tokenizers import pre_tokenizers, processors from ...tokenization_utils_base import AddedToken, BatchEncoding, EncodedInput from ...tokenization_utils_fast import PreTrainedTokenizerFast from ...utils import PaddingStrategy, logging from .tokenization_led import LEDTokenizer lowerCAmelCase: Dict = logging.get_logger(__name__) lowerCAmelCase: str = {'vocab_file': 'vocab.json', 'merges_file': 'merges.txt', 'tokenizer_file': 'tokenizer.json'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json', }, 'merges_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt', }, 'tokenizer_file': { 'allenai/led-base-16384': 'https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json', }, } lowerCAmelCase: str = { 'allenai/led-base-16384': 1_6_3_8_4, } class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = LEDTokenizer lowercase__ = ["""input_ids""", """attention_mask"""] def __init__( self : List[Any] , __snake_case : Optional[Any]=None , __snake_case : List[str]=None , __snake_case : Tuple=None , __snake_case : Dict="replace" , __snake_case : int="<s>" , __snake_case : Any="</s>" , __snake_case : Optional[Any]="</s>" , __snake_case : Optional[Any]="<s>" , __snake_case : Optional[Any]="<unk>" , __snake_case : List[str]="<pad>" , __snake_case : int="<mask>" , __snake_case : int=False , __snake_case : str=True , **__snake_case : Tuple , ): super().__init__( __snake_case , __snake_case , tokenizer_file=__snake_case , errors=__snake_case , bos_token=__snake_case , eos_token=__snake_case , sep_token=__snake_case , cls_token=__snake_case , unk_token=__snake_case , pad_token=__snake_case , mask_token=__snake_case , add_prefix_space=__snake_case , trim_offsets=__snake_case , **__snake_case , ) a : str = json.loads(self.backend_tokenizer.pre_tokenizer.__getstate__() ) if pre_tok_state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : List[Any] = getattr(__snake_case , pre_tok_state.pop('type' ) ) a : Optional[Any] = add_prefix_space a : Optional[Any] = pre_tok_class(**__snake_case ) a : Optional[int] = add_prefix_space # the pre_tokenizer is already updated in the GPT2TokenizerFast `__init__` a : Dict = 'post_processor' a : int = getattr(self.backend_tokenizer , __snake_case , __snake_case ) if tokenizer_component_instance: a : Tuple = json.loads(tokenizer_component_instance.__getstate__() ) # The lists 'sep' and 'cls' must be cased in tuples for the object `post_processor_class` if "sep" in state: a : Any = tuple(state['sep'] ) if "cls" in state: a : Any = tuple(state['cls'] ) a : Optional[Any] = False if state.get('add_prefix_space' , __snake_case ) != add_prefix_space: a : Any = add_prefix_space a : Optional[Any] = True if state.get('trim_offsets' , __snake_case ) != trim_offsets: a : List[Any] = trim_offsets a : Union[str, Any] = True if changes_to_apply: a : int = getattr(__snake_case , state.pop('type' ) ) a : List[Any] = component_class(**__snake_case ) setattr(self.backend_tokenizer , __snake_case , __snake_case ) @property # Copied from transformers.models.bart.tokenization_bart_fast.BartTokenizerFast.mask_token with BART->LED def lowercase_ ( self : Dict ): if self._mask_token is None: if self.verbose: logger.error('Using mask_token, but it is not set yet.' ) return None return str(self._mask_token ) @mask_token.setter def lowercase_ ( self : Dict , __snake_case : List[str] ): a : Tuple = AddedToken(__snake_case , lstrip=__snake_case , rstrip=__snake_case ) if isinstance(__snake_case , __snake_case ) else value a : Optional[int] = value def lowercase_ ( self : Optional[Any] , *__snake_case : Any , **__snake_case : Union[str, Any] ): a : Dict = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._batch_encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Union[str, Any] , *__snake_case : Optional[int] , **__snake_case : List[str] ): a : Optional[int] = kwargs.get('is_split_into_words' , __snake_case ) if is_split_into_words and not self.add_prefix_space: raise ValueError( F"""You need to instantiate {self.__class__.__name__} with add_prefix_space=True """ 'to use it with pretokenized inputs.' ) return super()._encode_plus(*__snake_case , **__snake_case ) def lowercase_ ( self : Dict , __snake_case : str , __snake_case : Optional[str] = None ): a : Union[str, Any] = self._tokenizer.model.save(__snake_case , name=__snake_case ) return tuple(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : int=None ): a : List[Any] = [self.bos_token_id] + token_ids_a + [self.eos_token_id] if token_ids_a is None: return output return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id] def lowercase_ ( self : Optional[int] , __snake_case : List[int] , __snake_case : Optional[List[int]] = None ): a : int = [self.sep_token_id] a : Optional[Any] = [self.cls_token_id] if token_ids_a is None: return len(cls + token_ids_a + sep ) * [0] return len(cls + token_ids_a + sep + sep + token_ids_a + sep ) * [0] def lowercase_ ( self : List[str] , __snake_case : Union[Dict[str, EncodedInput], BatchEncoding] , __snake_case : Optional[int] = None , __snake_case : PaddingStrategy = PaddingStrategy.DO_NOT_PAD , __snake_case : Optional[int] = None , __snake_case : Optional[bool] = None , ): a : Optional[Any] = super()._pad( encoded_inputs=__snake_case , max_length=__snake_case , padding_strategy=__snake_case , pad_to_multiple_of=__snake_case , return_attention_mask=__snake_case , ) # Load from model defaults if return_attention_mask is None: a : str = 'attention_mask' in self.model_input_names if return_attention_mask and "global_attention_mask" in encoded_inputs: a : Any = encoded_inputs[self.model_input_names[0]] # `global_attention_mask` need to have the same length as other (sequential) inputs. a : Union[str, Any] = len(encoded_inputs['global_attention_mask'] ) != len(__snake_case ) if needs_to_be_padded: a : str = len(__snake_case ) - len(encoded_inputs['global_attention_mask'] ) if self.padding_side == "right": # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend` a : Dict = ( encoded_inputs['global_attention_mask'] + [-1] * difference ) elif self.padding_side == "left": a : Union[str, Any] = [-1] * difference + encoded_inputs[ 'global_attention_mask' ] else: raise ValueError('Invalid padding strategy:' + str(self.padding_side ) ) return encoded_inputs
297
1
'''simple docstring''' import inspect import unittest from transformers import ViTConfig from transformers.testing_utils import ( require_accelerate, require_torch, require_torch_gpu, require_vision, slow, torch_device, ) from transformers.utils import cached_property, is_torch_available, is_vision_available from ...test_configuration_common import ConfigTester from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor from ...test_pipeline_mixin import PipelineTesterMixin if is_torch_available(): import torch from torch import nn from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST if is_vision_available(): from PIL import Image from transformers import ViTImageProcessor class a__: def __init__( self : Optional[Any] , __snake_case : Optional[int] , __snake_case : Optional[Any]=13 , __snake_case : List[str]=30 , __snake_case : Optional[int]=2 , __snake_case : List[str]=3 , __snake_case : Tuple=True , __snake_case : List[str]=True , __snake_case : List[Any]=32 , __snake_case : Any=5 , __snake_case : Optional[Any]=4 , __snake_case : Union[str, Any]=37 , __snake_case : Optional[int]="gelu" , __snake_case : Optional[int]=0.1 , __snake_case : List[str]=0.1 , __snake_case : int=10 , __snake_case : Tuple=0.02 , __snake_case : Dict=None , __snake_case : str=2 , ): a : Tuple = parent a : Any = batch_size a : Any = image_size a : Dict = patch_size a : str = num_channels a : int = is_training a : List[str] = use_labels a : List[str] = hidden_size a : Union[str, Any] = num_hidden_layers a : List[str] = num_attention_heads a : Optional[Any] = intermediate_size a : Optional[int] = hidden_act a : Dict = hidden_dropout_prob a : List[str] = attention_probs_dropout_prob a : List[str] = type_sequence_label_size a : str = initializer_range a : Dict = scope a : Dict = encoder_stride # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token) a : Union[str, Any] = (image_size // patch_size) ** 2 a : List[Any] = num_patches + 1 def lowercase_ ( self : Tuple ): a : Union[str, Any] = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] ) a : Any = None if self.use_labels: a : Tuple = ids_tensor([self.batch_size] , self.type_sequence_label_size ) a : List[Any] = self.get_config() return config, pixel_values, labels def lowercase_ ( self : Optional[int] ): return ViTConfig( image_size=self.image_size , patch_size=self.patch_size , num_channels=self.num_channels , hidden_size=self.hidden_size , num_hidden_layers=self.num_hidden_layers , num_attention_heads=self.num_attention_heads , intermediate_size=self.intermediate_size , hidden_act=self.hidden_act , hidden_dropout_prob=self.hidden_dropout_prob , attention_probs_dropout_prob=self.attention_probs_dropout_prob , is_decoder=__snake_case , initializer_range=self.initializer_range , encoder_stride=self.encoder_stride , ) def lowercase_ ( self : List[Any] , __snake_case : Optional[Any] , __snake_case : str , __snake_case : List[Any] ): a : List[Any] = ViTModel(config=__snake_case ) model.to(__snake_case ) model.eval() a : Any = model(__snake_case ) self.parent.assertEqual(result.last_hidden_state.shape , (self.batch_size, self.seq_length, self.hidden_size) ) def lowercase_ ( self : Tuple , __snake_case : Any , __snake_case : int , __snake_case : int ): a : Tuple = ViTForMaskedImageModeling(config=__snake_case ) model.to(__snake_case ) model.eval() a : Tuple = model(__snake_case ) self.parent.assertEqual( result.reconstruction.shape , (self.batch_size, self.num_channels, self.image_size, self.image_size) ) # test greyscale images a : Union[str, Any] = 1 a : List[str] = ViTForMaskedImageModeling(__snake_case ) model.to(__snake_case ) model.eval() a : List[Any] = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) a : List[str] = model(__snake_case ) self.parent.assertEqual(result.reconstruction.shape , (self.batch_size, 1, self.image_size, self.image_size) ) def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] , __snake_case : str , __snake_case : Optional[Any] ): a : int = self.type_sequence_label_size a : Optional[int] = ViTForImageClassification(__snake_case ) model.to(__snake_case ) model.eval() a : Dict = model(__snake_case , labels=__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) # test greyscale images a : Tuple = 1 a : Optional[Any] = ViTForImageClassification(__snake_case ) model.to(__snake_case ) model.eval() a : str = floats_tensor([self.batch_size, 1, self.image_size, self.image_size] ) a : Optional[int] = model(__snake_case ) self.parent.assertEqual(result.logits.shape , (self.batch_size, self.type_sequence_label_size) ) def lowercase_ ( self : Any ): a : int = self.prepare_config_and_inputs() ( ( a ) , ( a ) , ( a ) , ) : Optional[Any] = config_and_inputs a : List[Any] = {'pixel_values': pixel_values} return config, inputs_dict @require_torch class a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = ( ( ViTModel, ViTForImageClassification, ViTForMaskedImageModeling, ) if is_torch_available() else () ) lowercase__ = ( {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification} if is_torch_available() else {} ) lowercase__ = True lowercase__ = False lowercase__ = False lowercase__ = False def lowercase_ ( self : str ): a : Any = ViTModelTester(self ) a : int = ConfigTester(self , config_class=__snake_case , has_text_modality=__snake_case , hidden_size=37 ) def lowercase_ ( self : List[str] ): self.config_tester.run_common_tests() @unittest.skip(reason='ViT does not use inputs_embeds' ) def lowercase_ ( self : str ): pass def lowercase_ ( self : Union[str, Any] ): a , a : str = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : Optional[Any] = model_class(__snake_case ) self.assertIsInstance(model.get_input_embeddings() , (nn.Module) ) a : Optional[int] = model.get_output_embeddings() self.assertTrue(x is None or isinstance(__snake_case , nn.Linear ) ) def lowercase_ ( self : List[str] ): a , a : int = self.model_tester.prepare_config_and_inputs_for_common() for model_class in self.all_model_classes: a : Tuple = model_class(__snake_case ) a : int = inspect.signature(model.forward ) # signature.parameters is an OrderedDict => so arg_names order is deterministic a : str = [*signature.parameters.keys()] a : str = ['pixel_values'] self.assertListEqual(arg_names[:1] , __snake_case ) def lowercase_ ( self : Any ): a : Optional[int] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_model(*__snake_case ) def lowercase_ ( self : Optional[int] ): a : Union[str, Any] = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_masked_image_modeling(*__snake_case ) def lowercase_ ( self : Optional[int] ): a : Dict = self.model_tester.prepare_config_and_inputs() self.model_tester.create_and_check_for_image_classification(*__snake_case ) @slow def lowercase_ ( self : Optional[int] ): for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : str = ViTModel.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) def lowerCamelCase__ ( ): a : int = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png' ) return image @require_torch @require_vision class a__( unittest.TestCase ): @cached_property def lowercase_ ( self : List[Any] ): return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224' ) if is_vision_available() else None @slow def lowercase_ ( self : Dict ): a : List[str] = ViTForImageClassification.from_pretrained('google/vit-base-patch16-224' ).to(__snake_case ) a : List[str] = self.default_image_processor a : List[str] = prepare_img() a : int = image_processor(images=__snake_case , return_tensors='pt' ).to(__snake_case ) # forward pass with torch.no_grad(): a : Union[str, Any] = model(**__snake_case ) # verify the logits a : str = torch.Size((1, 10_00) ) self.assertEqual(outputs.logits.shape , __snake_case ) a : Optional[Any] = torch.tensor([-0.2744, 0.8215, -0.0836] ).to(__snake_case ) self.assertTrue(torch.allclose(outputs.logits[0, :3] , __snake_case , atol=1e-4 ) ) @slow def lowercase_ ( self : int ): # ViT models have an `interpolate_pos_encoding` argument in their forward method, # allowing to interpolate the pre-trained position embeddings in order to use # the model on higher resolutions. The DINO model by Facebook AI leverages this # to visualize self-attention on higher resolution images. a : Any = ViTModel.from_pretrained('facebook/dino-vits8' ).to(__snake_case ) a : List[str] = ViTImageProcessor.from_pretrained('facebook/dino-vits8' , size=4_80 ) a : List[Any] = prepare_img() a : Optional[int] = image_processor(images=__snake_case , return_tensors='pt' ) a : Tuple = inputs.pixel_values.to(__snake_case ) # forward pass with torch.no_grad(): a : int = model(__snake_case , interpolate_pos_encoding=__snake_case ) # verify the logits a : Any = torch.Size((1, 36_01, 3_84) ) self.assertEqual(outputs.last_hidden_state.shape , __snake_case ) a : Optional[int] = torch.tensor( [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]] ).to(__snake_case ) self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3] , __snake_case , atol=1e-4 ) ) @slow @require_accelerate @require_torch_gpu def lowercase_ ( self : Dict ): a : Optional[Any] = ViTModel.from_pretrained('facebook/dino-vits8' , torch_dtype=torch.floataa , device_map='auto' ) a : Tuple = self.default_image_processor a : Any = prepare_img() a : List[Any] = image_processor(images=__snake_case , return_tensors='pt' ) a : Tuple = inputs.pixel_values.to(__snake_case ) # forward pass to make sure inference works in fp16 with torch.no_grad(): a : Any = model(__snake_case )
297
'''simple docstring''' import copy import os import cva import numpy as np from matplotlib import pyplot as plt class a__: def __init__( self : Tuple ): a : Optional[int] = '' a : Optional[Any] = '' a : str = [] a : int = 0 a : str = 2_56 a : Union[str, Any] = 0 a : Any = 0 a : Optional[int] = 0 a : List[str] = 0 def lowercase_ ( self : str , __snake_case : str ): a : Any = cva.imread(__snake_case , 0 ) a : Optional[Any] = copy.deepcopy(self.img ) a , a , a : int = plt.hist(self.img.ravel() , 2_56 , [0, 2_56] , label='x' ) a : Optional[int] = np.sum(__snake_case ) for i in range(len(__snake_case ) ): a : Optional[Any] = x[i] / self.k self.sk += prk a : str = (self.L - 1) * self.sk if self.rem != 0: a : Optional[int] = int(last % last ) a : int = int(last + 1 if self.rem >= 0.5 else last ) self.last_list.append(__snake_case ) a : str = int(np.ma.count(self.img ) / self.img[1].size ) a : Optional[int] = self.img[1].size for i in range(self.number_of_cols ): for j in range(self.number_of_rows ): a : Any = self.img[j][i] if num != self.last_list[num]: a : str = self.last_list[num] cva.imwrite('output_data/output.jpg' , self.img ) def lowercase_ ( self : Dict ): plt.hist(self.img.ravel() , 2_56 , [0, 2_56] ) def lowercase_ ( self : List[Any] ): cva.imshow('Output-Image' , self.img ) cva.imshow('Input-Image' , self.original_image ) cva.waitKey(50_00 ) cva.destroyAllWindows() if __name__ == "__main__": lowerCAmelCase: Optional[Any] = os.path.join(os.path.basename(__file__), 'image_data/input.jpg') lowerCAmelCase: Tuple = ConstantStretch() stretcher.stretch(file_path) stretcher.plot_histogram() stretcher.show_image()
297
1
'''simple docstring''' from decimal import Decimal, getcontext from math import ceil, factorial def lowerCamelCase__ ( _A ): if not isinstance(_A , _A ): raise TypeError('Undefined for non-integers' ) elif precision < 1: raise ValueError('Undefined for non-natural numbers' ) a : Union[str, Any] = precision a : Optional[Any] = ceil(precision / 14 ) a : List[str] = 42_6880 * Decimal(1_0005 ).sqrt() a : Any = 1 a : int = 1359_1409 a : Tuple = Decimal(_A ) for k in range(1 , _A ): a : Any = factorial(6 * k ) // (factorial(3 * k ) * factorial(_A ) ** 3) linear_term += 5_4514_0134 exponential_term *= -26_2537_4126_4076_8000 partial_sum += Decimal(multinomial_term * linear_term ) / exponential_term return str(constant_term / partial_sum )[:-1] if __name__ == "__main__": lowerCAmelCase: List[Any] = 5_0 print(F"The first {n} digits of pi is: {pi(n)}")
297
'''simple docstring''' import baseaa import io import json import os from copy import deepcopy from ..optimizer import AcceleratedOptimizer from ..scheduler import AcceleratedScheduler class a__: def __init__( self : List[Any] , __snake_case : Union[str, Any] ): if isinstance(__snake_case , __snake_case ): # Don't modify user's data should they want to reuse it (e.g. in tests), because once we # modified it, it will not be accepted here again, since `auto` values would have been overridden a : str = deepcopy(__snake_case ) elif os.path.exists(__snake_case ): with io.open(__snake_case , 'r' , encoding='utf-8' ) as f: a : Optional[Any] = json.load(__snake_case ) else: try: a : Any = baseaa.urlsafe_baadecode(__snake_case ).decode('utf-8' ) a : Union[str, Any] = json.loads(__snake_case ) except (UnicodeDecodeError, AttributeError, ValueError): raise ValueError( F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}""" ) a : List[str] = config self.set_stage_and_offload() def lowercase_ ( self : List[str] ): # zero stage - this is done as early as possible, before model is created, to allow # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object # during ``zero.Init()`` which needs to know the dtype, and some other hparams. a : Dict = self.get_value('zero_optimization.stage' , -1 ) # offload a : str = False if self.is_zeroa() or self.is_zeroa(): a : Union[str, Any] = set(['cpu', 'nvme'] ) a : Optional[Any] = set( [ self.get_value('zero_optimization.offload_optimizer.device' ), self.get_value('zero_optimization.offload_param.device' ), ] ) if len(offload_devices & offload_devices_valid ) > 0: a : List[str] = True def lowercase_ ( self : Optional[Any] , __snake_case : Optional[Any] ): a : str = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) a : Dict = nodes.pop() for node in nodes: a : List[Any] = config.get(__snake_case ) if config is None: return None, ds_key return config, ds_key def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] , __snake_case : Any=None ): a , a : List[Any] = self.find_config_node(__snake_case ) if config is None: return default return config.get(__snake_case , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Any] , __snake_case : List[str]=False ): a : Optional[Any] = self.config # find the config node of interest if it exists a : List[str] = ds_key_long.split('.' ) for node in nodes: a : str = config a : Dict = config.get(__snake_case ) if config is None: if must_exist: raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}""" ) else: return # if found remove it if parent_config is not None: parent_config.pop(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[int] ): a : Union[str, Any] = self.get_value(__snake_case ) return False if value is None else bool(__snake_case ) def lowercase_ ( self : Union[str, Any] , __snake_case : str ): a : Optional[Any] = self.get_value(__snake_case ) return False if value is None else not bool(__snake_case ) def lowercase_ ( self : Optional[Any] ): return self._stage == 2 def lowercase_ ( self : Union[str, Any] ): return self._stage == 3 def lowercase_ ( self : str ): return self._offload class a__: def __init__( self : Tuple , __snake_case : str ): a : Optional[Any] = engine def lowercase_ ( self : Union[str, Any] , __snake_case : str , **__snake_case : Tuple ): # runs backpropagation and handles mixed precision self.engine.backward(__snake_case , **__snake_case ) # Deepspeed's `engine.step` performs the following operations: # - gradient accumulation check # - gradient clipping # - optimizer step # - zero grad # - checking overflow # - lr_scheduler step (only if engine.lr_scheduler is not None) self.engine.step() # and this plugin overrides the above calls with no-ops when Accelerate runs under # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple # training loop that works transparently under many training regimes. class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : List[str] ): super().__init__(__snake_case , device_placement=__snake_case , scaler=__snake_case ) a : Optional[Any] = hasattr(self.optimizer , 'overflow' ) def lowercase_ ( self : Dict , __snake_case : Dict=None ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed def lowercase_ ( self : Optional[Any] ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed @property def lowercase_ ( self : Tuple ): if self.__has_overflow__: return self.optimizer.overflow return False class a__( lowerCamelCase__ ): def __init__( self : List[Any] , __snake_case : List[Any] , __snake_case : Optional[Any] ): super().__init__(__snake_case , __snake_case ) def lowercase_ ( self : Any ): pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed class a__: def __init__( self : List[Any] , __snake_case : str , __snake_case : Dict=0.001 , __snake_case : Union[str, Any]=0 , **__snake_case : List[Any] ): a : Optional[Any] = params a : str = lr a : List[str] = weight_decay a : str = kwargs class a__: def __init__( self : str , __snake_case : Optional[Any] , __snake_case : List[str]=None , __snake_case : Tuple=0 , **__snake_case : Any ): a : Union[str, Any] = optimizer a : Any = total_num_steps a : List[str] = warmup_num_steps a : int = kwargs
297
1
'''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 a__( lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = StableDiffusionSAGPipeline lowercase__ = TEXT_TO_IMAGE_PARAMS lowercase__ = TEXT_TO_IMAGE_BATCH_PARAMS lowercase__ = TEXT_TO_IMAGE_IMAGE_PARAMS lowercase__ = TEXT_TO_IMAGE_IMAGE_PARAMS lowercase__ = False def lowercase_ ( self : Tuple ): torch.manual_seed(0 ) a : Any = UNetaDConditionModel( block_out_channels=(32, 64) , layers_per_block=2 , sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('DownBlock2D', 'CrossAttnDownBlock2D') , up_block_types=('CrossAttnUpBlock2D', 'UpBlock2D') , cross_attention_dim=32 , ) a : str = DDIMScheduler( beta_start=0.00085 , beta_end=0.012 , beta_schedule='scaled_linear' , clip_sample=__snake_case , set_alpha_to_one=__snake_case , ) torch.manual_seed(0 ) a : List[str] = AutoencoderKL( block_out_channels=[32, 64] , in_channels=3 , out_channels=3 , down_block_types=['DownEncoderBlock2D', 'DownEncoderBlock2D'] , up_block_types=['UpDecoderBlock2D', 'UpDecoderBlock2D'] , latent_channels=4 , ) torch.manual_seed(0 ) a : Tuple = CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) a : List[str] = CLIPTextModel(__snake_case ) a : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) a : Union[str, Any] = { 'unet': unet, 'scheduler': scheduler, 'vae': vae, 'text_encoder': text_encoder, 'tokenizer': tokenizer, 'safety_checker': None, 'feature_extractor': None, } return components def lowercase_ ( self : str , __snake_case : str , __snake_case : Union[str, Any]=0 ): if str(__snake_case ).startswith('mps' ): a : int = torch.manual_seed(__snake_case ) else: a : int = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) a : Dict = { 'prompt': '.', 'generator': generator, 'num_inference_steps': 2, 'guidance_scale': 1.0, 'sag_scale': 1.0, 'output_type': 'numpy', } return inputs def lowercase_ ( self : List[str] ): super().test_inference_batch_single_identical(expected_max_diff=3e-3 ) @slow @require_torch_gpu class a__( unittest.TestCase ): def lowercase_ ( self : Optional[Any] ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Tuple ): a : Union[str, Any] = StableDiffusionSAGPipeline.from_pretrained('CompVis/stable-diffusion-v1-4' ) a : List[Any] = sag_pipe.to(__snake_case ) sag_pipe.set_progress_bar_config(disable=__snake_case ) a : str = '.' a : Optional[int] = torch.manual_seed(0 ) a : Optional[Any] = sag_pipe( [prompt] , generator=__snake_case , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='np' ) a : Any = output.images a : Any = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) a : List[Any] = np.array([0.1568, 0.1738, 0.1695, 0.1693, 0.1507, 0.1705, 0.1547, 0.1751, 0.1949] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def lowercase_ ( self : List[Any] ): a : Union[str, Any] = StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) a : Optional[int] = sag_pipe.to(__snake_case ) sag_pipe.set_progress_bar_config(disable=__snake_case ) a : Optional[int] = '.' a : str = torch.manual_seed(0 ) a : Dict = sag_pipe( [prompt] , generator=__snake_case , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='np' ) a : Dict = output.images a : List[str] = image[0, -3:, -3:, -1] assert image.shape == (1, 5_12, 5_12, 3) a : List[str] = np.array([0.3459, 0.2876, 0.2537, 0.3002, 0.2671, 0.2160, 0.3026, 0.2262, 0.2371] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 5e-2 def lowercase_ ( self : Any ): a : Optional[int] = StableDiffusionSAGPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base' ) a : Tuple = sag_pipe.to(__snake_case ) sag_pipe.set_progress_bar_config(disable=__snake_case ) a : Optional[int] = '.' a : List[Any] = torch.manual_seed(0 ) a : Optional[Any] = sag_pipe( [prompt] , width=7_68 , height=5_12 , generator=__snake_case , guidance_scale=7.5 , sag_scale=1.0 , num_inference_steps=20 , output_type='np' , ) a : Optional[int] = output.images assert image.shape == (1, 5_12, 7_68, 3)
297
'''simple docstring''' import ast import os import re import shutil import tempfile import unittest from unittest import mock import torch from accelerate.test_utils.examples import compare_against_test from accelerate.test_utils.testing import TempDirTestCase, require_trackers, run_command, slow from accelerate.utils import write_basic_config # DataLoaders built from `test_samples/MRPC` for quick testing # Should mock `{script_name}.get_dataloaders` via: # @mock.patch("{script_name}.get_dataloaders", mocked_dataloaders) lowerCAmelCase: int = [ 'cross_validation.py', 'gradient_accumulation.py', 'local_sgd.py', 'multi_process_metrics.py', 'memory.py', 'automatic_gradient_accumulation.py', 'fsdp_with_peak_mem_tracking.py', 'deepspeed_with_config_support.py', 'megatron_lm_gpt_pretraining.py', ] class a__( unittest.TestCase ): def lowercase_ ( self : int , __snake_case : str , __snake_case : bool , __snake_case : str = None , __snake_case : list = None ): a : Optional[int] = None a : Tuple = os.path.abspath(os.path.join('examples' , 'by_feature' ) ) a : List[str] = os.path.abspath('examples' ) for item in os.listdir(__snake_case ): if item not in EXCLUDE_EXAMPLES: a : int = os.path.join(__snake_case , __snake_case ) if os.path.isfile(__snake_case ) and ".py" in item_path: with self.subTest( tested_script=__snake_case , feature_script=__snake_case , tested_section='main()' if parser_only else 'training_function()' , ): a : List[Any] = compare_against_test( os.path.join(__snake_case , __snake_case ) , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = '\n'.join(__snake_case ) if special_strings is not None: for string in special_strings: a : Union[str, Any] = diff.replace(__snake_case , '' ) self.assertEqual(__snake_case , '' ) def lowercase_ ( self : Optional[Any] ): self.one_complete_example('complete_nlp_example.py' , __snake_case ) self.one_complete_example('complete_nlp_example.py' , __snake_case ) def lowercase_ ( self : Any ): a : Dict = os.path.abspath(os.path.join('examples' , 'cv_example.py' ) ) a : int = [ ' ' * 16 + '{\n\n', ' ' * 20 + '"accuracy": eval_metric["accuracy"],\n\n', ' ' * 20 + '"f1": eval_metric["f1"],\n\n', ' ' * 20 + '"train_loss": total_loss.item() / len(train_dataloader),\n\n', ' ' * 20 + '"epoch": epoch,\n\n', ' ' * 16 + '},\n\n', ' ' * 16 + 'step=epoch,\n', ' ' * 12, ' ' * 8 + 'for step, batch in enumerate(active_dataloader):\n', ] self.one_complete_example('complete_cv_example.py' , __snake_case , __snake_case , __snake_case ) self.one_complete_example('complete_cv_example.py' , __snake_case , __snake_case , __snake_case ) @mock.patch.dict(os.environ , {"""TESTING_MOCKED_DATALOADERS""": """1"""} ) class a__( lowerCamelCase__ ): lowercase__ = False @classmethod def lowercase_ ( cls : Optional[int] ): super().setUpClass() a : List[str] = tempfile.mkdtemp() a : Tuple = os.path.join(cls._tmpdir , 'default_config.yml' ) write_basic_config(save_location=cls.configPath ) a : Optional[int] = ['accelerate', 'launch', '--config_file', cls.configPath] @classmethod def lowercase_ ( cls : Optional[int] ): super().tearDownClass() shutil.rmtree(cls._tmpdir ) def lowercase_ ( self : Tuple ): a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps epoch --output_dir {self.tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'epoch_0' ) ) ) def lowercase_ ( self : Dict ): a : Union[str, Any] = F""" examples/by_feature/checkpointing.py --checkpointing_steps 1 --output_dir {self.tmpdir} """.split() a : int = run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(self.tmpdir , 'step_2' ) ) ) def lowercase_ ( self : Any ): a : Tuple = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "epoch_0" )} """.split() a : int = run_command(self._launch_args + testargs , return_stdout=__snake_case ) self.assertNotIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) def lowercase_ ( self : int ): a : Optional[int] = F""" examples/by_feature/checkpointing.py --resume_from_checkpoint {os.path.join(self.tmpdir , "step_2" )} """.split() a : Union[str, Any] = run_command(self._launch_args + testargs , return_stdout=__snake_case ) if torch.cuda.is_available(): a : Any = torch.cuda.device_count() else: a : str = 1 if num_processes > 1: self.assertNotIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) else: self.assertIn('epoch 0:' , __snake_case ) self.assertIn('epoch 1:' , __snake_case ) @slow def lowercase_ ( self : Tuple ): a : Tuple = '\n examples/by_feature/cross_validation.py\n --num_folds 2\n '.split() with mock.patch.dict(os.environ , {'TESTING_MOCKED_DATALOADERS': '0'} ): a : Any = run_command(self._launch_args + testargs , return_stdout=__snake_case ) a : Optional[Any] = re.findall('({.+})' , __snake_case ) a : str = [r for r in results if 'accuracy' in r][-1] a : str = ast.literal_eval(__snake_case ) self.assertGreaterEqual(results['accuracy'] , 0.75 ) def lowercase_ ( self : Optional[int] ): a : int = ['examples/by_feature/multi_process_metrics.py'] run_command(self._launch_args + testargs ) @require_trackers @mock.patch.dict(os.environ , {'WANDB_MODE': 'offline'} ) def lowercase_ ( self : Optional[int] ): with tempfile.TemporaryDirectory() as tmpdir: a : Optional[Any] = F""" examples/by_feature/tracking.py --with_tracking --project_dir {tmpdir} """.split() run_command(self._launch_args + testargs ) self.assertTrue(os.path.exists(os.path.join(__snake_case , 'tracking' ) ) ) def lowercase_ ( self : List[str] ): a : Optional[Any] = ['examples/by_feature/gradient_accumulation.py'] run_command(self._launch_args + testargs ) def lowercase_ ( self : int ): a : Optional[Any] = ['examples/by_feature/local_sgd.py'] run_command(self._launch_args + testargs )
297
1
'''simple docstring''' import logging import os import sys from dataclasses import dataclass, field from importlib import import_module from typing import Dict, List, Optional, Tuple import numpy as np from seqeval.metrics import accuracy_score, fa_score, precision_score, recall_score from torch import nn from utils_ner import Split, TokenClassificationDataset, TokenClassificationTask import transformers from transformers import ( AutoConfig, AutoModelForTokenClassification, AutoTokenizer, DataCollatorWithPadding, EvalPrediction, HfArgumentParser, Trainer, TrainingArguments, set_seed, ) from transformers.trainer_utils import is_main_process lowerCAmelCase: Any = logging.getLogger(__name__) @dataclass class a__: lowercase__ = field( metadata={"""help""": """Path to pretrained model or model identifier from huggingface.co/models"""} ) lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """Pretrained config name or path if not the same as model_name"""} ) lowercase__ = field( default="""NER""" , metadata={"""help""": """Task type to fine tune in training (e.g. NER, POS, etc)"""} ) lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """Pretrained tokenizer name or path if not the same as model_name"""} ) lowercase__ = field(default=lowerCamelCase__ , metadata={"""help""": """Set this flag to use fast tokenization."""} ) # If you want to tweak more attributes on your tokenizer, you should do it in a distinct script, # or just modify its tokenizer_config.json. lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """Where do you want to store the pretrained models downloaded from huggingface.co"""} , ) @dataclass class a__: lowercase__ = field( metadata={"""help""": """The input data dir. Should contain the .txt files for a CoNLL-2003-formatted task."""} ) lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """Path to a file containing all labels. If not specified, CoNLL-2003 labels are used."""} , ) lowercase__ = field( default=1_28 , metadata={ """help""": ( """The maximum total input sequence length after tokenization. Sequences longer """ """than this will be truncated, sequences shorter will be padded.""" ) } , ) lowercase__ = field( default=lowerCamelCase__ , metadata={"""help""": """Overwrite the cached training and evaluation sets"""} ) def lowerCamelCase__ ( ): # See all possible arguments in src/transformers/training_args.py # or by passing the --help flag to this script. # We now keep distinct sets of args, for a cleaner separation of concerns. a : Tuple = 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 : Optional[Any] = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1] ) ) else: a , a , a : Dict = parser.parse_args_into_dataclasses() if ( os.path.exists(training_args.output_dir ) and os.listdir(training_args.output_dir ) and training_args.do_train and not training_args.overwrite_output_dir ): raise ValueError( f"""Output directory ({training_args.output_dir}) already exists and is not empty. Use""" ' --overwrite_output_dir to overcome.' ) a : Union[str, Any] = import_module('tasks' ) try: a : Optional[int] = getattr(_A , model_args.task_type ) a : TokenClassificationTask = token_classification_task_clazz() except AttributeError: raise ValueError( f"""Task {model_args.task_type} needs to be defined as a TokenClassificationTask subclass in {module}. """ f"""Available tasks classes are: {TokenClassificationTask.__subclasses__()}""" ) # Setup logging logging.basicConfig( format='%(asctime)s - %(levelname)s - %(name)s - %(message)s' , datefmt='%m/%d/%Y %H:%M:%S' , level=logging.INFO if training_args.local_rank in [-1, 0] else logging.WARN , ) logger.warning( 'Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s' , training_args.local_rank , training_args.device , training_args.n_gpu , bool(training_args.local_rank != -1 ) , training_args.fpaa , ) # Set the verbosity to info of the Transformers logger (on main process only): if is_main_process(training_args.local_rank ): transformers.utils.logging.set_verbosity_info() transformers.utils.logging.enable_default_handler() transformers.utils.logging.enable_explicit_format() logger.info('Training/evaluation parameters %s' , _A ) # Set seed set_seed(training_args.seed ) # Prepare CONLL-2003 task a : int = token_classification_task.get_labels(data_args.labels ) a : Dict[int, str] = dict(enumerate(_A ) ) a : Optional[Any] = len(_A ) # Load pretrained model and tokenizer # # Distributed training: # The .from_pretrained methods guarantee that only one local process can concurrently # download model & vocab. a : List[Any] = AutoConfig.from_pretrained( model_args.config_name if model_args.config_name else model_args.model_name_or_path , num_labels=_A , idalabel=_A , labelaid={label: i for i, label in enumerate(_A )} , cache_dir=model_args.cache_dir , ) a : Any = AutoTokenizer.from_pretrained( model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path , cache_dir=model_args.cache_dir , use_fast=model_args.use_fast , ) a : Optional[int] = AutoModelForTokenClassification.from_pretrained( model_args.model_name_or_path , from_tf=bool('.ckpt' in model_args.model_name_or_path ) , config=_A , cache_dir=model_args.cache_dir , ) # Get datasets a : Optional[Any] = ( TokenClassificationDataset( token_classification_task=_A , data_dir=data_args.data_dir , tokenizer=_A , labels=_A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.train , ) if training_args.do_train else None ) a : Optional[int] = ( TokenClassificationDataset( token_classification_task=_A , data_dir=data_args.data_dir , tokenizer=_A , labels=_A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.dev , ) if training_args.do_eval else None ) def align_predictions(_A , _A ) -> Tuple[List[int], List[int]]: a : Dict = np.argmax(_A , axis=2 ) a , a : Dict = preds.shape a : Any = [[] for _ in range(_A )] a : Dict = [[] for _ in range(_A )] for i in range(_A ): for j in range(_A ): if label_ids[i, j] != nn.CrossEntropyLoss().ignore_index: out_label_list[i].append(label_map[label_ids[i][j]] ) preds_list[i].append(label_map[preds[i][j]] ) return preds_list, out_label_list def compute_metrics(_A ) -> Dict: a , a : Any = align_predictions(p.predictions , p.label_ids ) return { "accuracy_score": accuracy_score(_A , _A ), "precision": precision_score(_A , _A ), "recall": recall_score(_A , _A ), "f1": fa_score(_A , _A ), } # Data collator a : Optional[int] = DataCollatorWithPadding(_A , pad_to_multiple_of=8 ) if training_args.fpaa else None # Initialize our Trainer a : Dict = Trainer( model=_A , args=_A , train_dataset=_A , eval_dataset=_A , compute_metrics=_A , data_collator=_A , ) # Training if training_args.do_train: trainer.train( model_path=model_args.model_name_or_path if os.path.isdir(model_args.model_name_or_path ) else None ) trainer.save_model() # For convenience, we also re-save the tokenizer to the same directory, # so that you can share your model easily on huggingface.co/models =) if trainer.is_world_process_zero(): tokenizer.save_pretrained(training_args.output_dir ) # Evaluation a : Optional[Any] = {} if training_args.do_eval: logger.info('*** Evaluate ***' ) a : Optional[int] = trainer.evaluate() a : List[Any] = os.path.join(training_args.output_dir , 'eval_results.txt' ) if trainer.is_world_process_zero(): with open(_A , 'w' ) as writer: logger.info('***** Eval results *****' ) for key, value in result.items(): logger.info(' %s = %s' , _A , _A ) writer.write('%s = %s\n' % (key, value) ) results.update(_A ) # Predict if training_args.do_predict: a : List[str] = TokenClassificationDataset( token_classification_task=_A , data_dir=data_args.data_dir , tokenizer=_A , labels=_A , model_type=config.model_type , max_seq_length=data_args.max_seq_length , overwrite_cache=data_args.overwrite_cache , mode=Split.test , ) a , a , a : int = trainer.predict(_A ) a , a : Optional[Any] = align_predictions(_A , _A ) a : List[str] = os.path.join(training_args.output_dir , 'test_results.txt' ) if trainer.is_world_process_zero(): with open(_A , 'w' ) as writer: for key, value in metrics.items(): logger.info(' %s = %s' , _A , _A ) writer.write('%s = %s\n' % (key, value) ) # Save predictions a : int = os.path.join(training_args.output_dir , 'test_predictions.txt' ) if trainer.is_world_process_zero(): with open(_A , 'w' ) as writer: with open(os.path.join(data_args.data_dir , 'test.txt' ) , 'r' ) as f: token_classification_task.write_predictions_to_file(_A , _A , _A ) return results def lowerCamelCase__ ( _A ): # For xla_spawn (TPUs) main() if __name__ == "__main__": main()
297
'''simple docstring''' import json import multiprocessing import os import re from collections import defaultdict import torch from accelerate import Accelerator from accelerate.utils import set_seed from arguments import HumanEvalArguments from datasets import load_dataset, load_metric from torch.utils.data import IterableDataset from torch.utils.data.dataloader import DataLoader from tqdm import tqdm import transformers from transformers import AutoModelForCausalLM, AutoTokenizer, HfArgumentParser, StoppingCriteria, StoppingCriteriaList lowerCAmelCase: List[str] = ['\nclass', '\ndef', '\n#', '\n@', '\nprint', '\nif'] class a__( lowerCamelCase__ ): def __init__( self : Any , __snake_case : List[str] , __snake_case : Union[str, Any] , __snake_case : List[Any]=None , __snake_case : Optional[Any]=1 ): a : Union[str, Any] = tokenizer a : Union[str, Any] = dataset a : Any = len(__snake_case ) if n_tasks is None else n_tasks a : List[str] = n_copies def __iter__( self : str ): a : List[Any] = [] for task in range(self.n_tasks ): # without strip, the model generate commented codes ... prompts.append(self.tokenizer.eos_token + self.dataset[task]['prompt'].strip() ) a : Dict = self.tokenizer(__snake_case , padding=__snake_case , return_tensors='pt' ) for task in range(self.n_tasks ): for _ in range(self.n_copies ): yield { "ids": outputs.input_ids[task], "task_id": task, "input_len": outputs.attention_mask[task].sum(), } class a__( lowerCamelCase__ ): def __init__( self : Union[str, Any] , __snake_case : int , __snake_case : Optional[Any] , __snake_case : str ): a : Dict = start_length a : Dict = eof_strings a : str = tokenizer def __call__( self : Optional[Any] , __snake_case : Optional[Any] , __snake_case : Any , **__snake_case : Union[str, Any] ): a : int = self.tokenizer.batch_decode(input_ids[:, self.start_length :] ) a : Optional[int] = [] for decoded_generation in decoded_generations: done.append(any(stop_string in decoded_generation for stop_string in self.eof_strings ) ) return all(__snake_case ) def lowerCamelCase__ ( _A ): a : Optional[Any] = re.split('(%s)' % '|'.join(_A ) , _A ) # last string should be "" return "".join(string_list[:-2] ) def lowerCamelCase__ ( _A , _A , _A , _A , _A , _A=20 , **_A ): a : Optional[Any] = defaultdict(_A ) # dict of list of generated tokens for step, batch in tqdm(enumerate(_A ) ): with torch.no_grad(): a : Optional[Any] = batch['ids'].shape[-1] a : Optional[Any] = accelerator.unwrap_model(_A ).generate( input_ids=batch['ids'][:, : batch['input_len']] , num_return_sequences=_A , **_A ) # each task is generated batch_size times a : Tuple = batch['task_id'].repeat(_A ) a : List[Any] = accelerator.pad_across_processes( _A , dim=1 , pad_index=tokenizer.pad_token_id ) a , a : Union[str, Any] = accelerator.gather((generated_tokens, generated_tasks) ) a : List[str] = generated_tokens.cpu().numpy() a : int = generated_tasks.cpu().numpy() for task, generated_tokens in zip(_A , _A ): gen_token_dict[task].append(_A ) a : Any = [[] for _ in range(_A )] for task, generated_tokens in gen_token_dict.items(): for s in generated_tokens: a : Optional[int] = tokenizer.decode(_A , skip_special_tokens=_A , clean_up_tokenization_spaces=_A ) code_gens[task].append(remove_last_block(_A ) ) return code_gens def lowerCamelCase__ ( ): # Setup configuration a : Dict = HfArgumentParser(_A ) a : Any = parser.parse_args() transformers.logging.set_verbosity_error() # enables code execution in code_eval metric a : List[Any] = args.HF_ALLOW_CODE_EVAL # make sure tokenizer plays nice with multiprocessing a : int = 'false' if args.num_workers is None: a : Dict = multiprocessing.cpu_count() # Use dataset load to feed to accelerate a : List[Any] = Accelerator() set_seed(args.seed , device_specific=_A ) # Load model and tokenizer a : Dict = AutoTokenizer.from_pretrained(args.model_ckpt ) a : str = tokenizer.eos_token a : List[Any] = AutoModelForCausalLM.from_pretrained(args.model_ckpt ) # Generation settings a : Optional[Any] = { 'do_sample': args.do_sample, 'temperature': args.temperature, 'max_new_tokens': args.max_new_tokens, 'top_p': args.top_p, 'top_k': args.top_k, 'stopping_criteria': StoppingCriteriaList([EndOfFunctionCriteria(0 , _A , _A )] ), } # Load evaluation dataset and metric a : Optional[int] = load_dataset('openai_humaneval' ) a : Optional[Any] = load_metric('code_eval' ) a : Optional[int] = args.num_tasks if args.num_tasks is not None else len(human_eval['test'] ) a : Optional[Any] = args.n_samples // args.batch_size a : Any = TokenizedDataset(_A , human_eval['test'] , n_copies=_A , n_tasks=_A ) # do not confuse args.batch_size, which is actually the num_return_sequences a : int = DataLoader(_A , batch_size=1 ) # Run a quick test to see if code evaluation is enabled try: a : int = code_eval_metric.compute(references=[''] , predictions=[['']] ) except ValueError as exception: print( 'Code evaluation not enabled. Read the warning below carefully and then use `--HF_ALLOW_CODE_EVAL="1"`' ' flag to enable code evaluation.' ) raise exception a , a : int = accelerator.prepare(_A , _A ) a : int = complete_code( _A , _A , _A , _A , n_tasks=_A , batch_size=args.batch_size , **_A , ) if accelerator.is_main_process: a : List[str] = [] for task in tqdm(range(_A ) ): a : int = human_eval['test'][task]['test'] a : int = f"""check({human_eval["test"][task]["entry_point"]})""" references.append('\n' + test_func + '\n' + entry_point ) # Evaluate completions with "code_eval" metric a , a : Tuple = code_eval_metric.compute( references=_A , predictions=_A , num_workers=args.num_workers ) print(f"""Results: {pass_at_k}""" ) # Save results to json file with open(args.output_file , 'w' ) as fp: json.dump(_A , _A ) # For some reason the folliwng seems to be necessary sometimes for code_eval to work nice with multiprocessing # https://stackoverflow.com/questions/60804599/python-multiprocessing-keeps-spawning-the-whole-script if __name__ == "__main__": main()
297
1
'''simple docstring''' from __future__ import annotations lowerCAmelCase: List[str] = tuple[int, int, int] lowerCAmelCase: str = tuple[str, str, str] # used alphabet -------------------------- # from string.ascii_uppercase lowerCAmelCase: List[Any] = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' # -------------------------- default selection -------------------------- # rotors -------------------------- lowerCAmelCase: List[Any] = 'EGZWVONAHDCLFQMSIPJBYUKXTR' lowerCAmelCase: int = 'FOBHMDKEXQNRAULPGSJVTYICZW' lowerCAmelCase: Any = 'ZJXESIUQLHAVRMDOYGTNFWPBKC' # reflector -------------------------- lowerCAmelCase: Optional[int] = { 'A': 'N', 'N': 'A', 'B': 'O', 'O': 'B', 'C': 'P', 'P': 'C', 'D': 'Q', 'Q': 'D', 'E': 'R', 'R': 'E', 'F': 'S', 'S': 'F', 'G': 'T', 'T': 'G', 'H': 'U', 'U': 'H', 'I': 'V', 'V': 'I', 'J': 'W', 'W': 'J', 'K': 'X', 'X': 'K', 'L': 'Y', 'Y': 'L', 'M': 'Z', 'Z': 'M', } # -------------------------- extra rotors -------------------------- lowerCAmelCase: str = 'RMDJXFUWGISLHVTCQNKYPBEZOA' lowerCAmelCase: List[Any] = 'SGLCPQWZHKXAREONTFBVIYJUDM' lowerCAmelCase: Dict = 'HVSICLTYKQUBXDWAJZOMFGPREN' lowerCAmelCase: List[Any] = 'RZWQHFMVDBKICJLNTUXAGYPSOE' lowerCAmelCase: Union[str, Any] = 'LFKIJODBEGAMQPXVUHYSTCZRWN' lowerCAmelCase: Any = 'KOAEGVDHXPQZMLFTYWJNBRCIUS' def lowerCamelCase__ ( _A , _A , _A ): # Checks if there are 3 unique rotors if (unique_rotsel := len(set(_A ) )) < 3: a : Union[str, Any] = f"""Please use 3 unique rotors (not {unique_rotsel})""" raise Exception(_A ) # Checks if rotor positions are valid a , a , a : Union[str, Any] = rotpos if not 0 < rotorposa <= len(_A ): a : Tuple = f"""First rotor position is not within range of 1..26 ({rotorposa}""" raise ValueError(_A ) if not 0 < rotorposa <= len(_A ): a : Optional[int] = f"""Second rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(_A ) if not 0 < rotorposa <= len(_A ): a : Any = f"""Third rotor position is not within range of 1..26 ({rotorposa})""" raise ValueError(_A ) # Validates string and returns dict a : Union[str, Any] = _plugboard(_A ) return rotpos, rotsel, pbdict def lowerCamelCase__ ( _A ): # tests the input string if it # a) is type string # b) has even length (so pairs can be made) if not isinstance(_A , _A ): a : Optional[Any] = f"""Plugboard setting isn't type string ({type(_A )})""" raise TypeError(_A ) elif len(_A ) % 2 != 0: a : List[str] = f"""Odd number of symbols ({len(_A )})""" raise Exception(_A ) elif pbstring == "": return {} pbstring.replace(' ' , '' ) # Checks if all characters are unique a : Dict = set() for i in pbstring: if i not in abc: a : Dict = f"""'{i}' not in list of symbols""" raise Exception(_A ) elif i in tmppbl: a : str = f"""Duplicate symbol ({i})""" raise Exception(_A ) else: tmppbl.add(_A ) del tmppbl # Created the dictionary a : List[str] = {} for j in range(0 , len(_A ) - 1 , 2 ): a : int = pbstring[j + 1] a : str = pbstring[j] return pb def lowerCamelCase__ ( _A , _A , _A = (rotora, rotora, rotora) , _A = "" , ): a : Tuple = text.upper() a , a , a : List[str] = _validator( _A , _A , plugb.upper() ) a , a , a : Tuple = rotor_position a , a , a : Optional[int] = rotor_selection rotorposa -= 1 rotorposa -= 1 rotorposa -= 1 a : Optional[Any] = [] # encryption/decryption process -------------------------- for symbol in text: if symbol in abc: # 1st plugboard -------------------------- if symbol in plugboard: a : Tuple = plugboard[symbol] # rotor ra -------------------------- a : Tuple = abc.index(_A ) + rotorposa a : Dict = rotora[index % len(_A )] # rotor rb -------------------------- a : Optional[Any] = abc.index(_A ) + rotorposa a : List[Any] = rotora[index % len(_A )] # rotor rc -------------------------- a : List[str] = abc.index(_A ) + rotorposa a : List[str] = rotora[index % len(_A )] # reflector -------------------------- # this is the reason you don't need another machine to decipher a : Optional[Any] = reflector[symbol] # 2nd rotors a : List[Any] = abc[rotora.index(_A ) - rotorposa] a : List[Any] = abc[rotora.index(_A ) - rotorposa] a : str = abc[rotora.index(_A ) - rotorposa] # 2nd plugboard if symbol in plugboard: a : Tuple = plugboard[symbol] # moves/resets rotor positions rotorposa += 1 if rotorposa >= len(_A ): a : List[str] = 0 rotorposa += 1 if rotorposa >= len(_A ): a : Optional[Any] = 0 rotorposa += 1 if rotorposa >= len(_A ): a : Optional[int] = 0 # else: # pass # Error could be also raised # raise ValueError( # 'Invalid symbol('+repr(symbol)+')') result.append(_A ) return "".join(_A ) if __name__ == "__main__": lowerCAmelCase: Union[str, Any] = 'This is my Python script that emulates the Enigma machine from WWII.' lowerCAmelCase: Union[str, Any] = (1, 1, 1) lowerCAmelCase: int = 'pictures' lowerCAmelCase: List[Any] = (rotora, rotora, rotora) lowerCAmelCase: Dict = enigma(message, rotor_pos, rotor_sel, pb) print('Encrypted message:', en) print('Decrypted message:', enigma(en, rotor_pos, rotor_sel, pb))
297
'''simple docstring''' import inspect from typing import Optional, Union import numpy as np import PIL import torch from torch.nn import functional as F from torchvision import transforms from transformers import CLIPFeatureExtractor, CLIPModel, CLIPTextModel, CLIPTokenizer from diffusers import ( AutoencoderKL, DDIMScheduler, DiffusionPipeline, DPMSolverMultistepScheduler, LMSDiscreteScheduler, PNDMScheduler, UNetaDConditionModel, ) from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion import StableDiffusionPipelineOutput from diffusers.utils import ( PIL_INTERPOLATION, randn_tensor, ) def lowerCamelCase__ ( _A , _A , _A ): if isinstance(_A , torch.Tensor ): return image elif isinstance(_A , PIL.Image.Image ): a : Any = [image] if isinstance(image[0] , PIL.Image.Image ): a : List[str] = [np.array(i.resize((w, h) , resample=PIL_INTERPOLATION['lanczos'] ) )[None, :] for i in image] a : int = np.concatenate(_A , axis=0 ) a : int = np.array(_A ).astype(np.floataa ) / 255.0 a : str = image.transpose(0 , 3 , 1 , 2 ) a : str = 2.0 * image - 1.0 a : Optional[int] = torch.from_numpy(_A ) elif isinstance(image[0] , torch.Tensor ): a : Optional[Any] = torch.cat(_A , dim=0 ) return image def lowerCamelCase__ ( _A , _A , _A , _A=0.9995 ): if not isinstance(_A , np.ndarray ): a : Dict = True a : Optional[Any] = va.device a : Optional[int] = va.cpu().numpy() a : Union[str, Any] = va.cpu().numpy() a : Any = np.sum(va * va / (np.linalg.norm(_A ) * np.linalg.norm(_A )) ) if np.abs(_A ) > DOT_THRESHOLD: a : Any = (1 - t) * va + t * va else: a : Any = np.arccos(_A ) a : Tuple = np.sin(_A ) a : Optional[Any] = theta_a * t a : List[Any] = np.sin(_A ) a : Dict = np.sin(theta_a - theta_t ) / sin_theta_a a : int = sin_theta_t / sin_theta_a a : Any = sa * va + sa * va if inputs_are_torch: a : Dict = torch.from_numpy(_A ).to(_A ) return va def lowerCamelCase__ ( _A , _A ): a : Optional[int] = F.normalize(_A , dim=-1 ) a : str = F.normalize(_A , dim=-1 ) return (x - y).norm(dim=-1 ).div(2 ).arcsin().pow(2 ).mul(2 ) def lowerCamelCase__ ( _A , _A ): for param in model.parameters(): a : int = value class a__( lowerCamelCase__ ): def __init__( self : str , __snake_case : AutoencoderKL , __snake_case : CLIPTextModel , __snake_case : CLIPModel , __snake_case : CLIPTokenizer , __snake_case : UNetaDConditionModel , __snake_case : Union[PNDMScheduler, LMSDiscreteScheduler, DDIMScheduler, DPMSolverMultistepScheduler] , __snake_case : CLIPFeatureExtractor , __snake_case : List[str]=None , __snake_case : List[str]=None , __snake_case : List[Any]=None , ): super().__init__() self.register_modules( vae=__snake_case , text_encoder=__snake_case , clip_model=__snake_case , tokenizer=__snake_case , unet=__snake_case , scheduler=__snake_case , feature_extractor=__snake_case , coca_model=__snake_case , coca_tokenizer=__snake_case , coca_transform=__snake_case , ) a : Optional[Any] = ( feature_extractor.size if isinstance(feature_extractor.size , __snake_case ) else feature_extractor.size['shortest_edge'] ) a : Optional[int] = transforms.Normalize(mean=feature_extractor.image_mean , std=feature_extractor.image_std ) set_requires_grad(self.text_encoder , __snake_case ) set_requires_grad(self.clip_model , __snake_case ) def lowercase_ ( self : int , __snake_case : Optional[Union[str, int]] = "auto" ): if slice_size == "auto": # half the attention head size is usually a good trade-off between # speed and memory a : Union[str, Any] = self.unet.config.attention_head_dim // 2 self.unet.set_attention_slice(__snake_case ) def lowercase_ ( self : Union[str, Any] ): self.enable_attention_slicing(__snake_case ) def lowercase_ ( self : Optional[Any] ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : Tuple ): set_requires_grad(self.vae , __snake_case ) def lowercase_ ( self : int ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : Union[str, Any] ): set_requires_grad(self.unet , __snake_case ) def lowercase_ ( self : int , __snake_case : Dict , __snake_case : str , __snake_case : Optional[int] ): # get the original timestep using init_timestep a : Optional[Any] = min(int(num_inference_steps * strength ) , __snake_case ) a : Union[str, Any] = max(num_inference_steps - init_timestep , 0 ) a : List[Any] = self.scheduler.timesteps[t_start:] return timesteps, num_inference_steps - t_start def lowercase_ ( self : Dict , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : List[Any] , __snake_case : Union[str, Any] , __snake_case : Any , __snake_case : Optional[Any]=None ): if not isinstance(__snake_case , torch.Tensor ): raise ValueError(F"""`image` has to be of type `torch.Tensor` but is {type(__snake_case )}""" ) a : Optional[Any] = image.to(device=__snake_case , dtype=__snake_case ) if isinstance(__snake_case , __snake_case ): a : Optional[int] = [ self.vae.encode(image[i : i + 1] ).latent_dist.sample(generator[i] ) for i in range(__snake_case ) ] a : Optional[Any] = torch.cat(__snake_case , dim=0 ) else: a : Union[str, Any] = self.vae.encode(__snake_case ).latent_dist.sample(__snake_case ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : List[str] = 0.18215 * init_latents a : str = init_latents.repeat_interleave(__snake_case , dim=0 ) a : Dict = randn_tensor(init_latents.shape , generator=__snake_case , device=__snake_case , dtype=__snake_case ) # get latents a : Dict = self.scheduler.add_noise(__snake_case , __snake_case , __snake_case ) a : int = init_latents return latents def lowercase_ ( self : List[str] , __snake_case : Dict ): a : List[Any] = self.coca_transform(__snake_case ).unsqueeze(0 ) with torch.no_grad(), torch.cuda.amp.autocast(): a : Optional[Any] = self.coca_model.generate(transformed_image.to(device=self.device , dtype=self.coca_model.dtype ) ) a : Union[str, Any] = self.coca_tokenizer.decode(generated[0].cpu().numpy() ) return generated.split('<end_of_text>' )[0].replace('<start_of_text>' , '' ).rstrip(' .,' ) def lowercase_ ( self : Tuple , __snake_case : Any , __snake_case : Optional[Any] ): a : List[Any] = self.feature_extractor.preprocess(__snake_case ) a : Optional[Any] = torch.from_numpy(clip_image_input['pixel_values'][0] ).unsqueeze(0 ).to(self.device ).half() a : int = self.clip_model.get_image_features(__snake_case ) a : str = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : Tuple = image_embeddings_clip.repeat_interleave(__snake_case , dim=0 ) return image_embeddings_clip @torch.enable_grad() def lowercase_ ( self : Tuple , __snake_case : Optional[Any] , __snake_case : List[str] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : Dict , __snake_case : Union[str, Any] , __snake_case : List[Any] , ): a : Optional[Any] = latents.detach().requires_grad_() a : List[Any] = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : Any = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample if isinstance(self.scheduler , (PNDMScheduler, DDIMScheduler, DPMSolverMultistepScheduler) ): a : int = self.scheduler.alphas_cumprod[timestep] a : Any = 1 - alpha_prod_t # compute predicted original sample from predicted noise also called # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf a : List[str] = (latents - beta_prod_t ** 0.5 * noise_pred) / alpha_prod_t ** 0.5 a : Tuple = torch.sqrt(__snake_case ) a : str = pred_original_sample * (fac) + latents * (1 - fac) elif isinstance(self.scheduler , __snake_case ): a : List[Any] = self.scheduler.sigmas[index] a : Optional[int] = latents - sigma * noise_pred else: raise ValueError(F"""scheduler type {type(self.scheduler )} not supported""" ) # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Union[str, Any] = 1 / 0.18215 * sample a : str = self.vae.decode(__snake_case ).sample a : List[Any] = (image / 2 + 0.5).clamp(0 , 1 ) a : Tuple = transforms.Resize(self.feature_extractor_size )(__snake_case ) a : List[str] = self.normalize(__snake_case ).to(latents.dtype ) a : List[str] = self.clip_model.get_image_features(__snake_case ) a : Tuple = image_embeddings_clip / image_embeddings_clip.norm(p=2 , dim=-1 , keepdim=__snake_case ) a : int = spherical_dist_loss(__snake_case , __snake_case ).mean() * clip_guidance_scale a : List[str] = -torch.autograd.grad(__snake_case , __snake_case )[0] if isinstance(self.scheduler , __snake_case ): a : List[Any] = latents.detach() + grads * (sigma**2) a : Optional[int] = noise_pred_original else: a : List[Any] = noise_pred_original - torch.sqrt(__snake_case ) * grads return noise_pred, latents @torch.no_grad() def __call__( self : Optional[int] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Union[torch.FloatTensor, PIL.Image.Image] , __snake_case : Optional[str] = None , __snake_case : Optional[str] = None , __snake_case : Optional[int] = 5_12 , __snake_case : Optional[int] = 5_12 , __snake_case : float = 0.6 , __snake_case : Optional[int] = 50 , __snake_case : Optional[float] = 7.5 , __snake_case : Optional[int] = 1 , __snake_case : float = 0.0 , __snake_case : Optional[float] = 1_00 , __snake_case : Optional[torch.Generator] = None , __snake_case : Optional[str] = "pil" , __snake_case : bool = True , __snake_case : float = 0.8 , __snake_case : float = 0.1 , __snake_case : float = 0.1 , ): if isinstance(__snake_case , __snake_case ) and len(__snake_case ) != batch_size: raise ValueError(F"""You have passed {batch_size} batch_size, but only {len(__snake_case )} generators.""" ) if height % 8 != 0 or width % 8 != 0: raise ValueError(F"""`height` and `width` have to be divisible by 8 but are {height} and {width}.""" ) if isinstance(__snake_case , torch.Generator ) and batch_size > 1: a : Dict = [generator] + [None] * (batch_size - 1) a : Any = [ ('model', self.coca_model is None), ('tokenizer', self.coca_tokenizer is None), ('transform', self.coca_transform is None), ] a : List[str] = [x[0] for x in coca_is_none if x[1]] a : List[str] = ', '.join(__snake_case ) # generate prompts with coca model if prompt is None if content_prompt is None: if len(__snake_case ): raise ValueError( F"""Content prompt is None and CoCa [{coca_is_none_str}] is None.""" F"""Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : int = self.get_image_description(__snake_case ) if style_prompt is None: if len(__snake_case ): raise ValueError( F"""Style prompt is None and CoCa [{coca_is_none_str}] is None.""" F""" Set prompt or pass Coca [{coca_is_none_str}] to DiffusionPipeline.""" ) a : Union[str, Any] = self.get_image_description(__snake_case ) # get prompt text embeddings for content and style a : Optional[Any] = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(content_text_input.input_ids.to(self.device ) )[0] a : Dict = self.tokenizer( __snake_case , padding='max_length' , max_length=self.tokenizer.model_max_length , truncation=__snake_case , return_tensors='pt' , ) a : Dict = self.text_encoder(style_text_input.input_ids.to(self.device ) )[0] a : Any = slerp(__snake_case , __snake_case , __snake_case ) # duplicate text embeddings for each generation per prompt a : Optional[Any] = text_embeddings.repeat_interleave(__snake_case , dim=0 ) # set timesteps a : int = 'offset' in set(inspect.signature(self.scheduler.set_timesteps ).parameters.keys() ) a : Any = {} if accepts_offset: a : Optional[Any] = 1 self.scheduler.set_timesteps(__snake_case , **__snake_case ) # Some schedulers like PNDM have timesteps as arrays # It's more optimized to move all timesteps to correct device beforehand self.scheduler.timesteps.to(self.device ) a , a : Tuple = self.get_timesteps(__snake_case , __snake_case , self.device ) a : Optional[int] = timesteps[:1].repeat(__snake_case ) # Preprocess image a : Optional[Any] = preprocess(__snake_case , __snake_case , __snake_case ) a : List[Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : str = preprocess(__snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.prepare_latents( __snake_case , __snake_case , __snake_case , text_embeddings.dtype , self.device , __snake_case ) a : Union[str, Any] = slerp(__snake_case , __snake_case , __snake_case ) if clip_guidance_scale > 0: a : Dict = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : int = self.get_clip_image_embeddings(__snake_case , __snake_case ) a : List[str] = slerp( __snake_case , __snake_case , __snake_case ) # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2) # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1` # corresponds to doing no classifier free guidance. a : int = guidance_scale > 1.0 # get unconditional embeddings for classifier free guidance if do_classifier_free_guidance: a : Any = content_text_input.input_ids.shape[-1] a : List[Any] = self.tokenizer([''] , padding='max_length' , max_length=__snake_case , return_tensors='pt' ) a : List[str] = self.text_encoder(uncond_input.input_ids.to(self.device ) )[0] # duplicate unconditional embeddings for each generation per prompt a : Dict = uncond_embeddings.repeat_interleave(__snake_case , dim=0 ) # For classifier free guidance, we need to do two forward passes. # Here we concatenate the unconditional and text embeddings into a single batch # to avoid doing two forward passes a : Any = torch.cat([uncond_embeddings, text_embeddings] ) # get the initial random noise unless the user supplied it # Unlike in other pipelines, latents need to be generated in the target device # for 1-to-1 results reproducibility with the CompVis implementation. # However this currently doesn't work in `mps`. a : List[str] = (batch_size, self.unet.config.in_channels, height // 8, width // 8) a : List[str] = text_embeddings.dtype if latents is None: if self.device.type == "mps": # randn does not work reproducibly on mps a : int = torch.randn(__snake_case , generator=__snake_case , device='cpu' , dtype=__snake_case ).to( self.device ) else: a : Optional[int] = torch.randn(__snake_case , generator=__snake_case , device=self.device , dtype=__snake_case ) else: if latents.shape != latents_shape: raise ValueError(F"""Unexpected latents shape, got {latents.shape}, expected {latents_shape}""" ) a : List[str] = latents.to(self.device ) # scale the initial noise by the standard deviation required by the scheduler a : Any = latents * self.scheduler.init_noise_sigma # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers. # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502 # and should be between [0, 1] a : Optional[Any] = 'eta' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) a : Union[str, Any] = {} if accepts_eta: a : List[str] = eta # check if the scheduler accepts generator a : List[Any] = 'generator' in set(inspect.signature(self.scheduler.step ).parameters.keys() ) if accepts_generator: a : Any = generator with self.progress_bar(total=__snake_case ): for i, t in enumerate(__snake_case ): # expand the latents if we are doing classifier free guidance a : Tuple = torch.cat([latents] * 2 ) if do_classifier_free_guidance else latents a : Dict = self.scheduler.scale_model_input(__snake_case , __snake_case ) # predict the noise residual a : List[Any] = self.unet(__snake_case , __snake_case , encoder_hidden_states=__snake_case ).sample # perform classifier free guidance if do_classifier_free_guidance: a , a : List[str] = noise_pred.chunk(2 ) a : Union[str, Any] = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond) # perform clip guidance if clip_guidance_scale > 0: a : Optional[Any] = ( text_embeddings.chunk(2 )[1] if do_classifier_free_guidance else text_embeddings ) a , a : Union[str, Any] = self.cond_fn( __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case , ) # compute the previous noisy sample x_t -> x_t-1 a : Any = self.scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample # Hardcode 0.18215 because stable-diffusion-2-base has not self.vae.config.scaling_factor a : Tuple = 1 / 0.18215 * latents a : Optional[int] = self.vae.decode(__snake_case ).sample a : List[str] = (image / 2 + 0.5).clamp(0 , 1 ) a : Any = image.cpu().permute(0 , 2 , 3 , 1 ).numpy() if output_type == "pil": a : str = self.numpy_to_pil(__snake_case ) if not return_dict: return (image, None) return StableDiffusionPipelineOutput(images=__snake_case , nsfw_content_detected=__snake_case )
297
1
'''simple docstring''' import unittest from transformers import load_tool from transformers.utils import is_torch_available if is_torch_available(): import torch from transformers.testing_utils import require_torch from .test_tools_common import ToolTesterMixin @require_torch class a__( unittest.TestCase , lowerCamelCase__ ): def lowercase_ ( self : Dict ): a : Union[str, Any] = load_tool('text-to-speech' ) self.tool.setup() def lowercase_ ( self : str ): # SpeechT5 isn't deterministic torch.manual_seed(0 ) a : Union[str, Any] = self.tool('hey' ) a : str = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0005966668832115829, -0.0003657640190795064, -0.00013439502799883485] ) , ) ) def lowercase_ ( self : str ): # SpeechT5 isn't deterministic torch.manual_seed(0 ) a : Tuple = self.tool('hey' ) a : Union[str, Any] = result.to_raw() self.assertTrue( torch.allclose( resulting_tensor[:3] , torch.tensor([-0.0005966668832115829, -0.0003657640190795064, -0.00013439502799883485] ) , ) )
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A , _A , _A , _A , ): a : Dict = [redshift, radiation_density, matter_density, dark_energy] if any(p < 0 for p in parameters ): raise ValueError('All input parameters must be positive' ) if any(p > 1 for p in parameters[1:4] ): raise ValueError('Relative densities cannot be greater than one' ) else: a : Union[str, Any] = 1 - (matter_density + radiation_density + dark_energy) a : Union[str, Any] = ( radiation_density * (redshift + 1) ** 4 + matter_density * (redshift + 1) ** 3 + curvature * (redshift + 1) ** 2 + dark_energy ) a : int = hubble_constant * e_a ** (1 / 2) return hubble if __name__ == "__main__": import doctest # run doctest doctest.testmod() # demo LCDM approximation lowerCAmelCase: Optional[Any] = 0.3 print( hubble_parameter( hubble_constant=68.3, radiation_density=1e-4, matter_density=matter_density, dark_energy=1 - matter_density, redshift=0, ) )
297
1
'''simple docstring''' import warnings from typing import Dict import numpy as np from ..utils import ExplicitEnum, add_end_docstrings, is_tf_available, is_torch_available from .base import PIPELINE_INIT_ARGS, GenericTensor, Pipeline if is_tf_available(): from ..models.auto.modeling_tf_auto import TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if is_torch_available(): from ..models.auto.modeling_auto import MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING def lowerCamelCase__ ( _A ): return 1.0 / (1.0 + np.exp(-_outputs )) def lowerCamelCase__ ( _A ): a : Tuple = np.max(_outputs , axis=-1 , keepdims=_A ) a : Any = np.exp(_outputs - maxes ) return shifted_exp / shifted_exp.sum(axis=-1 , keepdims=_A ) class a__( lowerCamelCase__ ): lowercase__ = """sigmoid""" lowercase__ = """softmax""" lowercase__ = """none""" @add_end_docstrings( lowerCamelCase__ , R""" return_all_scores (`bool`, *optional*, defaults to `False`): Whether to return all prediction scores or just the one of the predicted class. function_to_apply (`str`, *optional*, defaults to `\"default\"`): The function to apply to the model outputs in order to retrieve the scores. Accepts four different values: - `\"default\"`: if the model has a single label, will apply the sigmoid function on the output. If the model has several labels, will apply the softmax function on the output. - `\"sigmoid\"`: Applies the sigmoid function on the output. - `\"softmax\"`: Applies the softmax function on the output. - `\"none\"`: Does not apply any function on the output. """ , ) class a__( lowerCamelCase__ ): lowercase__ = False lowercase__ = ClassificationFunction.NONE def __init__( self : List[str] , **__snake_case : str ): super().__init__(**__snake_case ) self.check_model_type( TF_MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING if self.framework == 'tf' else MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING ) def lowercase_ ( self : Union[str, Any] , __snake_case : List[Any]=None , __snake_case : List[Any]=None , __snake_case : Union[str, Any]="" , **__snake_case : Dict ): # Using "" as default argument because we're going to use `top_k=None` in user code to declare # "No top_k" a : Tuple = tokenizer_kwargs a : Optional[int] = {} if hasattr(self.model.config , 'return_all_scores' ) and return_all_scores is None: a : str = self.model.config.return_all_scores if isinstance(__snake_case , __snake_case ) or top_k is None: a : Optional[int] = top_k a : Union[str, Any] = False elif return_all_scores is not None: warnings.warn( '`return_all_scores` is now deprecated, if want a similar functionality use `top_k=None` instead of' ' `return_all_scores=True` or `top_k=1` instead of `return_all_scores=False`.' , __snake_case , ) if return_all_scores: a : Optional[Any] = None else: a : Any = 1 if isinstance(__snake_case , __snake_case ): a : Union[str, Any] = ClassificationFunction[function_to_apply.upper()] if function_to_apply is not None: a : str = function_to_apply return preprocess_params, {}, postprocess_params def __call__( self : Optional[Any] , *__snake_case : Any , **__snake_case : str ): a : List[str] = super().__call__(*__snake_case , **__snake_case ) # TODO try and retrieve it in a nicer way from _sanitize_parameters. a : Any = 'top_k' not in kwargs if isinstance(args[0] , __snake_case ) and _legacy: # This pipeline is odd, and return a list when single item is run return [result] else: return result def lowercase_ ( self : Union[str, Any] , __snake_case : List[str] , **__snake_case : str ): a : List[Any] = self.framework if isinstance(__snake_case , __snake_case ): return self.tokenizer(**__snake_case , return_tensors=__snake_case , **__snake_case ) elif isinstance(__snake_case , __snake_case ) and len(__snake_case ) == 1 and isinstance(inputs[0] , __snake_case ) and len(inputs[0] ) == 2: # It used to be valid to use a list of list of list for text pairs, keeping this path for BC return self.tokenizer( text=inputs[0][0] , text_pair=inputs[0][1] , return_tensors=__snake_case , **__snake_case ) elif isinstance(__snake_case , __snake_case ): # This is likely an invalid usage of the pipeline attempting to pass text pairs. raise ValueError( 'The pipeline received invalid inputs, if you are trying to send text pairs, you can try to send a' ' dictionary `{"text": "My text", "text_pair": "My pair"}` in order to send a text pair.' ) return self.tokenizer(__snake_case , return_tensors=__snake_case , **__snake_case ) def lowercase_ ( self : Optional[Any] , __snake_case : Tuple ): return self.model(**__snake_case ) def lowercase_ ( self : Any , __snake_case : int , __snake_case : List[str]=None , __snake_case : int=1 , __snake_case : Any=True ): # `_legacy` is used to determine if we're running the naked pipeline and in backward # compatibility mode, or if running the pipeline with `pipeline(..., top_k=1)` we're running # the more natural result containing the list. # Default value before `set_parameters` if function_to_apply is None: if self.model.config.problem_type == "multi_label_classification" or self.model.config.num_labels == 1: a : Optional[int] = ClassificationFunction.SIGMOID elif self.model.config.problem_type == "single_label_classification" or self.model.config.num_labels > 1: a : Optional[Any] = ClassificationFunction.SOFTMAX elif hasattr(self.model.config , 'function_to_apply' ) and function_to_apply is None: a : Any = self.model.config.function_to_apply else: a : int = ClassificationFunction.NONE a : int = model_outputs['logits'][0] a : List[Any] = outputs.numpy() if function_to_apply == ClassificationFunction.SIGMOID: a : Dict = sigmoid(__snake_case ) elif function_to_apply == ClassificationFunction.SOFTMAX: a : str = softmax(__snake_case ) elif function_to_apply == ClassificationFunction.NONE: a : List[str] = outputs else: raise ValueError(F"""Unrecognized `function_to_apply` argument: {function_to_apply}""" ) if top_k == 1 and _legacy: return {"label": self.model.config.idalabel[scores.argmax().item()], "score": scores.max().item()} a : Any = [ {'label': self.model.config.idalabel[i], 'score': score.item()} for i, score in enumerate(__snake_case ) ] if not _legacy: dict_scores.sort(key=lambda __snake_case : x["score"] , reverse=__snake_case ) if top_k is not None: a : Union[str, Any] = dict_scores[:top_k] return dict_scores
297
'''simple docstring''' from __future__ import annotations import math class a__: def __init__( self : List[str] , __snake_case : int ): a : str = size # approximate the overall size of segment tree with given value a : Optional[int] = [0 for i in range(0 , 4 * size )] # create array to store lazy update a : Any = [0 for i in range(0 , 4 * size )] a : Dict = [0 for i in range(0 , 4 * size )] # flag for lazy update def lowercase_ ( self : int , __snake_case : int ): return idx * 2 def lowercase_ ( self : Dict , __snake_case : int ): return idx * 2 + 1 def lowercase_ ( self : Dict , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : list[int] ): if left_element == right_element: a : Tuple = a[left_element - 1] else: a : Tuple = (left_element + right_element) // 2 self.build(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case ) self.build(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case ) a : Union[str, Any] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) def lowercase_ ( self : Optional[Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : int = self.lazy[idx] a : Union[str, Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : int = self.lazy[idx] a : Tuple = True a : Optional[Any] = True if right_element < a or left_element > b: return True if left_element >= a and right_element <= b: a : int = val if left_element != right_element: a : int = val a : Dict = val a : List[str] = True a : List[str] = True return True a : Tuple = (left_element + right_element) // 2 self.update(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case , __snake_case ) self.update(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case , __snake_case ) a : Optional[int] = max( self.segment_tree[self.left(__snake_case )] , self.segment_tree[self.right(__snake_case )] ) return True def lowercase_ ( self : Union[str, Any] , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int , __snake_case : int ): if self.flag[idx] is True: a : str = self.lazy[idx] a : Optional[Any] = False if left_element != right_element: a : Dict = self.lazy[idx] a : Union[str, Any] = self.lazy[idx] a : Dict = True a : int = True if right_element < a or left_element > b: return -math.inf if left_element >= a and right_element <= b: return self.segment_tree[idx] a : Dict = (left_element + right_element) // 2 a : Optional[int] = self.query(self.left(__snake_case ) , __snake_case , __snake_case , __snake_case , __snake_case ) a : Union[str, Any] = self.query(self.right(__snake_case ) , mid + 1 , __snake_case , __snake_case , __snake_case ) return max(__snake_case , __snake_case ) def __str__( self : Any ): return str([self.query(1 , 1 , self.size , __snake_case , __snake_case ) for i in range(1 , self.size + 1 )] ) if __name__ == "__main__": lowerCAmelCase: Optional[int] = [1, 2, -4, 7, 3, -5, 6, 1_1, -2_0, 9, 1_4, 1_5, 5, 2, -8] lowerCAmelCase: int = 1_5 lowerCAmelCase: Optional[int] = SegmentTree(size) segt.build(1, 1, size, A) print(segt.query(1, 1, size, 4, 6)) print(segt.query(1, 1, size, 7, 1_1)) print(segt.query(1, 1, size, 7, 1_2)) segt.update(1, 1, size, 1, 3, 1_1_1) print(segt.query(1, 1, size, 1, 1_5)) segt.update(1, 1, size, 7, 8, 2_3_5) print(segt)
297
1
'''simple docstring''' from math import acos, sin from typing import List, Tuple, Union import numpy as np import torch from PIL import Image from ...models import AutoencoderKL, UNetaDConditionModel from ...schedulers import DDIMScheduler, DDPMScheduler from ...utils import randn_tensor from ..pipeline_utils import AudioPipelineOutput, BaseOutput, DiffusionPipeline, ImagePipelineOutput from .mel import Mel class a__( lowerCamelCase__ ): lowercase__ = ["""vqvae"""] def __init__( self : int , __snake_case : AutoencoderKL , __snake_case : UNetaDConditionModel , __snake_case : Mel , __snake_case : Union[DDIMScheduler, DDPMScheduler] , ): super().__init__() self.register_modules(unet=__snake_case , scheduler=__snake_case , mel=__snake_case , vqvae=__snake_case ) def lowercase_ ( self : str ): return 50 if isinstance(self.scheduler , __snake_case ) else 10_00 @torch.no_grad() def __call__( self : Optional[int] , __snake_case : int = 1 , __snake_case : str = None , __snake_case : np.ndarray = None , __snake_case : int = 0 , __snake_case : int = 0 , __snake_case : int = None , __snake_case : torch.Generator = None , __snake_case : float = 0 , __snake_case : float = 0 , __snake_case : torch.Generator = None , __snake_case : float = 0 , __snake_case : torch.Tensor = None , __snake_case : torch.Tensor = None , __snake_case : Union[str, Any]=True , ): a : List[str] = steps or self.get_default_steps() self.scheduler.set_timesteps(__snake_case ) a : int = step_generator or generator # For backwards compatibility if type(self.unet.config.sample_size ) == int: a : Optional[Any] = (self.unet.config.sample_size, self.unet.config.sample_size) if noise is None: a : List[str] = randn_tensor( ( batch_size, self.unet.config.in_channels, self.unet.config.sample_size[0], self.unet.config.sample_size[1], ) , generator=__snake_case , device=self.device , ) a : str = noise a : str = None if audio_file is not None or raw_audio is not None: self.mel.load_audio(__snake_case , __snake_case ) a : str = self.mel.audio_slice_to_image(__snake_case ) a : Union[str, Any] = np.frombuffer(input_image.tobytes() , dtype='uint8' ).reshape( (input_image.height, input_image.width) ) a : Optional[int] = (input_image / 2_55) * 2 - 1 a : str = torch.tensor(input_image[np.newaxis, :, :] , dtype=torch.float ).to(self.device ) if self.vqvae is not None: a : int = self.vqvae.encode(torch.unsqueeze(__snake_case , 0 ) ).latent_dist.sample( generator=__snake_case )[0] a : Any = self.vqvae.config.scaling_factor * input_images if start_step > 0: a : List[Any] = self.scheduler.add_noise(__snake_case , __snake_case , self.scheduler.timesteps[start_step - 1] ) a : int = ( self.unet.config.sample_size[1] * self.mel.get_sample_rate() / self.mel.x_res / self.mel.hop_length ) a : str = int(mask_start_secs * pixels_per_second ) a : List[str] = int(mask_end_secs * pixels_per_second ) a : str = self.scheduler.add_noise(__snake_case , __snake_case , torch.tensor(self.scheduler.timesteps[start_step:] ) ) for step, t in enumerate(self.progress_bar(self.scheduler.timesteps[start_step:] ) ): if isinstance(self.unet , __snake_case ): a : int = self.unet(__snake_case , __snake_case , __snake_case )['sample'] else: a : List[str] = self.unet(__snake_case , __snake_case )['sample'] if isinstance(self.scheduler , __snake_case ): a : Union[str, Any] = self.scheduler.step( model_output=__snake_case , timestep=__snake_case , sample=__snake_case , eta=__snake_case , generator=__snake_case , )['prev_sample'] else: a : Dict = self.scheduler.step( model_output=__snake_case , timestep=__snake_case , sample=__snake_case , generator=__snake_case , )['prev_sample'] if mask is not None: if mask_start > 0: a : Union[str, Any] = mask[:, step, :, :mask_start] if mask_end > 0: a : List[str] = mask[:, step, :, -mask_end:] if self.vqvae is not None: # 0.18215 was scaling factor used in training to ensure unit variance a : Any = 1 / self.vqvae.config.scaling_factor * images a : List[Any] = self.vqvae.decode(__snake_case )['sample'] a : Any = (images / 2 + 0.5).clamp(0 , 1 ) a : str = images.cpu().permute(0 , 2 , 3 , 1 ).numpy() a : List[Any] = (images * 2_55).round().astype('uint8' ) a : Any = list( (Image.fromarray(_[:, :, 0] ) for _ in images) if images.shape[3] == 1 else (Image.fromarray(__snake_case , mode='RGB' ).convert('L' ) for _ in images) ) a : Dict = [self.mel.image_to_audio(__snake_case ) for _ in images] if not return_dict: return images, (self.mel.get_sample_rate(), audios) return BaseOutput(**AudioPipelineOutput(np.array(__snake_case )[:, np.newaxis, :] ) , **ImagePipelineOutput(__snake_case ) ) @torch.no_grad() def lowercase_ ( self : str , __snake_case : List[Image.Image] , __snake_case : int = 50 ): assert isinstance(self.scheduler , __snake_case ) self.scheduler.set_timesteps(__snake_case ) a : List[str] = np.array( [np.frombuffer(image.tobytes() , dtype='uint8' ).reshape((1, image.height, image.width) ) for image in images] ) a : Union[str, Any] = (sample / 2_55) * 2 - 1 a : str = torch.Tensor(__snake_case ).to(self.device ) for t in self.progress_bar(torch.flip(self.scheduler.timesteps , (0,) ) ): a : Optional[Any] = t - self.scheduler.config.num_train_timesteps // self.scheduler.num_inference_steps a : List[Any] = self.scheduler.alphas_cumprod[t] a : List[str] = ( self.scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.scheduler.final_alpha_cumprod ) a : Optional[Any] = 1 - alpha_prod_t a : int = self.unet(__snake_case , __snake_case )['sample'] a : Optional[int] = (1 - alpha_prod_t_prev) ** 0.5 * model_output a : int = (sample - pred_sample_direction) * alpha_prod_t_prev ** (-0.5) a : List[Any] = sample * alpha_prod_t ** 0.5 + beta_prod_t ** 0.5 * model_output return sample @staticmethod def lowercase_ ( __snake_case : torch.Tensor , __snake_case : torch.Tensor , __snake_case : float ): a : str = acos(torch.dot(torch.flatten(__snake_case ) , torch.flatten(__snake_case ) ) / torch.norm(__snake_case ) / torch.norm(__snake_case ) ) return sin((1 - alpha) * theta ) * xa / sin(__snake_case ) + sin(alpha * theta ) * xa / sin(__snake_case )
297
'''simple docstring''' def lowerCamelCase__ ( _A , _A ): while second != 0: a : Union[str, Any] = first & second first ^= second a : Tuple = c << 1 return first if __name__ == "__main__": import doctest doctest.testmod() lowerCAmelCase: Optional[int] = int(input('Enter the first number: ').strip()) lowerCAmelCase: Union[str, Any] = int(input('Enter the second number: ').strip()) print(F"{add(first, second) = }")
297
1
'''simple docstring''' def lowerCamelCase__ ( _A = "The quick brown fox jumps over the lazy dog" , ): a : Dict = set() # Replace all the whitespace in our sentence a : Any = input_str.replace(' ' , '' ) for alpha in input_str: if "a" <= alpha.lower() <= "z": frequency.add(alpha.lower() ) return len(_A ) == 26 def lowerCamelCase__ ( _A = "The quick brown fox jumps over the lazy dog" , ): a : Optional[int] = [False] * 26 for char in input_str: if char.islower(): a : List[str] = True elif char.isupper(): a : int = True return all(_A ) def lowerCamelCase__ ( _A = "The quick brown fox jumps over the lazy dog" , ): return len({char for char in input_str.lower() if char.isalpha()} ) == 26 def lowerCamelCase__ ( ): from timeit import timeit a : List[Any] = 'from __main__ import is_pangram, is_pangram_faster, is_pangram_fastest' print(timeit('is_pangram()' , setup=_A ) ) print(timeit('is_pangram_faster()' , setup=_A ) ) print(timeit('is_pangram_fastest()' , setup=_A ) ) # 5.348480500048026, 2.6477354579837993, 1.8470395830227062 # 5.036091582966037, 2.644472333951853, 1.8869528750656173 if __name__ == "__main__": import doctest doctest.testmod() benchmark()
297
'''simple docstring''' import io import json import fsspec import pytest from datasets import Dataset, DatasetDict, Features, NamedSplit, Value from datasets.io.json import JsonDatasetReader, JsonDatasetWriter from ..utils import assert_arrow_memory_doesnt_increase, assert_arrow_memory_increases def lowerCamelCase__ ( _A , _A ): assert isinstance(_A , _A ) assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Optional[int] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , keep_in_memory=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : str = tmp_path / 'cache' a : Tuple = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Dict = features.copy() if features else default_expected_features a : Union[str, Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Tuple = tmp_path / 'cache' a : Optional[Any] = {'col_3': 'float64', 'col_1': 'string', 'col_2': 'int64'} a : Optional[int] = features.copy() if features else default_expected_features a : Dict = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Optional[int] = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_3", "col_1", "col_2"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype def lowerCamelCase__ ( _A , _A ): # jsonl_312_path features are {"col_3": "float64", "col_1": "string", "col_2": "int64"} a : Dict = {'col_2': 'int64', 'col_3': 'float64', 'col_1': 'string'} a : int = features.copy() a : List[Any] = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : Dict = tmp_path / 'cache' a : Any = JsonDatasetReader(_A , features=_A , cache_dir=_A ).read() assert isinstance(_A , _A ) assert dataset.num_rows == 2 assert dataset.num_columns == 3 assert dataset.column_names == ["col_2", "col_3", "col_1"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[str] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = JsonDatasetReader(_A , cache_dir=_A , split=_A ).read() _check_json_dataset(_A , _A ) assert dataset.split == split if split else "train" @pytest.mark.parametrize('path_type' , [str, list] ) def lowerCamelCase__ ( _A , _A , _A ): if issubclass(_A , _A ): a : Optional[int] = jsonl_path elif issubclass(_A , _A ): a : Optional[int] = [jsonl_path] a : List[str] = tmp_path / 'cache' a : Dict = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_dataset(_A , _A ) def lowerCamelCase__ ( _A , _A , _A=("train",) ): assert isinstance(_A , _A ) for split in splits: a : str = dataset_dict[split] assert dataset.num_rows == 4 assert dataset.num_columns == 3 assert dataset.column_names == ["col_1", "col_2", "col_3"] for feature, expected_dtype in expected_features.items(): assert dataset.features[feature].dtype == expected_dtype @pytest.mark.parametrize('keep_in_memory' , [False, True] ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : Any = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} with assert_arrow_memory_increases() if keep_in_memory else assert_arrow_memory_doesnt_increase(): a : int = JsonDatasetReader({'train': jsonl_path} , cache_dir=_A , keep_in_memory=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize( 'features' , [ None, {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'}, {'col_1': 'string', 'col_2': 'string', 'col_3': 'string'}, {'col_1': 'int32', 'col_2': 'int32', 'col_3': 'int32'}, {'col_1': 'float32', 'col_2': 'float32', 'col_3': 'float32'}, ] , ) def lowerCamelCase__ ( _A , _A , _A ): a : Dict = tmp_path / 'cache' a : List[Any] = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : List[Any] = features.copy() if features else default_expected_features a : Any = ( Features({feature: Value(_A ) for feature, dtype in features.items()} ) if features is not None else None ) a : List[str] = JsonDatasetReader({'train': jsonl_path} , features=_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A ) @pytest.mark.parametrize('split' , [None, NamedSplit('train' ), 'train', 'test'] ) def lowerCamelCase__ ( _A , _A , _A ): if split: a : Any = {split: jsonl_path} else: a : List[Any] = 'train' a : List[str] = {'train': jsonl_path, 'test': jsonl_path} a : List[Any] = tmp_path / 'cache' a : str = {'col_1': 'string', 'col_2': 'int64', 'col_3': 'float64'} a : Tuple = JsonDatasetReader(_A , cache_dir=_A ).read() _check_json_datasetdict(_A , _A , splits=list(path.keys() ) ) assert all(dataset[split].split == split for split in path.keys() ) def lowerCamelCase__ ( _A ): return json.load(_A ) def lowerCamelCase__ ( _A ): return [json.loads(_A ) for line in buffer] class a__: @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : Tuple , __snake_case : int , __snake_case : Optional[int] , __snake_case : Any ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case ).write() buffer.seek(0 ) a : List[str] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Tuple , __snake_case : Tuple , __snake_case : Any , __snake_case : Any , __snake_case : List[str] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 @pytest.mark.parametrize('lines, load_json_function' , [(True, load_json_lines), (False, load_json)] ) def lowercase_ ( self : List[Any] , __snake_case : Any , __snake_case : Optional[int] , __snake_case : Optional[Any] ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : List[Any] = load_json_function(__snake_case ) assert isinstance(__snake_case , __snake_case ) assert isinstance(exported_content[0] , __snake_case ) assert len(__snake_case ) == 10 @pytest.mark.parametrize( 'orient, container, keys, len_at' , [ ('records', list, {'tokens', 'labels', 'answers', 'id'}, None), ('split', dict, {'columns', 'data'}, 'data'), ('index', dict, set('0123456789' ), None), ('columns', dict, {'tokens', 'labels', 'answers', 'id'}, 'tokens'), ('values', list, None, None), ('table', dict, {'schema', 'data'}, 'data'), ] , ) def lowercase_ ( self : Optional[int] , __snake_case : Any , __snake_case : str , __snake_case : int , __snake_case : List[Any] , __snake_case : Dict ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , lines=__snake_case , orient=__snake_case , num_proc=2 ).write() buffer.seek(0 ) a : int = load_json(__snake_case ) assert isinstance(__snake_case , __snake_case ) if keys: if container is dict: assert exported_content.keys() == keys else: assert exported_content[0].keys() == keys else: assert not hasattr(__snake_case , 'keys' ) and not hasattr(exported_content[0] , 'keys' ) if len_at: assert len(exported_content[len_at] ) == 10 else: assert len(__snake_case ) == 10 def lowercase_ ( self : List[str] , __snake_case : str ): with pytest.raises(__snake_case ): with io.BytesIO() as buffer: JsonDatasetWriter(__snake_case , __snake_case , num_proc=0 ) @pytest.mark.parametrize('compression, extension' , [('gzip', 'gz'), ('bz2', 'bz2'), ('xz', 'xz')] ) def lowercase_ ( self : Tuple , __snake_case : Dict , __snake_case : List[Any] , __snake_case : int , __snake_case : List[str] , __snake_case : Optional[int] ): a : Tuple = tmp_path_factory.mktemp('data' ) / F"""test.json.{extension}""" a : List[Any] = str(shared_datadir / F"""test_file.json.{extension}""" ) JsonDatasetWriter(__snake_case , __snake_case , compression=__snake_case ).write() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() with fsspec.open(__snake_case , 'rb' , compression='infer' ) as f: a : Union[str, Any] = f.read() assert exported_content == original_content
297
1
'''simple docstring''' import absl # noqa: F401 # Here to have a nice missing dependency error message early on import nltk # noqa: F401 # Here to have a nice missing dependency error message early on import numpy # noqa: F401 # Here to have a nice missing dependency error message early on import six # noqa: F401 # Here to have a nice missing dependency error message early on from rouge_score import rouge_scorer, scoring import datasets lowerCAmelCase: Tuple = '\\n@inproceedings{lin-2004-rouge,\n title = "{ROUGE}: A Package for Automatic Evaluation of Summaries",\n author = "Lin, Chin-Yew",\n booktitle = "Text Summarization Branches Out",\n month = jul,\n year = "2004",\n address = "Barcelona, Spain",\n publisher = "Association for Computational Linguistics",\n url = "https://www.aclweb.org/anthology/W04-1013",\n pages = "74--81",\n}\n' lowerCAmelCase: Optional[Any] = '\\nROUGE, or Recall-Oriented Understudy for Gisting Evaluation, is a set of metrics and a software package used for\nevaluating automatic summarization and machine translation software in natural language processing.\nThe metrics compare an automatically produced summary or translation against a reference or a set of references (human-produced) summary or translation.\n\nNote that ROUGE is case insensitive, meaning that upper case letters are treated the same way as lower case letters.\n\nThis metrics is a wrapper around Google Research reimplementation of ROUGE:\nhttps://github.com/google-research/google-research/tree/master/rouge\n' lowerCAmelCase: Optional[int] = '\nCalculates average rouge scores for a list of hypotheses and references\nArgs:\n predictions: list of predictions to score. Each prediction\n should be a string with tokens separated by spaces.\n references: list of reference for each prediction. Each\n reference should be a string with tokens separated by spaces.\n rouge_types: A list of rouge types to calculate.\n Valid names:\n `"rouge{n}"` (e.g. `"rouge1"`, `"rouge2"`) where: {n} is the n-gram based scoring,\n `"rougeL"`: Longest common subsequence based scoring.\n `"rougeLSum"`: rougeLsum splits text using `"\n"`.\n See details in https://github.com/huggingface/datasets/issues/617\n use_stemmer: Bool indicating whether Porter stemmer should be used to strip word suffixes.\n use_aggregator: Return aggregates if this is set to True\nReturns:\n rouge1: rouge_1 (precision, recall, f1),\n rouge2: rouge_2 (precision, recall, f1),\n rougeL: rouge_l (precision, recall, f1),\n rougeLsum: rouge_lsum (precision, recall, f1)\nExamples:\n\n >>> rouge = datasets.load_metric(\'rouge\')\n >>> predictions = ["hello there", "general kenobi"]\n >>> references = ["hello there", "general kenobi"]\n >>> results = rouge.compute(predictions=predictions, references=references)\n >>> print(list(results.keys()))\n [\'rouge1\', \'rouge2\', \'rougeL\', \'rougeLsum\']\n >>> print(results["rouge1"])\n AggregateScore(low=Score(precision=1.0, recall=1.0, fmeasure=1.0), mid=Score(precision=1.0, recall=1.0, fmeasure=1.0), high=Score(precision=1.0, recall=1.0, fmeasure=1.0))\n >>> print(results["rouge1"].mid.fmeasure)\n 1.0\n' @datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION , _KWARGS_DESCRIPTION ) class a__( datasets.Metric ): def lowercase_ ( self : Dict ): return datasets.MetricInfo( description=_DESCRIPTION , citation=_CITATION , inputs_description=_KWARGS_DESCRIPTION , features=datasets.Features( { 'predictions': datasets.Value('string' , id='sequence' ), 'references': datasets.Value('string' , id='sequence' ), } ) , codebase_urls=['https://github.com/google-research/google-research/tree/master/rouge'] , reference_urls=[ 'https://en.wikipedia.org/wiki/ROUGE_(metric)', 'https://github.com/google-research/google-research/tree/master/rouge', ] , ) def lowercase_ ( self : List[str] , __snake_case : List[str] , __snake_case : Dict , __snake_case : str=None , __snake_case : Tuple=True , __snake_case : int=False ): if rouge_types is None: a : Dict = ['rouge1', 'rouge2', 'rougeL', 'rougeLsum'] a : Any = rouge_scorer.RougeScorer(rouge_types=__snake_case , use_stemmer=__snake_case ) if use_aggregator: a : List[Any] = scoring.BootstrapAggregator() else: a : List[Any] = [] for ref, pred in zip(__snake_case , __snake_case ): a : List[Any] = scorer.score(__snake_case , __snake_case ) if use_aggregator: aggregator.add_scores(__snake_case ) else: scores.append(__snake_case ) if use_aggregator: a : Optional[int] = aggregator.aggregate() else: a : Union[str, Any] = {} for key in scores[0]: a : str = [score[key] for score in scores] return result
297
'''simple docstring''' from itertools import zip_longest import requests from bsa import BeautifulSoup from pandas import DataFrame def lowerCamelCase__ ( _A = "laptop" ): a : Any = f"""https://www.amazon.in/laptop/s?k={product}""" a : Tuple = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36\n (KHTML, like Gecko)Chrome/44.0.2403.157 Safari/537.36', 'Accept-Language': 'en-US, en;q=0.5', } a : Any = BeautifulSoup(requests.get(_A , headers=_A ).text ) # Initialize a Pandas dataframe with the column titles a : Any = DataFrame( columns=[ 'Product Title', 'Product Link', 'Current Price of the product', 'Product Rating', 'MRP of the product', 'Discount', ] ) # Loop through each entry and store them in the dataframe for item, _ in zip_longest( soup.find_all( 'div' , attrs={'class': 's-result-item', 'data-component-type': 's-search-result'} , ) , soup.find_all('div' , attrs={'class': 'a-row a-size-base a-color-base'} ) , ): try: a : Optional[int] = item.ha.text a : str = 'https://www.amazon.in/' + item.ha.a['href'] a : List[str] = item.find('span' , attrs={'class': 'a-offscreen'} ).text try: a : Optional[Any] = item.find('span' , attrs={'class': 'a-icon-alt'} ).text except AttributeError: a : Union[str, Any] = 'Not available' try: a : str = ( '₹' + item.find( 'span' , attrs={'class': 'a-price a-text-price'} ).text.split('₹' )[1] ) except AttributeError: a : int = '' try: a : Union[str, Any] = float( ( ( float(product_mrp.strip('₹' ).replace(',' , '' ) ) - float(product_price.strip('₹' ).replace(',' , '' ) ) ) / float(product_mrp.strip('₹' ).replace(',' , '' ) ) ) * 100 ) except ValueError: a : Any = float('nan' ) except AttributeError: pass a : Any = [ product_title, product_link, product_price, product_rating, product_mrp, discount, ] a : Any = ' ' a : List[str] = ' ' data_frame.index += 1 return data_frame if __name__ == "__main__": lowerCAmelCase: str = 'headphones' get_amazon_product_data(product).to_csv(F"Amazon Product Data for {product}.csv")
297
1
'''simple docstring''' def lowerCamelCase__ ( _A , _A , _A=False ): if isinstance(_A , _A ) and isinstance(_A , _A ): a : List[Any] = len(set_a.intersection(_A ) ) if alternative_union: a : Union[str, Any] = len(_A ) + len(_A ) else: a : Any = len(set_a.union(_A ) ) return intersection / union if isinstance(_A , (list, tuple) ) and isinstance(_A , (list, tuple) ): a : int = [element for element in set_a if element in set_b] if alternative_union: a : Dict = len(_A ) + len(_A ) return len(_A ) / union else: a : List[Any] = set_a + [element for element in set_b if element not in set_a] return len(_A ) / len(_A ) return len(_A ) / len(_A ) return None if __name__ == "__main__": lowerCAmelCase: Any = {'a', 'b', 'c', 'd', 'e'} lowerCAmelCase: Union[str, Any] = {'c', 'd', 'e', 'f', 'h', 'i'} print(jaccard_similarity(set_a, set_b))
297
'''simple docstring''' import gc import random import unittest import numpy as np import torch from transformers import ( CLIPImageProcessor, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, CLIPVisionConfig, CLIPVisionModelWithProjection, ) from diffusers import AutoencoderKL, DDIMScheduler, DDPMScheduler, StableUnCLIPImgaImgPipeline, UNetaDConditionModel from diffusers.pipelines.pipeline_utils import DiffusionPipeline from diffusers.pipelines.stable_diffusion.stable_unclip_image_normalizer import StableUnCLIPImageNormalizer from diffusers.utils.import_utils import is_xformers_available from diffusers.utils.testing_utils import ( enable_full_determinism, floats_tensor, load_image, load_numpy, require_torch_gpu, skip_mps, slow, torch_device, ) from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS from ..test_pipelines_common import ( PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin, assert_mean_pixel_difference, ) enable_full_determinism() class a__( lowerCamelCase__ , lowerCamelCase__ , lowerCamelCase__ , unittest.TestCase ): lowercase__ = StableUnCLIPImgaImgPipeline lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_PARAMS lowercase__ = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS lowercase__ = frozenset( [] ) # TO-DO: update image_params once pipeline is refactored with VaeImageProcessor.preprocess lowercase__ = frozenset([] ) def lowercase_ ( self : int ): a : Dict = 32 a : str = embedder_hidden_size # image encoding components a : List[Any] = CLIPImageProcessor(crop_size=32 , size=32 ) torch.manual_seed(0 ) a : Dict = CLIPVisionModelWithProjection( CLIPVisionConfig( hidden_size=__snake_case , projection_dim=__snake_case , num_hidden_layers=5 , num_attention_heads=4 , image_size=32 , intermediate_size=37 , patch_size=1 , ) ) # regular denoising components torch.manual_seed(0 ) a : Dict = StableUnCLIPImageNormalizer(embedding_dim=__snake_case ) a : Optional[int] = DDPMScheduler(beta_schedule='squaredcos_cap_v2' ) torch.manual_seed(0 ) a : Any = CLIPTokenizer.from_pretrained('hf-internal-testing/tiny-random-clip' ) torch.manual_seed(0 ) a : Tuple = CLIPTextModel( CLIPTextConfig( bos_token_id=0 , eos_token_id=2 , hidden_size=__snake_case , projection_dim=32 , intermediate_size=37 , layer_norm_eps=1e-0_5 , num_attention_heads=4 , num_hidden_layers=5 , pad_token_id=1 , vocab_size=10_00 , ) ) torch.manual_seed(0 ) a : Union[str, Any] = UNetaDConditionModel( sample_size=32 , in_channels=4 , out_channels=4 , down_block_types=('CrossAttnDownBlock2D', 'DownBlock2D') , up_block_types=('UpBlock2D', 'CrossAttnUpBlock2D') , block_out_channels=(32, 64) , attention_head_dim=(2, 4) , class_embed_type='projection' , projection_class_embeddings_input_dim=embedder_projection_dim * 2 , cross_attention_dim=__snake_case , layers_per_block=1 , upcast_attention=__snake_case , use_linear_projection=__snake_case , ) torch.manual_seed(0 ) a : List[Any] = DDIMScheduler( beta_schedule='scaled_linear' , beta_start=0.00085 , beta_end=0.012 , prediction_type='v_prediction' , set_alpha_to_one=__snake_case , steps_offset=1 , ) torch.manual_seed(0 ) a : List[str] = AutoencoderKL() a : str = { # image encoding components 'feature_extractor': feature_extractor, 'image_encoder': image_encoder.eval(), # image noising components 'image_normalizer': image_normalizer.eval(), 'image_noising_scheduler': image_noising_scheduler, # regular denoising components 'tokenizer': tokenizer, 'text_encoder': text_encoder.eval(), 'unet': unet.eval(), 'scheduler': scheduler, 'vae': vae.eval(), } return components def lowercase_ ( self : Tuple , __snake_case : List[str] , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=True ): if str(__snake_case ).startswith('mps' ): a : Tuple = torch.manual_seed(__snake_case ) else: a : List[Any] = torch.Generator(device=__snake_case ).manual_seed(__snake_case ) a : Optional[Any] = floats_tensor((1, 3, 32, 32) , rng=random.Random(__snake_case ) ).to(__snake_case ) if pil_image: a : Optional[Any] = input_image * 0.5 + 0.5 a : Optional[Any] = input_image.clamp(0 , 1 ) a : Dict = input_image.cpu().permute(0 , 2 , 3 , 1 ).float().numpy() a : int = DiffusionPipeline.numpy_to_pil(__snake_case )[0] return { "prompt": "An anime racoon running a marathon", "image": input_image, "generator": generator, "num_inference_steps": 2, "output_type": "np", } @skip_mps def lowercase_ ( self : Optional[Any] ): a : List[Any] = 'cpu' # ensure determinism for the device-dependent torch.Generator a : Union[str, Any] = self.get_dummy_components() a : Any = StableUnCLIPImgaImgPipeline(**__snake_case ) a : Tuple = sd_pipe.to(__snake_case ) sd_pipe.set_progress_bar_config(disable=__snake_case ) a : Union[str, Any] = self.get_dummy_inputs(__snake_case ) inputs.update({'image_embeds': None} ) a : str = sd_pipe(**__snake_case ).images a : Optional[int] = image[0, -3:, -3:, -1] assert image.shape == (1, 32, 32, 3) a : Optional[int] = np.array([0.3872, 0.7224, 0.5601, 0.4741, 0.6872, 0.5814, 0.4636, 0.3867, 0.5078] ) assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-3 def lowercase_ ( self : List[str] ): a : int = torch_device in ['cpu', 'mps'] self._test_attention_slicing_forward_pass(test_max_difference=__snake_case ) def lowercase_ ( self : int ): a : Optional[int] = torch_device in ['cpu', 'mps'] self._test_inference_batch_single_identical(test_max_difference=__snake_case ) @unittest.skipIf( torch_device != 'cuda' or not is_xformers_available() , reason='XFormers attention is only available with CUDA and `xformers` installed' , ) def lowercase_ ( self : Dict ): self._test_xformers_attention_forwardGenerator_pass(test_max_difference=__snake_case ) @slow @require_torch_gpu class a__( unittest.TestCase ): def lowercase_ ( self : Any ): # clean up the VRAM after each test super().tearDown() gc.collect() torch.cuda.empty_cache() def lowercase_ ( self : Optional[Any] ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Union[str, Any] = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_l_img2img_anime_turtle_fp16.npy' ) a : Optional[Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-l-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = torch.Generator(device='cpu' ).manual_seed(0 ) a : Optional[int] = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Optional[int] ): a : int = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) a : Any = load_numpy( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/stable_unclip_2_1_h_img2img_anime_turtle_fp16.npy' ) a : Union[str, Any] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) # stable unclip will oom when integration tests are run on a V100, # so turn on memory savings pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[Any] = torch.Generator(device='cpu' ).manual_seed(0 ) a : str = pipe(__snake_case , 'anime turle' , generator=__snake_case , output_type='np' ) a : List[str] = output.images[0] assert image.shape == (7_68, 7_68, 3) assert_mean_pixel_difference(__snake_case , __snake_case ) def lowercase_ ( self : Any ): a : Optional[Any] = load_image( 'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/stable_unclip/turtle.png' ) torch.cuda.empty_cache() torch.cuda.reset_max_memory_allocated() torch.cuda.reset_peak_memory_stats() a : List[str] = StableUnCLIPImgaImgPipeline.from_pretrained( 'fusing/stable-unclip-2-1-h-img2img' , torch_dtype=torch.floataa ) a : Optional[Any] = pipe.to(__snake_case ) pipe.set_progress_bar_config(disable=__snake_case ) pipe.enable_attention_slicing() pipe.enable_sequential_cpu_offload() a : Optional[int] = pipe( __snake_case , 'anime turtle' , num_inference_steps=2 , output_type='np' , ) a : int = torch.cuda.max_memory_allocated() # make sure that less than 7 GB is allocated assert mem_bytes < 7 * 10**9
297
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available lowerCAmelCase: str = {'configuration_swin': ['SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP', 'SwinConfig', 'SwinOnnxConfig']} try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: str = [ 'SWIN_PRETRAINED_MODEL_ARCHIVE_LIST', 'SwinForImageClassification', 'SwinForMaskedImageModeling', 'SwinModel', 'SwinPreTrainedModel', 'SwinBackbone', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: int = [ 'TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFSwinForImageClassification', 'TFSwinForMaskedImageModeling', 'TFSwinModel', 'TFSwinPreTrainedModel', ] if TYPE_CHECKING: from .configuration_swin import SWIN_PRETRAINED_CONFIG_ARCHIVE_MAP, SwinConfig, SwinOnnxConfig try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_swin import ( SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, SwinBackbone, SwinForImageClassification, SwinForMaskedImageModeling, SwinModel, SwinPreTrainedModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_swin import ( TF_SWIN_PRETRAINED_MODEL_ARCHIVE_LIST, TFSwinForImageClassification, TFSwinForMaskedImageModeling, TFSwinModel, TFSwinPreTrainedModel, ) else: import sys lowerCAmelCase: str = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
'''simple docstring''' from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxSeqaSeqConfigWithPast from ...utils import logging lowerCAmelCase: Union[str, Any] = logging.get_logger(__name__) lowerCAmelCase: List[str] = { 't5-small': 'https://huggingface.co/t5-small/resolve/main/config.json', 't5-base': 'https://huggingface.co/t5-base/resolve/main/config.json', 't5-large': 'https://huggingface.co/t5-large/resolve/main/config.json', 't5-3b': 'https://huggingface.co/t5-3b/resolve/main/config.json', 't5-11b': 'https://huggingface.co/t5-11b/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """t5""" lowercase__ = ["""past_key_values"""] lowercase__ = {"""hidden_size""": """d_model""", """num_attention_heads""": """num_heads""", """num_hidden_layers""": """num_layers"""} def __init__( self : Union[str, Any] , __snake_case : int=3_21_28 , __snake_case : str=5_12 , __snake_case : Dict=64 , __snake_case : Optional[int]=20_48 , __snake_case : Tuple=6 , __snake_case : Any=None , __snake_case : Optional[int]=8 , __snake_case : str=32 , __snake_case : Union[str, Any]=1_28 , __snake_case : Optional[int]=0.1 , __snake_case : Dict=1e-6 , __snake_case : int=1.0 , __snake_case : Optional[int]="relu" , __snake_case : Any=True , __snake_case : List[str]=True , __snake_case : Union[str, Any]=0 , __snake_case : Dict=1 , **__snake_case : Optional[int] , ): a : Optional[int] = vocab_size a : Dict = d_model a : Union[str, Any] = d_kv a : Dict = d_ff a : Tuple = num_layers a : Dict = ( num_decoder_layers if num_decoder_layers is not None else self.num_layers ) # default = symmetry a : int = num_heads a : str = relative_attention_num_buckets a : List[Any] = relative_attention_max_distance a : int = dropout_rate a : Tuple = layer_norm_epsilon a : str = initializer_factor a : List[Any] = feed_forward_proj a : Union[str, Any] = use_cache a : List[str] = self.feed_forward_proj.split('-' ) a : int = act_info[-1] a : Union[str, Any] = act_info[0] == 'gated' if len(__snake_case ) > 1 and act_info[0] != "gated" or len(__snake_case ) > 2: raise ValueError( F"""`feed_forward_proj`: {feed_forward_proj} is not a valid activation function of the dense layer.""" 'Please make sure `feed_forward_proj` is of the format `gated-{ACT_FN}` or `{ACT_FN}`, e.g. ' '\'gated-gelu\' or \'relu\'' ) # for backwards compatibility if feed_forward_proj == "gated-gelu": a : Optional[Any] = 'gelu_new' super().__init__( pad_token_id=__snake_case , eos_token_id=__snake_case , is_encoder_decoder=__snake_case , **__snake_case , ) class a__( lowerCamelCase__ ): @property def lowercase_ ( self : Optional[int] ): a : Dict = { 'input_ids': {0: 'batch', 1: 'encoder_sequence'}, 'attention_mask': {0: 'batch', 1: 'encoder_sequence'}, } if self.use_past: a : Dict = 'past_encoder_sequence + sequence' a : Dict = {0: 'batch'} a : Any = {0: 'batch', 1: 'past_decoder_sequence + sequence'} else: a : Optional[Any] = {0: 'batch', 1: 'decoder_sequence'} a : List[str] = {0: 'batch', 1: 'decoder_sequence'} if self.use_past: self.fill_with_past_key_values_(__snake_case , direction='inputs' ) return common_inputs @property def lowercase_ ( self : List[Any] ): return 13
297
1
'''simple docstring''' import tempfile import torch from diffusers import ( DEISMultistepScheduler, DPMSolverMultistepScheduler, DPMSolverSinglestepScheduler, UniPCMultistepScheduler, ) from .test_schedulers import SchedulerCommonTest class a__( lowerCamelCase__ ): lowercase__ = (DPMSolverSinglestepScheduler,) lowercase__ = (("""num_inference_steps""", 25),) def lowercase_ ( self : int , **__snake_case : List[Any] ): a : List[Any] = { 'num_train_timesteps': 10_00, 'beta_start': 0.0001, 'beta_end': 0.02, 'beta_schedule': 'linear', 'solver_order': 2, 'prediction_type': 'epsilon', 'thresholding': False, 'sample_max_value': 1.0, 'algorithm_type': 'dpmsolver++', 'solver_type': 'midpoint', 'lambda_min_clipped': -float('inf' ), 'variance_type': None, } config.update(**__snake_case ) return config def lowercase_ ( self : Any , __snake_case : Dict=0 , **__snake_case : str ): a : Optional[int] = dict(self.forward_default_kwargs ) a : str = kwargs.pop('num_inference_steps' , __snake_case ) a : Tuple = self.dummy_sample a : str = 0.1 * sample a : Union[str, Any] = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: a : Optional[Any] = self.get_scheduler_config(**__snake_case ) a : Tuple = scheduler_class(**__snake_case ) scheduler.set_timesteps(__snake_case ) # copy over dummy past residuals a : int = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__snake_case ) a : Optional[Any] = scheduler_class.from_pretrained(__snake_case ) new_scheduler.set_timesteps(__snake_case ) # copy over dummy past residuals a : str = dummy_past_residuals[: new_scheduler.config.solver_order] a , a : List[Any] = sample, sample for t in range(__snake_case , time_step + scheduler.config.solver_order + 1 ): a : str = scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample a : int = new_scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowercase_ ( self : Optional[int] ): pass def lowercase_ ( self : Any , __snake_case : Union[str, Any]=0 , **__snake_case : Optional[Any] ): a : Tuple = dict(self.forward_default_kwargs ) a : Any = kwargs.pop('num_inference_steps' , __snake_case ) a : Tuple = self.dummy_sample a : List[str] = 0.1 * sample a : str = [residual + 0.2, residual + 0.15, residual + 0.10] for scheduler_class in self.scheduler_classes: a : Any = self.get_scheduler_config() a : str = scheduler_class(**__snake_case ) scheduler.set_timesteps(__snake_case ) # copy over dummy past residuals (must be after setting timesteps) a : List[str] = dummy_past_residuals[: scheduler.config.solver_order] with tempfile.TemporaryDirectory() as tmpdirname: scheduler.save_config(__snake_case ) a : Dict = scheduler_class.from_pretrained(__snake_case ) # copy over dummy past residuals new_scheduler.set_timesteps(__snake_case ) # copy over dummy past residual (must be after setting timesteps) a : int = dummy_past_residuals[: new_scheduler.config.solver_order] a : Any = scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample a : List[str] = new_scheduler.step(__snake_case , __snake_case , __snake_case , **__snake_case ).prev_sample assert torch.sum(torch.abs(output - new_output ) ) < 1e-5, "Scheduler outputs are not identical" def lowercase_ ( self : Union[str, Any] , __snake_case : str=None , **__snake_case : Union[str, Any] ): if scheduler is None: a : List[str] = self.scheduler_classes[0] a : Dict = self.get_scheduler_config(**__snake_case ) a : List[str] = scheduler_class(**__snake_case ) a : Tuple = self.scheduler_classes[0] a : Optional[int] = self.get_scheduler_config(**__snake_case ) a : Tuple = scheduler_class(**__snake_case ) a : int = 10 a : Tuple = self.dummy_model() a : str = self.dummy_sample_deter scheduler.set_timesteps(__snake_case ) for i, t in enumerate(scheduler.timesteps ): a : Optional[Any] = model(__snake_case , __snake_case ) a : str = scheduler.step(__snake_case , __snake_case , __snake_case ).prev_sample return sample def lowercase_ ( self : Optional[Any] ): a : List[Any] = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) a : Dict = 50 a : str = self.dummy_model() a : Dict = self.dummy_sample_deter scheduler.set_timesteps(__snake_case ) # make sure that the first t is uneven for i, t in enumerate(scheduler.timesteps[3:] ): a : int = model(__snake_case , __snake_case ) a : Dict = scheduler.step(__snake_case , __snake_case , __snake_case ).prev_sample a : List[Any] = torch.mean(torch.abs(__snake_case ) ) assert abs(result_mean.item() - 0.2574 ) < 1e-3 def lowercase_ ( self : Optional[int] ): for timesteps in [25, 50, 1_00, 9_99, 10_00]: self.check_over_configs(num_train_timesteps=__snake_case ) def lowercase_ ( self : Any ): # make sure that iterating over schedulers with same config names gives same results # for defaults a : Tuple = DPMSolverSinglestepScheduler(**self.get_scheduler_config() ) a : Dict = self.full_loop(scheduler=__snake_case ) a : List[Any] = torch.mean(torch.abs(__snake_case ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 a : Optional[int] = DEISMultistepScheduler.from_config(scheduler.config ) a : Dict = DPMSolverMultistepScheduler.from_config(scheduler.config ) a : Optional[Any] = UniPCMultistepScheduler.from_config(scheduler.config ) a : Any = DPMSolverSinglestepScheduler.from_config(scheduler.config ) a : Dict = self.full_loop(scheduler=__snake_case ) a : str = torch.mean(torch.abs(__snake_case ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 def lowercase_ ( self : Optional[int] ): self.check_over_configs(thresholding=__snake_case ) for order in [1, 2, 3]: for solver_type in ["midpoint", "heun"]: for threshold in [0.5, 1.0, 2.0]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( thresholding=__snake_case , prediction_type=__snake_case , sample_max_value=__snake_case , algorithm_type='dpmsolver++' , solver_order=__snake_case , solver_type=__snake_case , ) def lowercase_ ( self : Optional[Any] ): for prediction_type in ["epsilon", "v_prediction"]: self.check_over_configs(prediction_type=__snake_case ) def lowercase_ ( self : List[str] ): for algorithm_type in ["dpmsolver", "dpmsolver++"]: for solver_type in ["midpoint", "heun"]: for order in [1, 2, 3]: for prediction_type in ["epsilon", "sample"]: self.check_over_configs( solver_order=__snake_case , solver_type=__snake_case , prediction_type=__snake_case , algorithm_type=__snake_case , ) a : List[str] = self.full_loop( solver_order=__snake_case , solver_type=__snake_case , prediction_type=__snake_case , algorithm_type=__snake_case , ) assert not torch.isnan(__snake_case ).any(), "Samples have nan numbers" def lowercase_ ( self : int ): self.check_over_configs(lower_order_final=__snake_case ) self.check_over_configs(lower_order_final=__snake_case ) def lowercase_ ( self : str ): self.check_over_configs(lambda_min_clipped=-float('inf' ) ) self.check_over_configs(lambda_min_clipped=-5.1 ) def lowercase_ ( self : str ): self.check_over_configs(variance_type=__snake_case ) self.check_over_configs(variance_type='learned_range' ) def lowercase_ ( self : int ): for num_inference_steps in [1, 2, 3, 5, 10, 50, 1_00, 9_99, 10_00]: self.check_over_forward(num_inference_steps=__snake_case , time_step=0 ) def lowercase_ ( self : Tuple ): a : Union[str, Any] = self.full_loop() a : Tuple = torch.mean(torch.abs(__snake_case ) ) assert abs(result_mean.item() - 0.2791 ) < 1e-3 def lowercase_ ( self : int ): a : Tuple = self.full_loop(use_karras_sigmas=__snake_case ) a : List[str] = torch.mean(torch.abs(__snake_case ) ) assert abs(result_mean.item() - 0.2248 ) < 1e-3 def lowercase_ ( self : Optional[Any] ): a : Optional[int] = self.full_loop(prediction_type='v_prediction' ) a : List[str] = torch.mean(torch.abs(__snake_case ) ) assert abs(result_mean.item() - 0.1453 ) < 1e-3 def lowercase_ ( self : Optional[int] ): a : str = self.full_loop(prediction_type='v_prediction' , use_karras_sigmas=__snake_case ) a : Tuple = torch.mean(torch.abs(__snake_case ) ) assert abs(result_mean.item() - 0.0649 ) < 1e-3 def lowercase_ ( self : List[str] ): a : str = self.scheduler_classes[0] a : List[Any] = self.get_scheduler_config(thresholding=__snake_case , dynamic_thresholding_ratio=0 ) a : Tuple = scheduler_class(**__snake_case ) a : List[Any] = 10 a : Optional[Any] = self.dummy_model() a : Dict = self.dummy_sample_deter.half() scheduler.set_timesteps(__snake_case ) for i, t in enumerate(scheduler.timesteps ): a : Optional[int] = model(__snake_case , __snake_case ) a : List[Any] = scheduler.step(__snake_case , __snake_case , __snake_case ).prev_sample assert sample.dtype == torch.floataa
297
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def lowerCamelCase__ ( _A , _A ): if inductance <= 0: raise ValueError('Inductance cannot be 0 or negative' ) elif capacitance <= 0: raise ValueError('Capacitance cannot be 0 or negative' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
297
1
'''simple docstring''' from __future__ import annotations from math import pi, sqrt def lowerCamelCase__ ( _A , _A ): if inductance <= 0: raise ValueError('Inductance cannot be 0 or negative' ) elif capacitance <= 0: raise ValueError('Capacitance cannot be 0 or negative' ) else: return ( "Resonant frequency", float(1 / (2 * pi * (sqrt(inductance * capacitance ))) ), ) if __name__ == "__main__": import doctest doctest.testmod()
297
'''simple docstring''' import collections import os from typing import List, Optional, Tuple from transformers.utils import is_jieba_available, requires_backends if is_jieba_available(): import jieba from ...tokenization_utils import PreTrainedTokenizer from ...utils import logging lowerCAmelCase: Any = logging.get_logger(__name__) lowerCAmelCase: Any = {'vocab_file': 'vocab.txt'} lowerCAmelCase: List[Any] = { 'vocab_file': { 'openbmb/cpm-ant-10b': 'https://huggingface.co/openbmb/cpm-ant-10b/blob/main/vocab.txt', }, } lowerCAmelCase: str = { 'openbmb/cpm-ant-10b': 1_0_2_4, } def lowerCamelCase__ ( _A ): a : Union[str, Any] = collections.OrderedDict() with open(_A , 'r' , encoding='utf-8' ) as reader: a : int = reader.readlines() for index, token in enumerate(_A ): a : int = token.rstrip('\n' ) a : List[Any] = index return vocab class a__( lowerCamelCase__ ): def __init__( self : Dict , __snake_case : Any , __snake_case : Dict="<unk>" , __snake_case : str=2_00 ): a : List[Any] = vocab a : Any = unk_token a : List[str] = max_input_chars_per_word def lowercase_ ( self : Optional[int] , __snake_case : Union[str, Any] ): a : Optional[Any] = list(__snake_case ) if len(__snake_case ) > self.max_input_chars_per_word: return [self.unk_token] a : Any = 0 a : Optional[Any] = [] while start < len(__snake_case ): a : Optional[int] = len(__snake_case ) a : str = None while start < end: a : Optional[Any] = ''.join(chars[start:end] ) if substr in self.vocab: a : List[str] = substr break end -= 1 if cur_substr is None: sub_tokens.append(self.unk_token ) start += 1 else: sub_tokens.append(__snake_case ) a : List[str] = end return sub_tokens class a__( lowerCamelCase__ ): lowercase__ = VOCAB_FILES_NAMES lowercase__ = PRETRAINED_VOCAB_FILES_MAP lowercase__ = PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES lowercase__ = ["""input_ids""", """attention_mask"""] lowercase__ = False def __init__( self : Any , __snake_case : str , __snake_case : Tuple="<d>" , __snake_case : List[str]="</d>" , __snake_case : Dict="<s>" , __snake_case : List[Any]="</s>" , __snake_case : int="<pad>" , __snake_case : Any="<unk>" , __snake_case : List[str]="</n>" , __snake_case : int="</_>" , __snake_case : Optional[Any]="left" , **__snake_case : Dict , ): requires_backends(self , ['jieba'] ) super().__init__( bod_token=__snake_case , eod_token=__snake_case , bos_token=__snake_case , eos_token=__snake_case , pad_token=__snake_case , unk_token=__snake_case , line_token=__snake_case , space_token=__snake_case , padding_side=__snake_case , **__snake_case , ) a : Union[str, Any] = bod_token a : Any = eod_token a : List[str] = load_vocab(__snake_case ) a : Optional[int] = self.encoder[space_token] a : str = self.encoder[line_token] del self.encoder[space_token] del self.encoder[line_token] a : str = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) a : Tuple = {v: k for k, v in self.encoder.items()} a : List[str] = WordpieceTokenizer(vocab=self.encoder , unk_token=self.unk_token ) @property def lowercase_ ( self : Optional[int] ): return self.encoder[self.bod_token] @property def lowercase_ ( self : Dict ): return self.encoder[self.eod_token] @property def lowercase_ ( self : Any ): return self.encoder["\n"] @property def lowercase_ ( self : Tuple ): return len(self.encoder ) def lowercase_ ( self : str ): return dict(self.encoder , **self.added_tokens_encoder ) def lowercase_ ( self : Union[str, Any] , __snake_case : List[str] ): a : List[str] = [] for x in jieba.cut(__snake_case , cut_all=__snake_case ): output_tokens.extend(self.wordpiece_tokenizer.tokenize(__snake_case ) ) return output_tokens def lowercase_ ( self : Union[str, Any] , __snake_case : Optional[Any] , **__snake_case : Optional[Any] ): a : Optional[int] = [i for i in token_ids if i >= 0] a : Any = [ x for x in token_ids if x != self.pad_token_id and x != self.eos_token_id and x != self.bos_token_id ] return super()._decode(__snake_case , **__snake_case ) def lowercase_ ( self : Optional[int] , __snake_case : int ): return token in self.encoder def lowercase_ ( self : int , __snake_case : List[str] ): return "".join(__snake_case ) def lowercase_ ( self : List[str] , __snake_case : Union[str, Any] ): return self.encoder.get(__snake_case , self.encoder.get(self.unk_token ) ) def lowercase_ ( self : Tuple , __snake_case : List[str] ): return self.decoder.get(__snake_case , self.unk_token ) def lowercase_ ( self : Union[str, Any] , __snake_case : str , __snake_case : Optional[str] = None ): if os.path.isdir(__snake_case ): a : Optional[int] = os.path.join( __snake_case , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file'] ) else: a : int = (filename_prefix + '-' if filename_prefix else '') + save_directory a : Any = 0 if " " in self.encoder: a : Union[str, Any] = self.encoder[' '] del self.encoder[" "] if "\n" in self.encoder: a : Tuple = self.encoder['\n'] del self.encoder["\n"] a : Dict = collections.OrderedDict(sorted(self.encoder.items() , key=lambda __snake_case : x[1] ) ) with open(__snake_case , 'w' , encoding='utf-8' ) as writer: for token, token_index in self.encoder.items(): if index != token_index: logger.warning( F"""Saving vocabulary to {vocab_file}: vocabulary indices are not consecutive.""" ' Please check that the vocabulary is not corrupted!' ) a : List[Any] = token_index writer.write(token + '\n' ) index += 1 return (vocab_file,) def lowercase_ ( self : Union[str, Any] , __snake_case : List[int] , __snake_case : List[int] = None ): if token_ids_a is None: return [self.bos_token_id] + token_ids_a return [self.bos_token_id] + token_ids_a + [self.bos_token_id] + token_ids_a def lowercase_ ( self : Dict , __snake_case : List[int] , __snake_case : Optional[List[int]] = None , __snake_case : bool = False ): if already_has_special_tokens: return super().get_special_tokens_mask( token_ids_a=__snake_case , token_ids_a=__snake_case , already_has_special_tokens=__snake_case ) if token_ids_a is not None: return [1] + ([0] * len(__snake_case )) + [1] + ([0] * len(__snake_case )) return [1] + ([0] * len(__snake_case ))
297
1
'''simple docstring''' import datetime import platform import subprocess from typing import Optional, Tuple, Union import numpy as np def lowerCamelCase__ ( _A , _A ): a : Tuple = f"""{sampling_rate}""" a : List[str] = '1' a : Optional[Any] = 'f32le' a : int = [ 'ffmpeg', '-i', 'pipe:0', '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] try: with subprocess.Popen(_A , stdin=subprocess.PIPE , stdout=subprocess.PIPE ) as ffmpeg_process: a : Tuple = ffmpeg_process.communicate(_A ) except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to load audio files from filename' ) from error a : Optional[Any] = output_stream[0] a : Optional[Any] = np.frombuffer(_A , np.floataa ) if audio.shape[0] == 0: raise ValueError('Malformed soundfile' ) return audio def lowerCamelCase__ ( _A , _A , _A = "f32le" , ): a : Union[str, Any] = f"""{sampling_rate}""" a : Union[str, Any] = '1' if format_for_conversion == "s16le": a : Tuple = 2 elif format_for_conversion == "f32le": a : str = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) a : Optional[Any] = platform.system() if system == "Linux": a : Optional[int] = 'alsa' a : Dict = 'default' elif system == "Darwin": a : Optional[int] = 'avfoundation' a : List[Any] = ':0' elif system == "Windows": a : Optional[Any] = 'dshow' a : List[str] = 'default' a : Tuple = [ 'ffmpeg', '-f', format_, '-i', input_, '-ac', ac, '-ar', ar, '-f', format_for_conversion, '-fflags', 'nobuffer', '-hide_banner', '-loglevel', 'quiet', 'pipe:1', ] a : int = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample a : List[Any] = _ffmpeg_stream(_A , _A ) for item in iterator: yield item def lowerCamelCase__ ( _A , _A , _A = None , _A = None , _A = "f32le" , ): if stream_chunk_s is not None: a : Union[str, Any] = stream_chunk_s else: a : Tuple = chunk_length_s a : Optional[Any] = ffmpeg_microphone(_A , _A , format_for_conversion=_A ) if format_for_conversion == "s16le": a : Tuple = np.intaa a : Optional[int] = 2 elif format_for_conversion == "f32le": a : Optional[Any] = np.floataa a : Tuple = 4 else: raise ValueError(f"""Unhandled format `{format_for_conversion}`. Please use `s16le` or `f32le`""" ) if stride_length_s is None: a : List[Any] = chunk_length_s / 6 a : int = int(round(sampling_rate * chunk_length_s ) ) * size_of_sample if isinstance(_A , (int, float) ): a : str = [stride_length_s, stride_length_s] a : List[Any] = int(round(sampling_rate * stride_length_s[0] ) ) * size_of_sample a : Union[str, Any] = int(round(sampling_rate * stride_length_s[1] ) ) * size_of_sample a : Optional[Any] = datetime.datetime.now() a : Optional[int] = datetime.timedelta(seconds=_A ) for item in chunk_bytes_iter(_A , _A , stride=(stride_left, stride_right) , stream=_A ): # Put everything back in numpy scale a : int = np.frombuffer(item['raw'] , dtype=_A ) a : str = ( item['stride'][0] // size_of_sample, item['stride'][1] // size_of_sample, ) a : Union[str, Any] = sampling_rate audio_time += delta if datetime.datetime.now() > audio_time + 10 * delta: # We're late !! SKIP continue yield item def lowerCamelCase__ ( _A , _A , _A , _A = False ): a : List[str] = B'' a , a : List[Any] = stride if stride_left + stride_right >= chunk_len: raise ValueError( f"""Stride needs to be strictly smaller than chunk_len: ({stride_left}, {stride_right}) vs {chunk_len}""" ) a : Optional[Any] = 0 for raw in iterator: acc += raw if stream and len(_A ) < chunk_len: a : str = (_stride_left, 0) yield {"raw": acc[:chunk_len], "stride": stride, "partial": True} else: while len(_A ) >= chunk_len: # We are flushing the accumulator a : Tuple = (_stride_left, stride_right) a : Tuple = {'raw': acc[:chunk_len], 'stride': stride} if stream: a : Optional[int] = False yield item a : str = stride_left a : int = acc[chunk_len - stride_left - stride_right :] # Last chunk if len(_A ) > stride_left: a : Any = {'raw': acc, 'stride': (_stride_left, 0)} if stream: a : Tuple = False yield item def lowerCamelCase__ ( _A , _A ): a : Any = 2**24 # 16Mo try: with subprocess.Popen(_A , stdout=subprocess.PIPE , bufsize=_A ) as ffmpeg_process: while True: a : Dict = ffmpeg_process.stdout.read(_A ) if raw == b"": break yield raw except FileNotFoundError as error: raise ValueError('ffmpeg was not found but is required to stream audio files from filename' ) from error
297
'''simple docstring''' from __future__ import annotations import unittest from transformers import is_tf_available, is_torch_available from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, SMALL_MODEL_IDENTIFIER, is_pt_tf_cross_test, slow if is_tf_available(): from transformers import ( AutoConfig, BertConfig, GPTaConfig, TaConfig, TFAutoModel, TFAutoModelForCausalLM, TFAutoModelForMaskedLM, TFAutoModelForPreTraining, TFAutoModelForQuestionAnswering, TFAutoModelForSeqaSeqLM, TFAutoModelForSequenceClassification, TFAutoModelWithLMHead, TFBertForMaskedLM, TFBertForPreTraining, TFBertForQuestionAnswering, TFBertForSequenceClassification, TFBertModel, TFGPTaLMHeadModel, TFRobertaForMaskedLM, TFTaForConditionalGeneration, ) from transformers.models.bert.modeling_tf_bert import TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.gpta.modeling_tf_gpta import TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST from transformers.models.ta.modeling_tf_ta import TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST if is_torch_available(): from transformers import ( AutoModel, AutoModelForCausalLM, AutoModelForMaskedLM, AutoModelForPreTraining, AutoModelForQuestionAnswering, AutoModelForSeqaSeqLM, AutoModelForSequenceClassification, AutoModelWithLMHead, BertForMaskedLM, BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification, BertModel, GPTaLMHeadModel, RobertaForMaskedLM, TaForConditionalGeneration, ) @is_pt_tf_cross_test class a__( unittest.TestCase ): @slow def lowercase_ ( self : List[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[int] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = TFAutoModel.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModel.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Union[str, Any] = TFAutoModelForPreTraining.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = AutoModelForPreTraining.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_GPT2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Union[str, Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForCausalLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Any = TFAutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForCausalLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForCausalLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Any ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[str] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[int] ): for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : List[str] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Optional[Any] = TFAutoModelForMaskedLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Optional[int] = TFAutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = AutoModelForMaskedLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : Tuple = AutoModelForMaskedLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : int ): for model_name in TF_T5_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : str = TFAutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_pt=__snake_case ) a , a : Tuple = TFAutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSeqaSeqLM.from_pretrained(__snake_case , from_tf=__snake_case ) a , a : str = AutoModelForSeqaSeqLM.from_pretrained( __snake_case , output_loading_info=__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : Optional[Any] ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Tuple = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : List[Any] = TFAutoModelForSequenceClassification.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Dict = AutoModelForSequenceClassification.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) @slow def lowercase_ ( self : str ): # for model_name in TF_BERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]: for model_name in ["bert-base-uncased"]: a : Optional[Any] = AutoConfig.from_pretrained(__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : int = TFAutoModelForQuestionAnswering.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) a : Tuple = AutoModelForQuestionAnswering.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsNotNone(__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) def lowercase_ ( self : Tuple ): a : List[Any] = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[int] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) def lowercase_ ( self : Any ): a : int = TFAutoModelWithLMHead.from_pretrained(__snake_case , from_pt=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 ) a : Optional[Any] = AutoModelWithLMHead.from_pretrained(__snake_case , from_tf=__snake_case ) self.assertIsInstance(__snake_case , __snake_case ) self.assertEqual(model.num_parameters() , 1_44_10 ) self.assertEqual(model.num_parameters(only_trainable=__snake_case ) , 1_44_10 )
297
1
'''simple docstring''' from typing import TYPE_CHECKING from ...utils import ( OptionalDependencyNotAvailable, _LazyModule, is_tf_available, is_torch_available, is_vision_available, ) lowerCAmelCase: Union[str, Any] = { 'configuration_blip': [ 'BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP', 'BlipConfig', 'BlipTextConfig', 'BlipVisionConfig', ], 'processing_blip': ['BlipProcessor'], } try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Tuple = ['BlipImageProcessor'] try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: Dict = [ 'BLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'BlipModel', 'BlipPreTrainedModel', 'BlipForConditionalGeneration', 'BlipForQuestionAnswering', 'BlipVisionModel', 'BlipTextModel', 'BlipForImageTextRetrieval', ] try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: lowerCAmelCase: List[Any] = [ 'TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST', 'TFBlipModel', 'TFBlipPreTrainedModel', 'TFBlipForConditionalGeneration', 'TFBlipForQuestionAnswering', 'TFBlipVisionModel', 'TFBlipTextModel', 'TFBlipForImageTextRetrieval', ] if TYPE_CHECKING: from .configuration_blip import BLIP_PRETRAINED_CONFIG_ARCHIVE_MAP, BlipConfig, BlipTextConfig, BlipVisionConfig from .processing_blip import BlipProcessor try: if not is_vision_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .image_processing_blip import BlipImageProcessor try: if not is_torch_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_blip import ( BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, BlipForConditionalGeneration, BlipForImageTextRetrieval, BlipForQuestionAnswering, BlipModel, BlipPreTrainedModel, BlipTextModel, BlipVisionModel, ) try: if not is_tf_available(): raise OptionalDependencyNotAvailable() except OptionalDependencyNotAvailable: pass else: from .modeling_tf_blip import ( TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST, TFBlipForConditionalGeneration, TFBlipForImageTextRetrieval, TFBlipForQuestionAnswering, TFBlipModel, TFBlipPreTrainedModel, TFBlipTextModel, TFBlipVisionModel, ) else: import sys lowerCAmelCase: Union[str, Any] = _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)
297
'''simple docstring''' from collections import OrderedDict from typing import Mapping from ...configuration_utils import PretrainedConfig from ...onnx import OnnxConfig from ...utils import logging lowerCAmelCase: List[Any] = logging.get_logger(__name__) lowerCAmelCase: List[Any] = { 'roberta-base': 'https://huggingface.co/roberta-base/resolve/main/config.json', 'roberta-large': 'https://huggingface.co/roberta-large/resolve/main/config.json', 'roberta-large-mnli': 'https://huggingface.co/roberta-large-mnli/resolve/main/config.json', 'distilroberta-base': 'https://huggingface.co/distilroberta-base/resolve/main/config.json', 'roberta-base-openai-detector': 'https://huggingface.co/roberta-base-openai-detector/resolve/main/config.json', 'roberta-large-openai-detector': 'https://huggingface.co/roberta-large-openai-detector/resolve/main/config.json', } class a__( lowerCamelCase__ ): lowercase__ = """roberta""" def __init__( self : Tuple , __snake_case : List[str]=5_02_65 , __snake_case : int=7_68 , __snake_case : Union[str, Any]=12 , __snake_case : Dict=12 , __snake_case : Tuple=30_72 , __snake_case : Optional[Any]="gelu" , __snake_case : str=0.1 , __snake_case : Any=0.1 , __snake_case : str=5_12 , __snake_case : int=2 , __snake_case : Any=0.02 , __snake_case : int=1e-1_2 , __snake_case : str=1 , __snake_case : Union[str, Any]=0 , __snake_case : Tuple=2 , __snake_case : Optional[int]="absolute" , __snake_case : Union[str, Any]=True , __snake_case : Union[str, Any]=None , **__snake_case : str , ): super().__init__(pad_token_id=__snake_case , bos_token_id=__snake_case , eos_token_id=__snake_case , **__snake_case ) a : List[str] = vocab_size a : str = hidden_size a : Tuple = num_hidden_layers a : Dict = num_attention_heads a : List[Any] = hidden_act a : str = intermediate_size a : Union[str, Any] = hidden_dropout_prob a : Optional[Any] = attention_probs_dropout_prob a : Any = max_position_embeddings a : Optional[int] = type_vocab_size a : str = initializer_range a : List[Any] = layer_norm_eps a : Optional[int] = position_embedding_type a : Dict = use_cache a : Any = classifier_dropout class a__( lowerCamelCase__ ): @property def lowercase_ ( self : int ): if self.task == "multiple-choice": a : Optional[Any] = {0: 'batch', 1: 'choice', 2: 'sequence'} else: a : str = {0: 'batch', 1: 'sequence'} return OrderedDict( [ ('input_ids', dynamic_axis), ('attention_mask', dynamic_axis), ] )
297
1