repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_copy_generator.py
import unittest from onmt.modules.copy_generator import CopyGenerator, CopyGeneratorLoss import itertools from copy import deepcopy import torch from torch.nn.functional import softmax from onmt.tests.utils_for_tests import product_dict class TestCopyGenerator(unittest.TestCase): INIT_CASES = list(product_dict...
5,518
39.284672
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_text_dataset.py
import unittest from onmt.inputters.text_dataset import TextMultiField, TextDataReader import itertools import os from copy import deepcopy from torchtext.data import Field from onmt.tests.utils_for_tests import product_dict class TestTextMultiField(unittest.TestCase): INIT_CASES = list(product_dict( b...
7,251
39.741573
76
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_beam_search.py
import unittest from onmt.translate.beam_search import BeamSearch, GNMTGlobalScorer from copy import deepcopy import torch class GlobalScorerStub(object): alpha = 0 beta = 0 def __init__(self): self.length_penalty = lambda x, alpha: 1. self.cov_penalty = lambda cov, beta: torch.zeros( ...
27,033
46.345009
79
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_translation_server.py
import unittest from onmt.translate.translation_server import ServerModel, TranslationServer import os from six import string_types from textwrap import dedent import torch from onmt.translate.translator import Translator TEST_DIR = os.path.dirname(os.path.abspath(__file__)) class TestServerModel(unittest.TestCa...
8,233
34.339056
77
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_greedy_search.py
import unittest from onmt.translate.greedy_search import GreedySearch import torch class TestGreedySearch(unittest.TestCase): BATCH_SZ = 3 INP_SEQ_LEN = 53 DEAD_SCORE = -1e20 BLOCKED_SCORE = -10e20 def test_doesnt_predict_eos_if_shorter_than_min_len(self): # batch 0 will always predict ...
9,200
41.400922
78
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_models.py
import copy import unittest import math import torch import onmt import onmt.inputters import onmt.opts from onmt.model_builder import build_embeddings, \ build_encoder, build_decoder from onmt.encoders.image_encoder import ImageEncoder from onmt.encoders.audio_encoder import AudioEncoder from onmt.utils.parse im...
11,557
34.563077
76
py
data-to-text-hierarchical
data-to-text-hierarchical-master/onmt/tests/test_image_dataset.py
import unittest from onmt.inputters.image_dataset import ImageDataReader import os import shutil import cv2 import numpy as np import torch class TestImageDataReader(unittest.TestCase): # this test touches the file system, so it could be considered an # integration test _THIS_DIR = os.path.dirname(os.pa...
3,641
38.16129
76
py
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/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/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/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/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/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/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/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/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_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/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/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/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/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/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/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/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/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
triton
triton-main/python/triton/compiler/compiler.py
from __future__ import annotations import functools import hashlib import json import os import re import subprocess import tempfile from collections import namedtuple from pathlib import Path from typing import Any, Tuple from .._C.libtriton.triton import (add_external_libs, compile_ptx_to_cubin, ...
23,660
36.797125
144
py
triton
triton-main/python/triton/language/core.py
from __future__ import annotations from contextlib import contextmanager from enum import Enum from functools import wraps from typing import Callable, List, Sequence, TypeVar from .._C.libtriton.triton import ir from ..runtime.jit import jit from . import math, semantic T = TypeVar('T') TRITON_MAX_TENSOR_NUMEL = 1...
62,163
31.175983
137
py
triton
triton-main/python/triton/language/math.py
import functools import os from . import core @functools.lru_cache() def libdevice_path(): import torch third_party_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "third_party") if torch.version.hip is None: default = os.path.join(third_party_dir, "cuda", "lib", "libdevice.1...
75,127
47.943322
157
py
triton
triton-main/python/triton/ops/flash_attention.py
""" Fused Attention =============== This is a Triton implementation of the Flash Attention algorithm (see: Dao et al., https://arxiv.org/pdf/2205.14135v2.pdf; Rabe and Staats https://arxiv.org/pdf/2112.05682v2.pdf) Sequence Parallel implementation inspired by HazyResearch (see https://github.com/HazyResearch/flash-att...
15,056
35.107914
113
py
triton
triton-main/python/triton/ops/cross_entropy.py
import torch from .. import heuristics, jit from .. import language as tl from .. import next_power_of_2 def num_warps(N): if N < 2048: return 4 elif N < 8192: return 8 return 16 @heuristics({'num_warps': lambda nargs: num_warps(nargs['N'])}) @heuristics({'BLOCK': lambda nargs: next_pow...
3,450
34.947917
89
py
triton
triton-main/python/triton/ops/matmul.py
import torch from .. import Config, autotune, cdiv, heuristics, jit from .. import language as tl from .matmul_perf_model import early_config_prune, estimate_matmul_time _ordered_datatypes = [torch.float16, torch.bfloat16, torch.float32] def get_higher_dtype(a, b): if a is b: return a assert a in _...
8,026
41.696809
127
py
triton
triton-main/python/triton/ops/matmul_perf_model.py
import heapq import torch from .. import cdiv from .._C.libtriton.triton import runtime from ..runtime import driver from ..testing import get_dram_gbps, get_max_simd_tflops, get_max_tensorcore_tflops def get_tensorcore_tflops(backend, device, num_ctas, num_warps, dtype): ''' return compute throughput in TOPS '...
6,369
39.062893
117
py
triton
triton-main/python/triton/ops/blocksparse/softmax.py
import torch from ... import jit from ... import language as tl from ... import next_power_of_2 def num_warps(n): if n <= 128: return 1 if n <= 256: return 2 if n <= 512: return 4 if n <= 4096: return 8 return 16 @jit def _blocksparse_softmax_fwd( Out, A, str...
7,905
31.804979
94
py
triton
triton-main/python/triton/ops/blocksparse/matmul.py
import torch from ... import cdiv, heuristics, jit from ... import language as tl # ******************************************************** # -------------------------------------------------------- # Sparse = Dense x Dense (SDD) # This operation uses super-blocking to make sure that # it's done efficiently when sma...
15,615
34.652968
114
py
G-PATE
G-PATE-master/rdp_utils.py
import numpy as np import math import sys from sklearn.preprocessing import normalize from pate_core import * from numpy import linalg as LA EPS = sys.float_info.epsilon # Algorithm 1 in 'Scalable Private Learning with PATE' def gnmax_thresh_aggregator(counts, thresh_cnt, sigma_thresh, sigma, orders): log_pr_an...
12,952
36.436416
124
py
G-PATE
G-PATE-master/model.py
from __future__ import division import os import time import math from glob import glob import tensorflow as tf import numpy as np from six.moves import xrange import json import sys from keras.datasets import cifar10 from ops import * from utils import * from rdp_utils import * from pate_core import * import pickle fr...
57,590
43.575077
156
py
G-PATE
G-PATE-master/evaluation/train-classifier-celebA.py
#!/usr/bin/env python # coding: utf-8 import numpy as np import argparse import joblib import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True # config.gpu_options.per_process_gpu_memory_fraction = 0.3 tf.keras.backend.set_session(tf.Session(config=config)); def load_celeb(): ...
2,797
30.438202
107
py
G-PATE
G-PATE-master/evaluation/train-classifier-fmnist.py
#!/usr/bin/env python # coding: utf-8 import numpy as np import argparse import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True # config.gpu_options.per_process_gpu_memory_fraction = 0.3 tf.keras.backend.set_session(tf.Session(config=config)); def pipeline(): parser = argpars...
2,846
32.892857
109
py
G-PATE
G-PATE-master/evaluation/train-classifier-mnist.py
#!/usr/bin/env python # coding: utf-8 import numpy as np import argparse import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True # config.gpu_options.per_process_gpu_memory_fraction = 0.3 tf.keras.backend.set_session(tf.Session(config=config)); def pipeline(): parser = argpa...
2,661
32.696203
109
py
G-PATE
G-PATE-master/evaluation/train-classifier-hair.py
#!/usr/bin/env python # coding: utf-8 # In[13]: import numpy as np import argparse import joblib import tensorflow as tf config = tf.ConfigProto() config.gpu_options.allow_growth = True # config.gpu_options.per_process_gpu_memory_fraction = 0.3 tf.keras.backend.set_session(tf.Session(config=config)); def load_cel...
2,820
29.010638
107
py
G-PATE
G-PATE-master/evaluation/train-classifier-small-celebA.py
#!/usr/bin/env python # coding: utf-8 import numpy as np import argparse parser = argparse.ArgumentParser(description='Train classifier and evaluate their accuracy') parser.add_argument('--data', type=str, help='datafile name') args = parser.parse_args() import joblib data = joblib.load(args.data) print(args.data) ...
2,390
27.129412
107
py
kraken
kraken-main/kraken/align.py
# # Copyright 2021 Teklia # Copyright 2021 Benjamin Kiessling # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
6,614
32.75
137
py
kraken
kraken-main/kraken/blla.py
# # Copyright 2019 Benjamin Kiessling # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
15,295
41.371191
140
py
kraken
kraken-main/kraken/kraken.py
# # Copyright 2015 Benjamin Kiessling # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
30,865
42.351124
139
py
kraken
kraken-main/kraken/repo.py
# # Copyright 2015 Benjamin Kiessling # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
10,633
39.280303
124
py
kraken
kraken-main/kraken/ketos/segmentation.py
# # Copyright 2022 Benjamin Kiessling # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
29,987
48.98
151
py
kraken
kraken-main/kraken/ketos/__init__.py
# # Copyright 2015 Benjamin Kiessling # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
2,546
28.275862
113
py