




'''simple docstring'''



import collections
import types

import numpy as np

from ..utils import (
    add_end_docstrings,
    is_tensorflow_probability_available,
    is_tf_available,
    is_torch_available,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ArgumentHandler, Dataset, Pipeline, PipelineException


if is_torch_available():
     import torch

     from ..models.auto.modeling_auto import (
         MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
         MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
     )

if is_tf_available() and is_tensorflow_probability_available():
     import tensorflow as tf
     import tensorflow_probability as tfp

     from ..models.auto.modeling_tf_auto import (
         TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING,
         TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING,
     )





class     lowerCAmelCase   ( __lowerCAmelCase):


       def __call__(   self    ,  __SCREAMING_SNAKE_CASE=None    ,  __SCREAMING_SNAKE_CASE=None    ,  **__SCREAMING_SNAKE_CASE  )      ->  List[Any]:



            '''simple docstring'''




            requires_backends(self    ,  '''pandas'''  )
            import pandas as pd

            if table is None:
                 raise ValueError('''Keyword argument `table` cannot be None.'''  )
            elif query is None:
                 if isinstance(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  ) and table.get('''query'''  ) is not None and table.get('''table'''  ) is not None:
                      __snake_case    					=  [table]
                 elif isinstance(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  ) and len(__SCREAMING_SNAKE_CASE  ) > 0:
                      if not all(isinstance(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  ) for d in table  ):
                           raise ValueError(
                               F'''Keyword argument `table` should be a list of dict, but is {(type(__SCREAMING_SNAKE_CASE  ) for d in table)}'''  )

                      if table[0].get('''query'''  ) is not None and table[0].get('''table'''  ) is not None:
                           __snake_case    					=  table
                      else:
                           raise ValueError(
                               '''If keyword argument `table` is a list of dictionaries, each dictionary should have a `table`'''
                               F''' and `query` key, but only dictionary has keys {table[0].keys()} `table` and `query` keys.'''  )
                 elif Dataset is not None and isinstance(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  ) or isinstance(__SCREAMING_SNAKE_CASE    ,  types.GeneratorType  ):
                      return table
                 else:
                      raise ValueError(
                          '''Invalid input. Keyword argument `table` should be either of type `dict` or `list`, but '''
                          F'''is {type(__SCREAMING_SNAKE_CASE  )})'''  )
            else:
                 __snake_case    					=  [{'''table''': table, '''query''': query}]

            for tqa_pipeline_input in tqa_pipeline_inputs:
                 if not isinstance(tqa_pipeline_input['''table''']    ,  pd.DataFrame  ):
                      if tqa_pipeline_input["table"] is None:
                           raise ValueError('''Table cannot be None.'''  )

                      __snake_case    					=  pd.DataFrame(tqa_pipeline_input['''table''']  )

            return tqa_pipeline_inputs





@add_end_docstrings(__lowerCAmelCase)
class     lowerCAmelCase   ( __lowerCAmelCase):
       __lowercase  :      Union[str, Any]        =			'''table,query'''


       def __init__(   self    ,  __SCREAMING_SNAKE_CASE=TableQuestionAnsweringArgumentHandler()    ,  *__SCREAMING_SNAKE_CASE    ,  **__SCREAMING_SNAKE_CASE  )      ->  Any:



            '''simple docstring'''




            super().__init__(*__SCREAMING_SNAKE_CASE    ,  **__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  args_parser

            self.check_model_type(
                dict(
                    TF_MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items()
                    + TF_MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()  )
                if self.framework == '''tf'''
                else dict(
                    MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING.items() + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING.items()  )  )

            __snake_case    					=  bool(getattr(self.model.config    ,  '''aggregation_labels'''    ,  __SCREAMING_SNAKE_CASE  )  ) and bool(
                getattr(self.model.config    ,  '''num_aggregation_labels'''    ,  __SCREAMING_SNAKE_CASE  )  )
            __snake_case    					=  '''tapas''' if hasattr(self.model.config    ,  '''aggregation_labels'''  ) else None


       def       lowerCAmelCase      (   self    ,  **__SCREAMING_SNAKE_CASE  )      ->  Optional[int]:



            '''simple docstring'''




            return self.model(**__SCREAMING_SNAKE_CASE  )


       def       lowerCAmelCase      (   self    ,  **__SCREAMING_SNAKE_CASE  )      ->  List[str]:



            '''simple docstring'''




            if self.framework == "pt":
                 __snake_case    					=  []
                 __snake_case    					=  []
                 __snake_case    					=  None
                 __snake_case    					=  inputs['''input_ids'''].shape[0]

                 __snake_case    					=  inputs['''input_ids'''].to(self.device  )
                 __snake_case    					=  inputs['''attention_mask'''].to(self.device  )
                 __snake_case    					=  inputs['''token_type_ids'''].to(self.device  )
                 __snake_case    					=  None

                 for index in range(__SCREAMING_SNAKE_CASE  ):
                      # If sequences have already been processed, the token type IDs will be created according to the previous
                      # answer.
                      if prev_answers is not None:
                           __snake_case    					=  token_type_ids_example[:, 3]  # shape (seq_len,)
                           __snake_case    					=  np.zeros_like(prev_labels_example.cpu().numpy()  )  # shape (seq_len,)

                           __snake_case    					=  token_type_ids[index]  # shape (seq_len, 7)
                           for i in range(model_labels.shape[0]  ):
                                __snake_case    					=  token_type_ids_example[:, 0].tolist()[i]
                                __snake_case    					=  token_type_ids_example[:, 1].tolist()[i] - 1
                                __snake_case    					=  token_type_ids_example[:, 2].tolist()[i] - 1

                                if row_id >= 0 and col_id >= 0 and segment_id == 1:
                                     __snake_case    					=  int(prev_answers[(col_id, row_id)]  )

                           __snake_case    					=  torch.from_numpy(__SCREAMING_SNAKE_CASE  ).type(torch.long  ).to(self.device  )

                      __snake_case    					=  input_ids[index]
                      __snake_case    					=  attention_mask[index]  # shape (seq_len,)
                      __snake_case    					=  token_type_ids[index]  # shape (seq_len, 7)
                      __snake_case    					=  self.model(
                          input_ids=input_ids_example.unsqueeze(0  )    ,  attention_mask=attention_mask_example.unsqueeze(0  )    ,  token_type_ids=token_type_ids_example.unsqueeze(0  )    ,  )
                      __snake_case    					=  outputs.logits

                      if self.aggregate:
                           all_aggregations.append(outputs.logits_aggregation  )

                      all_logits.append(__SCREAMING_SNAKE_CASE  )

                      __snake_case    					=  torch.distributions.Bernoulli(logits=__SCREAMING_SNAKE_CASE  )
                      __snake_case    					=  dist_per_token.probs * attention_mask_example.type(torch.floataa  ).to(
                          dist_per_token.probs.device  )

                      __snake_case    					=  collections.defaultdict(__SCREAMING_SNAKE_CASE  )
                      for i, p in enumerate(probabilities.squeeze().tolist()  ):
                           __snake_case    					=  token_type_ids_example[:, 0].tolist()[i]
                           __snake_case    					=  token_type_ids_example[:, 1].tolist()[i] - 1
                           __snake_case    					=  token_type_ids_example[:, 2].tolist()[i] - 1
                           if col >= 0 and row >= 0 and segment_id == 1:
                                coords_to_probs[(col, row)].append(__SCREAMING_SNAKE_CASE  )

                      __snake_case    					=  {key: np.array(coords_to_probs[key]  ).mean() > 0.5 for key in coords_to_probs}

                 __snake_case    					=  torch.cat(tuple(__SCREAMING_SNAKE_CASE  )    ,  0  )

                 return (logits_batch,) if not self.aggregate else (logits_batch, torch.cat(tuple(__SCREAMING_SNAKE_CASE  )    ,  0  ))
            else:
                 __snake_case    					=  []
                 __snake_case    					=  []
                 __snake_case    					=  None
                 __snake_case    					=  inputs['''input_ids'''].shape[0]

                 __snake_case    					=  inputs['''input_ids''']
                 __snake_case    					=  inputs['''attention_mask''']
                 __snake_case    					=  inputs['''token_type_ids'''].numpy()
                 __snake_case    					=  None

                 for index in range(__SCREAMING_SNAKE_CASE  ):
                      # If sequences have already been processed, the token type IDs will be created according to the previous
                      # answer.
                      if prev_answers is not None:
                           __snake_case    					=  token_type_ids_example[:, 3]  # shape (seq_len,)
                           __snake_case    					=  np.zeros_like(__SCREAMING_SNAKE_CASE    ,  dtype=np.intaa  )  # shape (seq_len,)

                           __snake_case    					=  token_type_ids[index]  # shape (seq_len, 7)
                           for i in range(model_labels.shape[0]  ):
                                __snake_case    					=  token_type_ids_example[:, 0].tolist()[i]
                                __snake_case    					=  token_type_ids_example[:, 1].tolist()[i] - 1
                                __snake_case    					=  token_type_ids_example[:, 2].tolist()[i] - 1

                                if row_id >= 0 and col_id >= 0 and segment_id == 1:
                                     __snake_case    					=  int(prev_answers[(col_id, row_id)]  )

                           __snake_case    					=  model_labels

                      __snake_case    					=  input_ids[index]
                      __snake_case    					=  attention_mask[index]  # shape (seq_len,)
                      __snake_case    					=  token_type_ids[index]  # shape (seq_len, 7)
                      __snake_case    					=  self.model(
                          input_ids=np.expand_dims(__SCREAMING_SNAKE_CASE    ,  axis=0  )    ,  attention_mask=np.expand_dims(__SCREAMING_SNAKE_CASE    ,  axis=0  )    ,  token_type_ids=np.expand_dims(__SCREAMING_SNAKE_CASE    ,  axis=0  )    ,  )
                      __snake_case    					=  outputs.logits

                      if self.aggregate:
                           all_aggregations.append(outputs.logits_aggregation  )

                      all_logits.append(__SCREAMING_SNAKE_CASE  )

                      __snake_case    					=  tfp.distributions.Bernoulli(logits=__SCREAMING_SNAKE_CASE  )
                      __snake_case    					=  dist_per_token.probs_parameter() * tf.cast(__SCREAMING_SNAKE_CASE    ,  tf.floataa  )

                      __snake_case    					=  collections.defaultdict(__SCREAMING_SNAKE_CASE  )
                      __snake_case    					=  token_type_ids_example
                      for i, p in enumerate(tf.squeeze(__SCREAMING_SNAKE_CASE  ).numpy().tolist()  ):
                           __snake_case    					=  token_type_ids_example[:, 0].tolist()[i]
                           __snake_case    					=  token_type_ids_example[:, 1].tolist()[i] - 1
                           __snake_case    					=  token_type_ids_example[:, 2].tolist()[i] - 1
                           if col >= 0 and row >= 0 and segment_id == 1:
                                coords_to_probs[(col, row)].append(__SCREAMING_SNAKE_CASE  )

                      __snake_case    					=  {key: np.array(coords_to_probs[key]  ).mean() > 0.5 for key in coords_to_probs}

                 __snake_case    					=  tf.concat(tuple(__SCREAMING_SNAKE_CASE  )    ,  0  )

                 return (logits_batch,) if not self.aggregate else (logits_batch, tf.concat(tuple(__SCREAMING_SNAKE_CASE  )    ,  0  ))


       def __call__(   self    ,  *__SCREAMING_SNAKE_CASE    ,  **__SCREAMING_SNAKE_CASE  )      ->  Optional[int]:



            '''simple docstring'''




            __snake_case    					=  self._args_parser(*__SCREAMING_SNAKE_CASE    ,  **__SCREAMING_SNAKE_CASE  )

            __snake_case    					=  super().__call__(__SCREAMING_SNAKE_CASE    ,  **__SCREAMING_SNAKE_CASE  )
            if len(__SCREAMING_SNAKE_CASE  ) == 1:
                 return results[0]
            return results


       def       lowerCAmelCase      (   self    ,  __SCREAMING_SNAKE_CASE=None    ,  __SCREAMING_SNAKE_CASE=None    ,  __SCREAMING_SNAKE_CASE=None    ,  **__SCREAMING_SNAKE_CASE  )      ->  Union[str, Any]:



            '''simple docstring'''




            __snake_case    					=  {}
            if padding is not None:
                 __snake_case    					=  padding
            if truncation is not None:
                 __snake_case    					=  truncation

            __snake_case    					=  {}
            if sequential is not None:
                 __snake_case    					=  sequential
            return preprocess_params, forward_params, {}


       def       lowerCAmelCase      (   self    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE=None    ,  __SCREAMING_SNAKE_CASE=True    ,  __SCREAMING_SNAKE_CASE=None  )      ->  List[str]:



            '''simple docstring'''




            if truncation is None:
                 if self.type == "tapas":
                      __snake_case    					=  '''drop_rows_to_fit'''
                 else:
                      __snake_case    					=  '''do_not_truncate'''

            __snake_case					,    __snake_case    					=  pipeline_input['''table'''], pipeline_input['''query''']
            if table.empty:
                 raise ValueError('''table is empty'''  )
            if query is None or query == "":
                 raise ValueError('''query is empty'''  )
            __snake_case    					=  self.tokenizer(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  return_tensors=self.framework    ,  truncation=__SCREAMING_SNAKE_CASE    ,  padding=__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  table
            return inputs


       def       lowerCAmelCase      (   self    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE=False  )      ->  Optional[Any]:



            '''simple docstring'''




            __snake_case    					=  model_inputs.pop('''table'''  )

            if self.type == "tapas":
                 if sequential:
                      __snake_case    					=  self.sequential_inference(**__SCREAMING_SNAKE_CASE  )
                 else:
                      __snake_case    					=  self.batch_inference(**__SCREAMING_SNAKE_CASE  )
            else:
                 __snake_case    					=  self.model.generate(**__SCREAMING_SNAKE_CASE  )
            __snake_case    					=  {'''model_inputs''': model_inputs, '''table''': table, '''outputs''': outputs}
            return model_outputs




       def       lowerCAmelCase      (   self    ,  __SCREAMING_SNAKE_CASE  )      ->  Any:



            '''simple docstring'''




            __snake_case    					=  model_outputs['''model_inputs''']
            __snake_case    					=  model_outputs['''table''']
            __snake_case    					=  model_outputs['''outputs''']
            if self.type == "tapas":
                 if self.aggregate:
                      __snake_case					,    __snake_case    					=  outputs[:2]
                      __snake_case    					=  self.tokenizer.convert_logits_to_predictions(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  )
                      __snake_case					,    __snake_case    					=  predictions
                      __snake_case    					=  {i: self.model.config.aggregation_labels[pred] for i, pred in enumerate(__SCREAMING_SNAKE_CASE  )}

                      __snake_case    					=  self.model.config.no_aggregation_label_index
                      __snake_case    					=  {
                          i: aggregators[i] + ''' > ''' for i, pred in enumerate(__SCREAMING_SNAKE_CASE  ) if pred != no_agg_label_index
                      }
                 else:
                      __snake_case    					=  outputs[0]
                      __snake_case    					=  self.tokenizer.convert_logits_to_predictions(__SCREAMING_SNAKE_CASE    ,  __SCREAMING_SNAKE_CASE  )
                      __snake_case    					=  predictions[0]
                      __snake_case    					=  {}
                      __snake_case    					=  {}
                 __snake_case    					=  []
                 for index, coordinates in enumerate(__SCREAMING_SNAKE_CASE  ):
                      __snake_case    					=  [table.iat[coordinate] for coordinate in coordinates]
                      __snake_case    					=  aggregators.get(__SCREAMING_SNAKE_CASE    ,  ''''''  )
                      __snake_case    					=  aggregators_prefix.get(__SCREAMING_SNAKE_CASE    ,  ''''''  )
                      __snake_case    					=  {
                          '''answer''': aggregator_prefix + ''', '''.join(__SCREAMING_SNAKE_CASE  ),
                          '''coordinates''': coordinates,
                          '''cells''': [table.iat[coordinate] for coordinate in coordinates],
                      }
                      if aggregator:
                           __snake_case    					=  aggregator

                      answers.append(__SCREAMING_SNAKE_CASE  )
                 if len(__SCREAMING_SNAKE_CASE  ) == 0:
                      raise PipelineException('''Empty answer'''  )
            else:
                 __snake_case    					=  [{'''answer''': answer} for answer in self.tokenizer.batch_decode(__SCREAMING_SNAKE_CASE    ,  skip_special_tokens=__SCREAMING_SNAKE_CASE  )]

            return answers if len(__SCREAMING_SNAKE_CASE  ) > 1 else answers[0]












'''simple docstring'''



from typing import Any

import numpy as np







def 			_UpperCamelCase (_lowerCamelCase							:     np.ndarray	)->   bool:




     '''simple docstring'''





     assert np.shape(_lowerCamelCase	)[0] == np.shape(_lowerCamelCase	)[1]

     # If matrix not symmetric, exit right away.
     if np.allclose(_lowerCamelCase   ,	matrix.T	) is False:
          return False

     # Get eigenvalues and eignevectors for a symmetric matrix.
     __snake_case					,    __snake_case    					=  np.linalg.eigh(_lowerCamelCase	)

     # Check sign of all eigenvalues.
     # np.all returns a value of type np.bool_
     return bool(np.all(eigen_values > 0	)	)







def 			_UpperCamelCase (_lowerCamelCase							:     int	)->   Any:




     '''simple docstring'''





     __snake_case    					=  np.random.randn(_lowerCamelCase   ,	_lowerCamelCase	)
     __snake_case    					=  np.dot(_lowerCamelCase   ,	random_matrix.T	)
     assert _is_matrix_spd(_lowerCamelCase	)
     return spd_matrix







def 			_UpperCamelCase (_lowerCamelCase							:     np.ndarray   ,	_lowerCamelCase							:     np.ndarray   ,	_lowerCamelCase							:     int = 10_00   ,	_lowerCamelCase							:     float = 1E-8   ,	)->   Any:




     '''simple docstring'''





     assert np.shape(_lowerCamelCase	)[0] == np.shape(_lowerCamelCase	)[1]
     assert np.shape(_lowerCamelCase	)[0] == np.shape(_lowerCamelCase	)[0]
     assert _is_matrix_spd(_lowerCamelCase	)

     # Initialize solution guess, residual, search direction.
     __snake_case    					=  np.zeros((np.shape(_lowerCamelCase	)[0], 1)	)
     __snake_case    					=  np.copy(_lowerCamelCase	)
     __snake_case    					=  np.copy(_lowerCamelCase	)

     # Set initial errors in solution guess and residual.
     __snake_case    					=  1E9
     __snake_case    					=  1E9
     __snake_case    					=  1E9

     # Set iteration counter to threshold number of iterations.
     __snake_case    					=  0

     while error > tol:
          # Save this value so we only calculate the matrix-vector product once.
          __snake_case    					=  np.dot(_lowerCamelCase   ,	_lowerCamelCase	)

          # The main algorithm.

          # Update search direction magnitude.
          __snake_case    					=  np.dot(ra.T   ,	_lowerCamelCase	) / np.dot(pa.T   ,	_lowerCamelCase	)
          # Update solution guess.
          __snake_case    					=  xa + alpha * pa
          # Calculate new residual.
          __snake_case    					=  ra - alpha * w
          # Calculate new Krylov subspace scale.
          __snake_case    					=  np.dot(r.T   ,	_lowerCamelCase	) / np.dot(ra.T   ,	_lowerCamelCase	)
          # Calculate new A conjuage search direction.
          __snake_case    					=  r + beta * pa

          # Calculate errors.
          __snake_case    					=  np.linalg.norm(r - ra	)
          __snake_case    					=  np.linalg.norm(x - xa	)
          __snake_case    					=  np.maximum(_lowerCamelCase   ,	_lowerCamelCase	)

          # Update variables.
          __snake_case    					=  np.copy(_lowerCamelCase	)
          __snake_case    					=  np.copy(_lowerCamelCase	)
          __snake_case    					=  np.copy(_lowerCamelCase	)

          # Update number of iterations.
          iterations += 1
          if iterations > max_iterations:
               break

     return x







def 			_UpperCamelCase ()->   None:




     '''simple docstring'''





     __snake_case    					=  3
     __snake_case    					=  _create_spd_matrix(_lowerCamelCase	)
     __snake_case    					=  np.random.randn(_lowerCamelCase   ,	1	)
     __snake_case    					=  np.dot(_lowerCamelCase   ,	_lowerCamelCase	)

     # Numpy solution.
     __snake_case    					=  np.linalg.solve(_lowerCamelCase   ,	_lowerCamelCase	)

     # Our implementation.
     __snake_case    					=  conjugate_gradient(_lowerCamelCase   ,	_lowerCamelCase	)

     # Ensure both solutions are close to x_true (and therefore one another).
     assert np.linalg.norm(x_numpy - x_true	) <= 1E-6
     assert np.linalg.norm(x_conjugate_gradient - x_true	) <= 1E-6


if __name__ == "__main__":
     import doctest

     doctest.testmod()
     test_conjugate_gradient()






