



import argparse
import json
import math
import os
import time
import traceback
import zipfile
from collections import Counter

import requests
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__=None						):
 __lowerCamelCase		:							Dict		 =						None
 if token is not None:
  __lowerCamelCase		:							Tuple		 =						{'Accept': 'application/vnd.github+json', 'Authorization': f'Bearer {token}'}

 __lowerCamelCase		:							int		 =						f'https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100'
 __lowerCamelCase		:							str		 =						requests.get(lowerCAmelCase__      ,	headers=lowerCAmelCase__						).json()
 __lowerCamelCase		:							Any		 =						{}

 try:
  job_links.update({job['name']: job['html_url'] for job in result['jobs']}						)
  __lowerCamelCase		:							Dict		 =						math.ceil((result['total_count'] - 100) / 100						)

  for i in range(lowerCAmelCase__						):
   __lowerCamelCase		:							List[Any]		 =						requests.get(url + f'&page={i + 2}'      ,	headers=lowerCAmelCase__						).json()
   job_links.update({job['name']: job['html_url'] for job in result['jobs']}						)

  return job_links
 except Exception:
  print(f'Unknown error, could not fetch links:\n{traceback.format_exc()}'						)

 return {}
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__=None						):
 __lowerCamelCase		:							List[Any]		 =						None
 if token is not None:
  __lowerCamelCase		:							Dict		 =						{'Accept': 'application/vnd.github+json', 'Authorization': f'Bearer {token}'}

 __lowerCamelCase		:							Dict		 =						f'https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100'
 __lowerCamelCase		:							int		 =						requests.get(lowerCAmelCase__      ,	headers=lowerCAmelCase__						).json()
 __lowerCamelCase		:							Optional[Any]		 =						{}

 try:
  artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']}						)
  __lowerCamelCase		:							Union[str, Any]		 =						math.ceil((result['total_count'] - 100) / 100						)

  for i in range(lowerCAmelCase__						):
   __lowerCamelCase		:							int		 =						requests.get(url + f'&page={i + 2}'      ,	headers=lowerCAmelCase__						).json()
   artifacts.update({artifact['name']: artifact['archive_download_url'] for artifact in result['artifacts']}						)

  return artifacts
 except Exception:
  print(f'Unknown error, could not fetch links:\n{traceback.format_exc()}'						)

 return {}
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							Any		 =						None
 if token is not None:
  __lowerCamelCase		:							Optional[Any]		 =						{'Accept': 'application/vnd.github+json', 'Authorization': f'Bearer {token}'}

 __lowerCamelCase		:							str		 =						requests.get(lowerCAmelCase__      ,	headers=lowerCAmelCase__      ,	allow_redirects=lowerCAmelCase__						)
 __lowerCamelCase		:							Any		 =						result.headers['Location']
 __lowerCamelCase		:							List[str]		 =						requests.get(lowerCAmelCase__      ,	allow_redirects=lowerCAmelCase__						)
 __lowerCamelCase		:							Optional[int]		 =						os.path.join(lowerCAmelCase__      ,	f'{artifact_name}.zip'						)
 with open(lowerCAmelCase__      ,	'wb'						) as fp:
  fp.write(response.content						)
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__=None						):
 __lowerCamelCase		:							str		 =						[]
 __lowerCamelCase		:							List[Any]		 =						[]
 __lowerCamelCase		:							int		 =						None

 with zipfile.ZipFile(lowerCAmelCase__						) as z:
  for filename in z.namelist():
   if not os.path.isdir(lowerCAmelCase__						):
    # read the file
    if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]:
     with z.open(lowerCAmelCase__						) as f:
      for line in f:
       __lowerCamelCase		:							Union[str, Any]		 =						line.decode('UTF-8'						).strip()
       if filename == "failures_line.txt":
        try:
         # `error_line` is the place where `error` occurs
         __lowerCamelCase		:							int		 =						line[: line.index(': '						)]
         __lowerCamelCase		:							Dict		 =						line[line.index(': '						) + len(': '						) :]
         errors.append([error_line, error]						)
        except Exception:
         # skip un-related lines
         pass
       elif filename == "summary_short.txt" and line.startswith('FAILED '						):
        # `test` is the test method that failed
        __lowerCamelCase		:							Optional[Any]		 =						line[len('FAILED '						) :]
        failed_tests.append(lowerCAmelCase__						)
       elif filename == "job_name.txt":
        __lowerCamelCase		:							Optional[Any]		 =						line

 if len(lowerCAmelCase__						) != len(lowerCAmelCase__						):
  raise ValueError(
      f'`errors` and `failed_tests` should have the same number of elements. Got {len(lowerCAmelCase__						)} for `errors` '
      f'and {len(lowerCAmelCase__						)} for `failed_tests` instead. The test reports in {artifact_zip_path} have some'
      ' problem.'						)

 __lowerCamelCase		:							int		 =						None
 if job_name and job_links:
  __lowerCamelCase		:							Dict		 =						job_links.get(lowerCAmelCase__      ,	lowerCAmelCase__						)

 # A list with elements of the form (line of error, error, failed test)
 __lowerCamelCase		:							Optional[int]		 =						[x + [y] + [job_link] for x, y in zip(lowerCAmelCase__      ,	lowerCAmelCase__						)]

 return result
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__=None						):
 __lowerCamelCase		:							Union[str, Any]		 =						[]

 __lowerCamelCase		:							Any		 =						[os.path.join(lowerCAmelCase__      ,	lowerCAmelCase__						) for p in os.listdir(lowerCAmelCase__						) if p.endswith('.zip'						)]
 for p in paths:
  errors.extend(get_errors_from_single_artifact(lowerCAmelCase__      ,	job_links=lowerCAmelCase__						)						)

 return errors
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__=None						):
 __lowerCamelCase		:							int		 =						Counter()
 counter.update([x[1] for x in logs]						)
 __lowerCamelCase		:							List[Any]		 =						counter.most_common()
 __lowerCamelCase		:							Any		 =						{}
 for error, count in counts:
  if error_filter is None or error not in error_filter:
   __lowerCamelCase		:							Optional[Any]		 =						{'count': count, 'failed_tests': [(x[2], x[0]) for x in logs if x[1] == error]}

 __lowerCamelCase		:							Any		 =						dict(sorted(r.items()      ,	key=lambda SCREAMING_SNAKE_CASE__						: item[1]["count"]      ,	reverse=lowerCAmelCase__						)						)
 return r
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							Union[str, Any]		 =						test.split('::'						)[0]
 if test.startswith('tests/models/'						):
  __lowerCamelCase		:							Union[str, Any]		 =						test.split('/'						)[2]
 else:
  __lowerCamelCase		:							Optional[Any]		 =						None

 return test
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__=None						):
 __lowerCamelCase		:							Any		 =						[(x[0], x[1], get_model(x[2]						)) for x in logs]
 __lowerCamelCase		:							List[str]		 =						[x for x in logs if x[2] is not None]
 __lowerCamelCase		:							List[Any]		 =						{x[2] for x in logs}

 __lowerCamelCase		:							str		 =						{}
 for test in tests:
  __lowerCamelCase		:							Any		 =						Counter()
  # count by errors in `test`
  counter.update([x[1] for x in logs if x[2] == test]						)
  __lowerCamelCase		:							Any		 =						counter.most_common()
  __lowerCamelCase		:							Dict		 =						{error: count for error, count in counts if (error_filter is None or error not in error_filter)}
  __lowerCamelCase		:							str		 =						sum(error_counts.values()						)
  if n_errors > 0:
   __lowerCamelCase		:							Any		 =						{'count': n_errors, 'errors': error_counts}

 __lowerCamelCase		:							List[str]		 =						dict(sorted(r.items()      ,	key=lambda SCREAMING_SNAKE_CASE__						: item[1]["count"]      ,	reverse=lowerCAmelCase__						)						)
 return r
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							Union[str, Any]		 =						'| no. | error | status |'
 __lowerCamelCase		:							List[Any]		 =						'|-:|:-|:-|'
 __lowerCamelCase		:							Tuple		 =						[header, sep]
 for error in reduced_by_error:
  __lowerCamelCase		:							int		 =						reduced_by_error[error]['count']
  __lowerCamelCase		:							List[Any]		 =						f'| {count} | {error[:100]} |  |'
  lines.append(lowerCAmelCase__						)

 return "\n".join(lowerCAmelCase__						)
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							int		 =						'| model | no. of errors | major error | count |'
 __lowerCamelCase		:							Optional[Any]		 =						'|-:|-:|-:|-:|'
 __lowerCamelCase		:							str		 =						[header, sep]
 for model in reduced_by_model:
  __lowerCamelCase		:							Dict		 =						reduced_by_model[model]['count']
  __lowerCamelCase ,					__lowerCamelCase		:							str		 =						list(reduced_by_model[model]['errors'].items()						)[0]
  __lowerCamelCase		:							Dict		 =						f'| {model} | {count} | {error[:60]} | {_count} |'
  lines.append(lowerCAmelCase__						)

 return "\n".join(lowerCAmelCase__						)


