






"""simple docstring"""

import math
from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
import torch
from transformers import CLIPTextModelWithProjection, CLIPTokenizer

from ...models import PriorTransformer
from ...pipelines import DiffusionPipeline
from ...schedulers import HeunDiscreteScheduler
from ...utils import (
    BaseOutput,
    is_accelerate_available,
    is_accelerate_version,
    logging,
    randn_tensor,
    replace_example_docstring,
)
from .renderer import ShapERenderer


lowercase           =							logging.get_logger(__name__)  # pylint: disable=invalid-name

lowercase           =							'''
    Examples:
        ```py
        >>> import torch
        >>> from diffusers import DiffusionPipeline
        >>> from diffusers.utils import export_to_gif

        >>> device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

        >>> repo = "openai/shap-e"
        >>> pipe = DiffusionPipeline.from_pretrained(repo, torch_dtype=torch.float16)
        >>> pipe = pipe.to(device)

        >>> guidance_scale = 15.0
        >>> prompt = "a shark"

        >>> images = pipe(
        ...     prompt,
        ...     guidance_scale=guidance_scale,
        ...     num_inference_steps=64,
        ...     frame_size=256,
        ... ).images

        >>> gif_path = export_to_gif(images[0], "shark_3d.gif")
        ```
'''

@dataclass
class     A_				(   snake_case_	):
				UpperCAmelCase__										=					42





