





"""simple docstring"""
from collections import OrderedDict
from typing import Any, List, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast, PatchingSpec
from ...utils import logging


lowerCamelCase_       =		logging.get_logger(__name__)


lowerCamelCase_       =		{
    "Salesforce/codegen-350M-nl": "https://huggingface.co/Salesforce/codegen-350M-nl/resolve/main/config.json",
    "Salesforce/codegen-350M-multi": "https://huggingface.co/Salesforce/codegen-350M-multi/resolve/main/config.json",
    "Salesforce/codegen-350M-mono": "https://huggingface.co/Salesforce/codegen-350M-mono/resolve/main/config.json",
    "Salesforce/codegen-2B-nl": "https://huggingface.co/Salesforce/codegen-2B-nl/resolve/main/config.json",
    "Salesforce/codegen-2B-multi": "https://huggingface.co/Salesforce/codegen-2B-multi/resolve/main/config.json",
    "Salesforce/codegen-2B-mono": "https://huggingface.co/Salesforce/codegen-2B-mono/resolve/main/config.json",
    "Salesforce/codegen-6B-nl": "https://huggingface.co/Salesforce/codegen-6B-nl/resolve/main/config.json",
    "Salesforce/codegen-6B-multi": "https://huggingface.co/Salesforce/codegen-6B-multi/resolve/main/config.json",
    "Salesforce/codegen-6B-mono": "https://huggingface.co/Salesforce/codegen-6B-mono/resolve/main/config.json",
    "Salesforce/codegen-16B-nl": "https://huggingface.co/Salesforce/codegen-16B-nl/resolve/main/config.json",
    "Salesforce/codegen-16B-multi": "https://huggingface.co/Salesforce/codegen-16B-multi/resolve/main/config.json",
    "Salesforce/codegen-16B-mono": "https://huggingface.co/Salesforce/codegen-16B-mono/resolve/main/config.json",
}






class  _SCREAMING_SNAKE_CASE(       A  ):
       SCREAMING_SNAKE_CASE_       :				Tuple     						=  '''codegen'''
       SCREAMING_SNAKE_CASE_       :				Tuple     						=  {
           '''max_position_embeddings''': '''n_positions''',
           '''hidden_size''': '''n_embd''',
           '''num_attention_heads''': '''n_head''',
           '''num_hidden_layers''': '''n_layer''',
       }




       def __init__(						self		,SCREAMING_SNAKE_CASE__=5_04_00		,SCREAMING_SNAKE_CASE__=20_48		,SCREAMING_SNAKE_CASE__=20_48		,SCREAMING_SNAKE_CASE__=40_96		,SCREAMING_SNAKE_CASE__=28		,SCREAMING_SNAKE_CASE__=16		,SCREAMING_SNAKE_CASE__=64		,SCREAMING_SNAKE_CASE__=None		,SCREAMING_SNAKE_CASE__="gelu_new"		,SCREAMING_SNAKE_CASE__=0.0		,SCREAMING_SNAKE_CASE__=0.0		,SCREAMING_SNAKE_CASE__=0.0		,SCREAMING_SNAKE_CASE__=1E-5		,SCREAMING_SNAKE_CASE__=0.0_2		,SCREAMING_SNAKE_CASE__=True		,SCREAMING_SNAKE_CASE__=5_02_56		,SCREAMING_SNAKE_CASE__=5_02_56		,SCREAMING_SNAKE_CASE__=False		,**SCREAMING_SNAKE_CASE__		,)      ->				Tuple:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Dict		    =  vocab_size
             __SCREAMING_SNAKE_CASE       :List[str]		    =  n_ctx
             __SCREAMING_SNAKE_CASE       :int		    =  n_positions
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  n_embd
             __SCREAMING_SNAKE_CASE       :str		    =  n_layer
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  n_head
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  n_inner
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  rotary_dim
             __SCREAMING_SNAKE_CASE       :int		    =  activation_function
             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  resid_pdrop
             __SCREAMING_SNAKE_CASE       :Optional[int]		    =  embd_pdrop
             __SCREAMING_SNAKE_CASE       :List[str]		    =  attn_pdrop
             __SCREAMING_SNAKE_CASE       :List[Any]		    =  layer_norm_epsilon
             __SCREAMING_SNAKE_CASE       :str		    =  initializer_range
             __SCREAMING_SNAKE_CASE       :Tuple		    =  use_cache

             __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  bos_token_id
             __SCREAMING_SNAKE_CASE       :int		    =  eos_token_id

             super().__init__(
                 bos_token_id=SCREAMING_SNAKE_CASE__		,eos_token_id=SCREAMING_SNAKE_CASE__		,tie_word_embeddings=SCREAMING_SNAKE_CASE__		,**SCREAMING_SNAKE_CASE__							)