if __name__ == "__main__":
       lowercase_	   =     argparse.ArgumentParser()
       # Required parameters
       parser.add_argument('--workflow_run_id', type=str, required=True, help='A GitHub Actions workflow run id.')
       parser.add_argument(
           '--output_dir',
           type=str,
           required=True,
           help='Where to store the downloaded artifacts and other result files.',
       )
       parser.add_argument('--token', default=None, type=str, help='A token that has actions:read permission.')
       lowercase_	   =     parser.parse_args()

       os.makedirs(args.output_dir, exist_ok=True)

       lowercase_	   =     get_job_links(args.workflow_run_id, token=args.token)
       lowercase_	   =     {}
       # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee.
       # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`.
       if _job_links:
              for k, v in _job_links.items():
                     # This is how GitHub actions combine job names.
                     if " / " in k:
                            lowercase_	   =     k.find(' / ')
                            lowercase_	   =     k[index + len(' / ') :]
                     lowercase_	   =     v
       with open(os.path.join(args.output_dir, 'job_links.json'), 'w', encoding='UTF-8') as fp:
              json.dump(job_links, fp, ensure_ascii=False, indent=4)

       lowercase_	   =     get_artifacts_links(args.workflow_run_id, token=args.token)
       with open(os.path.join(args.output_dir, 'artifacts.json'), 'w', encoding='UTF-8') as fp:
              json.dump(artifacts, fp, ensure_ascii=False, indent=4)

       for idx, (name, url) in enumerate(artifacts.items()):
              download_artifact(name, url, args.output_dir, args.token)
              # Be gentle to GitHub
              time.sleep(1)

       lowercase_	   =     get_all_errors(args.output_dir, job_links=job_links)

       # `e[1]` is the error
       lowercase_	   =     Counter()
       counter.update([e[1] for e in errors])

       # print the top 30 most common test errors
       lowercase_	   =     counter.most_common(3_0)
       for item in most_common:
              print(item)

       with open(os.path.join(args.output_dir, 'errors.json'), 'w', encoding='UTF-8') as fp:
              json.dump(errors, fp, ensure_ascii=False, indent=4)

       lowercase_	   =     reduce_by_error(errors)
       lowercase_	   =     reduce_by_model(errors)

       lowercase_	   =     make_github_table(reduced_by_error)
       lowercase_	   =     make_github_table_per_model(reduced_by_model)

       with open(os.path.join(args.output_dir, 'reduced_by_error.txt'), 'w', encoding='UTF-8') as fp:
              fp.write(sa)
       with open(os.path.join(args.output_dir, 'reduced_by_model.txt'), 'w', encoding='UTF-8') as fp:
              fp.write(sa)





