






"""simple docstring"""






import argparse
import time

import torch
import transformers
from measures_util import end_measure, log_measures, start_measure
from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeqaSeqLM, AutoTokenizer

from accelerate.utils import compute_module_sizes


A_			  =    {
    "gpt-j-6b": {"is_causal": True, "model": "sgugger/sharded-gpt-j-6B", "tokenizer": "EleutherAI/gpt-j-6B"},
    "gpt-neox": {"is_causal": True, "model": "EleutherAI/gpt-neox-20b"},
    "opt": {"is_causal": True, "model": "facebook/opt-30b"},
    "T0pp": {"is_causal": False, "model": "bigscience/T0pp", "model_revision": "sharded"},
}

A_			  =    [
    "Hello, my name is",
    "Are unicorns real? Unicorns are",
    "For the first time in several years,",
    "My name is Julien and I am",
    "The goal of life is",
    "Whenever I'm sad, I like to",
]




def 						_UpperCamelCase			(  ):
      UpperCamelCase_     =argparse.ArgumentParser(description="Run and time generations on a big model using Accelerate."			)
      parser.add_argument("model_name"    ,       type=A    ,       default=A    ,       help="The name of the model to try."			)
      parser.add_argument(
          "--tokenizer_name"    ,       type=A    ,       default=A    ,       help="The name of the tokenizer (if different from the model."			)
      parser.add_argument("--is_causal"    ,       type=A    ,       default=A    ,       help="Whether or not the model is causal."			)
      parser.add_argument(
          "--model_revision"    ,       type=A    ,       default=A    ,       help="The revision to use for the model checkpoint."			)
      parser.add_argument("--torch_dtype"    ,       type=A    ,       default=A    ,       help="The dtype for the model."			)
      parser.add_argument("--disk_offload"    ,       action="store_true"			)

      UpperCamelCase_     =parser.parse_args()

      # Sanitize args
      if args.model_name in DEFAULT_MODELS:
            UpperCamelCase_     =DEFAULT_MODELS[args.model_name]
            UpperCamelCase_     =defaults["""model"""]
            if args.tokenizer_name is None:
                  UpperCamelCase_     =defaults.get("tokenizer"    ,       args.model_name			)
            if args.is_causal is None:
                  UpperCamelCase_     =defaults["""is_causal"""]
            if args.model_revision is None:
                  UpperCamelCase_     =defaults.get("model_revision"    ,       "main"			)

      if args.is_causal is None:
            raise ValueError("Could not infer the default for `--is_causal`, pass either True or False for it."			)
      if args.tokenizer_name is None:
            UpperCamelCase_     =args.model_name
      if args.model_revision is None:
            UpperCamelCase_     ="""main"""

      return args




