




'''simple docstring'''







import qiskit
from qiskit.providers import Backend






def    lowerCAmelCase__ (       lowerCamelCase  :    int						,lowerCamelCase  :    int     ):
       _A						,				_A  :			Optional[Any]											=      bin(__lowerCamelCase     )[2:], bin(__lowerCamelCase     )[2:]  # Remove leading '0b'

       # Ensure that both strings are of the same length
       if len(__lowerCamelCase     ) > len(__lowerCamelCase     ):
              _A  :			str											=      y.zfill(len(__lowerCamelCase     )     )
       else:
              _A  :			str											=      x.zfill(len(__lowerCamelCase     )     )

       # We need (3 * number of bits in the larger number)+1 qBits
       # The second parameter is the number of classical registers, to measure the result
       _A  :			List[str]											=      qiskit.QuantumCircuit((len(__lowerCamelCase     ) * 3) + 1						,len(__lowerCamelCase     ) + 1     )

       # We are essentially "not-ing" the bits that are 1
       # Reversed because it's easier to perform ops on more significant bits
       for i in range(len(__lowerCamelCase     )     ):
              if x[::-1][i] == "1":
                     circuit.x(__lowerCamelCase     )
       for j in range(len(__lowerCamelCase     )     ):
              if y[::-1][j] == "1":
                     circuit.x(len(__lowerCamelCase     ) + j     )

       return circuit, x, y






def    lowerCAmelCase__ (       lowerCamelCase  :    qiskit.QuantumCircuit						,lowerCamelCase  :    int						,lowerCamelCase  :    int						,lowerCamelCase  :    int						,lowerCamelCase  :    int						,):
       circuit.ccx(__lowerCamelCase						,__lowerCamelCase						,__lowerCamelCase     )
       circuit.cx(__lowerCamelCase						,__lowerCamelCase     )
       circuit.ccx(__lowerCamelCase						,__lowerCamelCase						,__lowerCamelCase     )
       circuit.cx(__lowerCamelCase						,__lowerCamelCase     )
       circuit.cx(__lowerCamelCase						,__lowerCamelCase     )






def    lowerCAmelCase__ (       lowerCamelCase  :    int						,lowerCamelCase  :    int						,lowerCamelCase  :    Backend = qiskit.Aer.get_backend('aer_simulator'     )						,):

       if vala < 0 or vala < 0:
              raise ValueError('Both Integers must be positive!'     )

       # Store the Integers
       _A						,				_A						,				_A  :			Dict											=      store_two_classics(__lowerCamelCase						,__lowerCamelCase     )
       for i in range(len(__lowerCamelCase     )     ):
              full_adder(__lowerCamelCase						,__lowerCamelCase						,len(__lowerCamelCase     ) + i						,len(__lowerCamelCase     ) + len(__lowerCamelCase     ) + i						,len(__lowerCamelCase     ) + len(__lowerCamelCase     ) + i + 1     )
              circuit.barrier()  # Optional, just for aesthetics

       # Measure the resultant qBits
       for i in range(len(__lowerCamelCase     ) + 1     ):
              circuit.measure([(len(__lowerCamelCase     ) * 2) + i]						,[i]     )

       _A  :			Any											=      qiskit.execute(__lowerCamelCase						,__lowerCamelCase						,shots=1     ).result()

       # The result is in binary. Convert it back to int
       return int(list(res.get_counts()     )[0]						,2     )


if __name__ == "__main__":
   import doctest

   doctest.testmod()










'''simple docstring'''







import jax
import jax.numpy as jnp
from bigbird_flax import FlaxBigBirdForNaturalQuestions
from datasets import load_from_disk

from transformers import BigBirdTokenizerFast


A   :  List[Any]       		=				{0: '''null''', 1: '''short''', 2: '''long''', 3: '''yes''', 4: '''no'''}
A   :  Optional[int]       		=				set(''''''.join(['''‘''', '''’''', '''´''', '''`''', '''.''', ''',''', '''-''', '''"''']))