import argparse
import json
import os

import torch

from transformers import LukeConfig, LukeModel, LukeTokenizer, RobertaTokenizer
from transformers.tokenization_utils_base import AddedToken
@torch.no_grad()
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						):
 # Load configuration defined in the metadata file
 with open(SCREAMING_SNAKE_CASE__						) as metadata_file:
  __lowerCamelCase		:							List[str]		 =						json.load(SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase		:							int		 =						LukeConfig(use_entity_aware_attention=SCREAMING_SNAKE_CASE__      ,	**metadata['model_config']						)

 # Load in the weights from the checkpoint_path
 __lowerCamelCase		:							Union[str, Any]		 =						torch.load(SCREAMING_SNAKE_CASE__      ,	map_location='cpu'						)

 # Load the entity vocab file
 __lowerCamelCase		:							List[Any]		 =						load_entity_vocab(SCREAMING_SNAKE_CASE__						)

 __lowerCamelCase		:							Optional[int]		 =						RobertaTokenizer.from_pretrained(metadata['model_config']['bert_model_name']						)

 # Add special tokens to the token vocabulary for downstream tasks
 __lowerCamelCase		:							str		 =						AddedToken('<ent>'      ,	lstrip=SCREAMING_SNAKE_CASE__      ,	rstrip=SCREAMING_SNAKE_CASE__						)
 __lowerCamelCase		:							Dict		 =						AddedToken('<ent2>'      ,	lstrip=SCREAMING_SNAKE_CASE__      ,	rstrip=SCREAMING_SNAKE_CASE__						)
 tokenizer.add_special_tokens({'additional_special_tokens': [entity_token_a, entity_token_a]}						)
 config.vocab_size += 2

 print(f'Saving tokenizer to {pytorch_dump_folder_path}'						)
 tokenizer.save_pretrained(SCREAMING_SNAKE_CASE__						)
 with open(os.path.join(SCREAMING_SNAKE_CASE__      ,	LukeTokenizer.vocab_files_names['entity_vocab_file']						)      ,	'w'						) as f:
  json.dump(SCREAMING_SNAKE_CASE__      ,	SCREAMING_SNAKE_CASE__						)

 __lowerCamelCase		:							str		 =						LukeTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__						)

 # Initialize the embeddings of the special tokens
 __lowerCamelCase		:							Union[str, Any]		 =						state_dict['embeddings.word_embeddings.weight']
 __lowerCamelCase		:							Tuple		 =						word_emb[tokenizer.convert_tokens_to_ids(['@']						)[0]].unsqueeze(0						)
 __lowerCamelCase		:							Any		 =						word_emb[tokenizer.convert_tokens_to_ids(['#']						)[0]].unsqueeze(0						)
 __lowerCamelCase		:							List[str]		 =						torch.cat([word_emb, ent_emb, enta_emb]						)

 # Initialize the query layers of the entity-aware self-attention mechanism
 for layer_index in range(config.num_hidden_layers						):
  for matrix_name in ["query.weight", "query.bias"]:
   __lowerCamelCase		:							Optional[int]		 =						f'encoder.layer.{layer_index}.attention.self.'
   __lowerCamelCase		:							Dict		 =						state_dict[prefix + matrix_name]
   __lowerCamelCase		:							List[Any]		 =						state_dict[prefix + matrix_name]
   __lowerCamelCase		:							Union[str, Any]		 =						state_dict[prefix + matrix_name]

    # Initialize the embedding of the [MASK2] entity using that of the [MASK] entity for downstream tasks
 __lowerCamelCase		:							Optional[int]		 =						state_dict['entity_embeddings.entity_embeddings.weight']
 __lowerCamelCase		:							Union[str, Any]		 =						entity_emb[entity_vocab['[MASK]']]

 __lowerCamelCase		:							Optional[Any]		 =						LukeModel(config=SCREAMING_SNAKE_CASE__						).eval()

 __lowerCamelCase ,					__lowerCamelCase		:							List[Any]		 =						model.load_state_dict(SCREAMING_SNAKE_CASE__      ,	strict=SCREAMING_SNAKE_CASE__						)
 if not (len(SCREAMING_SNAKE_CASE__						) == 1 and missing_keys[0] == "embeddings.position_ids"):
  raise ValueError(f'Missing keys {", ".join(SCREAMING_SNAKE_CASE__						)}. Expected only missing embeddings.position_ids'						)
 if not (all(key.startswith('entity_predictions'						) or key.startswith('lm_head'						) for key in unexpected_keys						)):
  raise ValueError(
      'Unexpected keys'
      f' {", ".join([key for key in unexpected_keys if not (key.startswith("entity_predictions"						) or key.startswith("lm_head"						))]						)}'						)

 # Check outputs
 __lowerCamelCase		:							Optional[Any]		 =						LukeTokenizer.from_pretrained(SCREAMING_SNAKE_CASE__      ,	task='entity_classification'						)

 __lowerCamelCase		:							Dict		 =						(
     'Top seed Ana Ivanovic said on Thursday she could hardly believe her luck as a fortuitous netcord helped the'
     ' new world number one avoid a humiliating second- round exit at Wimbledon .'
 )
 __lowerCamelCase		:							Union[str, Any]		 =						(39, 42)
 __lowerCamelCase		:							Optional[Any]		 =						tokenizer(SCREAMING_SNAKE_CASE__      ,	entity_spans=[span]      ,	add_prefix_space=SCREAMING_SNAKE_CASE__      ,	return_tensors='pt'						)

 __lowerCamelCase		:							List[str]		 =						model(**SCREAMING_SNAKE_CASE__						)

 # Verify word hidden states
 if model_size == "large":
  __lowerCamelCase		:							Dict		 =						torch.Size((1, 42, 1_024)						)
  __lowerCamelCase		:							int		 =						torch.tensor(
      [[0.0_133, 0.0_865, 0.0_095], [0.3_093, -0.2_576, -0.7_418], [-0.1_720, -0.2_117, -0.2_869]]						)
 else:  # base
  __lowerCamelCase		:							Union[str, Any]		 =						torch.Size((1, 42, 768)						)
  __lowerCamelCase		:							Tuple		 =						torch.tensor([[0.0_037, 0.1_368, -0.0_091], [0.1_099, 0.3_329, -0.1_095], [0.0_765, 0.5_335, 0.1_179]]						)

 if not (outputs.last_hidden_state.shape == expected_shape):
  raise ValueError(
      f'Outputs.last_hidden_state.shape is {outputs.last_hidden_state.shape}, Expected shape is {expected_shape}'						)
 if not torch.allclose(outputs.last_hidden_state[0, :3, :3]      ,	SCREAMING_SNAKE_CASE__      ,	atol=1e-4						):
  raise ValueError

 # Verify entity hidden states
 if model_size == "large":
  __lowerCamelCase		:							Union[str, Any]		 =						torch.Size((1, 1, 1_024)						)
  __lowerCamelCase		:							Dict		 =						torch.tensor([[0.0_466, -0.0_106, -0.0_179]]						)
 else:  # base
  __lowerCamelCase		:							int		 =						torch.Size((1, 1, 768)						)
  __lowerCamelCase		:							Dict		 =						torch.tensor([[0.1_457, 0.1_044, 0.0_174]]						)

 if not (outputs.entity_last_hidden_state.shape != expected_shape):
  raise ValueError(
      f'Outputs.entity_last_hidden_state.shape is {outputs.entity_last_hidden_state.shape}, Expected shape is'
      f' {expected_shape}'						)
 if not torch.allclose(outputs.entity_last_hidden_state[0, :3, :3]      ,	SCREAMING_SNAKE_CASE__      ,	atol=1e-4						):
  raise ValueError

 # Finally, save our PyTorch model and tokenizer
 print('Saving PyTorch model to {}'.format(SCREAMING_SNAKE_CASE__						)						)
 model.save_pretrained(SCREAMING_SNAKE_CASE__						)
