import torch
from torch._inductor.select_algorithm import extern_kernels
import triton
import triton.language as tl
from torch._inductor.runtime.triton_heuristics import grid
from torch._C import _cuda_getCurrentRawStream as get_raw_stream
from torch._inductor.runtime.triton_helpers import libdevice
assert_size_stride = torch._C._dynamo.guards.assert_size_stride
empty_strided_cuda = torch._C._dynamo.guards._empty_strided_cuda
reinterpret_tensor = torch._C._dynamo.guards._reinterpret_tensor


@triton.jit
def triton_poi_fused_clone_0(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x0 = xindex % 16
    x1 = xindex // 16
    x2 = xindex
    tmp0 = tl.load(in_ptr0 + (x0 + 64 * x1), xmask)
    tl.store(out_ptr0 + x2, tmp0, xmask)


@triton.jit
def triton_poi_fused_add_tanh_1(in_out_ptr0, in_ptr0, xnumel, XBLOCK: tl.
    constexpr):
    xnumel = 64
    xoffset = tl.program_id(0) * XBLOCK
    xindex = xoffset + tl.arange(0, XBLOCK)[:]
    xmask = xindex < xnumel
    x2 = xindex
    x0 = xindex % 4
    tmp0 = tl.load(in_out_ptr0 + x2, xmask)
    tmp1 = tl.load(in_ptr0 + x0, xmask, eviction_policy='evict_last')
    tmp2 = tmp0 + tmp1
    tmp3 = libdevice.tanh(tmp2)
    tl.store(in_out_ptr0 + x2, tmp3, xmask)


def call(args):
    primals_1, primals_2, primals_3, primals_4, primals_5 = args
    args.clear()
    assert_size_stride(primals_1, (4, 4, 4, 4), (64, 16, 4, 1))
    assert_size_stride(primals_2, (4, 4), (4, 1))
    assert_size_stride(primals_3, (4,), (1,))
    assert_size_stride(primals_4, (4, 4), (4, 1))
    assert_size_stride(primals_5, (4,), (1,))
    with torch.cuda._DeviceGuard(0):
        torch.cuda.set_device(0)
        buf0 = empty_strided_cuda((4, 4, 4), (16, 4, 1), torch.float32)
        get_raw_stream(0)
        triton_poi_fused_clone_0[grid(64)](primals_1, buf0, 64, XBLOCK=64,
            num_warps=1, num_stages=1)
        del primals_1
        buf1 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
        extern_kernels.mm(reinterpret_tensor(buf0, (16, 4), (4, 1), 0),
            reinterpret_tensor(primals_2, (4, 4), (1, 4), 0), out=buf1)
        del primals_2
        buf2 = reinterpret_tensor(buf1, (4, 4, 4), (16, 4, 1), 0)
        del buf1
        triton_poi_fused_add_tanh_1[grid(64)](buf2, primals_3, 64, XBLOCK=
            64, num_warps=1, num_stages=1)
        del primals_3
        buf3 = empty_strided_cuda((16, 4), (4, 1), torch.float32)
        extern_kernels.addmm(primals_5, reinterpret_tensor(buf2, (16, 4), (
            4, 1), 0), reinterpret_tensor(primals_4, (4, 4), (1, 4), 0),
            alpha=1, beta=1, out=buf3)
        del primals_5
    return reinterpret_tensor(buf3, (4, 4, 4), (16, 4, 1), 0
        ), reinterpret_tensor(buf0, (16, 4), (4, 1), 0), buf2, primals_4


def get_args():
    parser = argparse.ArgumentParser()
    group = parser.add_argument_group(title='input data')
    group.add_argument('--input', type=str, required=True, help=
        'Path to input JSON')
    group.add_argument('--json-keys', nargs='+', default=['text'], help=
        'space separate listed of keys to extract from json')
    group.add_argument('--split-sentences', action='store_true', help=
        'Split documents into sentences.')
    group.add_argument('--keep-newlines', action='store_true', help=
        'Keep newlines between sentences when splitting.')
    group = parser.add_argument_group(title='tokenizer')
    group.add_argument('--tokenizer-type', type=str, required=True, choices
        =['BertWordPieceLowerCase', 'BertWordPieceCase', 'GPT2BPETokenizer'
        ], help='What type of tokenizer to use.')
    group.add_argument('--vocab-file', type=str, default=None, help=
        'Path to the vocab file')
    group.add_argument('--merge-file', type=str, default=None, help=
        'Path to the BPE merge file (if necessary).')
    group.add_argument('--append-eod', action='store_true', help=
        'Append an <eod> token to the end of a document.')
    group = parser.add_argument_group(title='output data')
    group.add_argument('--output-prefix', type=str, required=True, help=
        'Path to binary output file without suffix')
    group.add_argument('--dataset-impl', type=str, default='mmap', choices=
        ['lazy', 'cached', 'mmap'])
    group = parser.add_argument_group(title='runtime')
    group.add_argument('--workers', type=int, default=1, help=
        'Number of worker processes to launch')
    group.add_argument('--log-interval', type=int, default=100, help=
        'Interval between progress updates')
    args = parser.parse_args()
    args.keep_empty = False
    if args.tokenizer_type.lower().startswith('bert'):
        if not args.split_sentences:
            None
    args.rank = 0
    args.make_vocab_size_divisible_by = 128
    args.tensor_model_parallel_size = 1
    return args


def init_method_normal(sigma):
    """Init method based on N(0, sigma)."""

    def init_(tensor):
        return torch.nn.init.normal_(tensor, mean=0.0, std=sigma)
    return init_


class MegatronModule(torch.nn.Module):
    """Megatron specific extensions of torch Module with support
    for pipelining."""

    def __init__(self, share_word_embeddings=True):
        super(MegatronModule, self).__init__()
        self.share_word_embeddings = share_word_embeddings

    def state_dict_for_save_checkpoint(self, destination=None, prefix='',
        keep_vars=False):
        """Use this function to override the state dict for
        saving checkpoints."""
        return self.state_dict(destination, prefix, keep_vars)

    def word_embeddings_weight(self):
        if mpu.is_pipeline_first_stage(ignore_virtual=True):
            return self.language_model.embedding.word_embeddings.weight
        if mpu.is_pipeline_last_stage(ignore_virtual=True):
            if not self.share_word_embeddings:
                raise Exception(
                    'word_embeddings_weight() called for last stage, but share_word_embeddings is false'
                    )
            return self.word_embeddings.weight
        raise Exception(
            'word_embeddings_weight() should be called for first and last stage only'
            )

    def initialize_word_embeddings(self, init_method_normal):
        args = get_args()
        if not self.share_word_embeddings:
            raise Exception(
                'initialize_word_embeddings() was called but share_word_embeddings is false'
                )
        if args.pipeline_model_parallel_size == 1:
            return
        if mpu.is_pipeline_last_stage():
            assert not mpu.is_pipeline_first_stage()
            self._word_embeddings_for_head_key = 'word_embeddings_for_head'
            self.word_embeddings = mpu.VocabParallelEmbedding(args.
                padded_vocab_size, args.hidden_size, init_method=
                init_method_normal(args.init_method_std))
            self.word_embeddings.weight.data.fill_(0)
            self.word_embeddings.weight.shared = True
        if torch.distributed.is_initialized():
            if mpu.is_pipeline_first_stage() or mpu.is_pipeline_last_stage():
                torch.distributed.all_reduce(self.word_embeddings_weight().
                    data, group=mpu.get_embedding_group())
        else:
            None


class VitMlpHeadNew(MegatronModule):
    """Pooler layer.

    Pool hidden states of a specific token (for example start of the
    sequence) and add a linear transformation followed by a tanh.

    Arguments:
        hidden_size: hidden size
        init_method: weight initialization method for the linear layer.
            bias is set to zero.
    """

    def __init__(self, hidden_size, num_classes):
        super(VitMlpHeadNew, self).__init__()
        self.dense_in = torch.nn.Linear(hidden_size, hidden_size)
        self.dense_out = torch.nn.Linear(hidden_size, num_classes)
        torch.nn.init.constant_(self.dense_out.bias, -10)

    def forward(self, input_0):
        primals_2 = self.dense_in.weight
        primals_3 = self.dense_in.bias
        primals_4 = self.dense_out.weight
        primals_5 = self.dense_out.bias
        primals_1 = input_0
        output = call([primals_1, primals_2, primals_3, primals_4, primals_5])
        return output[0]


Measured latency_ms: 0.043633