def 						_UpperCamelCase			(  ):
      transformers.utils.logging.set_verbosity_error()
      UpperCamelCase_     =parse_args()

      if args.torch_dtype is None:
            UpperCamelCase_     =AutoConfig.from_pretrained(args.model_name			)
            UpperCamelCase_     =getattr(A    ,       "torch_dtype"    ,       torch.floataa			)
      else:
            UpperCamelCase_     =getattr(A    ,       args.torch_dtype			)
      UpperCamelCase_     =AutoModelForCausalLM if args.is_causal else AutoModelForSeqaSeqLM
      UpperCamelCase_     ={
          """torch_dtype""": torch_dtype,
          """revision""": args.model_revision,
      }
      if args.disk_offload:
            UpperCamelCase_     ="""tmp_offload"""
            UpperCamelCase_     =True

      UpperCamelCase_     =start_measure()
      UpperCamelCase_     =model_cls.from_pretrained(args.model_name    ,       device_map="auto"    ,       **A			)
      UpperCamelCase_     =end_measure(A			)
      log_measures(A    ,       "Model loading"			)

      UpperCamelCase_     =compute_module_sizes(A			)
      UpperCamelCase_     ={v: 0 for v in model.hf_device_map.values()}
      for module, device in model.hf_device_map.items():
            device_size[device] += module_sizes[module]
      UpperCamelCase_     ="""\n""".join([f"""- {device}: {size // 2**20}MiB""" for device, size in device_size.items()]			)
      print(f"""\nTheoretical use:\n{message}"""			)

      UpperCamelCase_     =AutoTokenizer.from_pretrained(args.tokenizer_name			)

      UpperCamelCase_     =start_measure()
      UpperCamelCase_     =[]
      UpperCamelCase_     =[]
      UpperCamelCase_     =[]
      for prompt in PROMPTS:
            UpperCamelCase_     =tokenizer(A    ,       return_tensors="pt"			).to(0			)
            UpperCamelCase_     =inputs["""input_ids"""][0].tolist()
            UpperCamelCase_     =time.time()
            UpperCamelCase_     =model.generate(inputs["input_ids"]			)
            UpperCamelCase_     =time.time()
            UpperCamelCase_     =outputs[0].tolist()
            UpperCamelCase_     =len(A			) if outputs[: len(A			)] != tokens else len(A			) - len(A			)
            UpperCamelCase_     =after_generate - before_generate

            UpperCamelCase_     =tokenizer.decode(A    ,       skip_special_tokens=A			)
            texts_outs.append(A			)
            generation_times.append(A			)
            gen_tokens.append(A			)
            print(f"""Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n"""			)

      UpperCamelCase_     =end_measure(A			)
      log_measures(A    ,       "Model generation"			)

      UpperCamelCase_     =[gen / tok for gen, tok in zip(A    ,       A			)]
      UpperCamelCase_     =sum(A			) / len(A			)
      print(f"""Average time of generation per token: {avg_gen:.2f}s"""			)
      print(f"""First generation (avg time per token): {generation_times_per_token[0]:.2f}s"""			)
      UpperCamelCase_     =sum(generation_times_per_token[1:]			) / (len(A			) - 1)
      print(f"""Average time of generation per token (excluding the first): {avg_gen:.2f}s"""			)


if __name__ == "__main__":
    main()








"""simple docstring"""






from math import radians as angle_to_radians
from math import sin

# Acceleration Constant on Earth (unit m/s^2)
A_			  =    9.80665




def 						_UpperCamelCase			(  A    ,       A			):

   # Ensure valid instance
   if not isinstance(A    ,       (int, float)			):
      raise TypeError("Invalid velocity. Should be a positive number."			)

   if not isinstance(A    ,       (int, float)			):
      raise TypeError("Invalid angle. Range is 1-90 degrees."			)

   # Ensure valid angle
   if angle > 90 or angle < 1:
      raise ValueError("Invalid angle. Range is 1-90 degrees."			)

   # Ensure valid velocity
   if init_velocity < 0:
      raise ValueError("Invalid velocity. Should be a positive number."			)




def 						_UpperCamelCase			(  A    ,       A			):
   check_args(A    ,       A			)
   UpperCamelCase_     =angle_to_radians(2 * angle			)
   return round(init_velocity**2 * sin(A			) / g    ,       2			)




def 						_UpperCamelCase			(  A    ,       A			):
   check_args(A    ,       A			)
   UpperCamelCase_     =angle_to_radians(A			)
   return round(init_velocity**2 * sin(A			) ** 2 / (2 * g)    ,       2			)




def 						_UpperCamelCase			(  A    ,       A			):
   check_args(A    ,       A			)
   UpperCamelCase_     =angle_to_radians(A			)
   return round(2 * init_velocity * sin(A			) / g    ,       2			)




def 						_UpperCamelCase			(  ):
   UpperCamelCase_    ,							UpperCamelCase_     =25, 20
   assert horizontal_distance(A    ,       A			) == 40.97
   assert max_height(A    ,       A			) == 3.73
   assert total_time(A    ,       A			) == 1.74


if __name__ == "__main__":
    from doctest import testmod

    testmod()

    # Get input from user
    A_			  =    float(input("Initial Velocity: ").strip())

    # Get input from user
    A_			  =    float(input("angle: ").strip())

    # Print results
    print()
    print("Results: ")
    print(f'''Horizontal Distance: {horizontal_distance(init_vel, angle)!s} [m]''')
    print(f'''Maximum Height: {max_height(init_vel, angle)!s} [m]''')
    print(f'''Total Time: {total_time(init_vel, angle)!s} [s]''')