class     A_				(   snake_case_	):







				def __init__(				self				:    Dict    ,     __lowerCamelCase				:    PriorTransformer    ,     __lowerCamelCase				:    CLIPTextModelWithProjection    ,     __lowerCamelCase				:    CLIPTokenizer    ,     __lowerCamelCase				:    HeunDiscreteScheduler    ,     __lowerCamelCase				:    ShapERenderer    ,     )					->       str:
										super().__init__()

										self.register_modules(
										    prior=__lowerCamelCase    ,     text_encoder=__lowerCamelCase    ,     tokenizer=__lowerCamelCase    ,     scheduler=__lowerCamelCase    ,     renderer=__lowerCamelCase    ,     )







				def      _snake_case       (				self				:    Optional[int]    ,     __lowerCamelCase				:    str    ,     __lowerCamelCase				:    Any    ,     __lowerCamelCase				:    List[str]    ,     __lowerCamelCase				:    int    ,     __lowerCamelCase				:    Any    ,     __lowerCamelCase				:    List[str]						)					->       Optional[Any]:
										if latents is None:
																__magic_name__      =  randn_tensor(__lowerCamelCase    ,     generator=__lowerCamelCase    ,     device=__lowerCamelCase    ,     dtype=__lowerCamelCase						)
										else:
																if latents.shape != shape:
																						raise ValueError(f'''Unexpected latents shape, got {latents.shape}, expected {shape}'''						)
																__magic_name__      =  latents.to(__lowerCamelCase						)

										__magic_name__      =  latents * scheduler.init_noise_sigma
										return latents







				def      _snake_case       (				self				:    Tuple    ,     __lowerCamelCase				:    Any=0						)					->       Any:
										if is_accelerate_available():
																from accelerate import cpu_offload
										else:
																raise ImportError("Please install accelerate via `pip install accelerate`"						)

										__magic_name__      =  torch.device(f'''cuda:{gpu_id}'''						)

										__magic_name__      =  [self.text_encoder, self.prior]
										for cpu_offloaded_model in models:
																if cpu_offloaded_model is not None:
																						cpu_offload(__lowerCamelCase    ,     __lowerCamelCase						)







				def      _snake_case       (				self				:    List[str]    ,     __lowerCamelCase				:    str=0						)					->       Optional[int]:
										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."						)

										__magic_name__      =  torch.device(f'''cuda:{gpu_id}'''						)

										if self.device.type != "cpu":
																self.to("cpu"    ,     silence_dtype_warnings=__lowerCamelCase						)
																torch.cuda.empty_cache()  # otherwise we don't see the memory savings (but they probably exist)

										__magic_name__      =  None
										for cpu_offloaded_model in [self.text_encoder, self.prior, self.renderer]:
																__magic_name__   ,     __magic_name__      =  cpu_offload_with_hook(__lowerCamelCase    ,     __lowerCamelCase    ,     prev_module_hook=__lowerCamelCase						)

										if self.safety_checker is not None:
																__magic_name__   ,     __magic_name__      =  cpu_offload_with_hook(self.safety_checker    ,     __lowerCamelCase    ,     prev_module_hook=__lowerCamelCase						)

										# We'll offload the last model manually.
										__magic_name__      =  hook







				@property
				def      _snake_case       (				self				:    Optional[Any]						)					->       Dict:
										if self.device != torch.device("meta"						) or not hasattr(self.text_encoder    ,     "_hf_hook"						):
																return self.device
										for module in self.text_encoder.modules():
																if (
																    hasattr(__lowerCamelCase    ,     "_hf_hook"						)
																    and hasattr(module._hf_hook    ,     "execution_device"						)
																    and module._hf_hook.execution_device is not None
																):
																						return torch.device(module._hf_hook.execution_device						)
										return self.device







				def      _snake_case       (				self				:    Any    ,     __lowerCamelCase				:    Union[str, Any]    ,     __lowerCamelCase				:    List[Any]    ,     __lowerCamelCase				:    int    ,     __lowerCamelCase				:    Union[str, Any]    ,     )					->       str:
										len(__lowerCamelCase						) if isinstance(__lowerCamelCase    ,     __lowerCamelCase						) else 1

										# YiYi Notes: set pad_token_id to be 0, not sure why I can't set in the config file
										__magic_name__      =  0
										# get prompt text embeddings
										__magic_name__      =  self.tokenizer(
										    __lowerCamelCase    ,     padding="max_length"    ,     max_length=self.tokenizer.model_max_length    ,     truncation=__lowerCamelCase    ,     return_tensors="pt"    ,     )
										__magic_name__      =  text_inputs.input_ids
										__magic_name__      =  self.tokenizer(__lowerCamelCase    ,     padding="longest"    ,     return_tensors="pt"						).input_ids

										if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]						)
																logger.warning(
																    "The following part of your input was truncated because CLIP can only handle sequences up to"
																    f''' {self.tokenizer.model_max_length} tokens: {removed_text}'''						)

										__magic_name__      =  self.text_encoder(text_input_ids.to(__lowerCamelCase						)						)
										__magic_name__      =  text_encoder_output.text_embeds

										__magic_name__      =  prompt_embeds.repeat_interleave(__lowerCamelCase    ,     dim=0						)
										# in Shap-E it normalize the prompt_embeds and then later rescale it
										__magic_name__      =  prompt_embeds / torch.linalg.norm(__lowerCamelCase    ,     dim=-1    ,     keepdim=__lowerCamelCase						)

										if do_classifier_free_guidance:
																__magic_name__      =  torch.zeros_like(__lowerCamelCase						)

																# 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
																__magic_name__      =  torch.cat([negative_prompt_embeds, prompt_embeds]						)

										# Rescale the features to have unit variance
										__magic_name__      =  math.sqrt(prompt_embeds.shape[1]						) * prompt_embeds

										return prompt_embeds







				@torch.no_grad()
				@replace_example_docstring(__lowerCamelCase						)
				def __call__(				self				:    int    ,     __lowerCamelCase				:    str    ,     __lowerCamelCase				:    int = 1    ,     __lowerCamelCase				:    int = 2_5    ,     __lowerCamelCase				:    Optional[Union[torch.Generator, List[torch.Generator]]] = None    ,     __lowerCamelCase				:    Optional[torch.FloatTensor] = None    ,     __lowerCamelCase				:    float = 4.0    ,     __lowerCamelCase				:    int = 6_4    ,     __lowerCamelCase				:    Optional[str] = "pil"    ,     __lowerCamelCase				:    bool = True    ,     )					->       List[Any]:

										if isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  1
										elif isinstance(__lowerCamelCase    ,     __lowerCamelCase						):
																__magic_name__      =  len(__lowerCamelCase						)
										else:
																raise ValueError(f'''`prompt` has to be of type `str` or `list` but is {type(__lowerCamelCase						)}'''						)

										__magic_name__      =  self._execution_device

										__magic_name__      =  batch_size * num_images_per_prompt

										__magic_name__      =  guidance_scale > 1.0
										__magic_name__      =  self._encode_prompt(__lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase						)

										# prior

										self.scheduler.set_timesteps(__lowerCamelCase    ,     device=__lowerCamelCase						)
										__magic_name__      =  self.scheduler.timesteps

										__magic_name__      =  self.prior.config.num_embeddings
										__magic_name__      =  self.prior.config.embedding_dim

										__magic_name__      =  self.prepare_latents(
										    (batch_size, num_embeddings * embedding_dim)    ,     prompt_embeds.dtype    ,     __lowerCamelCase    ,     __lowerCamelCase    ,     __lowerCamelCase    ,     self.scheduler    ,     )

										# YiYi notes: for testing only to match ldm, we can directly create a latents with desired shape: batch_size, num_embeddings, embedding_dim
										__magic_name__      =  latents.reshape(latents.shape[0]    ,     __lowerCamelCase    ,     __lowerCamelCase						)

										for i, t in enumerate(self.progress_bar(__lowerCamelCase						)						):
																# expand the latents if we are doing classifier free guidance
																__magic_name__      =  torch.cat([latents] * 2						) if do_classifier_free_guidance else latents
																__magic_name__      =  self.scheduler.scale_model_input(__lowerCamelCase    ,     __lowerCamelCase						)

																__magic_name__      =  self.prior(
																    __lowerCamelCase    ,     timestep=__lowerCamelCase    ,     proj_embedding=__lowerCamelCase    ,     ).predicted_image_embedding

																# remove the variance
																__magic_name__   ,     __magic_name__      =  noise_pred.split(
																    scaled_model_input.shape[2]    ,     dim=2						)  # batch_size, num_embeddings, embedding_dim

																if do_classifier_free_guidance is not None:
																						__magic_name__   ,     __magic_name__      =  noise_pred.chunk(2						)
																						__magic_name__      =  noise_pred_uncond + guidance_scale * (noise_pred - noise_pred_uncond)

																__magic_name__      =  self.scheduler.step(
																    __lowerCamelCase    ,     timestep=__lowerCamelCase    ,     sample=__lowerCamelCase    ,     ).prev_sample

										if output_type == "latent":
																return ShapEPipelineOutput(images=__lowerCamelCase						)

										__magic_name__      =  []
										for i, latent in enumerate(__lowerCamelCase						):
																__magic_name__      =  self.renderer.decode(
																    latent[None, :]    ,     __lowerCamelCase    ,     size=__lowerCamelCase    ,     ray_batch_size=4_0_9_6    ,     n_coarse_samples=6_4    ,     n_fine_samples=1_2_8    ,     )
																images.append(__lowerCamelCase						)

										__magic_name__      =  torch.stack(__lowerCamelCase						)

										if output_type not in ["np", "pil"]:
																raise ValueError(f'''Only the output types `pil` and `np` are supported not output_type={output_type}'''						)

										__magic_name__      =  images.cpu().numpy()

										if output_type == "pil":
																__magic_name__      =  [self.numpy_to_pil(__lowerCamelCase						) for image in images]

										# Offload last model to CPU
										if hasattr(self    ,     "final_offload_hook"						) and self.final_offload_hook is not None:
																self.final_offload_hook.offload()

										if not return_dict:
																return (images,)

										return ShapEPipelineOutput(images=__lowerCamelCase						)











"""simple docstring"""

from __future__ import annotations

lowercase           =							{1: 1}






def _lowerCAmelCase						(	__lowerCamelCase:int ):

						'''simple docstring'''






						if n in COLLATZ_SEQUENCE_LENGTHS:
												return COLLATZ_SEQUENCE_LENGTHS[n]
						__magic_name__      =  n // 2 if n % 2 == 0 else 3 * n + 1
						__magic_name__      =  collatz_sequence_length(__lowerCamelCase ) + 1
						__magic_name__      =  sequence_length
						return sequence_length






def _lowerCAmelCase						(	__lowerCamelCase:int = 1_0_0_0_0_0_0 ):

						'''simple docstring'''






						__magic_name__      =  max((collatz_sequence_length(__lowerCamelCase ), i) for i in range(1			,    __lowerCamelCase ) )
						return result[1]


if __name__ == "__main__":
			print(solution(int(input().strip())))