class  _SCREAMING_SNAKE_CASE(       A  ):




       def __init__(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = "default"		,SCREAMING_SNAKE_CASE__ = None		,SCREAMING_SNAKE_CASE__ = False		,)      ->				Dict:





             """simple docstring"""






             super().__init__(SCREAMING_SNAKE_CASE__		,task=SCREAMING_SNAKE_CASE__		,patching_specs=SCREAMING_SNAKE_CASE__		,use_past=SCREAMING_SNAKE_CASE__							)
             if not getattr(self._config		,'''pad_token_id'''		,SCREAMING_SNAKE_CASE__							):
                   # TODO: how to do that better?
                   __SCREAMING_SNAKE_CASE       :Dict		    =  0




       @property
       def    _UpperCamelCase					(						self							)      ->				Mapping[str, Mapping[int, str]]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :List[str]		    =  OrderedDict({'''input_ids''': {0: '''batch''', 1: '''sequence'''}}							)
             if self.use_past:
                   self.fill_with_past_key_values_(SCREAMING_SNAKE_CASE__		,direction='''inputs'''							)
                   __SCREAMING_SNAKE_CASE       :Dict		    =  {0: '''batch''', 1: '''past_sequence + sequence'''}
             else:
                   __SCREAMING_SNAKE_CASE       :Union[str, Any]		    =  {0: '''batch''', 1: '''sequence'''}

             return common_inputs




       @property
       def    _UpperCamelCase					(						self							)      ->				int:





             """simple docstring"""






             return self._config.n_layer




       @property
       def    _UpperCamelCase					(						self							)      ->				int:





             """simple docstring"""






             return self._config.n_head




       def    _UpperCamelCase					(						self		,SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__ = -1		,SCREAMING_SNAKE_CASE__ = -1		,SCREAMING_SNAKE_CASE__ = False		,SCREAMING_SNAKE_CASE__ = None		,)      ->				Mapping[str, Any]:





             """simple docstring"""






             __SCREAMING_SNAKE_CASE       :Dict		    =  super(SCREAMING_SNAKE_CASE__		,self							).generate_dummy_inputs(
                 SCREAMING_SNAKE_CASE__		,batch_size=SCREAMING_SNAKE_CASE__		,seq_length=SCREAMING_SNAKE_CASE__		,is_pair=SCREAMING_SNAKE_CASE__		,framework=SCREAMING_SNAKE_CASE__							)

             # We need to order the input in the way they appears in the forward()
             __SCREAMING_SNAKE_CASE       :Any		    =  OrderedDict({'''input_ids''': common_inputs['''input_ids''']}							)

             # Need to add the past_keys
             if self.use_past:
                   if not is_torch_available():
                         raise ValueError('''Cannot generate dummy past_keys inputs without PyTorch installed.'''							)
                   else:
                         import torch

                         __SCREAMING_SNAKE_CASE       :int		    =  common_inputs['''input_ids'''].shape
                         # Not using the same length for past_key_values
                         __SCREAMING_SNAKE_CASE       :Any		    =  seqlen + 2
                         __SCREAMING_SNAKE_CASE       :List[str]		    =  (
                             batch,
                             self.num_attention_heads,
                             past_key_values_length,
                             self._config.hidden_size // self.num_attention_heads,
                         )
                         __SCREAMING_SNAKE_CASE       :List[str]		    =  [
                             (torch.zeros(SCREAMING_SNAKE_CASE__							), torch.zeros(SCREAMING_SNAKE_CASE__							)) for _ in range(self.num_layers							)
                         ]

             __SCREAMING_SNAKE_CASE       :Any		    =  common_inputs['''attention_mask''']
             if self.use_past:
                   __SCREAMING_SNAKE_CASE       :List[Any]		    =  ordered_inputs['''attention_mask'''].dtype
                   __SCREAMING_SNAKE_CASE       :List[str]		    =  torch.cat(
                       [ordered_inputs['''attention_mask'''], torch.ones(SCREAMING_SNAKE_CASE__		,SCREAMING_SNAKE_CASE__		,dtype=SCREAMING_SNAKE_CASE__							)]		,dim=1							)

             return ordered_inputs




       @property
       def    _UpperCamelCase					(						self							)      ->				int:





             """simple docstring"""






             return 13







"""simple docstring"""
import json
import os
from datetime import date
from pathlib import Path

from tabulate import DataRow, TableFormat, tabulate


lowerCamelCase_       =		TableFormat(
    lineabove=None,
    linebelowheader=None,
    linebetweenrows=None,
    linebelow=None,
    headerrow=DataRow("", "|", "|"),
    datarow=DataRow("", "|", "|"),
    padding=1,
    with_header_hide=None,
)


lowerCamelCase_       =		[]
lowerCamelCase_       =		[]

