python_code
stringlengths
0
1.02M
repo_name
stringlengths
9
48
file_path
stringlengths
5
114
import os import fire import random from retry.api import retry_call from tqdm import tqdm from datetime import datetime from functools import wraps from lightweight_gan import Trainer, NanException from lightweight_gan.diff_augment_test import DiffAugmentTest import torch import torch.multiprocessing as mp import tor...
lightweight-gan-main
lightweight_gan/cli.py
import os import tempfile from pathlib import Path from shutil import copyfile import torch import torchvision from torch import nn from torch.utils.data import DataLoader from lightweight_gan.lightweight_gan import AugWrapper, ImageDataset assert torch.cuda.is_available(), 'You need to have an Nvidia GPU with CUDA...
lightweight-gan-main
lightweight_gan/diff_augment_test.py
import os import json import multiprocessing from random import random import math from math import log2, floor from functools import lru_cache, partial from contextlib import contextmanager, ExitStack from pathlib import Path from shutil import rmtree import torch from torch.cuda.amp import autocast, GradScaler from ...
lightweight-gan-main
lightweight_gan/lightweight_gan.py
from setuptools import setup, find_packages setup( name = 'routing_transformer', packages = find_packages(exclude=['examples']), version = '1.6.1', license='MIT', description = 'Routing Transformer (Pytorch)', author = 'Phil Wang, Aran Komatsuzaki', author_email = 'lucidrains@gmail.com, aran1234321@gmail...
routing-transformer-master
setup.py
import deepspeed from routing_transformer import RoutingTransformerLM from routing_transformer.autoregressive_wrapper import AutoregressiveWrapper import argparse import random import tqdm import gzip import numpy as np import torch import torch.optim as optim from torch.nn import functional as F from torch.utils.dat...
routing-transformer-master
examples/enwik8_deepspeed/train.py
import torch import numpy as np import math import time import random from torch.optim import Adam from routing_transformer.routing_transformer import RoutingTransformerLM from routing_transformer.autoregressive_wrapper import AutoregressiveWrapper s = RoutingTransformerLM( num_tokens = 256 + 4, dim = 1024, ...
routing-transformer-master
examples/toy_tasks/increment.py
import tqdm import torch import torch.optim as optim from routing_transformer import RoutingTransformerEncDec # constants NUM_BATCHES = int(1e5) BATCH_SIZE = 32 LEARNING_RATE = 1e-4 GENERATE_EVERY = 100 NUM_TOKENS = 256 + 2 ENC_SEQ_LEN = 128 DEC_SEQ_LEN = 256 # helpers def cycle(): while True: prefix ...
routing-transformer-master
examples/toy_tasks/enc_dec_copy_task.py
from routing_transformer import RoutingTransformerLM from routing_transformer.autoregressive_wrapper import AutoregressiveWrapper import random import tqdm import gzip import numpy as np import torch import torch.optim as optim from torch.nn import functional as F from torch.utils.data import DataLoader, Dataset # co...
routing-transformer-master
examples/enwik8_simple/train.py
import math import torch from torch import nn from routing_transformer.routing_transformer import RoutingTransformer import torch.nn.functional as F def find_module(nn_module, type): for module in nn_module.modules(): if isinstance(module, type): return module return None def pad_to_multip...
routing-transformer-master
routing_transformer/autopadder.py
from functools import partial import torch import random from torch import nn import torch.nn.functional as F from torch.nn.utils.rnn import pad_sequence from routing_transformer.routing_transformer import RoutingTransformerLM from routing_transformer.autopadder import Autopadder def default(value, default): retur...
routing-transformer-master
routing_transformer/autoregressive_wrapper.py
import torch import torch.nn as nn from operator import itemgetter from torch.autograd.function import Function from torch.utils.checkpoint import get_device_states, set_device_states # for routing arguments into the functions of the reversible layer def route_args(router, args, depth): routed_args = [(dict(), di...
routing-transformer-master
routing_transformer/reversible.py
import re from inspect import isfunction import torch from torch import nn from routing_transformer.routing_transformer import RoutingTransformerLM, update_kmeans_on_backwards from routing_transformer.autoregressive_wrapper import AutoregressiveWrapper ENC_PREFIX = 'enc_' DEC_PREFIX = 'dec_' def default(x, d): if...
routing-transformer-master
routing_transformer/encoder_decoder.py
from routing_transformer.routing_transformer import RoutingTransformer, RoutingTransformerLM, KmeansAttention, update_kmeans_on_backwards from routing_transformer.encoder_decoder import RoutingTransformerEncDec from routing_transformer.autoregressive_wrapper import AutoregressiveWrapper from routing_transformer.autopad...
routing-transformer-master
routing_transformer/__init__.py
import torch import torch.nn as nn import torch.nn.functional as F import math from inspect import isfunction from operator import mul from functools import partial, reduce, wraps from einops import rearrange, repeat from einops.layers.torch import Rearrange from local_attention import LocalAttention from product_ke...
routing-transformer-master
routing_transformer/routing_transformer.py
import os import re from subprocess import check_call from setuptools import setup, find_packages from setuptools.command.install import install __pkg_name__ = 'bonito' verstrline = open(os.path.join(__pkg_name__, '__init__.py'), 'r').read() vsre = r"^__version__ = ['\"]([^'\"]*)['\"]" mo = re.search(vsre, verstrlin...
bonito-master
setup.py
""" Bonito Aligner """ from threading import Thread from functools import partial from mappy import Aligner, ThreadBuffer from bonito.multiprocessing import ThreadMap, ProcessMap def align_map(aligner, sequences, n_thread=4): """ Align `sequences` with minimap using `n_thread` threads. """ return Th...
bonito-master
bonito/aligner.py
""" Bonito Fast5 Utils """ import sys from glob import glob from pathlib import Path from functools import partial from multiprocessing import Pool from itertools import chain, starmap import torch import numpy as np from scipy.signal import find_peaks from ont_fast5_api.fast5_interface import get_fast5_file class ...
bonito-master
bonito/fast5.py
""" Bonito utils """ import os import re import sys import random from glob import glob from itertools import groupby from operator import itemgetter from importlib import import_module from collections import deque, defaultdict, OrderedDict import toml import torch import parasail import numpy as np from torch.cuda ...
bonito-master
bonito/util.py
""" Bonito nn modules. """ import torch from torch import nn from torch.nn import Module from torch.nn.init import orthogonal_ layers = {} def register(layer): layer.name = layer.__name__.lower() layers[layer.name] = layer return layer register(torch.nn.ReLU) register(torch.nn.Tanh) @register class...
bonito-master
bonito/nn.py
""" Bonito Input/Output """ import os import sys import csv import pandas as pd from warnings import warn from threading import Thread from logging import getLogger from contextlib import contextmanager from os.path import realpath, splitext, dirname import numpy as np from mappy import revcomp import bonito from bo...
bonito-master
bonito/io.py
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser from bonito.cli import basecaller, train, evaluate, view, convert, download, export, duplex modules = [ 'basecaller', 'train', 'evaluate', 'view', 'convert', 'download', 'export', 'duplex', ] __version__ = '0.4.0' def main(): parser = Argume...
bonito-master
bonito/__init__.py
""" Bonito Multiprocesing """ import queue from itertools import count from threading import Thread from functools import partial from collections import deque from signal import signal, SIGINT from multiprocessing import Process, Queue, Event, Lock, cpu_count def process_iter(iterator, maxsize=1): """ Take ...
bonito-master
bonito/multiprocessing.py
""" Bonito train """ import os import re from glob import glob from functools import partial from time import perf_counter from collections import OrderedDict from datetime import datetime from bonito.util import accuracy, decode_ref, permute, concat, match_names import bonito import torch import numpy as np import ...
bonito-master
bonito/training.py
""" Bonito Download """ import os import re from shutil import rmtree from zipfile import ZipFile from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from bonito.util import __data__, __models__ from bonito.cli.convert import main as convert from bonito.cli.convert import argparser as cargparser impor...
bonito-master
bonito/cli/download.py
#!/usr/bin/env python """ Convert a Taiyaki chunkify training file to set of Bonito CTC .npy files """ import os import h5py import random import numpy as np from argparse import ArgumentParser from collections import OrderedDict from itertools import islice as take from argparse import ArgumentDefaultsHelpFormatter ...
bonito-master
bonito/cli/convert.py
bonito-master
bonito/cli/__init__.py
""" Bonito Export """ import os import re import sys import json import torch import bonito import hashlib import numpy as np from glob import glob from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter class JsonEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, np.integer...
bonito-master
bonito/cli/export.py
""" Bonito model viewer - display a model architecture for a given config. """ import toml import argparse from bonito.util import load_symbol def main(args): config = toml.load(args.config) Model = load_symbol(config, "Model") model = Model(config) print(model) print("Total parameters in model",...
bonito-master
bonito/cli/view.py
""" Bonito Basecaller """ import sys import torch import numpy as np from tqdm import tqdm from time import perf_counter from datetime import timedelta from itertools import islice as take from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from bonito.aligner import Aligner from bonito.io import CTCWr...
bonito-master
bonito/cli/basecaller.py
""" Bonito Duplex consensus decoding. https://www.biorxiv.org/content/10.1101/2020.02.25.956771v1 """ import os import sys import json from glob import glob from pathlib import Path from os.path import basename from functools import partial from time import perf_counter from datetime import timedelta from multiproces...
bonito-master
bonito/cli/duplex.py
#!/usr/bin/env python3 """ Bonito training. """ import os from argparse import ArgumentParser from argparse import ArgumentDefaultsHelpFormatter from bonito.util import __models__, default_config, default_data from bonito.util import load_data, load_model, load_symbol, init, half_supported from bonito.training impor...
bonito-master
bonito/cli/train.py
""" Bonito model evaluator """ import os import time import torch import numpy as np from itertools import starmap from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from bonito.training import ChunkDataSet from bonito.util import accuracy, poa, decode_ref, half_supported from bonito.util import init,...
bonito-master
bonito/cli/evaluate.py
from .model import Model from .basecall import basecall
bonito-master
bonito/crf/__init__.py
""" Bonito CTC-CRF Model. """ import torch import numpy as np from bonito.nn import Module, Convolution, SHABlock, LinearCRFEncoder, Serial, Permute, layers, from_dict import seqdist.sparse from seqdist.ctc_simple import logZ_cupy, viterbi_alignments from seqdist.core import SequenceDist, Max, Log, semiring def get...
bonito-master
bonito/crf/model.py
""" Bonito CRF basecall """ import torch import numpy as np from kbeam import beamsearch from itertools import groupby from functools import partial from operator import itemgetter import bonito from bonito.io import Writer from bonito.fast5 import get_reads from bonito.aligner import align_map from bonito.multiproce...
bonito-master
bonito/crf/basecall.py
from .model import Model from .basecall import basecall
bonito-master
bonito/ctc/__init__.py
""" Bonito Model template """ import numpy as np from bonito.nn import Permute, layers import torch from torch.nn.functional import log_softmax, ctc_loss from torch.nn import Module, ModuleList, Sequential, Conv1d, BatchNorm1d, Dropout from fast_ctc_decode import beam_search, viterbi_search class Model(Module): ...
bonito-master
bonito/ctc/model.py
""" Bonito basecall """ import torch import numpy as np from functools import partial from bonito.fast5 import ReadChunk from bonito.aligner import align_map from bonito.multiprocessing import process_map, thread_map from bonito.util import mean_qscore_from_qstring, half_supported from bonito.util import chunk, stitch...
bonito-master
bonito/ctc/basecall.py
# Always prefer setuptools over distutils # To use a consistent encoding from codecs import open import os from os import path from setuptools import setup here = path.abspath(path.dirname(__file__)) # get keops version with open(os.path.join(here, "pykeops", "keops_version"), encoding="utf-8") as v: current_ve...
keops-main
pykeops/setup.py
import importlib.util import sysconfig from os.path import join, dirname, realpath ############################################################### # Initialize some variables: the values may be redefined later numpy_found = importlib.util.find_spec("numpy") is not None torch_found = importlib.util.find_spec("torch") ...
keops-main
pykeops/pykeops/config.py
import os import keopscore import keopscore.config import keopscore.config.config from keopscore.config.config import get_build_folder as keops_get_build_folder from . import config as pykeopsconfig ########################################################### # Verbosity level verbose = True if os.getenv("PYKEOPS_VER...
keops-main
pykeops/pykeops/__init__.py
import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 1000, 1000, 3, 1 dtype = torch.float32 device_id = "cpu" # "cuda" if torch.cuda.is_available() else "cpu" torch.backends.cuda.matmul.allow_tf32 = False torch.manual_seed(0) x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt...
keops-main
pykeops/pykeops/test/test_lazytensor_gaussian_cpu.py
import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 2500, 2000, 3, 1 dtype = torch.float64 sum_scheme = "block_sum" torch.backends.cuda.matmul.allow_tf32 = False device_id = 0 if torch.cuda.is_available() else -1 torch.manual_seed(0) x = torch.rand(M, 1, D, dtype=dtype) / math.sqrt(D) y = to...
keops-main
pykeops/pykeops/test/test_lazytensor_gaussian_fromhost.py
import math import torch from pykeops.torch import LazyTensor B1, B2, M, N, D, DV = 2, 3, 200, 300, 3, 300 dtype = torch.float32 sum_scheme = "block_sum" torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = torch.rand(B1, B2, M, 1, D, de...
keops-main
pykeops/pykeops/test/test_finalchunks_ranges.py
import unittest import itertools import numpy as np import pykeops import pykeops.config from pykeops.numpy.utils import ( squared_distances, np_kernel, log_np_kernel, grad_np_kernel, differences, log_sum_exp, ) class PytorchUnitTestCase(unittest.TestCase): A = int(5) # Batchdim 1 B ...
keops-main
pykeops/pykeops/test/test_torch.py
import math import torch from pykeops.torch import LazyTensor B1, B2, M, N, D, DV = 2, 3, 200, 300, 300, 1 dtype = torch.float32 sum_scheme = "block_sum" torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = torch.rand(B1, B2, M, 1, D, de...
keops-main
pykeops/pykeops/test/test_chunks_ranges.py
keops-main
pykeops/pykeops/test/__init__.py
import torch from pykeops.torch import LazyTensor M, N, D = 1000, 1000, 3 torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = torch.randn(M, 1, D, requires_grad=True, device=device_id) y = torch.randn(1, N, D, device=device_id) a = -1.23...
keops-main
pykeops/pykeops/test/test_lazytensor_clamp.py
import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 200, 300, 300, 1 dtype = torch.float32 sum_scheme = "block_sum" torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = torch.rand(M, 1, D, device=device_id, dtype=...
keops-main
pykeops/pykeops/test/test_chunks.py
from pykeops.numpy import LazyTensor import numpy as np np.random.seed(0) a1 = np.random.rand(2, 1000, 5) a2 = np.ascontiguousarray(a1.transpose(2, 0, 1)).transpose(1, 2, 0) b = np.random.rand(2, 1000, 5) c = np.random.rand(2, 1000, 5) b_j = LazyTensor(b[:, None]) a1_i = LazyTensor(a1[:, :, None]) dist1 = a1_i.sqdi...
keops-main
pykeops/pykeops/test/test_contiguous_numpy.py
import math import numpy as np from pykeops.numpy import LazyTensor M, N, D, DV = 3000, 2000, 3, 1 dtype = np.float32 np.random.seed(0) x = np.random.rand(M, 1, D).astype(dtype) / math.sqrt(D) y = np.random.rand(1, N, D).astype(dtype) / math.sqrt(D) b = np.random.randn(N, DV).astype(dtype) a = np.empty((M, DV), dtyp...
keops-main
pykeops/pykeops/test/test_lazytensor_gaussian_numpy_inplace.py
import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 200, 300, 3, 300 dtype = torch.float32 sum_scheme = "block_sum" torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = torch.rand(M, 1, D, device=device_id, dtype=...
keops-main
pykeops/pykeops/test/test_finalchunks.py
import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 2000, 3000, 3, 1 dtype = torch.float32 torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, ...
keops-main
pykeops/pykeops/test/conv2d.py
import torch from pykeops.torch import LazyTensor M, N = 2, 10 # Matrix multiplication as a special case of Tensordot torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) a = torch.randn(4 * 7, requires_grad=True, device=device_id, dtype=torc...
keops-main
pykeops/pykeops/test/test_lazytensor_tensordot.py
# Test for Clamp operation using LazyTensors import pytest import torch from pykeops.torch import LazyTensor dtype = torch.float16 M, N, D = 5, 5, 1 torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = torch.randn(M, 1, D, dtype=dtype, req...
keops-main
pykeops/pykeops/test/test_float16.py
import math import pytest import torch from pykeops.torch import LazyTensor M, N, D, DV = 1000, 1000, 3, 1 dtype = torch.float32 device_id = "cpu" torch.backends.cuda.matmul.allow_tf32 = False torch.manual_seed(0) x = torch.rand(M, 1, D, device=device_id, dtype=dtype) / math.sqrt(D) y = torch.rand(1, N, D, device=d...
keops-main
pykeops/pykeops/test/test_gpu_cpu.py
import numpy as np from pykeops.numpy import LazyTensor, ComplexLazyTensor M, N, D = 1000, 1000, 3 dtype = "float32" np.random.seed(0) x = np.random.rand(M, 1, D).astype(dtype) + 1j * np.random.rand(M, 1, D).astype(dtype) y = np.random.rand(1, N, D).astype(dtype) + 1j * np.random.rand(1, N, D).astype(dtype) def fu...
keops-main
pykeops/pykeops/test/test_complex_numpy.py
from pykeops.torch import LazyTensor import torch torch.backends.cuda.matmul.allow_tf32 = False torch.manual_seed(0) a1 = torch.rand(2, 1000, 5) a2 = ((a1.permute(2, 0, 1)).contiguous()).permute(1, 2, 0) b = torch.rand(2, 1000, 5) c = torch.rand(2, 1000, 5) b_j = LazyTensor(b[:, None]) a1_i = LazyTensor(a1[:, :, N...
keops-main
pykeops/pykeops/test/test_contiguous_torch.py
import torch from pykeops.torch import LazyTensor M, N, D, DV = 100, 100, 3, 1 dtype = torch.float32 torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = torch.rand(M, 1, D, requires_grad=True, device=device_id, dtype=dtype) y = torch.r...
keops-main
pykeops/pykeops/test/test_lazytensor_grad.py
# Non-Uniform Discrete Fourier Tranform example import math import torch from pykeops.torch import LazyTensor dtype = torch.float32 dtype_c = torch.complex64 M, N, D = 1000, 1000, 1 torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = tor...
keops-main
pykeops/pykeops/test/test_complex.py
import os.path import sys sys.path.append( os.path.join( os.path.dirname(os.path.abspath(__file__)), os.path.sep.join([os.pardir] * 2) ) ) sys.path.append( os.path.join( os.path.dirname(os.path.abspath(__file__)), os.path.sep.join([os.pardir] * 3), "keopscore", ) ) impo...
keops-main
pykeops/pykeops/test/test_numpy.py
import math import torch from pykeops.torch import LazyTensor B1, B2, M, N, D, DV = 3, 4, 20, 25, 3, 2 torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda" if torch.cuda.is_available() else "cpu" torch.manual_seed(1) x = torch.rand(1, B2, M, 1, D, device=device_id) / math.sqrt(D) y = torch.rand(B1, B2, 1...
keops-main
pykeops/pykeops/test/test_lazytensor_gaussian_batch.py
import math import torch from pykeops.torch import LazyTensor M, N, D, DV = 20, 30, 3, 1 dtype = torch.float32 sum_scheme = "block_sum" torch.backends.cuda.matmul.allow_tf32 = False device_id = "cuda:0" if torch.cuda.is_available() else "cpu" torch.manual_seed(0) x = torch.rand(M, 1, D, device=device_id, dtype=dtyp...
keops-main
pykeops/pykeops/test/test_lazytensor_gaussian_inplace.py
import torch from pykeops.common.parse_type import get_type def make_odd_cat(y): bdims = y.shape[:-2] N, D = y.shape[-2:] if N % 2 == 0: ycut = y[..., :-1, :].view(bdims + (N - 1, D)) yend = y[..., -1, :].view(bdims + (1, D)) y = torch.cat((y, yend, ycut), dim=-2) else: ...
keops-main
pykeops/pykeops/torch/half2_convert.py
import torch from .. import config as pykeopsconfig ########################################################## # Check Pytorch install # is the proper torch version installed ? torch_version_required = "1.3" if torch.__version__ < torch_version_required: raise ImportError( "[pyKeOps]: The pytorch versio...
keops-main
pykeops/pykeops/torch/__init__.py
import torch from pykeops.common.get_options import get_tag_backend from pykeops.common.keops_io import keops_binder from pykeops.common.operations import ConjugateGradientSolver from pykeops.common.parse_type import ( get_type, get_sizes, complete_aliases, get_optional_flags, ) from pykeops.common.uti...
keops-main
pykeops/pykeops/torch/operations.py
import torch from pykeops.torch import Genred, KernelSolve from pykeops.torch.cluster import swap_axes as torch_swap_axes # from pykeops.torch.generic.generic_red import GenredLowlevel def is_on_device(x): return x.is_cuda class torchtools: copy = torch.clone exp = torch.exp log = torch.log n...
keops-main
pykeops/pykeops/torch/utils.py
import torch from pykeops.common.utils import pyKeOps_Message formula = "SqNorm2(x - y)" var = ["x = Vi(3)", "y = Vj(3)"] expected_res = [63.0, 90.0] def test_torch_bindings(): """ This function try to compile a simple keops formula using the pytorch binder. """ x = torch.arange(1, 10, dtype=torch.f...
keops-main
pykeops/pykeops/torch/test_install.py
import torch def from_matrix(ranges_i, ranges_j, keep): r"""Turns a boolean matrix into a KeOps-friendly **ranges** argument. This routine is a helper for the **block-sparse** reduction mode of KeOps, allowing you to turn clustering information (**ranges_i**, **ranges_j**) and a cluster-to-cluster bo...
keops-main
pykeops/pykeops/torch/cluster/matrix.py
import torch def grid_cluster(x, size): r"""Simplistic clustering algorithm which distributes points into cubic bins. Args: x ((M,D) Tensor): List of points :math:`x_i \in \mathbb{R}^D`. size (float or (D,) Tensor): Dimensions of the cubic cells ("voxels"). Returns: (M,) IntTenso...
keops-main
pykeops/pykeops/torch/cluster/grid_cluster.py
from .grid_cluster import grid_cluster from .matrix import from_matrix from .utils import ( sort_clusters, cluster_ranges, cluster_centroids, cluster_ranges_centroids, swap_axes, ) # N.B.: the order is important for the autodoc in sphinx! __all__ = sorted( [ "grid_cluster", "fro...
keops-main
pykeops/pykeops/torch/cluster/__init__.py
import torch def sort_clusters(x, lab): r"""Sorts a list of points and labels to make sure that the clusters are contiguous in memory. On the GPU, **contiguous memory accesses** are key to high performances. By making sure that points in the same cluster are stored next to each other in memory, this ...
keops-main
pykeops/pykeops/torch/cluster/utils.py
keops-main
pykeops/pykeops/torch/lazytensor/__init__.py
import torch from pykeops.common.lazy_tensor import GenericLazyTensor, ComplexGenericLazyTensor from pykeops.torch.utils import torchtools # Convenient aliases: def Var(x_or_ind, dim=None, cat=None): if dim is None: # init via data: we assume x_or_ind is data return LazyTensor(x_or_ind, axis=ca...
keops-main
pykeops/pykeops/torch/lazytensor/LazyTensor.py
import torch from pykeops.common.get_options import get_tag_backend from pykeops.common.operations import preprocess, postprocess from pykeops.common.parse_type import ( get_type, get_sizes, complete_aliases, get_optional_flags, ) from pykeops.common.utils import axis2cat from pykeops import default_de...
keops-main
pykeops/pykeops/torch/generic/generic_red.py
keops-main
pykeops/pykeops/torch/generic/__init__.py
from pykeops.common.parse_type import get_type from pykeops.common.utils import cat2axis from pykeops.torch import Genred def generic_sum(formula, output, *aliases, **kwargs): r"""Alias for :class:`torch.Genred <pykeops.torch.Genred>` with a "Sum" reduction. Args: formula (string): Symbolic KeOps exp...
keops-main
pykeops/pykeops/torch/generic/generic_ops.py
########################################################## # Import pyKeOps routines from .generic.generic_red import Genred from .operations import KernelSolve from .generic.generic_ops import ( generic_sum, generic_logsumexp, generic_argmin, generic_argkmin, ) from .lazytensor.LazyTensor import Lazy...
keops-main
pykeops/pykeops/numpy/__init__.py
import numpy as np from pykeops.common.get_options import get_tag_backend from pykeops.common.keops_io import keops_binder from pykeops.common.operations import ConjugateGradientSolver from pykeops.common.parse_type import get_sizes, complete_aliases, get_optional_flags from pykeops.common.utils import axis2cat from p...
keops-main
pykeops/pykeops/numpy/operations.py
import numpy as np from pykeops.numpy import Genred, KernelSolve from pykeops.numpy.cluster import swap_axes as np_swap_axes import pykeops.config class numpytools: norm = np.linalg.norm arraysum = np.sum exp = np.exp log = np.log Genred = Genred KernelSolve = KernelSolve swap_axes = np_s...
keops-main
pykeops/pykeops/numpy/utils.py
import numpy as np from pykeops.common.utils import pyKeOps_Message formula = "SqNorm2(x - y)" var = ["x = Vi(3)", "y = Vj(3)"] expected_res = np.array([63.0, 90.0]) def test_numpy_bindings(): """ This function try to compile a simple keops formula using the numpy binder. """ x = np.arange(1, 10).re...
keops-main
pykeops/pykeops/numpy/test_install.py
import numpy as np def from_matrix(ranges_i, ranges_j, keep): r"""Turns a boolean matrix into a KeOps-friendly **ranges** argument. This routine is a helper for the **block-sparse** reduction mode of KeOps, allowing you to turn clustering information (**ranges_i**, **ranges_j**) and a cluster-to-clus...
keops-main
pykeops/pykeops/numpy/cluster/matrix.py
import numpy as np def grid_cluster(x, size): r"""Simplistic clustering algorithm which distributes points into cubic bins. Args: x ((M,D) array): List of points :math:`x_i \in \mathbb{R}^D`. size (float or (D,) array): Dimensions of the cubic cells ("voxels"). Returns: (M,) inte...
keops-main
pykeops/pykeops/numpy/cluster/grid_cluster.py
from .grid_cluster import grid_cluster from .matrix import from_matrix from .utils import ( sort_clusters, cluster_ranges, cluster_centroids, cluster_ranges_centroids, swap_axes, ) # N.B.: the order is important for the autodoc in sphinx! __all__ = sorted( [ "grid_cluster", "fro...
keops-main
pykeops/pykeops/numpy/cluster/__init__.py
import numpy as np def sort_clusters(x, lab): r"""Sorts a list of points and labels to make sure that the clusters are contiguous in memory. On the GPU, **contiguous memory accesses** are key to high performances. By making sure that points in the same cluster are stored next to each other in memory,...
keops-main
pykeops/pykeops/numpy/cluster/utils.py
keops-main
pykeops/pykeops/numpy/lazytensor/__init__.py
import numpy as np from pykeops.common.lazy_tensor import GenericLazyTensor, ComplexGenericLazyTensor from pykeops.numpy.utils import numpytools # Convenient aliases: def Var(x_or_ind, dim=None, cat=None): if dim is None: # init via data: we assume x_or_ind is data return LazyTensor(x_or_ind, ax...
keops-main
pykeops/pykeops/numpy/lazytensor/LazyTensor.py
import numpy as np from pykeops.common.get_options import get_tag_backend from pykeops.common.operations import preprocess, postprocess from pykeops.common.parse_type import get_sizes, complete_aliases, get_optional_flags from pykeops.common.utils import axis2cat from pykeops import default_device_id from pykeops.comm...
keops-main
pykeops/pykeops/numpy/generic/generic_red.py
keops-main
pykeops/pykeops/numpy/generic/__init__.py
from pykeops.common.parse_type import get_type from pykeops.common.utils import cat2axis from pykeops.numpy import Genred def generic_sum(formula, output, *aliases, **kwargs): r"""Alias for :class:`numpy.Genred <pykeops.numpy.Genred>` with a "Sum" reduction. Args: formula (string): Symbolic KeOps exp...
keops-main
pykeops/pykeops/numpy/generic/generic_ops.py
import copy import re import math import numpy as np from pykeops.common.utils import check_broadcasting def same_or_one_test(*dims): # test wether input dimensions are compatible with broadcasting return len(set(list(dims) + [1])) <= 2 def is_scalar_and_equals(x, val): # test wether the input x is a ...
keops-main
pykeops/pykeops/common/lazy_tensor.py
import re from collections import OrderedDict from pykeops.common.utils import pyKeOps_Message categories = OrderedDict([("Vi", 0), ("Vj", 1), ("Pm", 2)]) def complete_aliases(formula, aliases): """ This function parse formula (a string) to find pattern like 'Var(x,x,x)'. It then append to aliases (list...
keops-main
pykeops/pykeops/common/parse_type.py
keops-main
pykeops/pykeops/common/__init__.py
import numpy as np from pykeops.common.utils import get_tools # Some advance operations defined at user level use in fact other reductions. def preprocess(reduction_op, formula2): reduction_op = reduction_op if ( reduction_op == "SumSoftMaxWeight" or reduction_op == "SoftMax" ): # SoftMax is ju...
keops-main
pykeops/pykeops/common/operations.py
import fcntl import functools import importlib.util import os import pykeops.config c_type = dict(float16="half2", float32="float", float64="double") def axis2cat(axis): """ Axis is the dimension to sum (the pythonic way). Cat is the dimension that remains at the end (the Keops way). :param axis: 0 ...
keops-main
pykeops/pykeops/common/utils.py
import re import numpy as np from collections import OrderedDict import pykeops import pykeops.config ############################################################ # define backend ############################################################ class SetBackend: """ This class is used to centralized the opt...
keops-main
pykeops/pykeops/common/get_options.py
from keopscore.utils.gpu_utils import get_gpu_props def get_gpu_number(): return get_gpu_props()[0]
keops-main
pykeops/pykeops/common/gpu_utils.py
import os import keopscore.config.config from keopscore.config.config import get_build_folder import pykeops from keopscore.binders.nvrtc.Gpu_link_compile import Gpu_link_compile from keopscore.utils.Cache import Cache_partial from pykeops.common.keops_io.LoadKeOps import LoadKeOps from pykeops.common.utils import pyK...
keops-main
pykeops/pykeops/common/keops_io/LoadKeOps_nvrtc.py
import types from functools import reduce import numpy as np from keopscore.get_keops_dll import get_keops_dll from pykeops.common.parse_type import parse_dtype_acc class LoadKeOps: null_range = np.array([-1], dtype="int32") empty_ranges_new = tuple([null_range.__array_interface__["data"][0]] * 7) def ...
keops-main
pykeops/pykeops/common/keops_io/LoadKeOps.py
import keopscore.config if keopscore.config.config.use_cuda: from . import LoadKeOps_nvrtc, LoadKeOps_cpp keops_binder = { "nvrtc": LoadKeOps_nvrtc.LoadKeOps_nvrtc, "cpp": LoadKeOps_cpp.LoadKeOps_cpp, } else: from . import LoadKeOps_cpp keops_binder = {"cpp": LoadKeOps_cpp.LoadKeO...
keops-main
pykeops/pykeops/common/keops_io/__init__.py