
from __future__ import annotations

import unittest

from transformers import AutoTokenizer, GPTJConfig, is_tf_available
from transformers.testing_utils import require_tf, slow, tooslow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin
from ...utils.test_modeling_tf_core import TFCoreModelTesterMixin


if is_tf_available():
 import tensorflow as tf

 from transformers.models.gptj.modeling_tf_gptj import (
     TFGPTJForCausalLM,
     TFGPTJForQuestionAnswering,
     TFGPTJForSequenceClassification,
     TFGPTJModel,
     shape_list,
 )


class   __lowerCAmelCase		:



      """simple docstring"""







      def __init__( self						:    Tuple			,    _snake_case						:    List[Any]			):
          __lowercase						:     Optional[Any]		      =    parent
          __lowercase						:     Any		      =    13
          __lowercase						:     Union[str, Any]		      =    7
          __lowercase						:     Dict		      =    True
          __lowercase						:     str		      =    True
          __lowercase						:     Dict		      =    True
          __lowercase						:     int		      =    True
          __lowercase						:     Any		      =    True
          __lowercase						:     Dict		      =    99
          __lowercase						:     Optional[int]		      =    32
          __lowercase						:     Optional[Any]		      =    4
          __lowercase						:     Union[str, Any]		      =    2
          __lowercase						:     Tuple		      =    4
          __lowercase						:     Union[str, Any]		      =    37
          __lowercase						:     Tuple		      =    "gelu"
          __lowercase						:     Tuple		      =    0.1
          __lowercase						:     List[Any]		      =    0.1
          __lowercase						:     Optional[int]		      =    512
          __lowercase						:     Any		      =    16
          __lowercase						:     Dict		      =    2
          __lowercase						:     Tuple		      =    0.02
          __lowercase						:     Tuple		      =    3
          __lowercase						:     str		      =    4
          __lowercase						:     Tuple		      =    None
          __lowercase						:     int		      =    self.vocab_size - 1
          __lowercase						:     Dict		      =    self.vocab_size - 1
          __lowercase						:     Optional[Any]		      =    self.vocab_size - 1




      def 						snake_case_     ( self						:    str			):
          __lowercase						:     str		      =    ids_tensor([self.batch_size, self.seq_length]			,    self.vocab_size			)

          __lowercase						:     Union[str, Any]		      =    None
          if self.use_input_mask:
              __lowercase						:     List[Any]		      =    random_attention_mask([self.batch_size, self.seq_length]			)

          __lowercase						:     Union[str, Any]		      =    None
          if self.use_token_type_ids:
              __lowercase						:     Union[str, Any]		      =    ids_tensor([self.batch_size, self.seq_length]			,    self.type_vocab_size			)

          __lowercase						:     int		      =    None
          if self.use_mc_token_ids:
              __lowercase						:     List[Any]		      =    ids_tensor([self.batch_size, self.num_choices]			,    self.seq_length			)

          __lowercase						:     Optional[int]		      =    None
          __lowercase						:     Optional[Any]		      =    None
          __lowercase						:     Any		      =    None
          if self.use_labels:
              __lowercase						:     Union[str, Any]		      =    ids_tensor([self.batch_size]			,    self.type_sequence_label_size			)
              __lowercase						:     Optional[Any]		      =    ids_tensor([self.batch_size, self.seq_length]			,    self.num_labels			)
              __lowercase						:     str		      =    ids_tensor([self.batch_size]			,    self.num_choices			)

          __lowercase						:     Optional[int]		      =    GPTJConfig(
              vocab_size=self.vocab_size			,    n_embd=self.hidden_size			,    n_layer=self.num_hidden_layers			,    n_head=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			,    n_positions=self.max_position_embeddings			,    type_vocab_size=self.type_vocab_size			,    initializer_range=self.initializer_range			,    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_dict=_snake_case			,    )

          __lowercase						:     List[str]		      =    ids_tensor([self.num_hidden_layers, self.num_attention_heads]			,    2			)

          return (
              config,
              input_ids,
              input_mask,
              head_mask,
              token_type_ids,
              mc_token_ids,
              sequence_labels,
              token_labels,
              choice_labels,
          )




      def 						snake_case_     ( self						:    Tuple			,    _snake_case						:    str			,    _snake_case						:    List[str]			,    _snake_case						:    Dict			,    _snake_case						:    int			,    _snake_case						:    List[str]			,    *_snake_case						:    int			):
          __lowercase						:     Optional[Any]		      =    TFGPTJModel(config=_snake_case			)
          __lowercase						:     List[Any]		      =    {
              "input_ids": input_ids,
              "attention_mask": input_mask,
              "token_type_ids": token_type_ids,
          }
          __lowercase						:     List[Any]		      =    model(_snake_case			)

          __lowercase						:     Dict		      =    [input_ids, None, input_mask]  # None is the input for 'past'
          __lowercase						:     List[str]		      =    model(_snake_case			)

          __lowercase						:     str		      =    model(_snake_case			)

          self.parent.assertEqual(result.last_hidden_state.shape			,    (self.batch_size, self.seq_length, self.hidden_size)			)




      def 						snake_case_     ( self						:    Tuple			,    _snake_case						:    str			,    _snake_case						:    Any			,    _snake_case						:    List[str]			,    _snake_case						:    str			,    _snake_case						:    str			,    *_snake_case						:    List[Any]			):
          __lowercase						:     Dict		      =    TFGPTJModel(config=_snake_case			)

          # first forward pass
          __lowercase						:     List[str]		      =    model(_snake_case			,    token_type_ids=_snake_case			,    use_cache=_snake_case			)
          __lowercase						:     Union[str, Any]		      =    model(_snake_case			,    token_type_ids=_snake_case			)
          __lowercase						:     Dict		      =    model(_snake_case			,    token_type_ids=_snake_case			,    use_cache=_snake_case			)

          self.parent.assertTrue(len(_snake_case			) == len(_snake_case			)			)
          self.parent.assertTrue(len(_snake_case			) == len(_snake_case			) + 1			)

          __lowercase						:     Any		      =    outputs.to_tuple()

          # create hypothetical next token and extent to next_input_ids
          __lowercase						:     Tuple		      =    ids_tensor((self.batch_size, 1)			,    config.vocab_size			)
          __lowercase						:     int		      =    ids_tensor([self.batch_size, 1]			,    self.type_vocab_size			)

          # append to next input_ids and token_type_ids
          __lowercase						:     Dict		      =    tf.concat([input_ids, next_tokens]			,    axis=-1			)
          __lowercase						:     Optional[Any]		      =    tf.concat([token_type_ids, next_token_types]			,    axis=-1			)

          __lowercase						:     int		      =    model(_snake_case			,    token_type_ids=_snake_case			)["last_hidden_state"]
          __lowercase						:     Tuple		      =    model(_snake_case			,    token_type_ids=_snake_case			,    past_key_values=_snake_case			)[
              "last_hidden_state"
          ]

          # select random slice
          __lowercase						:     List[str]		      =    int(ids_tensor((1,)			,    shape_list(_snake_case			)[-1]			)			)
          __lowercase						:     Optional[Any]		      =    output_from_no_past[:, -1, random_slice_idx]
          __lowercase						:     Optional[Any]		      =    output_from_past[:, 0, random_slice_idx]

          # test that outputs are equal for slice
          tf.debugging.assert_near(_snake_case			,    _snake_case			,    rtol=1E-6			)




      def 						snake_case_     ( self						:    str			,    _snake_case						:    Tuple			,    _snake_case						:    int			,    _snake_case						:    Dict			,    _snake_case						:    Dict			,    _snake_case						:    int			,    *_snake_case						:    Optional[Any]			):
          __lowercase						:     List[Any]		      =    TFGPTJModel(config=_snake_case			)

          # create attention mask
          __lowercase						:     Tuple		      =    self.seq_length // 2
          __lowercase						:     Tuple		      =    tf.ones((self.batch_size, half_seq_length)			,    dtype=tf.intaa			)
          __lowercase						:     Any		      =    tf.zeros((self.batch_size, self.seq_length - half_seq_length)			,    dtype=tf.intaa			)
          __lowercase						:     List[str]		      =    tf.concat([attn_mask_begin, attn_mask_end]			,    axis=1			)

          # first forward pass
          __lowercase						:     Any		      =    model(_snake_case			,    attention_mask=_snake_case			).to_tuple()

          # create hypothetical next token and extent to next_input_ids
          __lowercase						:     List[Any]		      =    ids_tensor((self.batch_size, 1)			,    config.vocab_size			)

          # change a random masked slice from input_ids
          __lowercase						:     List[str]		      =    ids_tensor((1,)			,    _snake_case			).numpy() + 1
          __lowercase						:     List[Any]		      =    ids_tensor((self.batch_size, self.seq_length)			,    config.vocab_size			)
          __lowercase						:     str		      =    tf.range(self.seq_length			) == (self.seq_length - random_seq_idx_to_change)
          __lowercase						:     Dict		      =    tf.transpose(
              tf.broadcast_to(tf.expand_dims(_snake_case			,    -1			)			,    (self.seq_length, self.batch_size)			)			)
          __lowercase						:     int		      =    tf.where(_snake_case			,    _snake_case			,    _snake_case			)

          # append to next input_ids and attn_mask
          __lowercase						:     int		      =    tf.concat([input_ids, next_tokens]			,    axis=-1			)
          __lowercase						:     Union[str, Any]		      =    tf.concat([attn_mask, tf.ones((shape_list(_snake_case			)[0], 1)			,    dtype=tf.intaa			)]			,    axis=1			)

          # get two different outputs
          __lowercase						:     Optional[Any]		      =    model(_snake_case			,    attention_mask=_snake_case			)["last_hidden_state"]
          __lowercase						:     int		      =    model(_snake_case			,    past_key_values=_snake_case			,    attention_mask=_snake_case			)[
              "last_hidden_state"
          ]

          # select random slice
          __lowercase						:     Optional[Any]		      =    int(ids_tensor((1,)			,    shape_list(_snake_case			)[-1]			)			)
          __lowercase						:     Union[str, Any]		      =    output_from_no_past[:, -1, random_slice_idx]
          __lowercase						:     Optional[Any]		      =    output_from_past[:, 0, random_slice_idx]

          # test that outputs are equal for slice
          tf.debugging.assert_near(_snake_case			,    _snake_case			,    rtol=1E-1_2			)




      def 						snake_case_     ( self						:    Tuple			,    _snake_case						:    Optional[int]			,    _snake_case						:    Tuple			,    _snake_case						:    Union[str, Any]			,    _snake_case						:    List[Any]			,    _snake_case						:    Any			,    *_snake_case						:    Union[str, Any]			):
          __lowercase						:     int		      =    TFGPTJModel(config=_snake_case			)

          __lowercase						:     int		      =    input_ids[:1, :]
          __lowercase						:     Optional[int]		      =    input_mask[:1, :]
          __lowercase						:     Optional[int]		      =    token_type_ids[:1, :]
          __lowercase						:     Optional[int]		      =    1

          # first forward pass
          __lowercase						:     Optional[int]		      =    model(_snake_case			,    attention_mask=_snake_case			,    token_type_ids=_snake_case			,    use_cache=_snake_case			)

          __lowercase						:     List[str]		      =    outputs.to_tuple()

          # create hypothetical next token and extent to next_input_ids
          __lowercase						:     int		      =    ids_tensor((self.batch_size, 3)			,    config.vocab_size			)
          __lowercase						:     str		      =    ids_tensor((self.batch_size, 3)			,    2			)
          __lowercase						:     int		      =    ids_tensor((self.batch_size, 3)			,    self.type_vocab_size			)

          # append to next input_ids and token_type_ids
          __lowercase						:     Union[str, Any]		      =    tf.concat([input_ids, next_tokens]			,    axis=-1			)
          __lowercase						:     Tuple		      =    tf.concat([input_mask, next_attn_mask]			,    axis=-1			)
          __lowercase						:     Optional[int]		      =    tf.concat([token_type_ids, next_token_types]			,    axis=-1			)

          __lowercase						:     List[Any]		      =    model(
              _snake_case			,    token_type_ids=_snake_case			,    attention_mask=_snake_case			)["last_hidden_state"]
          __lowercase						:     List[str]		      =    model(
              _snake_case			,    token_type_ids=_snake_case			,    attention_mask=_snake_case			,    past_key_values=_snake_case			,    )["last_hidden_state"]
          self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1]			)

          # select random slice
          __lowercase						:     int		      =    int(ids_tensor((1,)			,    shape_list(_snake_case			)[-1]			)			)
          __lowercase						:     Tuple		      =    output_from_no_past[:, -3:, random_slice_idx]
          __lowercase						:     List[str]		      =    output_from_past[:, :, random_slice_idx]

          # test that outputs are equal for slice
          tf.debugging.assert_near(_snake_case			,    _snake_case			,    rtol=1E-3			)




      def 						snake_case_     ( self						:    List[str]			,    _snake_case						:    List[str]			,    _snake_case						:    Tuple			,    _snake_case						:    Optional[int]			,    _snake_case						:    List[str]			,    _snake_case						:    str			,    *_snake_case						:    int			):
          __lowercase						:     Union[str, Any]		      =    TFGPTJForCausalLM(config=_snake_case			)
          __lowercase						:     List[Any]		      =    {
              "input_ids": input_ids,
              "attention_mask": input_mask,
              "token_type_ids": token_type_ids,
          }
          __lowercase						:     Optional[int]		      =    model(_snake_case			)
          self.parent.assertEqual(result.logits.shape			,    (self.batch_size, self.seq_length, self.vocab_size)			)




      def 						snake_case_     ( self						:    List[Any]			):
          __lowercase						:     Tuple		      =    self.prepare_config_and_inputs()

          (
              __lowercase
          )						:     List[str]		      =    config_and_inputs

          __lowercase						:     Union[str, Any]		      =    {
              "input_ids": input_ids,
              "token_type_ids": token_type_ids,
              "attention_mask": input_mask,
          }
          return config, inputs_dict