def    lowerCAmelCase__ (       lowerCamelCase  :    str						,lowerCamelCase  :    Dict=0						,lowerCamelCase  :    List[Any]=None     ):
       return [" ".join(x.split(' '     )[begin:end]     ) for x in answers if len(x.split(' '     )     ) > 1]






def    lowerCAmelCase__ (       lowerCamelCase  :    Dict						,lowerCamelCase  :    Tuple=False     ):
       if make_sub_answers:
              # if answers are longer than one word, make sure a predictions is correct if it coresponds to the complete 1: or :-1 sub word
              # *e.g.* if the correct answer contains a prefix such as "the", or "a"
              _A  :			str											=      (
                  given_answers + get_sub_answers(lowerCamelCase						,begin=1     ) + get_sub_answers(lowerCamelCase						,end=-1     )
              )
       _A  :			List[Any]											=      []
       for answer in given_answers:
              _A  :			List[str]											=      answer.replace('_'						,' '     ).lower()
              _A  :			Any											=      ''.join(c if c not in PUNCTUATION_SET_TO_EXCLUDE else ' ' for c in alias     )
              answers.append(' '.join(alias.split()     ).strip()     )
       return set(lowerCamelCase     )






def    lowerCAmelCase__ (       lowerCamelCase  :    List[Any]						,lowerCamelCase  :    Optional[int]						,lowerCamelCase  :    List[str]=1						,lowerCamelCase  :    Optional[int]=100     ):
       _A						,				_A  :			Dict											=      jax.lax.top_k(lowerCamelCase						,lowerCamelCase     )
       _A						,				_A  :			Dict											=      jax.lax.top_k(lowerCamelCase						,lowerCamelCase     )

       _A  :			List[str]											=      best_end_idx[:, None] - best_start_idx[None, :]
       _A  :			Any											=      jnp.logical_or(widths < 0						,widths > max_size     )
       _A  :			Any											=      (best_end_scores[:, None] + best_start_scores[None, :]) - (1E8 * mask)
       _A  :			List[Any]											=      jnp.argmax(lowerCamelCase     ).item()

       return best_start_idx[best_score % top_k], best_end_idx[best_score // top_k]






def    lowerCAmelCase__ (       lowerCamelCase  :    Dict     ):
       _A  :			Optional[Any]											=      sample['question']['text']
       _A  :			Any											=      sample['document']['tokens']['token']
       _A  :			List[str]											=      sample['document']['tokens']['is_html']
       _A  :			str											=      sample['annotations']['long_answer']
       _A  :			int											=      sample['annotations']['short_answers']

       _A  :			Optional[int]											=      ' '.join([context[i] for i in range(len(lowerCamelCase     )     ) if not is_html[i]]     )

       # 0 - No ; 1 - Yes
       for answer in sample["annotations"]["yes_no_answer"]:
              if answer == 0 or answer == 1:
                     return {
                         "question": question,
                         "context": context_string,
                         "short": [],
                         "long": [],
                         "category": "no" if answer == 0 else "yes",
                     }

       _A  :			Tuple											=      []
       for s in short_answers:
              short_targets.extend(s['text']     )
       _A  :			Dict											=      list(set(lowerCamelCase     )     )

       _A  :			List[str]											=      []
       for s in long_answers:
              if s["start_token"] == -1:
                     continue
              _A  :			Tuple											=      context[s['start_token'] : s['end_token']]
              _A  :			Optional[Any]											=      is_html[s['start_token'] : s['end_token']]
              _A  :			Optional[int]											=      ' '.join([answer[i] for i in range(len(lowerCamelCase     )     ) if not html[i]]     )
              if new_answer not in long_targets:
                     long_targets.append(lowerCamelCase     )

       _A  :			List[str]											=      'long_short' if len(short_targets + long_targets     ) > 0 else 'null'

       return {
           "question": question,
           "context": context_string,
           "short": short_targets,
           "long": long_targets,
           "category": category,
       }






def    lowerCAmelCase__ (       ):
       _A  :			Optional[Any]											=      load_from_disk('natural-questions-validation'     )
       _A  :			int											=      dataset.map(lowerCamelCase     ).remove_columns(['annotations', 'document', 'id']     )
       print(lowerCamelCase     )

       _A  :			int											=      dataset.filter(lambda lowerCamelCase     : (len(x['question']     ) + len(x['context']     )) < 4 * 4096     )
       _A  :			Dict											=      short_validation_dataset.filter(lambda lowerCamelCase     : x["category"] != "null"     )
       short_validation_dataset

       _A  :			Tuple											=      'vasudevgupta/flax-bigbird-natural-questions'
       _A  :			List[str]											=      FlaxBigBirdForNaturalQuestions.from_pretrained(lowerCamelCase     )
       _A  :			str											=      BigBirdTokenizerFast.from_pretrained(lowerCamelCase     )

       @jax.jit
       def forward(*lowerCamelCase  :    Optional[Any]						,**lowerCamelCase  :    Any     ):
              _A						,				_A						,				_A  :			Tuple											=      model(*lowerCamelCase						,**lowerCamelCase     )
              return start_logits, end_logits, jnp.argmax(lowerCamelCase						,axis=-1     )

       def evaluate(lowerCamelCase  :    Union[str, Any]     ):
              # encode question and context so that they are separated by a tokenizer.sep_token and cut at max_length
              _A  :			List[str]											=      tokenizer(
                  example['question']						,example['context']						,return_tensors='np'						,max_length=4096						,padding='max_length'						,truncation=lowerCamelCase						,)

              _A						,				_A						,				_A  :			Tuple											=      forward(**lowerCamelCase     )

              _A  :			List[Any]											=      CATEGORY_MAPPING[category.item()]

              _A  :			List[str]											=      example['long'] + example['short']
              if example["category"] in ["yes", "no", "null"]:
                     _A  :			Optional[int]											=      [example['category']]
              _A  :			List[Any]											=      example['category'] != 'null'
              # Now target can be: "yes", "no", "null", "list of long & short answers"

              if predicted_category in ["yes", "no", "null"]:
                     _A  :			Tuple											=      [predicted_category]
                     _A  :			Union[str, Any]											=      example['output'] == example['targets']
                     _A  :			Tuple											=      predicted_category != 'null'
                     return example

              _A  :			Dict											=      38 if predicted_category == 'short' else 1024
              _A						,				_A  :			List[Any]											=      get_best_valid_start_end_idx(
                  start_scores[0]						,end_scores[0]						,top_k=8						,max_size=lowerCamelCase     )

              _A  :			Optional[Any]											=      inputs['input_ids'][0].tolist()
              _A  :			Union[str, Any]											=      [tokenizer.decode(input_ids[start_score : end_score + 1]     )]

              _A  :			Union[str, Any]											=      expand_to_aliases(example['targets']						,make_sub_answers=lowerCamelCase     )
              _A  :			str											=      expand_to_aliases(example['output']     )

              # some preprocessing to both prediction and answer
              _A  :			Tuple											=      {''.join(a.split()     ) for a in answers}
              _A  :			Optional[Any]											=      {''.join(p.split()     ) for p in predictions}
              _A  :			Tuple											=      {s for s in predictions if s not in ['``', '\'\'', '`', '\'']}

              # if there is a common element, it's a exact match
              _A  :			Tuple											=      len(list(answers & predictions     )     ) > 0
              _A  :			Any											=      predicted_category != 'null' and len(lowerCamelCase     ) > 0

              return example

       _A  :			str											=      short_validation_dataset.map(lowerCamelCase     )

       _A  :			Optional[int]											=      len(lowerCamelCase     )
       _A  :			str											=      len(short_validation_dataset.filter(lambda lowerCamelCase     : x["match"] == 1     )     )
       print('EM score:'						,(matched / total) * 100						,'%'     )


if __name__ == "__main__":
   main()






