repo stringlengths 2 99 | file stringlengths 13 225 | code stringlengths 0 18.3M | file_length int64 0 18.3M | avg_line_length float64 0 1.36M | max_line_length int64 0 4.26M | extension_type stringclasses 1
value |
|---|---|---|---|---|---|---|
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/tests/test_audio_dataset.py | # -*- coding: utf-8 -*-
import unittest
from onmt.inputters.audio_dataset import AudioSeqField, AudioDataReader
import itertools
import os
import shutil
import torch
import torchaudio
from onmt.tests.utils_for_tests import product_dict
class TestAudioField(unittest.TestCase):
INIT_CASES = list(product_dict(
... | 9,704 | 41.565789 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/tests/__init__.py | 0 | 0 | 0 | py | |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/tests/test_structured_attention.py | import unittest
from onmt.modules.structured_attention import MatrixTree
import torch
class TestStructuredAttention(unittest.TestCase):
def test_matrix_tree_marg_pdfs_sum_to_1(self):
dtree = MatrixTree()
q = torch.rand(1, 5, 5)
marg = dtree.forward(q)
self.assertTrue(
... | 361 | 24.857143 | 56 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/tests/test_embeddings.py | import unittest
from onmt.modules.embeddings import Embeddings
import itertools
from copy import deepcopy
import torch
from onmt.tests.utils_for_tests import product_dict
class TestEmbeddings(unittest.TestCase):
INIT_CASES = list(product_dict(
word_vec_size=[172],
word_vocab_size=[319],
... | 6,207 | 40.66443 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/tests/test_attention.py | """
Here come the tests for attention types and their compatibility
"""
import unittest
import torch
from torch.autograd import Variable
import onmt
class TestAttention(unittest.TestCase):
def test_masked_global_attention(self):
source_lengths = torch.IntTensor([7, 3, 5, 2])
# illegal_weights_m... | 1,072 | 28 | 74 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/hierarchical_transformer.py | from onmt.modules.self_attention import MultiHeadSelfAttention
from onmt.encoders.encoder import EncoderBase
from onmt.utils.misc import nwise, aeq, sequence_mask
import torch, copy
import onmt
class ContainsNaN(Exception):
pass
def _check_for_nan(tensor, msg=''):
if (tensor!=tensor).any():
raise Co... | 10,534 | 39.833333 | 103 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/mean_encoder.py | """Define a minimal encoder."""
from onmt.encoders.encoder import EncoderBase
from onmt.utils.misc import sequence_mask
import torch
class MeanEncoder(EncoderBase):
"""A trivial non-recurrent encoder. Simply applies mean pooling.
Args:
num_layers (int): number of replicated layers
embeddings (o... | 1,404 | 29.543478 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/image_encoder.py | """Image Encoder."""
import torch.nn as nn
import torch.nn.functional as F
import torch
from onmt.encoders.encoder import EncoderBase
class ImageEncoder(EncoderBase):
"""A simple encoder CNN -> RNN for image src.
Args:
num_layers (int): number of encoder layers.
bidirectional (bool): bidirec... | 4,839 | 35.666667 | 76 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/rnn_encoder.py | """Define RNN-based encoders."""
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from onmt.encoders.encoder import EncoderBase
from onmt.utils.rnn_factory import rnn_factory
class RNNEncode... | 4,274 | 34.92437 | 73 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/audio_encoder.py | """Audio encoder"""
import math
import torch.nn as nn
from torch.nn.utils.rnn import pack_padded_sequence as pack
from torch.nn.utils.rnn import pad_packed_sequence as unpack
from onmt.utils.rnn_factory import rnn_factory
from onmt.encoders.encoder import EncoderBase
class AudioEncoder(EncoderBase):
"""A simpl... | 6,055 | 40.197279 | 77 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/encoder.py | """Base class for encoders and generic multi encoders."""
import torch.nn as nn
from onmt.utils.misc import aeq
class EncoderBase(nn.Module):
"""
Base encoder class. Specifies the interface used by different encoder types
and required by :class:`onmt.Models.NMTModel`.
.. mermaid::
graph BT
... | 1,383 | 22.457627 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/transformer.py | """
Implementation of "Attention is All You Need"
"""
import torch.nn as nn
from onmt.encoders.encoder import EncoderBase
from onmt.modules import MultiHeadedAttention
from onmt.modules.position_ffn import PositionwiseFeedForward
from onmt.utils.misc import sequence_mask
class TransformerEncoderLayer(nn.Module):
... | 4,661 | 33.279412 | 75 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/__init__.py | """Module defining encoders."""
from onmt.encoders.encoder import EncoderBase
from onmt.encoders.transformer import TransformerEncoder
from onmt.encoders.rnn_encoder import RNNEncoder
from onmt.encoders.cnn_encoder import CNNEncoder
from onmt.encoders.mean_encoder import MeanEncoder
from onmt.encoders.audio_encoder imp... | 861 | 46.888889 | 102 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/encoders/cnn_encoder.py | """
Implementation of "Convolutional Sequence to Sequence Learning"
"""
import torch.nn as nn
from onmt.encoders.encoder import EncoderBase
from onmt.utils.cnn_factory import shape_transform, StackedCNN
SCALE_WEIGHT = 0.5 ** 0.5
class CNNEncoder(EncoderBase):
"""Encoder based on "Convolutional Sequence to Seque... | 1,860 | 32.232143 | 73 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/translation_server.py | #!/usr/bin/env python
"""REST Translation server."""
from __future__ import print_function
import codecs
import sys
import os
import time
import json
import threading
import re
import traceback
import importlib
import torch
import onmt.opts
from onmt.utils.logging import init_logger
from onmt.utils.misc import set_ran... | 24,269 | 33.72103 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/decode_strategy.py | import torch
class DecodeStrategy(object):
"""Base class for generation strategies.
Args:
pad (int): Magic integer in output vocab.
bos (int): Magic integer in output vocab.
eos (int): Magic integer in output vocab.
batch_size (int): Current batch size.
parallel_paths ... | 8,761 | 38.647059 | 80 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/translation.py | """ Translation main class """
from __future__ import unicode_literals, print_function
import torch
from onmt.inputters.text_dataset import TextMultiField
from onmt.utils.alignment import build_align_pharaoh
class TranslationBuilder(object):
"""
Build a word-based translation from the batch output
of tra... | 7,226 | 37.854839 | 86 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/greedy_search.py | import torch
from onmt.translate.decode_strategy import DecodeStrategy
def sample_with_temperature(logits, sampling_temp, keep_topk):
"""Select next tokens randomly from the top k possible next tokens.
Samples from a categorical distribution over the ``keep_topk`` words using
the category probabilities ... | 6,843 | 39.258824 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/beam_search.py | import torch
from onmt.translate import penalties
from onmt.translate.decode_strategy import DecodeStrategy
from onmt.utils.misc import tile
import warnings
class BeamSearch(DecodeStrategy):
"""Generation beam search.
Note that the attributes list is not exhaustive. Rather, it highlights
tensors to docu... | 17,605 | 43.015 | 83 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/process_zh.py | from pyhanlp import HanLP
from snownlp import SnowNLP
import pkuseg
# Chinese segmentation
def zh_segmentator(line):
return " ".join(pkuseg.pkuseg().cut(line))
# Chinese simplify -> Chinese traditional standard
def zh_traditional_standard(line):
return HanLP.convertToTraditionalChinese(line)
# Chinese sim... | 753 | 21.176471 | 52 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/__init__.py | """ Modules for translation """
from onmt.translate.translator import Translator
from onmt.translate.translation import Translation, TranslationBuilder
from onmt.translate.beam_search import BeamSearch, GNMTGlobalScorer
from onmt.translate.decode_strategy import DecodeStrategy
from onmt.translate.greedy_search import G... | 695 | 45.4 | 70 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/penalties.py | from __future__ import division
import torch
class PenaltyBuilder(object):
"""Returns the Length and Coverage Penalty function for Beam Search.
Args:
length_pen (str): option name of length pen
cov_pen (str): option name of cov pen
Attributes:
has_cov_pen (bool): Whether coverage... | 3,710 | 35.029126 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/translate/translator.py | #!/usr/bin/env python
""" Translator Class and builder """
from __future__ import print_function
import codecs
import os
import time
import numpy as np
from itertools import count, zip_longest
import torch
import onmt.model_builder
import onmt.inputters as inputters
import onmt.decoders.ensemble
from onmt.translate.b... | 30,859 | 38.262087 | 99 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/rnn_factory.py | """
RNN tools
"""
import torch.nn as nn
import onmt.models
def rnn_factory(rnn_type, **kwargs):
""" rnn factory, Use pytorch version when available. """
no_pack_padded_seq = False
if rnn_type == "SRU":
# SRU doesn't support PackedSequence.
no_pack_padded_seq = True
rnn = onmt.mode... | 432 | 23.055556 | 60 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/optimizers.py | """ Optimizers class """
import torch
import torch.optim as optim
from torch.nn.utils import clip_grad_norm_
import operator
import functools
from copy import copy
from math import sqrt
import types
import importlib
from onmt.utils.misc import fn_args
def build_torch_optimizer(model, opt):
"""Builds the PyTorch o... | 27,188 | 38.461538 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/logging.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
from logging.handlers import RotatingFileHandler
logger = logging.getLogger()
def init_logger(log_file=None, log_file_level=logging.NOTSET):
log_format = logging.Formatter("[%(asctime)s %(levelname)s] %(message)s")
logger = logging... | 784 | 29.192308 | 77 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/loss.py | """
This includes: LossComputeBase and the standard NMTLossCompute, and
sharded loss compute stuff.
"""
from __future__ import division
import torch
import torch.nn as nn
import torch.nn.functional as F
import onmt
from onmt.modules.sparse_losses import SparsemaxLoss
from onmt.modules.sparse_activations... | 15,317 | 39.099476 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/misc.py | # -*- coding: utf-8 -*-
import torch
import random
import inspect
from itertools import islice, repeat
import os
def split_corpus(path, shard_size, default=None):
"""yield a `list` containing `shard_size` line of `path`,
or repeatly generate `default` if `path` is None.
"""
if path is not None:
... | 5,885 | 31.7 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/report_manager.py | """ Report manager utility """
from __future__ import print_function
import time
from datetime import datetime
import onmt
from onmt.utils.logging import logger
def build_report_manager(opt, gpu_rank):
if opt.tensorboard and gpu_rank == 0:
from torch.utils.tensorboard import SummaryWriter
tensor... | 5,323 | 33.128205 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/cnn_factory.py | """
Implementation of "Convolutional Sequence to Sequence Learning"
"""
import torch
import torch.nn as nn
import torch.nn.init as init
import onmt.modules
SCALE_WEIGHT = 0.5 ** 0.5
def shape_transform(x):
""" Tranform the size of the tensors to fit for conv input. """
return torch.unsqueeze(torch.transpose... | 1,620 | 28.472727 | 78 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/statistics.py | """ Statistics calculation utility """
from __future__ import division
import time
import math
import sys
from onmt.utils.logging import logger
class Statistics(object):
"""
Accumulator for loss statistics.
Currently calculates:
* accuracy
* perplexity
* elapsed time
"""
def __init_... | 4,291 | 30.328467 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/distributed.py | """ Pytorch Distributed utils
This piece of code was heavily inspired by the equivalent of Fairseq-py
https://github.com/pytorch/fairseq
"""
from __future__ import print_function
import math
import pickle
import torch.distributed
from onmt.utils.logging import logger
def is_master(opt, device_id):
ret... | 3,926 | 30.926829 | 77 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/alignment.py | # -*- coding: utf-8 -*-
import torch
from itertools import accumulate
def make_batch_align_matrix(index_tensor, size=None, normalize=False):
"""
Convert a sparse index_tensor into a batch of alignment matrix,
with row normalize to the sum of 1 if set normalize.
Args:
index_tensor (LongTensor... | 5,370 | 39.689394 | 76 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/__init__.py | """Module defining various utilities."""
from onmt.utils.misc import split_corpus, aeq, use_gpu, set_random_seed
from onmt.utils.alignment import make_batch_align_matrix
from onmt.utils.report_manager import ReportMgr, build_report_manager
from onmt.utils.statistics import Statistics
from onmt.utils.optimizers import M... | 696 | 48.785714 | 76 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/earlystopping.py |
from enum import Enum
from onmt.utils.logging import logger
class PatienceEnum(Enum):
IMPROVING = 0
DECREASING = 1
STOPPED = 2
class Scorer(object):
def __init__(self, best_score, name):
self.best_score = best_score
self.name = name
def is_improving(self, stats):
raise ... | 5,794 | 28.717949 | 79 | py |
data-to-text-hierarchical | data-to-text-hierarchical-master/onmt/utils/parse.py | import configargparse as cfargparse
import os
import torch
import onmt.opts as opts
from onmt.utils.logging import logger
class ArgumentParser(cfargparse.ArgumentParser):
def __init__(
self,
config_file_parser_class=cfargparse.YAMLConfigFileParser,
formatter_class=cfargparse.... | 7,089 | 41.45509 | 82 | py |
triton | triton-main/.github/workflows/torchinductor/scripts/check_acc.py | import csv
import sys
file_path = sys.argv[1]
with open(file_path) as f:
reader = csv.reader(f)
for i, row in enumerate(reader):
if i == 0:
continue
if row[3] != "pass":
print(f"{row[1]} failed on device {row[0]} with batch size {row[2]}")
| 289 | 23.166667 | 81 | py |
triton | triton-main/.github/workflows/torchinductor/scripts/check_perf.py | import argparse
import csv
from collections import namedtuple
# Create a named tuple for the output of the benchmark
BenchmarkOutput = namedtuple(
'BenchmarkOutput', ['dev', 'name', 'batch_size', 'speedup', 'latency'])
def parse_output(file_path: str) -> dict:
entries = {}
with open(file_path) as f:
... | 2,374 | 34.984848 | 100 | py |
triton | triton-main/python/setup.py | import os
import platform
import re
import shutil
import subprocess
import sys
import sysconfig
import tarfile
import tempfile
import urllib.request
from pathlib import Path
from typing import NamedTuple
from setuptools import Extension, setup
from setuptools.command.build_ext import build_ext
from setuptools.command.... | 11,910 | 34.876506 | 122 | py |
triton | triton-main/python/tutorials/05-layer-norm.py | """
Layer Normalization
====================
In this tutorial, you will write a high-performance layer normalization
kernel that runs faster than the PyTorch implementation.
In doing so, you will learn about:
* Implementing backward pass in Triton.
* Implementing parallel reduction in Triton.
"""
# %%
# Motivation... | 15,483 | 40.290667 | 214 | py |
triton | triton-main/python/tutorials/02-fused-softmax.py | """
Fused Softmax
=============
In this tutorial, you will write a fused softmax operation that is significantly faster
than PyTorch's native op for a particular class of matrices: those whose rows can fit in
the GPU's SRAM.
In doing so, you will learn about:
* The benefits of kernel fusion for bandwidth-bound opera... | 7,632 | 36.975124 | 128 | py |
triton | triton-main/python/tutorials/06-fused-attention.py | """
Fused Attention
===============
This is a Triton implementation of the Flash Attention v2 algorithm from Tri Dao (https://tridao.me/publications/flash2/flash2.pdf)
Extra Credits:
- Original flash attention paper (https://arxiv.org/abs/2205.14135)
- Rabe and Staats (https://arxiv.org/pdf/2112.05682v2.pdf)
- Adam P... | 16,390 | 36.1678 | 131 | py |
triton | triton-main/python/tutorials/01-vector-add.py | """
Vector Addition
===============
In this tutorial, you will write a simple vector addition using Triton.
In doing so, you will learn about:
* The basic programming model of Triton.
* The `triton.jit` decorator, which is used to define Triton kernels.
* The best practices for validating and benchmarking your cus... | 5,496 | 38.264286 | 139 | py |
triton | triton-main/python/tutorials/08-experimental-block-pointer.py | """
Block Pointer (Experimental)
============================
This tutorial will guide you through writing a matrix multiplication algorithm that utilizes block pointer semantics.
These semantics are more friendly for Triton to optimize and can result in better performance on specific hardware.
Note that this feature i... | 11,784 | 50.462882 | 147 | py |
triton | triton-main/python/tutorials/07-math-functions.py | """
Libdevice (`tl.math`) function
==============================
Triton can invoke a custom function from an external library.
In this example, we will use the `libdevice` library (a.k.a `math` in triton) to apply `asin` on a tensor.
Please refer to https://docs.nvidia.com/cuda/libdevice-users-guide/index.html regardi... | 2,597 | 34.108108 | 180 | py |
triton | triton-main/python/tutorials/04-low-memory-dropout.py | """
Low-Memory Dropout
==================
In this tutorial, you will write a memory-efficient implementation of dropout whose state
will be composed of a single int32 seed. This differs from more traditional implementations of dropout,
whose state is generally composed of a bit mask tensor of the same shape as the inp... | 6,337 | 35.425287 | 203 | py |
triton | triton-main/python/tutorials/03-matrix-multiplication.py | """
Matrix Multiplication
=====================
In this tutorial, you will write a very short high-performance FP16 matrix multiplication kernel that achieves
performance on parallel with cuBLAS.
You will specifically learn about:
* Block-level matrix multiplications.
* Multi-dimensional pointer arithmetics.
* Prog... | 14,818 | 41.219373 | 143 | py |
triton | triton-main/python/examples/copy_strided.py | import triton
import triton.language as tl
# triton kernel
@triton.jit
def kernel(X, stride_xm,
Z, stride_zn,
BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr):
off_m = tl.arange(0, BLOCK_M)
off_n = tl.arange(0, BLOCK_N)
Xs = X + off_m[:, None] * stride_xm + off_n[None, :] * 1
Zs = Z... | 531 | 27 | 103 | py |
triton | triton-main/python/examples/empty.py | import torch
import triton
import triton.language as tl
@triton.jit
def kernel(X, stride_xm, stride_xn, BLOCK: tl.constexpr):
pass
X = torch.randn(1, device="cuda")
pgm = kernel[(1,)](X, 1, 1, BLOCK=1024)
| 214 | 14.357143 | 57 | py |
triton | triton-main/python/test/tools/compare_files.py | import argparse
import difflib
import glob
import os
import sys
from typing import Dict, List, Optional, Tuple
import yaml
class ComparisonResult:
def __init__(self, name: str, extension: str, numComparisons: int, diffs: List[str] = None, errors: List[str] = None):
self.name = name
self.extension... | 8,889 | 32.931298 | 152 | py |
triton | triton-main/python/test/unit/tools/test_aot.py | import glob
import os
import subprocess
import sys
import tempfile
import numpy as np
import triton
from triton.common import cuda_include_dir, libcuda_dirs
kernel_utils_src = """
import triton
@triton.jit
def mul(x, y):
return x * y
"""
kernel_src = """
import triton
import triton.language as tl
import kernel... | 6,126 | 28.887805 | 180 | py |
triton | triton-main/python/test/unit/runtime/test_cache.py | import os
import shutil
import pytest
import torch
import triton
import triton.language as tl
from triton.runtime.jit import JITFunction
tmpdir = ".tmp"
@triton.jit
def function_1(i):
i = i + 1
i = function_2(i)
return i
@triton.jit
def function_2(i):
i = i + 1
return i
@triton.jit
def kern... | 5,762 | 26.574163 | 88 | py |
triton | triton-main/python/test/unit/runtime/test_driver.py | import sys
import triton
def test_is_lazy():
from importlib import reload
reload(sys.modules["triton.runtime.driver"])
reload(sys.modules["triton.runtime"])
mod = sys.modules[triton.runtime.driver.__module__]
assert isinstance(triton.runtime.driver, getattr(mod, "LazyProxy"))
assert triton.ru... | 488 | 31.6 | 87 | py |
triton | triton-main/python/test/unit/runtime/test_subproc.py | import multiprocessing
import os
import shutil
from collections import namedtuple
import torch
import triton
import triton.language as tl
tmpdir = ".tmp"
def reset_tmp_dir():
os.environ["TRITON_CACHE_DIR"] = tmpdir
if os.path.exists(tmpdir):
shutil.rmtree(tmpdir)
instance_descriptor = namedtuple(... | 1,989 | 22.690476 | 90 | py |
triton | triton-main/python/test/unit/runtime/test_autotuner.py | import torch
import triton
import triton.language as tl
def test_kwargs():
N = 1024
src = torch.empty(N, device='cuda')
dst = torch.empty(N, device='cuda')
configs = [triton.Config(kwargs={'BLOCK_SIZE': 32}), triton.Config(kwargs={'BLOCK_SIZE': 128})]
@triton.autotune(configs=configs, key=['N']... | 709 | 29.869565 | 99 | py |
triton | triton-main/python/test/unit/runtime/test_launch.py | import gc
# import importlib
# import os
# import sys
# import tempfile
# import textwrap
# import time
import tracemalloc
import torch
import triton
import triton.language as tl
# from typing import Tuple
def test_memory_leak() -> None:
@triton.jit
def kernel(in_ptr0, out_ptr0, xnumel, XBLOCK: tl.constex... | 3,409 | 30.869159 | 96 | py |
triton | triton-main/python/test/unit/interpreter/test_interpreter.py | import random
import torch
import triton
import triton.language as tl
from triton.interpreter.interpreter import program_ids_from_grid
def test_addition():
@triton.jit(interpret=True)
def add_kernel(
x_ptr,
y_ptr,
output_ptr,
n_elements,
BLOCK_SIZE: tl.constexpr,
... | 1,878 | 25.842857 | 65 | py |
triton | triton-main/python/test/unit/operators/test_inductor.py | import torch
import triton
import triton.language as tl
def test_normalization_with_remat():
@triton.jit
def triton_(in_out_ptr0, in_out_ptr1, in_ptr0, in_ptr1, in_ptr2, in_ptr3, xnumel, rnumel, XBLOCK: tl.constexpr, RBLOCK: tl.constexpr):
xnumel = 512
rnumel = 4096
xoffset = tl.prog... | 6,326 | 39.557692 | 138 | py |
triton | triton-main/python/test/unit/operators/test_cross_entropy.py | import pytest
import torch
import triton
import triton.ops
@pytest.mark.parametrize("M, N, dtype, mode",
[
(M, N, dtype, mode) for M in [1024, 821]
for N in [512, 857, 1871, 2089, 8573, 31000]
for dtype in... | 1,447 | 34.317073 | 99 | py |
triton | triton-main/python/test/unit/operators/test_blocksparse.py | import pytest
import torch
import triton
import triton.ops
def sparsify_tensor(x, mask, block):
ret = torch.empty((x.size(0), mask.sum(), block, block), dtype=x.dtype, device=x.device)
for idx, (h, i, j) in enumerate(zip(*mask.nonzero(as_tuple=True))):
ret[:, idx, :, :] = x[:, h, i * block:(i + 1) * ... | 7,887 | 34.854545 | 126 | py |
triton | triton-main/python/test/unit/operators/test_matmul.py | import itertools
import pytest
import torch
import triton
import triton.language as tl
import triton.ops
def f8_to_f16(x, dtype):
@triton.jit
def kernel(Y, X, N, BLOCK_SIZE: tl.constexpr):
pid = tl.program_id(0)
offs = pid * BLOCK_SIZE + tl.arange(0, BLOCK_SIZE)
mask = offs < N
... | 7,831 | 47.345679 | 127 | py |
triton | triton-main/python/test/unit/operators/test_flash_attention.py | import pytest
import torch
import triton
import triton.ops
@pytest.mark.parametrize('Z, H, N_CTX, D_HEAD', [(4, 48, 1024, 16),
(4, 48, 1024, 32),
(4, 48, 1024, 64),
(4, 4... | 2,243 | 43 | 113 | py |
triton | triton-main/python/test/unit/language/test_core.py | # flake8: noqa: F821,F841
import itertools
import os
import re
from typing import Optional, Union
import numpy as np
import pytest
import torch
from numpy.random import RandomState
import triton
import triton._C.libtriton.triton as _triton
import triton.language as tl
from triton.runtime.jit import JITFunction, Tenso... | 125,776 | 37.033565 | 204 | py |
triton | triton-main/python/test/unit/language/conftest.py | # content of conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption(
"--device", action="store", default='cuda'
)
@pytest.fixture
def device(request):
return request.config.getoption("--device")
| 238 | 14.933333 | 50 | py |
triton | triton-main/python/test/unit/language/assert_helper.py | import sys
import torch
from torch.testing import assert_close
import triton
import triton.language as tl
@triton.jit
def kernel_device_assert(X, Y, BLOCK: tl.constexpr):
x = tl.load(X + tl.arange(0, BLOCK))
tl.device_assert(x == 0, "x != 0")
tl.store(Y + tl.arange(0, BLOCK), x)
@triton.jit
def kernel... | 3,841 | 28.106061 | 90 | py |
triton | triton-main/python/test/unit/language/test_random.py | import numpy as np
import pytest
import scipy.stats
import torch
import triton
import triton.language as tl
#####################################
# Reference Philox Implementation
#####################################
class PhiloxConfig:
def __init__(self, PHILOX_ROUND_A, PHILOX_ROUND_B, PHILOX_KEY_A, PHILOX_KE... | 6,178 | 30.050251 | 90 | py |
triton | triton-main/python/test/unit/language/print_helper.py | import sys
import torch
from torch.testing import assert_close
import triton
import triton.language as tl
@triton.jit
def kernel_device_print(X, Y, BLOCK: tl.constexpr):
x = tl.load(X + tl.arange(0, BLOCK))
tl.device_print("", x)
tl.store(Y + tl.arange(0, BLOCK), x)
@triton.jit
def kernel_print(X, Y, ... | 1,244 | 25.489362 | 97 | py |
triton | triton-main/python/test/unit/language/test_subprocess.py | import os
import subprocess
import sys
import pytest
dir_path = os.path.dirname(os.path.realpath(__file__))
print_path = os.path.join(dir_path, "print_helper.py")
assert_path = os.path.join(dir_path, "assert_helper.py")
# TODO: bfloat16 after LLVM-15
assert_types = ["device_assert", "assert", "static_assert", "no_de... | 2,820 | 33.82716 | 145 | py |
triton | triton-main/python/test/unit/language/test_block_pointer.py | import pytest
import torch
import triton
import triton.language as tl
@triton.jit
def block_copy_kernel(a_ptr, b_ptr, N, BLOCK_SIZE: tl.constexpr, padding_option: tl.constexpr):
pid = tl.program_id(0)
# We only copy half of the data to see if the padding works
a_block_ptr = tl.make_block_ptr(base=a_ptr, ... | 4,453 | 42.242718 | 110 | py |
triton | triton-main/python/test/unit/language/test_line_info.py | import subprocess
import tempfile
import pytest
import torch
import triton
import triton.language as tl
@triton.jit
def kernel_single(X,
Y,
BLOCK: tl.constexpr):
x = tl.load(X + tl.arange(0, BLOCK))
tl.store(Y + tl.arange(0, BLOCK), x)
@triton.jit
def device_inline(x):
... | 3,867 | 30.966942 | 75 | py |
triton | triton-main/python/test/unit/language/test_annotations.py |
from __future__ import annotations
import torch
import triton
import triton.language as tl
def test_annotations(device):
@triton.jit
def _kernel(X: torch.Tensor, N: int, BLOCK_SIZE: tl.constexpr):
pass
x = torch.empty(1, device=device)
_kernel[(1,)](x, x.shape[0], 32)
try:
_ke... | 399 | 17.181818 | 67 | py |
triton | triton-main/python/test/backend/test_device_backend.py | import functools
import hashlib
import importlib
import os
import shutil
import subprocess
import sysconfig
import tempfile
from pathlib import Path
import setuptools
import torch
import triton
import triton.language as tl
from triton.common.backend import BaseBackend, register_backend
from triton.common.build import... | 8,692 | 32.053232 | 110 | py |
triton | triton-main/python/test/backend/third_party_backends/conftest.py | # content of conftest.py
import pytest
def pytest_addoption(parser):
parser.addoption(
"--backend", action="store", default="", help="Codegen backend"
)
@pytest.fixture
def cmdopt(request):
return request.config.getoption("--backend")
| 260 | 16.4 | 71 | py |
triton | triton-main/python/test/backend/third_party_backends/test_xpu_backend.py | import torch
import triton
import triton.language as tl
def test_xpu_backend(cmdopt):
if cmdopt == "xpu":
has_ipex = False
try:
# Import IPEX to provide Intel GPU runtime
import intel_extension_for_pytorch # type: ignore # noqa: F401
has_ipex = True if hasattr... | 1,059 | 30.176471 | 76 | py |
triton | triton-main/python/test/regression/test_functional_regressions.py | import numpy as np
import pytest
import torch
from numpy.random import RandomState
import triton
import triton.language as tl
def test_chained_matmul():
# Regression test for issue #1601
def chained_matmul_reference(a, b, c):
intermediate = torch.einsum('MK,NK->MN', a, b)
return torch.einsum(... | 9,166 | 38.683983 | 125 | py |
triton | triton-main/python/test/regression/test_performance.py | import subprocess
import sys
import pytest
import torch
import triton
import triton.language as tl
import triton.ops
from triton.testing import get_dram_gbps, get_max_tensorcore_tflops
DEVICE_NAME = {7: 'v100', 8: 'a100'}[torch.cuda.get_device_capability()[0]]
#######################
# Utilities
###################... | 9,987 | 42.807018 | 118 | py |
triton | triton-main/python/triton/testing.py | import functools
import os
import subprocess
import sys
from contextlib import contextmanager
from ._C.libtriton.triton import runtime
def nvsmi(attrs):
attrs = ','.join(attrs)
cmd = ['nvidia-smi', '-i', '0', '--query-gpu=' + attrs, '--format=csv,noheader,nounits']
out = subprocess.check_output(cmd)
... | 17,704 | 35.505155 | 189 | py |
triton | triton-main/python/triton/__init__.py | """isort:skip_file"""
__version__ = '2.1.0'
# ---------------------------------------
# Note: import order is significant here.
# submodules
from .runtime import (
autotune,
Config,
heuristics,
JITFunction,
KernelInterface,
reinterpret,
TensorWrapper,
OutOfResources,
MockTensor,
)
... | 1,230 | 16.84058 | 67 | py |
triton | triton-main/python/triton/tools/disasm.py | # MIT License
# Copyright (c) 2020 Da Yan @ HKUST
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge,... | 4,593 | 36.349593 | 90 | py |
triton | triton-main/python/triton/tools/link.py | from collections import defaultdict
from pathlib import Path
from typing import Sequence, Union
from dataclasses import dataclass
def _exists(x):
return x is not None
class LinkerError(Exception):
pass
@dataclass
class KernelLinkerMeta:
arg_names: Sequence[str]
arg_ctypes: Sequence[str]
sizes... | 6,857 | 34.169231 | 157 | py |
triton | triton-main/python/triton/tools/compile.py | import binascii
import hashlib
import importlib.util
import sys
from argparse import ArgumentParser
from pathlib import Path
from typing import List
import triton
from triton.compiler.code_generator import kernel_suffix
from triton.compiler.make_launcher import ty_to_cpp
desc = """
Triton ahead-of-time compiler:
Thi... | 5,337 | 42.754098 | 140 | py |
triton | triton-main/python/triton/tools/build_extern.py | import argparse
import subprocess
from abc import ABC, abstractmethod
from typing import Dict, List, Optional
class Symbol:
_name: str
_op_name: str
_ret_type: str
_arg_names: List[str]
_arg_types: List[str]
def __init__(
self,
name: str,
op_name: str,
ret_type... | 14,661 | 35.746867 | 130 | py |
triton | triton-main/python/triton/tools/__init__.py | 0 | 0 | 0 | py | |
triton | triton-main/python/triton/common/backend.py |
import importlib
import importlib.util
from typing import Dict
from ..runtime.driver import DriverBase
class BaseBackend:
def __init__(self, device_type: str) -> None:
self.device_type = device_type
def add_stages(self, arch, extern_libs, stages):
"""
Custom the arch, extern_libs an... | 2,628 | 26.103093 | 91 | py |
triton | triton-main/python/triton/common/__init__.py | from .build import _build, cuda_include_dir, libcuda_dirs
__all__ = ["_build", "libcuda_dirs", "cuda_include_dir"]
| 116 | 28.25 | 57 | py |
triton | triton-main/python/triton/common/build.py | import contextlib
import functools
import io
import os
import shutil
import subprocess
import sys
import sysconfig
import setuptools
# TODO: is_hip shouldn't be here
def is_hip():
import torch
return torch.version.hip is not None
@functools.lru_cache()
def libcuda_dirs():
locs = subprocess.check_output... | 3,661 | 30.568966 | 172 | py |
triton | triton-main/python/triton/runtime/jit.py | from __future__ import annotations, division
import ast
import functools
import hashlib
import inspect
import os
import subprocess
import textwrap
from collections import defaultdict, namedtuple
from typing import (Callable, Generic, Iterable, List, Optional, TypeVar, Union, cast,
overload)
from .... | 23,031 | 37.069421 | 213 | py |
triton | triton-main/python/triton/runtime/autotuner.py | from __future__ import annotations
import builtins
import time
from typing import Dict
from ..testing import do_bench
from .jit import KernelInterface
class OutOfResources(Exception):
def __init__(self, required, limit, name):
self.message = f'out of resource: {name}, '\
f'Require... | 10,907 | 41.776471 | 163 | py |
triton | triton-main/python/triton/runtime/driver.py | import abc
import hashlib
import os
import tempfile
from pathlib import Path
from ..common.build import _build
from .cache import get_cache_manager
class DriverBase(metaclass=abc.ABCMeta):
CUDA = 0
HIP = 1
@staticmethod
def third_party_dir():
return os.path.join(os.path.dirname(os.path.absp... | 5,045 | 27.834286 | 92 | py |
triton | triton-main/python/triton/runtime/errors.py |
class OutOfResources(Exception):
def __init__(self, required, limit, name):
self.message = f'out of resource: {name}, '\
f'Required: {required}, '\
f'Hardware limit: {limit}'
self.message += '. Reducing block sizes or `num_stages` may help.'
sel... | 591 | 36 | 74 | py |
triton | triton-main/python/triton/runtime/cache.py | import json
import os
import random
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, Optional
def default_cache_dir():
return os.path.join(Path.home(), ".triton", "cache")
class CacheManager(ABC):
def __init__(self, key):
pass
@abstractmethod
def get_fil... | 4,190 | 30.75 | 92 | py |
triton | triton-main/python/triton/runtime/__init__.py | from .autotuner import (Autotuner, Config, Heuristics, OutOfResources, autotune,
heuristics)
from .driver import driver
from .jit import (JITFunction, KernelInterface, MockTensor, TensorWrapper, reinterpret,
version_key)
__all__ = [
"driver",
"Config",
"Heuristics"... | 516 | 22.5 | 87 | py |
triton | triton-main/python/triton/interpreter/torch_wrapper.py | try:
import torch as _torch
except ImportError:
_torch = None
class TorchWrapper:
"""
Helps in making torch an optional dependency
"""
def __getattr__(self, name):
if _torch is None:
raise ImportError("Triton requires PyTorch to be installed")
return getattr(_torch... | 353 | 17.631579 | 72 | py |
triton | triton-main/python/triton/interpreter/core.py | from typing import Tuple
import dataclasses
@dataclasses.dataclass
class ExecutionContext:
program_id: Tuple[int]
program_size: Tuple[int]
| 150 | 14.1 | 28 | py |
triton | triton-main/python/triton/interpreter/tl_lang.py | from __future__ import annotations
from ..language import core as lcore
from . import torch_wrapper
from .core import ExecutionContext
from .memory_map import MemoryMap
torch = torch_wrapper.torch
def _primitive_to_tensor(x):
"""
Converts various Python primitive data types to PyTorch tensor.
"""
te... | 18,501 | 27.819315 | 118 | py |
triton | triton-main/python/triton/interpreter/interpreter.py | import itertools
import random
from typing import Tuple
from .. import language as tl
# import .language.core as lcore
from ..language import core as lcore
from . import torch_wrapper
from .core import ExecutionContext
from .memory_map import MemoryMap
from .tl_lang import (TritonLangProxy, WrappedTensor, _primitive_t... | 5,412 | 30.47093 | 114 | py |
triton | triton-main/python/triton/interpreter/memory_map.py | from __future__ import annotations
import dataclasses
from . import torch_wrapper
torch = torch_wrapper.torch
@dataclasses.dataclass
class RegisteredStorage:
storage: torch.Storage
dtype: torch.dtype
size: int
ptr: int
@property
def end_ptr(self) -> int:
return self.ptr + self.size... | 3,187 | 29.951456 | 116 | py |
triton | triton-main/python/triton/interpreter/__init__.py | 0 | 0 | 0 | py | |
triton | triton-main/python/triton/compiler/errors.py | import ast
from typing import Optional, Union
class CompilationError(Exception):
source_line_count_max_in_message = 12
def _format_message(self) -> str:
node = self.node
if self.src is None:
source_excerpt = " <source unavailable>"
else:
source_excerpt = self.s... | 1,666 | 30.45283 | 104 | py |
triton | triton-main/python/triton/compiler/make_launcher.py | import hashlib
import os
import tempfile
from ..common import _build
from ..runtime.cache import get_cache_manager
from ..runtime.jit import version_key
def is_hip():
import torch
return torch.version.hip is not None
# ----- stub --------
def make_so_cache_key(version_hash, signature, constants):
# G... | 11,854 | 30.697861 | 239 | py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.