def 				UpperCamelCase__					(  SCREAMING_SNAKE_CASE__						):
 __lowerCamelCase		:							Tuple		 =						{}
 with open(SCREAMING_SNAKE_CASE__      ,	'r'      ,	encoding='utf-8'						) as f:
  for index, line in enumerate(SCREAMING_SNAKE_CASE__						):
   __lowerCamelCase ,					__lowerCamelCase		:							List[Any]		 =						line.rstrip().split('\t'						)
   __lowerCamelCase		:							Any		 =						index

 return entity_vocab


if __name__ == "__main__":
       lowercase_	   =     argparse.ArgumentParser()
       # Required parameters
       parser.add_argument('--checkpoint_path', type=str, help='Path to a pytorch_model.bin file.')
       parser.add_argument(
           '--metadata_path', default=None, type=str, help='Path to a metadata.json file, defining the configuration.'
       )
       parser.add_argument(
           '--entity_vocab_path',
           default=None,
           type=str,
           help='Path to an entity_vocab.tsv file, containing the entity vocabulary.',
       )
       parser.add_argument(
           '--pytorch_dump_folder_path', default=None, type=str, help='Path to where to dump the output PyTorch model.'
       )
       parser.add_argument(
           '--model_size', default='base', type=str, choices=['base', 'large'], help='Size of the model to be converted.'
       )
       lowercase_	   =     parser.parse_args()
       convert_luke_checkpoint(
           args.checkpoint_path,
           args.metadata_path,
           args.entity_vocab_path,
           args.pytorch_dump_folder_path,
           args.model_size,
       )