lowerCamelCase_       =		{"type": "section", "text": {"type": "plain_text", "text": "No failed tests! 🤗", "emoji": True}}

lowerCamelCase_       =		[
    {
        "type": "header",
        "text": {
            "type": "plain_text",
            "text": f'🤗 Accelerate nightly {os.environ.get("TEST_TYPE", "")} test results',
            "emoji": True,
        },
    }
]

lowerCamelCase_       =		0
for log in Path().glob("*.log"):
  lowerCamelCase_       =		0
  with open(log, "r") as f:
    for line in f:
      lowerCamelCase_       =		json.loads(line)
      if line.get("nodeid", "") != "":
        lowerCamelCase_       =		line["nodeid"]
        if line.get("duration", None) is not None:
          lowerCamelCase_       =		f'{line["duration"]:.4f}'
          if line.get("outcome", "") == "failed":
            section_num_failed += 1
            failed.append([test, duration, log.name.split("_")[0]])
            total_num_failed += 1
  group_info.append([str(log), section_num_failed, failed])
  lowerCamelCase_       =		[]
  log.unlink()

lowerCamelCase_       =		""
lowerCamelCase_       =		[]
if total_num_failed > 0:
  for name, num_failed, failed_tests in group_info:
    if num_failed > 0:
      if num_failed == 1:
        message += f"*{name[1:]}: {num_failed} failed test*\n"
      else:
        message += f"*{name[1:]}: {num_failed} failed tests*\n"
      lowerCamelCase_       =		[]
      lowerCamelCase_       =		{}
      for test in failed_tests:
        lowerCamelCase_       =		test[0].split("::")
        lowerCamelCase_       =		data[0].split("/")[-1]
        if data[0] not in filesafailed:
          lowerCamelCase_       =		[data[1:]]
        else:
          filesafailed[data[0]] += [data[1:]]
        failed_table.append(data)

      lowerCamelCase_       =		[test[0] for test in failed_table]
      lowerCamelCase_       =		list(set(files))
      # Count number of instances in failed_tests
      lowerCamelCase_       =		[]
      for file in individual_files:
        table.append([file, len(filesafailed[file])])

      lowerCamelCase_       =		tabulate(
          table,
          headers=["Test Location", "Num Failed"],
          tablefmt=hf_table_format,
          stralign="right",
      )
      message += f"\n```\n{failed_table}\n```"
      all_filesafailed.append(filesafailed)
  if len(message) > 3_0_0_0:
    lowerCamelCase_       =		"Too many failed tests, please see the full report in the Action results."
    lowerCamelCase_       =		len(err) + 1_0
    lowerCamelCase_       =		message[: 3_0_0_0 - offset] + f'\n...\n```\n{err}'
  print(f'### {message}')
else:
  lowerCamelCase_       =		"No failed tests! 🤗"
  print(f'## {message}')
  payload.append(no_error_payload)

if os.environ.get("TEST_TYPE", "") != "":
  from slack_sdk import WebClient

  lowerCamelCase_       =		WebClient(token=os.environ["SLACK_API_TOKEN"])
  if message != "No failed tests! 🤗":
    lowerCamelCase_       =		{
        "type": "section",
        "text": {
            "type": "mrkdwn",
            "text": message,
        },
    }
    payload.append(md_report)
    lowerCamelCase_       =		{
        "type": "section",
        "text": {
            "type": "mrkdwn",
            "text": "*For more details:*",
        },
        "accessory": {
            "type": "button",
            "text": {
                "type": "plain_text",
                "text": "Check Action results",
                "emoji": True,
            },
            "url": f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}',
        },
    }
    payload.append(action_button)
    lowerCamelCase_       =		{
        "type": "context",
        "elements": [
            {
                "type": "plain_text",
                "text": f'Nightly {os.environ.get("TEST_TYPE")} test results for {date.today()}',
            }
        ],
    }
    payload.append(date_report)
  lowerCamelCase_       =		client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload)
  lowerCamelCase_       =		response.data["ts"]
  for failed_file in all_filesafailed:
    for test_location, test_failures in failed_file.items():
      # Keep only the first instance of the test name
      lowerCamelCase_       =		""
      for i, row in enumerate(test_failures):
        if row[0] != test_class:
          lowerCamelCase_       =		row[0]
        else:
          lowerCamelCase_       =		""

      lowerCamelCase_       =		{
          "type": "section",
          "text": {
              "type": "mrkdwn",
              "text": f'Test location: {test_location}\n```\n{tabulate(test_failures, headers=["Class", "Test"], tablefmt=hf_table_format, stralign="right")}\n```',
          },
      }

      client.chat_postMessage(
          channel="#accelerate-ci-daily",
          thread_ts=ts,
          blocks=[payload],
      )