python_code stringlengths 0 1.02M | repo_name stringlengths 9 48 | file_path stringlengths 5 114 |
|---|---|---|
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from typing import Callable, Union, Tuple, List, Any
import torch
import inspect
from functools import partial, w... | pytorch-master | functorch/functorch/_src/eager_transforms.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
import functools
from torch import Tensor
from typing import Any, Callable, Optional, Tuple, Union, ... | pytorch-master | functorch/functorch/_src/vmap.py |
import time
import os
import json
import torch
from torch.profiler import profile, ProfilerActivity
def synchronize():
pass
class NullContext:
def __enter__(self):
pass
def __exit__(self, exc_type, exc_val, exc_tb):
pass
def dump_chrome_trace(f, input, trace_filename, optimize_ctx, a... | pytorch-master | functorch/functorch/_src/benchmark_utils.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
import torch.nn as nn
from torch import Tensor
from typing import List, Tuple
from .named_members_po... | pytorch-master | functorch/functorch/_src/make_functional.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from contextlib import contextmanager
import os
import subprocess
import signal
@contextmanager
def magic_trace(o... | pytorch-master | functorch/functorch/dim/magic_trace.py |
import torch
from typing import Union, Sequence
import inspect
import dis
from .tree_map import tree_flatten, tree_map
from .wrap_type import wrap_type
from functorch._C import dim as _C
_C._patch_tensor_class()
dims, DimList, dimlists = _C.dims, _C.DimList, _C.dimlists
class DimensionMismatchError(Exception):
pas... | pytorch-master | functorch/functorch/dim/__init__.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
from . import _Tensor, Tensor
from .reference import _dims, _enable_layers, llist, ltuple
class Dela... | pytorch-master | functorch/functorch/dim/delayed_mul_tensor.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import torch
# pointwise operators can go through a faster pathway
tensor_magic_methods = [
'add',
''
]
p... | pytorch-master | functorch/functorch/dim/op_properties.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functorch._C import (
_vmap_add_layers,
_vmap_remove_layers,
)
from contextlib import contextmanager... | pytorch-master | functorch/functorch/dim/batch_tensor.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from types import FunctionType, BuiltinMethodType, MethodDescriptorType, WrapperDescriptorType, GetSetDescriptorT... | pytorch-master | functorch/functorch/dim/wrap_type.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
# reference python implementations for C ops
import torch
from .tree_map import tree_flatten, tree_map
from .batc... | pytorch-master | functorch/functorch/dim/reference.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
_vmap_levels = []
@dataclass
class LevelInfo:
level: int
alive: bool = True
class Dim:
def __init__(s... | pytorch-master | functorch/functorch/dim/dim.py |
# Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from functorch._C import dim
tree_flatten = dim.tree_flatten
def tree_map(fn, tree):
vs, unflatten = tree_fl... | pytorch-master | functorch/functorch/dim/tree_map.py |
from .._src.python_key import pythonkey_decompose
from .._src.decompositions import register_decomposition, decomposition_table, get_decompositions
from .._src.fx_minifier import minifier
from .._src.aot_autograd import (
aot_function,
aot_module,
compiled_function,
compiled_module,
num_of_recompila... | pytorch-master | functorch/functorch/compile/__init__.py |
import sys
log_file_path = sys.argv[1]
with open(log_file_path) as f:
lines = f.readlines()
for line in lines:
# Ignore errors from CPU instruction set, symbol existing testing,
# or compilation error formatting
ignored_keywords = [
'src.c',
'CheckSymbolExists.c',
'test_compil... | pytorch-master | .jenkins/pytorch/print_sccache_log.py |
from datetime import datetime, timedelta
from tempfile import mkdtemp
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes
temp_dir = m... | pytorch-master | .jenkins/pytorch/create_test_cert.py |
raise ModuleNotFoundError("Sorry PyTorch, but our NumPy is in the other folder")
| pytorch-master | .jenkins/pytorch/fake_numpy/numpy.py |
import sys
import json
import numpy
sample_data_list = sys.argv[1:]
sample_data_list = [float(v.strip()) for v in sample_data_list]
sample_mean = numpy.mean(sample_data_list)
sample_sigma = numpy.std(sample_data_list)
data = {
'mean': sample_mean,
'sigma': sample_sigma,
}
print(json.dumps(data))
| pytorch-master | .jenkins/pytorch/perf_test/get_stats.py |
import sys
import json
import math
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--test-name', dest='test_name', action='store',
required=True, help='test name')
parser.add_argument('--sample-stats', dest='sample_stats', action='store',
required=True, h... | pytorch-master | .jenkins/pytorch/perf_test/compare_with_baseline.py |
import sys
import json
data_file_path = sys.argv[1]
commit_hash = sys.argv[2]
with open(data_file_path) as data_file:
data = json.load(data_file)
data['commit'] = commit_hash
with open(data_file_path, 'w') as data_file:
json.dump(data, data_file)
| pytorch-master | .jenkins/pytorch/perf_test/update_commit_hash.py |
#!/usr/bin/env python3
import subprocess
import os
COMMON_TESTS = [
(
"Checking that torch is available",
"import torch",
),
(
"Checking that MKL is available",
"import torch; exit(0 if torch.backends.mkl.is_available() else 1)",
),
]
GPU_TESTS = [
(
"Check... | pytorch-master | .jenkins/pytorch/win-test-helpers/run_python_nn_smoketests.py |
import os
import fire
from collections import deque, namedtuple
from tqdm import tqdm
import numpy as np
import torch
from torch import nn
from torch.utils.data import Dataset, DataLoader
from torch.optim import Adam
from torch.distributions import Categorical
import torch.nn.functional as F
import gym
# constants
... | phasic-policy-gradient-master | train.py |
import os
from setuptools import find_packages, setup
CURRENT_DIR = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(CURRENT_DIR, "README.md"), encoding="utf-8") as f:
long_description = f.read()
setup(
name="nucleotide_transformer",
version="0.0.1",
packages=find_packages(),
ur... | nucleotide-transformer-main | setup.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or a... | nucleotide-transformer-main | nucleotide_transformer/pretrained.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or a... | nucleotide-transformer-main | nucleotide_transformer/constants.py |
nucleotide-transformer-main | nucleotide_transformer/__init__.py | |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or a... | nucleotide-transformer-main | nucleotide_transformer/types.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or a... | nucleotide-transformer-main | nucleotide_transformer/model.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or a... | nucleotide-transformer-main | nucleotide_transformer/layers.py |
# Copyright 2022 InstaDeep Ltd
#
# Licensed under the Creative Commons BY-NC-SA 4.0 License (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://creativecommons.org/licenses/by-nc-sa/4.0/
#
# Unless required by applicable law or a... | nucleotide-transformer-main | nucleotide_transformer/tokenizers.py |
import pathlib
import re
import setuptools
_here = pathlib.Path(__file__).resolve().parent
name = "equinox"
# for simplicity we actually store the version in the __version__ attribute in the
# source
with open(_here / name / "__init__.py") as f:
meta_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", f.r... | equinox-main | setup.py |
import jax
from .custom_types import PyTree
def _apply_update(u, p):
if u is None:
return p
else:
return p + u
def _is_none(x):
return x is None
def apply_updates(model: PyTree, updates: PyTree) -> PyTree:
"""A `jax.tree_map`-broadcasted version of
```python
model = model ... | equinox-main | equinox/update.py |
from typing import Any, Callable, Sequence, Union
import jax
import jax.numpy as jnp
import numpy as np
from .custom_types import PyTree
_sentinel = object()
_Leaf = Any
def tree_at(
where: Callable[[PyTree], Union[_Leaf, Sequence[_Leaf]]],
pytree: PyTree,
replace: Union[_Leaf, Sequence[_Leaf]] = _se... | equinox-main | equinox/tree.py |
import functools as ft
from dataclasses import dataclass
from typing import Any
import jax
from .deprecated import deprecated
from .filters import combine, is_array, partition, validate_filters
from .module import Module, static_field
class _Static(Module):
value: Any = static_field()
@ft.lru_cache(maxsize=40... | equinox-main | equinox/jit.py |
import functools as ft
import warnings
def deprecated(*, in_favour_of):
if not isinstance(in_favour_of, str):
in_favour_of = in_favour_of.__name__
def decorator(fn):
msg = f"{fn.__name__} is deprecated in favour of {in_favour_of}"
@ft.wraps(fn)
def wrapper(*args, **kwargs):
... | equinox-main | equinox/deprecated.py |
from . import nn
from .filters import (
combine,
filter,
is_array,
is_array_like,
is_inexact_array,
is_inexact_array_like,
merge,
partition,
split,
)
from .grad import (
filter_custom_vjp,
filter_grad,
filter_value_and_grad,
gradf,
value_and_grad_f,
)
from .jit im... | equinox-main | equinox/__init__.py |
import typing
from typing import Any
import jax
import jax.numpy as jnp
if getattr(typing, "GENERATING_DOCUMENTATION", False):
Array = "jax.numpy.ndarray"
else:
Array = jnp.ndarray
PyTree = Any
TreeDef = type(jax.tree_structure(0))
| equinox-main | equinox/custom_types.py |
import abc
import functools as ft
import inspect
from dataclasses import dataclass, field, fields
import jax
from .tree import tree_equal
def static_field(**kwargs):
"""Used for marking that a field should _not_ be treated as part of the PyTree
of a [`equinox.Module`][]. (And is instead just treated as extr... | equinox-main | equinox/module.py |
import functools as ft
import types
import typing
import jax
from .deprecated import deprecated
from .filters import (
combine,
is_array,
is_inexact_array,
merge,
partition,
split,
validate_filters,
)
def filter_value_and_grad(
fun, *, filter_spec=is_inexact_array, argnums=None, **gr... | equinox-main | equinox/grad.py |
from typing import Any, Callable, List, Optional, Tuple, Union
import jax
import jax.numpy as jnp
import numpy as np
from .custom_types import PyTree, TreeDef
from .deprecated import deprecated
#
# Filter functions
#
def is_array(element: Any) -> bool:
"""Returns `True` if `element` is a JAX array (but not a ... | equinox-main | equinox/filters.py |
import typing
from typing import Any, Callable, List, Optional, Sequence
import jax
import jax.nn as jnn
import jax.random as jrandom
from ..custom_types import Array
from ..module import Module, static_field
from .linear import Linear
def _identity(x):
return x
if getattr(typing, "GENERATING_DOCUMENTATION", ... | equinox-main | equinox/nn/composed.py |
import math
from typing import Optional, TypeVar
import jax
import jax.random as jrandom
from ..custom_types import Array
from ..module import Module, static_field
class Linear(Module):
"""Performs a linear transformation."""
weight: Array
bias: Optional[Array]
in_features: int = static_field()
... | equinox-main | equinox/nn/linear.py |
from .composed import MLP, Sequential
from .conv import Conv, Conv1d, Conv2d, Conv3d
from .dropout import Dropout
from .linear import Identity, Linear
from .rnn import GRUCell, LSTMCell
| equinox-main | equinox/nn/__init__.py |
from typing import Optional
import jax
import jax.numpy as jnp
import jax.random as jrandom
from ..custom_types import Array
from ..module import Module
class Dropout(Module):
"""Applies dropout."""
# Not static_fields as it makes sense to want to modify them via equinox.tree_at.
p: float = 0.5
det... | equinox-main | equinox/nn/dropout.py |
import collections
from itertools import repeat
from typing import Any, Optional, Sequence, Tuple, Union
import jax
import jax.numpy as jnp
import jax.random as jrandom
import numpy as np
from jax.lax import conv_general_dilated
from ..custom_types import Array
from ..module import Module, static_field
def _ntuple(... | equinox-main | equinox/nn/conv.py |
import math
import warnings
from typing import Optional
import jax
import jax.nn as jnn
import jax.numpy as jnp
import jax.random as jrandom
from ..custom_types import Array
from ..module import Module, static_field
class GRUCell(Module):
"""A single step of a Gated Recurrent Unit (GRU).
!!! example
... | equinox-main | equinox/nn/rnn.py |
import random
import jax.random as jrandom
import pytest
@pytest.fixture()
def getkey():
def _getkey():
# Not sure what the maximum actually is but this will do
return jrandom.PRNGKey(random.randint(0, 2 ** 31 - 1))
return _getkey
| equinox-main | tests/conftest.py |
import jax.numpy as jnp
import jax.random as jrandom
import pytest
import equinox as eqx
def test_tree_at_replace(getkey):
key = getkey()
key1, key2 = jrandom.split(key, 2)
pytree = [1, 2, {"a": jnp.array([1.0, 2.0])}, eqx.nn.Linear(1, 2, key=key1)]
true_pytree1 = [1, 2, {"a": "hi"}, eqx.nn.Linear(1,... | equinox-main | tests/test_tree.py |
from typing import Any
import jax
import pytest
import equinox as eqx
def test_module_not_enough_attributes():
class MyModule1(eqx.Module):
weight: Any
with pytest.raises(TypeError):
MyModule1()
class MyModule2(eqx.Module):
weight: Any
def __init__(self):
p... | equinox-main | tests/test_module.py |
import functools as ft
import jax
import jax.numpy as jnp
import jax.random as jrandom
import pytest
import equinox as eqx
def _eq(a, b):
return (type(a) is type(b)) and (a == b)
def test_jitf_filter_fn(getkey):
a = jrandom.normal(getkey(), (2, 3))
b = jrandom.normal(getkey(), (3,))
c = jrandom.no... | equinox-main | tests/test_jitf.py |
import jax.numpy as jnp
import jax.random as jrandom
import pytest
import equinox as eqx
def test_custom_init():
with pytest.raises(TypeError):
eqx.nn.Linear(1, 1, 1) # Matches the number of dataclass fields Linear has
with pytest.raises(TypeError):
eqx.nn.Linear(3, 4)
with pytest.rais... | equinox-main | tests/test_nn.py |
import jax.numpy as jnp
import pytest
import equinox as eqx
def test_apply_updates1():
params = [jnp.array([5]), jnp.array([2])]
grads = [-1, 1]
new_params = eqx.apply_updates(params, grads)
assert new_params == [jnp.array([4]), jnp.array([3])]
def test_apply_updates2():
o = object()
params... | equinox-main | tests/test_update.py |
import functools as ft
import jax
import jax.numpy as jnp
import jax.random as jrandom
import numpy as np
import pytest
import equinox as eqx
def test_gradf_filter_fn(getkey):
a = jrandom.normal(getkey(), (2, 3))
b = jrandom.normal(getkey(), (2, 3))
@ft.partial(eqx.gradf, filter_fn=lambda _: True)
... | equinox-main | tests/test_gradf.py |
import functools as ft
import jax
import jax.numpy as jnp
import jax.random as jrandom
import pytest
import equinox as eqx
def _eq(a, b):
return (type(a) is type(b)) and (a == b)
def test_filter_jit1(getkey):
a = jrandom.normal(getkey(), (2, 3))
b = jrandom.normal(getkey(), (3,))
c = jrandom.norma... | equinox-main | tests/test_filter_jit.py |
import jax
import jax.numpy as jnp
import numpy as np
import pytest
import equinox as eqx
def test_is_array(getkey):
objs = [
1,
2.0,
[2.0],
True,
object(),
jnp.array([1]),
jnp.array(1.0),
np.array(1.0),
np.array(1),
eqx.nn.Linear(1,... | equinox-main | tests/test_filters.py |
import functools as ft
import jax
import jax.numpy as jnp
import jax.random as jrandom
import numpy as np
import pytest
import equinox as eqx
def test_filter_grad1(getkey):
a = jrandom.normal(getkey(), (2, 3))
@ft.partial(eqx.filter_grad, filter_spec=lambda _: True)
def f(x):
return jnp.sum(x)
... | equinox-main | tests/test_filter_grad.py |
"""
Usage: python test.py <frameworks>
1. Installs part of dependencies (make sure `which pip` points to correct location)
2. Installs current version of einops in editable mode
3. Runs the tests
"""
import os
import shutil
import sys
from subprocess import Popen, PIPE
from pathlib import Path
__author__ = "Alex Rog... | einops-master | test.py |
import pytest
from einops import EinopsError
from einops.parsing import ParsedExpression, AnonymousAxis, _ellipsis
__author__ = 'Alex Rogozhnikov'
class AnonymousAxisPlaceholder:
def __init__(self, value: int):
self.value = value
assert isinstance(self.value, int)
def __eq__(self, other):
... | einops-master | tests/test_parsing.py |
import pickle
import tempfile
from collections import namedtuple
import numpy
import pytest
from einops import rearrange, reduce
from einops.einops import _reductions
from . import collect_test_backends, is_backend_tested
__author__ = "Alex Rogozhnikov"
testcase = namedtuple("testcase", ["pattern", "axes_lengths", ... | einops-master | tests/test_layers.py |
import logging
import os
from functools import lru_cache
from typing import List, Tuple
from einops import _backends
import warnings
__author__ = "Alex Rogozhnikov"
# minimize noise in tests logging
logging.getLogger("tensorflow").disabled = True
logging.getLogger("matplotlib").disabled = True
def find_names_of_a... | einops-master | tests/__init__.py |
from typing import Dict
from io import StringIO
from tests import parse_backends_to_test, is_backend_tested
__author__ = "Alex Rogozhnikov"
from pathlib import Path
import nbformat
import pytest
from nbconvert.preprocessors import ExecutePreprocessor
def render_notebook(filename: Path, replacements: Dict[str, str... | einops-master | tests/test_notebooks.py |
import dataclasses
import typing
import numpy as np
import pytest
from einops import EinopsError, asnumpy, pack, unpack
from tests import collect_test_backends
def pack_unpack(xs, pattern):
x, ps = pack(xs, pattern)
unpacked = unpack(xs, ps, pattern)
assert len(unpacked) == len(xs)
for a, b in zip(u... | einops-master | tests/test_packing.py |
from typing import Any, Callable
from venv import create
from . import collect_test_backends
from einops.einops import _compactify_pattern_for_einsum, einsum, EinopsError
import numpy as np
import pytest
import string
class Arguments:
def __init__(self, *args: Any, **kargs: Any):
self.args = args
... | einops-master | tests/test_einsum.py |
import itertools
import numpy
import pytest
from einops import EinopsError
from einops.einops import rearrange, reduce, repeat, _enumerate_directions, _reductions
from . import collect_test_backends, is_backend_tested
imp_op_backends = collect_test_backends(symbolic=False, layers=False)
sym_op_backends = collect_tes... | einops-master | tests/test_ops.py |
import sys
import unittest
from doctest import testmod
from typing import Dict, List, Optional
import numpy
import pytest
from parameterized import parameterized, parameterized_class
import einops
import einops.layers
import einops.parsing
from einops._backends import AbstractBackend
from einops.einops import rearra... | einops-master | tests/test_other.py |
import numpy
import pytest
from einops import rearrange, parse_shape, reduce
from tests import is_backend_tested
from tests.test_ops import imp_op_backends
def test_rearrange_examples():
def test1(x):
# transpose
y = rearrange(x, 'b c h w -> b h w c')
assert tuple(y.shape) == (10, 30, 40,... | einops-master | tests/test_examples.py |
"""
just run this script with python converter.py .
It will convert pytorch.ipynb to html page docs/pytorch-examples.html
"""
import nbformat
import markdown
from pygments import highlight
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
notebook = nbformat.read('Pytorch.ipynb', ... | einops-master | docs/source_examples/converter.py |
import numpy as np
from PIL.Image import fromarray
from IPython import get_ipython
def display_np_arrays_as_images():
def np_to_png(a):
if 2 <= len(a.shape) <= 3:
return fromarray(np.array(np.clip(a, 0, 1) * 255, dtype='uint8'))._repr_png_()
else:
return fromarray(np.zeros... | einops-master | docs/utils/__init__.py |
"""
This is a fake script, it is not used.
Seems github does not count contributions unless you have a setup.py
"""
__author__ = "Alex Rogozhnikov"
from setuptools import setup
setup(
name="einops",
version="0.7.0rc2",
description="A new flavour of deep learning operations",
long_description=open("REA... | einops-master | scripts/setup.py |
"""
Converts readme from github repo page to mkdocs-friendly
"""
from pathlib import Path
original_text = Path(__file__).parent.parent.joinpath('README.md').read_text(encoding='utf-8')
def replace_with_video_tag(line: str):
if line.startswith('https://') and line.endswith('.mp4') and ' ' not in line:
# t... | einops-master | scripts/convert_readme.py |
import functools
import itertools
import string
import typing
from collections import OrderedDict
from typing import Set, Tuple, List, Dict, Union, Callable, Optional, TypeVar, cast, Any
if typing.TYPE_CHECKING:
# for docstrings in pycharm
import numpy as np
from . import EinopsError
from ._backends import ge... | einops-master | einops/einops.py |
from typing import List, Tuple, Sequence
from .einops import Tensor, Reduction, EinopsError, _prepare_transformation_recipe, _apply_recipe_array_api
from .packing import analyze_pattern, prod
def reduce(tensor: Tensor, pattern: str, reduction: Reduction, **axes_lengths: int) -> Tensor:
if isinstance(tensor, list)... | einops-master | einops/array_api.py |
from einops import EinopsError
import keyword
import warnings
from typing import List, Optional, Set, Tuple, Union
_ellipsis: str = '…' # NB, this is a single unicode symbol. String is used as it is not a list, but can be iterated
class AnonymousAxis(object):
"""Important thing: all instances of this class are ... | einops-master | einops/parsing.py |
__author__ = 'Alex Rogozhnikov'
__version__ = '0.7.0rc2'
class EinopsError(RuntimeError):
""" Runtime error thrown by einops """
pass
__all__ = ['rearrange', 'reduce', 'repeat', 'einsum',
'pack', 'unpack',
'parse_shape', 'asnumpy', 'EinopsError']
from .einops import rearrange, reduce,... | einops-master | einops/__init__.py |
from functools import lru_cache
from typing import List, Union, TypeVar, Tuple, Sequence
from einops import EinopsError
from einops._backends import get_backend
from einops.parsing import ParsedExpression
Tensor = TypeVar('Tensor')
Shape = Union[Tuple[int, ...], List[int]]
@lru_cache(maxsize=128)
def analyze_patt... | einops-master | einops/packing.py |
"""
Specialization of einops for torch.
Unfortunately, torch's jit scripting mechanism isn't strong enough,
and to have scripting supported at least for layers,
a number of additional moves is needed.
Design of main operations (dynamic resolution by lookup) is unlikely
to be implemented by torch.jit.script,
but torc... | einops-master | einops/_torch_specific.py |
"""
Backends in `einops` are organized to meet the following requirements
- backends are not imported unless those are actually needed, because
- backends may not be installed
- importing all available backends will drive to significant memory footprint
- backends may by present but installed with errors (b... | einops-master | einops/_backends.py |
einops-master | einops/experimental/__init__.py | |
from typing import List, TypeVar, Tuple, Sequence
from einops import EinopsError
T = TypeVar('T')
Shape = Tuple[int, ...]
def pack(pattern: str, tensors: Sequence[T]) -> Tuple[T, List[Shape]]:
axes = pattern.split()
if len(axes) != len(set(axes)):
raise EinopsError(f'Duplicates in axes names in pac... | einops-master | einops/experimental/data_api_packing.py |
"""
Indexing one array with the other(s).
Concept for discussion.
Notation targets hard cases, not simple ones, like indexing of 1d-array with another 1d-array
(notation supports that, but you can't simplify arr[ind], and there is no reason to)
Examples
1. query for every token in sequence a token in the image. Im... | einops-master | einops/experimental/indexing.py |
__author__ = 'Alex Rogozhnikov'
from ..layers.tensorflow import Rearrange, Reduce, EinMix
keras_custom_objects = {
Rearrange.__name__: Rearrange,
Reduce.__name__: Reduce,
EinMix.__name__: EinMix,
}
| einops-master | einops/layers/keras.py |
from typing import Optional, Dict, cast
import paddle
from . import RearrangeMixin, ReduceMixin
from ._einmix import _EinmixMixin
__author__ = 'PaddlePaddle'
class Rearrange(RearrangeMixin, paddle.nn.Layer):
def forward(self, input):
return self._apply_recipe(input)
class Reduce(ReduceMixin, paddle.n... | einops-master | einops/layers/paddle.py |
__author__ = 'Alex Rogozhnikov'
from typing import Any, Dict
from ..einops import TransformRecipe, _apply_recipe, _prepare_recipes_for_all_dims, get_backend
from .. import EinopsError
class RearrangeMixin:
"""
Rearrange layer behaves identically to einops.rearrange operation.
:param pattern: str, rear... | einops-master | einops/layers/__init__.py |
from typing import List, Optional, Dict, cast
import tensorflow as tf
from tensorflow.keras.layers import Layer
from .._backends import UnknownSize
from . import RearrangeMixin, ReduceMixin
from ._einmix import _EinmixMixin
from ..einops import TransformRecipe, _reconstruct_from_shape_uncached
__author__ = 'Alex Rog... | einops-master | einops/layers/tensorflow.py |
from typing import Any, List, Optional, Dict
from einops import EinopsError
from einops.parsing import ParsedExpression
import warnings
import string
from ..einops import _product
def _report_axes(axes: set, report_message: str):
if len(axes) > 0:
raise EinopsError(report_message.format(axes))
class _E... | einops-master | einops/layers/_einmix.py |
from typing import Optional, Dict, cast
import torch
from . import RearrangeMixin, ReduceMixin
from ._einmix import _EinmixMixin
from .._torch_specific import apply_for_scriptable_torch
__author__ = 'Alex Rogozhnikov'
class Rearrange(RearrangeMixin, torch.nn.Module):
def forward(self, input):
recipe = ... | einops-master | einops/layers/torch.py |
from typing import Optional, Dict, cast
import oneflow as flow
from . import RearrangeMixin, ReduceMixin
from ._einmix import _EinmixMixin
__author__ = 'Tianhe Ren & Depeng Liang'
class Rearrange(RearrangeMixin, flow.nn.Module):
def forward(self, input):
return self._apply_recipe(input)
class Reduce(... | einops-master | einops/layers/oneflow.py |
from dataclasses import field
from typing import Optional, Dict, cast
import flax.linen as nn
import jax
import jax.numpy as jnp
from . import RearrangeMixin, ReduceMixin
from ._einmix import _EinmixMixin
__author__ = 'Alex Rogozhnikov'
class Reduce(nn.Module):
pattern: str
reduction: str
sizes: dict =... | einops-master | einops/layers/flax.py |
from typing import Optional, Dict, cast
import chainer
from . import RearrangeMixin, ReduceMixin
from ._einmix import _EinmixMixin
__author__ = 'Alex Rogozhnikov'
class Rearrange(RearrangeMixin, chainer.Link):
def __call__(self, x):
return self._apply_recipe(x)
class Reduce(ReduceMixin, chainer.Link)... | einops-master | einops/layers/chainer.py |
from setuptools import setup, find_packages
setup(
name="local-attention-flax",
packages=find_packages(),
version="0.0.2",
license="MIT",
description="Local Attention - Flax Module in Jax",
author="Phil Wang",
author_email="",
url="https://github.com/lucidrains/local-attention-flax",
... | local-attention-flax-main | setup.py |
from local_attention_flax.local_attention_flax import LocalAttention
| local-attention-flax-main | local_attention_flax/__init__.py |
import flax.linen as nn
from jax import numpy as np
from einops import rearrange
ATTN_MASK_VALUE = -1e10
class LocalAttention(nn.Module):
dim: int
window_size: int
heads: int = 8
dim_head: int = 64
@nn.compact
def __call__(self, x):
n, h, dim_head, wsz = x.shape[0], self.heads, self.d... | local-attention-flax-main | local_attention_flax/local_attention_flax.py |
from setuptools import setup, find_packages
from io import open
import versioneer
DESCRIPTION = (
"ANANSE: Prediction of key transcription factors in cell fate "
"determination using enhancer networks"
)
with open("README.md", encoding="utf-8") as f:
long_description = f.read().strip("\n")
setup(
nam... | ANANSE-master | setup.py |
# Version: 0.19
"""The Versioneer - like a rocketeer, but for versions.
The Versioneer
==============
* like a rocketeer, but for versions!
* https://github.com/python-versioneer/python-versioneer
* Brian Warner
* License: Public Domain
* Compatible with: Python 3.6, 3.7, 3.8, 3.9 and pypy3
* [![Latest Version][pypi... | ANANSE-master | versioneer.py |
import urllib
import pandas as pd
import numpy as np
import re
import sys
import os
from loguru import logger
import ananse
logger.remove()
logger.add(
sys.stderr, format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | {level} | {message}"
)
TFP_URL = "https://maayanlab.cloud/Enrichr/geneSetLibrary?mode=text&librar... | ANANSE-master | ananse/benchmark.py |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... | ANANSE-master | ananse/_version.py |
from glob import glob
import inspect
import os
import re
import sys
from tempfile import NamedTemporaryFile
from fluff.fluffio import load_heatmap_data
from genomepy import Genome
from gimmemotifs.motif import read_motifs
from gimmemotifs.scanner import scan_regionfile_to_table
from gimmemotifs.moap import moap
import... | ANANSE-master | ananse/peakpredictor.py |
from ._version import get_versions
import os
import sys
from loguru import logger
# Remove default logger
logger.remove()
# Add logger
logger.add(sys.stderr, format="{time} | {level} | {message}", level="INFO")
# This is here to prevent very high memory usage on numpy import.
# On a machine with many cores, just impo... | ANANSE-master | ananse/__init__.py |
#!/usr/bin/env python
# Copyright (c) 2009-2019 Quan Xu <qxuchn@gmail.com>
#
# This module is free software. You can redistribute it and/or modify it under
# the terms of the MIT License, see the file COPYING included with this
# distribution.
"""Predict TF influence score"""
# Python imports
from __future__ import ... | ANANSE-master | ananse/influence.py |
import os.path
import numpy as np
import pandas as pd
from scipy import stats
from ananse.utils import cleanpath
class Distributions:
def __init__(self):
# dist_functions = [f for f in dir(ananse.distributions) if f.endswith("_dist")]
dist_functions = [
scale_dist,
log_sc... | ANANSE-master | ananse/distributions.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.