@require_tf
class   __lowerCAmelCase		(		__A	,	__A	,	__A	,	unittest.TestCase ):



      """simple docstring"""







      A__		:     Dict       				=      (
          (TFGPTJForCausalLM, TFGPTJForSequenceClassification, TFGPTJForQuestionAnswering, TFGPTJModel)
          if is_tf_available()
          else ()
      )

      A__		:     Dict       				=      (TFGPTJForCausalLM,) if is_tf_available() else ()
      A__		:     List[str]       				=      (
          {
              '''feature-extraction''': TFGPTJModel,
              '''question-answering''': TFGPTJForQuestionAnswering,
              '''text-classification''': TFGPTJForSequenceClassification,
              '''text-generation''': TFGPTJForCausalLM,
              '''zero-shot''': TFGPTJForSequenceClassification,
          }
          if is_tf_available()
          else {}
      )
      A__		:     List[str]       				=      False
      A__		:     Union[str, Any]       				=      False
      A__		:     str       				=      False
      A__		:     Optional[Any]       				=      False




      def 						snake_case_     ( self						:    Optional[Any]			,    _snake_case						:    Optional[Any]			,    _snake_case						:    List[Any]			,    _snake_case						:    List[str]			,    _snake_case						:    Optional[Any]			,    _snake_case						:    List[str]			):

          if (
              pipeline_test_casse_name == "QAPipelineTests"
              and tokenizer_name is not None
              and not tokenizer_name.endswith('''Fast'''			)
          ):
              # `QAPipelineTests` fails for a few models when the slower tokenizer are used.
              # (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
              # TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
              return True

          return False




      def 						snake_case_     ( self						:    int			):
          __lowercase						:     Any		      =    TFGPTJModelTester(self			)
          __lowercase						:     int		      =    ConfigTester(self			,    config_class=_snake_case			,    n_embd=37			)




      def 						snake_case_     ( self						:    List[str]			):
          self.config_tester.run_common_tests()




      def 						snake_case_     ( self						:    Optional[Any]			):
          __lowercase						:     int		      =    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_gptj_model(*_snake_case			)




      def 						snake_case_     ( self						:    Optional[Any]			):
          __lowercase						:     List[Any]		      =    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_gptj_model_past(*_snake_case			)




      def 						snake_case_     ( self						:    Optional[Any]			):
          __lowercase						:     Optional[int]		      =    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_gptj_model_attention_mask_past(*_snake_case			)




      def 						snake_case_     ( self						:    Dict			):
          __lowercase						:     List[str]		      =    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_gptj_model_past_large_inputs(*_snake_case			)




      def 						snake_case_     ( self						:    Dict			):
          __lowercase						:     Optional[Any]		      =    self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_gptj_lm_head_model(*_snake_case			)




      @slow
      @unittest.skipIf(
          not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''			)			) > 0			,    '''skip testing on GPU for now to avoid GPU OOM.'''			,    )
      def 						snake_case_     ( self						:    Union[str, Any]			):
          __lowercase						:     Optional[Any]		      =    TFGPTJModel.from_pretrained('''EleutherAI/gpt-j-6B'''			,    from_pt=_snake_case			)
          self.assertIsNotNone(_snake_case			)




      @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.'''			)
      def 						snake_case_     ( self						:    List[str]			):
          super().test_resize_token_embeddings()






@require_tf
@tooslow
# Marked as @tooslow due to GPU OOM -- but still useful to run locally. Requires ~39GB of RAM.
class   __lowerCAmelCase		(		unittest.TestCase ):



      """simple docstring"""







      def 						snake_case_     ( self						:    Dict			):
          __lowercase						:     Optional[Any]		      =    TFGPTJForCausalLM.from_pretrained('''EleutherAI/gpt-j-6B'''			,    from_pt=_snake_case			)
          __lowercase						:     Optional[int]		      =    tf.convert_to_tensor([[464, 3290]]			,    dtype=tf.intaa			)  # The dog
          # fmt: off
          # The dog is a man's best friend. It is a loyal companion, and it is a friend
          __lowercase						:     str		      =    [464, 3290, 318, 257, 582, 338, 1266, 1545, 13, 632, 318, 257, 9112, 1_5185, 11, 290, 340, 318, 257, 1545]
          # fmt: on
          __lowercase						:     Optional[int]		      =    model.generate(_snake_case			,    do_sample=_snake_case			)
          self.assertListEqual(output_ids[0].numpy().tolist()			,    _snake_case			)




      def 						snake_case_     ( self						:    Union[str, Any]			):
          __lowercase						:     Tuple		      =    AutoTokenizer.from_pretrained('''EleutherAI/gpt-j-6B'''			,    revision='''float16'''			)
          __lowercase						:     int		      =    TFGPTJForCausalLM.from_pretrained('''EleutherAI/gpt-j-6B'''			,    revision='''float16'''			,    from_pt=_snake_case			)

          __lowercase						:     Union[str, Any]		      =    tokenizer('''Today is a nice day and'''			,    return_tensors='''tf'''			)
          # forces the generation to happen on CPU, to avoid GPU-related quirks
          with tf.device(''':/CPU:0'''			):
              __lowercase						:     Union[str, Any]		      =    model.generate(**_snake_case			,    do_sample=_snake_case			,    seed=[42, 0]			)
          __lowercase						:     List[Any]		      =    tokenizer.decode(output_ids[0]			,    skip_special_tokens=_snake_case			)

          __lowercase						:     Tuple		      =    "Today is a nice day and I’m going to go for a walk. I’"
          self.assertEqual(_snake_case			,    _snake_case			)




      def 						snake_case_     ( self						:    Tuple			):
          __lowercase						:     str		      =    TFGPTJForCausalLM.from_pretrained('''EleutherAI/gpt-j-6B'''			,    revision='''float16'''			,    from_pt=_snake_case			)
          __lowercase						:     Optional[int]		      =    AutoTokenizer.from_pretrained('''EleutherAI/gpt-j-6B'''			,    revision='''float16'''			)

          __lowercase						:     Any		      =    "left"

          # Define PAD Token = EOS Token = 50256
          __lowercase						:     Tuple		      =    tokenizer.eos_token
          __lowercase						:     Tuple		      =    model.config.eos_token_id

          # use different length sentences to test batching
          __lowercase						:     str		      =    [
              "Hello, my dog is a little",
              "Today, I",
          ]
          __lowercase						:     Union[str, Any]		      =    [
              "Hello, my dog is a little over a year old and has been diagnosed with hip dysplasia",
              "Today, I’m going to be talking about a topic that’",
          ]
          return model, tokenizer, sentences, expected_output_sentences




      def 						snake_case_     ( self						:    Optional[int]			):
          __lowercase						:     Union[str, Any]		      =    self._get_beam_search_test_objects()

          __lowercase						:     List[Any]		      =    tokenizer(_snake_case			,    return_tensors='''tf'''			,    padding=_snake_case			)
          __lowercase						:     str		      =    model.generate(**_snake_case			,    do_sample=_snake_case			,    num_beams=2			)
          __lowercase						:     Dict		      =    tokenizer.batch_decode(_snake_case			,    skip_special_tokens=_snake_case			)
          self.assertListEqual(_snake_case			,    _snake_case			)




      def 						snake_case_     ( self						:    List[str]			):
          __lowercase						:     Tuple		      =    self._get_beam_search_test_objects()

          __lowercase						:     List[Any]		      =    tokenizer(_snake_case			,    return_tensors='''tf'''			,    padding=_snake_case			)
          __lowercase						:     int		      =    tokenizer(sentences[0]			,    return_tensors='''tf'''			)
          __lowercase						:     List[Any]		      =    model.generate(**_snake_case			,    do_sample=_snake_case			,    num_beams=2			)
          __lowercase						:     List[Any]		      =    (
              shape_list(inputs_non_padded['''input_ids''']			)[-1]
              - tf.reduce_sum(tf.cast(inputs['''attention_mask'''][-1]			,    tf.intaa			)			).numpy()
          )
          __lowercase						:     Optional[Any]		      =    tokenizer(sentences[1]			,    return_tensors='''tf'''			)
          __lowercase						:     Dict		      =    model.generate(
              **_snake_case			,    do_sample=_snake_case			,    num_beams=2			,    max_length=model.config.max_length - num_paddings			)
          __lowercase						:     Dict		      =    tokenizer.decode(output_non_padded[0]			,    skip_special_tokens=_snake_case			)
          __lowercase						:     Union[str, Any]		      =    tokenizer.decode(output_padded[0]			,    skip_special_tokens=_snake_case			)
          self.assertListEqual(_snake_case			,    [non_padded_sentence, padded_sentence]			)




      def 						snake_case_     ( self						:    List[str]			):
          __lowercase						:     Union[str, Any]		      =    self._get_beam_search_test_objects()

          __lowercase						:     Optional[Any]		      =    tokenizer(_snake_case			,    return_tensors='''tf'''			,    padding=_snake_case			)
          __lowercase						:     Any		      =    tf.function(model.generate			,    jit_compile=_snake_case			)
          __lowercase						:     Tuple		      =    xla_generate(**_snake_case			,    do_sample=_snake_case			,    num_beams=2			)
          __lowercase						:     Any		      =    tokenizer.batch_decode(_snake_case			,    skip_special_tokens=_snake_case			)
          self.assertListEqual(_snake_case			,    _snake_case			)




from __future__ import annotations

from math import pi, pow


def       UpperCAmelCase_					(  __lowerCAmelCase		)	->  float:
    if side_length < 0:
        raise ValueError('''vol_cube() only accepts non-negative values'''		)
    return pow(__lowerCAmelCase		,   3		)


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if height < 0 or radius < 0:
        raise ValueError('''vol_spherical_cap() only accepts non-negative values'''		)
    # Volume is 1/3 pi * height squared * (3 * radius - height)
    return 1 / 3 * pi * pow(__lowerCAmelCase		,   2		) * (3 * radius - height)


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if radius_a < 0 or radius_a < 0 or centers_distance < 0:
        raise ValueError('''vol_spheres_intersect() only accepts non-negative values'''		)
    if centers_distance == 0:
        return vol_sphere(min(__lowerCAmelCase		,   __lowerCAmelCase		)		)

    __lowercase						:     Dict		      =    (
        (radius_a - radius_a + centers_distance)
        * (radius_a + radius_a - centers_distance)
        / (2 * centers_distance)
    )
    __lowercase						:     Optional[int]		      =    (
        (radius_a - radius_a + centers_distance)
        * (radius_a + radius_a - centers_distance)
        / (2 * centers_distance)
    )

    return vol_spherical_cap(__lowerCAmelCase		,   __lowerCAmelCase		) + vol_spherical_cap(__lowerCAmelCase		,   __lowerCAmelCase		)


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:

    if radius_a <= 0 or radius_a <= 0 or centers_distance < 0:
        raise ValueError(
            '''vol_spheres_union() only accepts non-negative values, non-zero radius'''		)

    if centers_distance == 0:
        return vol_sphere(max(__lowerCAmelCase		,   __lowerCAmelCase		)		)

    return (
        vol_sphere(__lowerCAmelCase		)
        + vol_sphere(__lowerCAmelCase		)
        - vol_spheres_intersect(__lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		)
    )


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if width < 0 or height < 0 or length < 0:
        raise ValueError('''vol_cuboid() only accepts non-negative values'''		)
    return float(width * height * length		)


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if height < 0 or area_of_base < 0:
        raise ValueError('''vol_cone() only accepts non-negative values'''		)
    return area_of_base * height / 3.0


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if height < 0 or radius < 0:
        raise ValueError('''vol_right_circ_cone() only accepts non-negative values'''		)
    return pi * pow(__lowerCAmelCase		,   2		) * height / 3.0


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if height < 0 or area_of_base < 0:
        raise ValueError('''vol_prism() only accepts non-negative values'''		)
    return float(area_of_base * height		)


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if height < 0 or area_of_base < 0:
        raise ValueError('''vol_pyramid() only accepts non-negative values'''		)
    return area_of_base * height / 3.0


def       UpperCAmelCase_					(  __lowerCAmelCase		)	->  float:
    if radius < 0:
        raise ValueError('''vol_sphere() only accepts non-negative values'''		)
    # Volume is 4/3 * pi * radius cubed
    return 4 / 3 * pi * pow(__lowerCAmelCase		,   3		)


def       UpperCAmelCase_					(  __lowerCAmelCase		)	->  float:
    if radius < 0:
        raise ValueError('''vol_hemisphere() only accepts non-negative values'''		)
    # Volume is radius cubed * pi * 2/3
    return pow(__lowerCAmelCase		,   3		) * pi * 2 / 3


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if height < 0 or radius < 0:
        raise ValueError('''vol_circular_cylinder() only accepts non-negative values'''		)
    # Volume is radius squared * height * pi
    return pow(__lowerCAmelCase		,   2		) * height * pi


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    # Volume - (outer_radius squared - inner_radius squared) * pi * height
    if inner_radius < 0 or outer_radius < 0 or height < 0:
        raise ValueError(
            '''vol_hollow_circular_cylinder() only accepts non-negative values'''		)
    if outer_radius <= inner_radius:
        raise ValueError('''outer_radius must be greater than inner_radius'''		)
    return pi * (pow(__lowerCAmelCase		,   2		) - pow(__lowerCAmelCase		,   2		)) * height


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    # Volume is 1/3 * pi * height *
    #           (radius_1 squared + radius_2 squared + radius_1 * radius_2)
    if radius_a < 0 or radius_a < 0 or height < 0:
        raise ValueError('''vol_conical_frustum() only accepts non-negative values'''		)
    return (
        1
        / 3
        * pi
        * height
        * (pow(__lowerCAmelCase		,   2		) + pow(__lowerCAmelCase		,   2		) + radius_a * radius_a)
    )


def       UpperCAmelCase_					(  __lowerCAmelCase		,   __lowerCAmelCase		)	->  float:
    if torus_radius < 0 or tube_radius < 0:
        raise ValueError('''vol_torus() only accepts non-negative values'''		)
    return 2 * pow(__lowerCAmelCase		,   2		) * torus_radius * pow(__lowerCAmelCase		,   2		)


def       UpperCAmelCase_					(  )	->  Optional[Any]:
    print('''Volumes:'''		)
    print(F'Cube: {vol_cube(2		) = }'		)  # = 8
    print(F'Cuboid: {vol_cuboid(2		,   2		,   2		) = }'		)  # = 8
    print(F'Cone: {vol_cone(2		,   2		) = }'		)  # ~= 1.33
    print(F'Right Circular Cone: {vol_right_circ_cone(2		,   2		) = }'		)  # ~= 8.38
    print(F'Prism: {vol_prism(2		,   2		) = }'		)  # = 4
    print(F'Pyramid: {vol_pyramid(2		,   2		) = }'		)  # ~= 1.33
    print(F'Sphere: {vol_sphere(2		) = }'		)  # ~= 33.5
    print(F'Hemisphere: {vol_hemisphere(2		) = }'		)  # ~= 16.75
    print(F'Circular Cylinder: {vol_circular_cylinder(2		,   2		) = }'		)  # ~= 25.1
    print(F'Torus: {vol_torus(2		,   2		) = }'		)  # ~= 157.9
    print(F'Conical Frustum: {vol_conical_frustum(2		,   2		,   4		) = }'		)  # ~= 58.6
    print(F'Spherical cap: {vol_spherical_cap(1		,   2		) = }'		)  # ~= 5.24
    print(F'Spheres intersetion: {vol_spheres_intersect(2		,   2		,   1		) = }'		)  # ~= 21.21
    print(F'Spheres union: {vol_spheres_union(2		,   2		,   1		) = }'		)  # ~= 45.81
    print(
        F'Hollow Circular Cylinder: {vol_hollow_circular_cylinder(1		,   2		,   3		) = }'		)  # ~= 28.3


if __name__ == "__main__":
 main()


