code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def testSphHarmOrderZeroDegreeZero(self):
"""Tests the spherical harmonics of order zero and degree zero."""
theta = jnp.array([0.3])
phi = jnp.array([2.3])
n_max = 0
expected = jnp.array([1.0 / jnp.sqrt(4.0 * np.pi)])
actual = jnp.real(
lsp_special.sph_harm(jnp.array([0]), jnp.array([0... | Tests the spherical harmonics of order zero and degree zero. | testSphHarmOrderZeroDegreeZero | python | jax-ml/jax | tests/lax_scipy_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_scipy_test.py | Apache-2.0 |
def testSphHarmOrderZeroDegreeOne(self):
"""Tests the spherical harmonics of order one and degree zero."""
theta = jnp.array([2.0])
phi = jnp.array([3.1])
n_max = 1
expected = jnp.sqrt(3.0 / (4.0 * np.pi)) * jnp.cos(phi)
actual = jnp.real(
lsp_special.sph_harm(jnp.array([0]), jnp.array(... | Tests the spherical harmonics of order one and degree zero. | testSphHarmOrderZeroDegreeOne | python | jax-ml/jax | tests/lax_scipy_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_scipy_test.py | Apache-2.0 |
def testSphHarmOrderOneDegreeOne(self):
"""Tests the spherical harmonics of order one and degree one."""
theta = jnp.array([2.0])
phi = jnp.array([2.5])
n_max = 1
expected = (-1.0 / 2.0 * jnp.sqrt(3.0 / (2.0 * np.pi)) *
jnp.sin(phi) * jnp.exp(1j * theta))
actual = lsp_special.sp... | Tests the spherical harmonics of order one and degree one. | testSphHarmOrderOneDegreeOne | python | jax-ml/jax | tests/lax_scipy_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_scipy_test.py | Apache-2.0 |
def testSphHarmForJitAndAgainstNumpy(self, l_max, num_z, dtype):
"""Tests against JIT compatibility and Numpy."""
if jtu.is_device_tpu_at_least(6):
self.skipTest("TODO(b/364258243): fails on TPU v6+")
n_max = l_max
shape = (num_z,)
rng = jtu.rand_int(self.rng(), -l_max, l_max + 1)
lsp_spe... | Tests against JIT compatibility and Numpy. | testSphHarmForJitAndAgainstNumpy | python | jax-ml/jax | tests/lax_scipy_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_scipy_test.py | Apache-2.0 |
def testSphHarmCornerCaseWithWrongNmax(self):
"""Tests the corner case where `n_max` is not the maximum value of `n`."""
m = jnp.array([2])
n = jnp.array([10])
n_clipped = jnp.array([6])
n_max = 6
theta = jnp.array([0.9])
phi = jnp.array([0.2])
expected = lsp_special.sph_harm(m, n, thet... | Tests the corner case where `n_max` is not the maximum value of `n`. | testSphHarmCornerCaseWithWrongNmax | python | jax-ml/jax | tests/lax_scipy_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_scipy_test.py | Apache-2.0 |
def testConvGeneralDilatedLocal(self, dtype, precision, n, padding, lhs_spec,
rhs_spec, out_spec):
"""Make sure LCN with tiled CNN kernel matches CNN."""
lhs_spec_default = 'NCHWDX'[:n + 2]
rhs_spec_default = 'OIHWDX'[:n + 2]
rng = jtu.rand_small(self.rng())
lhs_d... | Make sure LCN with tiled CNN kernel matches CNN. | testConvGeneralDilatedLocal | python | jax-ml/jax | tests/lax_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_test.py | Apache-2.0 |
def _conv_transpose_via_grad(data, kernel, strides, padding,
rhs_dilation=None, dimension_numbers=None):
"""Helper method: calculates conv transpose via grad for testing."""
assert len(data.shape) == len(kernel.shape)
nspatial = len(data.shape) - 2
one = (1,) * nspatial
... | Helper method: calculates conv transpose via grad for testing. | _conv_transpose_via_grad | python | jax-ml/jax | tests/lax_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_test.py | Apache-2.0 |
def testUnaryWeakTypes(self, op_name, rec_dtypes):
"""Test that all lax unary ops propagate weak_type information appropriately."""
if op_name == "bitwise_not":
raise unittest.SkipTest("https://github.com/jax-ml/jax/issues/12066")
# Find a valid dtype for the function.
for dtype in [float, int, co... | Test that all lax unary ops propagate weak_type information appropriately. | testUnaryWeakTypes | python | jax-ml/jax | tests/lax_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_test.py | Apache-2.0 |
def test_ragged_dot(self, m, k, n, num_groups, dtype):
"""Tests ragged_dot.
The ragged_dot is tested against numpy reference implementation, and by
running JAX compilation.
Raises:
SkipTest: in the case dtype is not supported.
"""
if (dtype == np.float16):
raise SkipTest(f"unsuppor... | Tests ragged_dot.
The ragged_dot is tested against numpy reference implementation, and by
running JAX compilation.
Raises:
SkipTest: in the case dtype is not supported.
| test_ragged_dot | python | jax-ml/jax | tests/lax_test.py | https://github.com/jax-ml/jax/blob/master/tests/lax_test.py | Apache-2.0 |
def _axis_for_ndim(ndim: int) -> Iterator[None | int | tuple[int, ...]]:
"""
Generate a range of valid axis arguments for a reduction over
an array with a given number of dimensions.
"""
yield from (None, ())
if ndim > 0:
yield from (0, (-1,))
if ndim > 1:
yield from (1, (0, 1), (-1, 0))
if ndim... |
Generate a range of valid axis arguments for a reduction over
an array with a given number of dimensions.
| _axis_for_ndim | python | jax-ml/jax | tests/linalg_test.py | https://github.com/jax-ml/jax/blob/master/tests/linalg_test.py | Apache-2.0 |
def osp_linalg_toeplitz(c: np.ndarray, r: np.ndarray | None = None) -> np.ndarray:
"""scipy.linalg.toeplitz with v1.17+ batching semantics."""
# TODO(dfm,jakevdp): Remove dev check after upstream PR is merged:
# https://github.com/scipy/scipy/issues/21466.
if scipy_version >= (1, 17, 0) and "dev0" not in scipy.... | scipy.linalg.toeplitz with v1.17+ batching semantics. | osp_linalg_toeplitz | python | jax-ml/jax | tests/linalg_test.py | https://github.com/jax-ml/jax/blob/master/tests/linalg_test.py | Apache-2.0 |
def testEigHandlesNanInputs(self, shape, dtype, compute_left_eigenvectors,
compute_right_eigenvectors):
"""Verifies that `eig` fails gracefully if given non-finite inputs."""
a = jnp.full(shape, jnp.nan, dtype)
results = lax.linalg.eig(
a, compute_left_eigenvectors=comp... | Verifies that `eig` fails gracefully if given non-finite inputs. | testEigHandlesNanInputs | python | jax-ml/jax | tests/linalg_test.py | https://github.com/jax-ml/jax/blob/master/tests/linalg_test.py | Apache-2.0 |
def mock_tpu_devices(x, y, z, dev_kind, one_device_per_chip, num_slices=1,
reorder=False):
"""Produce fake jax.devices() output for a TPU slice."""
assert x > 0 and y > 0 and z > 0
cores_per_chip = 1 if one_device_per_chip else 2
# 3D shape of the mesh of devices on each host (= process).... | Produce fake jax.devices() output for a TPU slice. | mock_tpu_devices | python | jax-ml/jax | tests/mesh_utils_test.py | https://github.com/jax-ml/jax/blob/master/tests/mesh_utils_test.py | Apache-2.0 |
def test_pytree_state(self):
"""Test calling odeint with y(t) values that are pytrees."""
def dynamics(y, _t):
return jax.tree.map(jnp.negative, y)
y0 = (np.array(-0.1), np.array([[[0.1]]]))
ts = np.linspace(0., 1., 11)
tol = 1e-1 if jtu.num_float_bits(np.float64) == 32 else 1e-3
integra... | Test calling odeint with y(t) values that are pytrees. | test_pytree_state | python | jax-ml/jax | tests/ode_test.py | https://github.com/jax-ml/jax/blob/master/tests/ode_test.py | Apache-2.0 |
def test_weird_time_pendulum_grads(self):
"""Test that gradients are correct when the dynamics depend on t."""
def dynamics(_np, y, t):
return _np.array([y[1] * -t, -1 * y[1] - 9.8 * _np.sin(y[0])])
y0 = [np.pi - 0.1, 0.0]
ts = np.linspace(0., 1., 11)
tol = 1e-1 if jtu.num_float_bits(np.float... | Test that gradients are correct when the dynamics depend on t. | test_weird_time_pendulum_grads | python | jax-ml/jax | tests/ode_test.py | https://github.com/jax-ml/jax/blob/master/tests/ode_test.py | Apache-2.0 |
def test_exported_names_match_module(self, module_name, include, exclude):
"""Test that all public exports have __module__ set correctly."""
module = importlib.import_module(module_name)
self.assertEqual(module.__name__, module_name)
for name in dir(module):
if name not in include and (name.starts... | Test that all public exports have __module__ set correctly. | test_exported_names_match_module | python | jax-ml/jax | tests/package_structure_test.py | https://github.com/jax-ml/jax/blob/master/tests/package_structure_test.py | Apache-2.0 |
def test_custom_partitioner_jit_annotated_function(self):
"""Test correct lowering of function with a @jax.jit annotated callee.
Annotating a callee with @jax.jit results in a module with a HLO CallOp.
This test is makes sure that the custom partitioner lowering supports
CallOps.
"""
self.skip... | Test correct lowering of function with a @jax.jit annotated callee.
Annotating a callee with @jax.jit results in a module with a HLO CallOp.
This test is makes sure that the custom partitioner lowering supports
CallOps.
| test_custom_partitioner_jit_annotated_function | python | jax-ml/jax | tests/pjit_test.py | https://github.com/jax-ml/jax/blob/master/tests/pjit_test.py | Apache-2.0 |
def distributed_matrix_vector(x, y):
"""Matrix vector multiply. First batch it and then row by row"""
fv = lambda z: lax.map(lambda j: vv(j, y), z)
res = self.pmap(fv)(x.reshape((jax.device_count(), -1) + tuple(x.shape[1:])))
res = res.reshape(res.shape[0] * res.shape[1], *res.shape[2:])
r... | Matrix vector multiply. First batch it and then row by row | distributed_matrix_vector | python | jax-ml/jax | tests/pmap_test.py | https://github.com/jax-ml/jax/blob/master/tests/pmap_test.py | Apache-2.0 |
def assertSetsAllClose(self, x, y, rtol=None, atol=None, check_dtypes=True):
"""Assert that x and y contain permutations of the same approximate set of values.
For non-complex inputs, this is accomplished by comparing the sorted inputs.
For complex, such an approach can be confounded by numerical errors. I... | Assert that x and y contain permutations of the same approximate set of values.
For non-complex inputs, this is accomplished by comparing the sorted inputs.
For complex, such an approach can be confounded by numerical errors. In this case,
we compute the structural rank of the pairwise comparison matrix: i... | assertSetsAllClose | python | jax-ml/jax | tests/polynomial_test.py | https://github.com/jax-ml/jax/blob/master/tests/polynomial_test.py | Apache-2.0 |
def _testPolarDecomposition(self, a, u, h, tol):
"""Tests that u*h is the polar decomposition of a"""
self._testReconstruction(a, u, h, tol)
self._testUnitary(u, tol)
self._testHermitian(h, tol) | Tests that u*h is the polar decomposition of a | _testPolarDecomposition | python | jax-ml/jax | tests/qdwh_test.py | https://github.com/jax-ml/jax/blob/master/tests/qdwh_test.py | Apache-2.0 |
def _testQdwh(self, a, dynamic_shape=None):
"""Computes the polar decomposition and tests its basic properties."""
eps = jnp.finfo(a.dtype).eps
u, h, iters, conv = qdwh.qdwh(a, dynamic_shape=dynamic_shape)
tol = 13 * eps
if dynamic_shape is not None:
m, n = dynamic_shape
a = a[:m, :n]
... | Computes the polar decomposition and tests its basic properties. | _testQdwh | python | jax-ml/jax | tests/qdwh_test.py | https://github.com/jax-ml/jax/blob/master/tests/qdwh_test.py | Apache-2.0 |
def testQdwhWithUpperTriangularInputAllOnes(self, shape, dtype):
"""Tests qdwh with upper triangular input of all ones."""
eps = jnp.finfo(dtype).eps
m, n = shape
a = jnp.triu(jnp.ones((m, n))).astype(dtype)
self._testQdwh(a) | Tests qdwh with upper triangular input of all ones. | testQdwhWithUpperTriangularInputAllOnes | python | jax-ml/jax | tests/qdwh_test.py | https://github.com/jax-ml/jax/blob/master/tests/qdwh_test.py | Apache-2.0 |
def testQdwhJitCompatibility(self, m, n, padding, dtype):
"""Tests JIT compilation of QDWH with and without dynamic shape."""
rng = jtu.rand_uniform(self.rng())
a = rng((m, n), dtype)
def lsp_linalg_fn(a):
if padding is not None:
pm, pn = padding
a = jnp.pad(a, [(0, pm), (0, pn)], ... | Tests JIT compilation of QDWH with and without dynamic shape. | testQdwhJitCompatibility | python | jax-ml/jax | tests/qdwh_test.py | https://github.com/jax-ml/jax/blob/master/tests/qdwh_test.py | Apache-2.0 |
def testQdwhWithTinyElement(self, m, n, r, c, dtype):
"""Tests qdwh on matrix with zeros and close-to-zero entries."""
a = jnp.zeros((m, n), dtype=dtype)
one = dtype(1.0)
tiny_elem = dtype(jnp.finfo(a.dtype).tiny)
a = a.at[r, c].set(tiny_elem)
@jax.jit
def lsp_linalg_fn(a):
u, h, _, _... | Tests qdwh on matrix with zeros and close-to-zero entries. | testQdwhWithTinyElement | python | jax-ml/jax | tests/qdwh_test.py | https://github.com/jax-ml/jax/blob/master/tests/qdwh_test.py | Apache-2.0 |
def get_energy_distance(samples_1, samples_2):
"""
Estimates the energy distance between two distributions, given
batches of independent samples from each.
For more information, see https://en.wikipedia.org/wiki/Energy_distance.
"""
x, xp = jnp.split(samples_1, 2)
y, yp = jnp.split(samples_2, 2)
return ... |
Estimates the energy distance between two distributions, given
batches of independent samples from each.
For more information, see https://en.wikipedia.org/wiki/Energy_distance.
| get_energy_distance | python | jax-ml/jax | tests/random_lax_test.py | https://github.com/jax-ml/jax/blob/master/tests/random_lax_test.py | Apache-2.0 |
def testRandomDistributionValues(self, case, make_key):
"""
Tests values output by various distributions. This will catch any
unintentional changes to the implementations that could result in
different random sequences.
Any refactoring of random distributions that leads to non-trivial
differenc... |
Tests values output by various distributions. This will catch any
unintentional changes to the implementations that could result in
different random sequences.
Any refactoring of random distributions that leads to non-trivial
differences in this test should follow the procedure outlined at
htt... | testRandomDistributionValues | python | jax-ml/jax | tests/random_test.py | https://github.com/jax-ml/jax/blob/master/tests/random_test.py | Apache-2.0 |
def scipy_mode_wrapper(a, axis=0, nan_policy='propagate', keepdims=None):
"""Wrapper to manage the shape discrepancies between scipy and jax"""
result = osp_stats.mode(a, axis=axis, nan_policy=nan_policy, keepdims=keepdims)
if a.size != 0 and axis == None and keepdims == True:
output_shape = ... | Wrapper to manage the shape discrepancies between scipy and jax | scipy_mode_wrapper | python | jax-ml/jax | tests/scipy_stats_test.py | https://github.com/jax-ml/jax/blob/master/tests/scipy_stats_test.py | Apache-2.0 |
def sampled_assertion(self,
e: DimSize,
fun: Callable,
*operands_sym: shape_poly.DimSize,
assertion: AssertionType = AssertionType.EQ
):
"""Checks `assertion(e, fun(*operands))` symbolically and c... | Checks `assertion(e, fun(*operands))` symbolically and concretely.
For the concrete check, it will sample the space of dimension variable
assignments for the dimension variables in `e`.
This is useful when `fun` can operate both with symbolic and with
concrete values, and we want to check that the beh... | sampled_assertion | python | jax-ml/jax | tests/shape_poly_test.py | https://github.com/jax-ml/jax/blob/master/tests/shape_poly_test.py | Apache-2.0 |
def _make_vmap_primitive_harnesses() -> Sequence[PolyHarness]:
"""For each harness group, pick a single dtype.
See PolyHarness for documentation.
"""
all_h = test_harnesses.all_harnesses
res = []
# Index by group
harness_groups: dict[
str, Sequence[test_harnesses.Harness]] = collections.defaultdict(... | For each harness group, pick a single dtype.
See PolyHarness for documentation.
| _make_vmap_primitive_harnesses | python | jax-ml/jax | tests/shape_poly_test.py | https://github.com/jax-ml/jax/blob/master/tests/shape_poly_test.py | Apache-2.0 |
def test_bcoo_dot_general_oob_and_unsorted_indices_cusparse(self):
"""Tests bcoo dot general with out-of-bound and unsorted indices."""
rhs = jnp.ones((5, 3), dtype=jnp.float32)
# It creates out-of-bound indices when nse > nnz.
lhs_mat_dense = jnp.array([[1, 0, 2, 3, 0], [0, 0, 0, 4, 0]],
... | Tests bcoo dot general with out-of-bound and unsorted indices. | test_bcoo_dot_general_oob_and_unsorted_indices_cusparse | python | jax-ml/jax | tests/sparse_bcoo_bcsr_test.py | https://github.com/jax-ml/jax/blob/master/tests/sparse_bcoo_bcsr_test.py | Apache-2.0 |
def make_test_string_array(self, device=None):
"""Makes and returns a simple 2x1 string array on the first CPU device."""
if device is None:
cpu_devices = jax.devices("cpu")
if len(cpu_devices) < 1:
self.skipTest(
"Skipping this test because no CPU devices are available."
... | Makes and returns a simple 2x1 string array on the first CPU device. | make_test_string_array | python | jax-ml/jax | tests/string_array_test.py | https://github.com/jax-ml/jax/blob/master/tests/string_array_test.py | Apache-2.0 |
def testSvdWithSkinnyTallInput(self, m, n):
"""Tests SVD with skinny and tall input."""
# Generates a skinny and tall input
with jax.default_matmul_precision('float32'):
np.random.seed(1235)
a = np.random.randn(m, n).astype(_SVD_TEST_DTYPE)
u, s, v = svd.svd(a, full_matrices=False, hermiti... | Tests SVD with skinny and tall input. | testSvdWithSkinnyTallInput | python | jax-ml/jax | tests/svd_test.py | https://github.com/jax-ml/jax/blob/master/tests/svd_test.py | Apache-2.0 |
def testSvdWithOnRankDeficientInput(self, m, r, log_cond):
"""Tests SVD with rank-deficient input."""
with jax.default_matmul_precision('float32'):
a = jnp.triu(jnp.ones((m, m))).astype(_SVD_TEST_DTYPE)
# Generates a rank-deficient input.
u, s, v = jnp.linalg.svd(a, full_matrices=False)
... | Tests SVD with rank-deficient input. | testSvdWithOnRankDeficientInput | python | jax-ml/jax | tests/svd_test.py | https://github.com/jax-ml/jax/blob/master/tests/svd_test.py | Apache-2.0 |
def testSvdAllZero(self, m, n, full_matrices, compute_uv, dtype):
"""Tests SVD on matrix of all zeros, +/-infinity or NaN."""
osp_fun = functools.partial(
osp_linalg.svd, full_matrices=full_matrices, compute_uv=compute_uv
)
lax_fun = functools.partial(
svd.svd, full_matrices=full_matrice... | Tests SVD on matrix of all zeros, +/-infinity or NaN. | testSvdAllZero | python | jax-ml/jax | tests/svd_test.py | https://github.com/jax-ml/jax/blob/master/tests/svd_test.py | Apache-2.0 |
def testSvdOnTinyElement(self, m, n, r, c, dtype):
"""Tests SVD on matrix of zeros and close-to-zero entries."""
a = jnp.zeros((m, n), dtype=dtype)
tiny_element = jnp.finfo(a.dtype).tiny
a = a.at[r, c].set(tiny_element)
@jax.jit
def lax_fun(a):
return svd.svd(a, full_matrices=False, compu... | Tests SVD on matrix of zeros and close-to-zero entries. | testSvdOnTinyElement | python | jax-ml/jax | tests/svd_test.py | https://github.com/jax-ml/jax/blob/master/tests/svd_test.py | Apache-2.0 |
def _host_to_device_funcs():
"""Generates host-to-device transfer functions."""
return [
# (function name, is an explicit transfer?, function)
("host_to_device_jax_device_put", True,
lambda: jax.device_put(np.ones(10))),
("host_to_device_jax_jit", False, lambda: jax.jit(lambda x: x)
... | Generates host-to-device transfer functions. | _host_to_device_funcs | python | jax-ml/jax | tests/transfer_guard_test.py | https://github.com/jax-ml/jax/blob/master/tests/transfer_guard_test.py | Apache-2.0 |
def _device_to_device_funcs():
"""Generates device-to-device transfer functions."""
if len(jax.local_devices()) < 2:
# device-to-device tests require at least 2 devices.
return []
with jax.transfer_guard_host_to_device("allow"):
device_arrays = [jnp.ones(1) for _ in range(2)]
return [
# (func... | Generates device-to-device transfer functions. | _device_to_device_funcs | python | jax-ml/jax | tests/transfer_guard_test.py | https://github.com/jax-ml/jax/blob/master/tests/transfer_guard_test.py | Apache-2.0 |
def _device_to_host_funcs():
"""Generates device-to-host transfer functions."""
if jax.default_backend() == "cpu":
# device-to-host does not incur transfer on the CPU backend.
return []
with jax.transfer_guard_host_to_device("allow"):
device_arrays = [jnp.ones(1) for _ in range(6)]
return [
#... | Generates device-to-host transfer functions. | _device_to_host_funcs | python | jax-ml/jax | tests/transfer_guard_test.py | https://github.com/jax-ml/jax/blob/master/tests/transfer_guard_test.py | Apache-2.0 |
def assertAllows(self, func_name):
"""Asserts that a transfer in the context is allowed."""
try:
yield
except Exception as e: # pylint: disable=broad-except
raise RuntimeError(
f"Expected a transfer to be allowed while running: {func_name}"
) from e | Asserts that a transfer in the context is allowed. | assertAllows | python | jax-ml/jax | tests/transfer_guard_test.py | https://github.com/jax-ml/jax/blob/master/tests/transfer_guard_test.py | Apache-2.0 |
def assertLogs(self, func_name):
"""Asserts that a transfer in the context is logged and allowed."""
# Only check if the transfer is allowed until Abseil provides an interface
# to capture logs.
with self.assertAllows(func_name):
yield | Asserts that a transfer in the context is logged and allowed. | assertLogs | python | jax-ml/jax | tests/transfer_guard_test.py | https://github.com/jax-ml/jax/blob/master/tests/transfer_guard_test.py | Apache-2.0 |
def assertDisallows(self, func_name):
"""Asserts that a transfer in the context is disallowed."""
try:
with self.assertRaises(Exception):
yield
except Exception as e: # pylint: disable=broad-except
raise RuntimeError(
f"Expected a transfer to be disallowed while running: {func... | Asserts that a transfer in the context is disallowed. | assertDisallows | python | jax-ml/jax | tests/transfer_guard_test.py | https://github.com/jax-ml/jax/blob/master/tests/transfer_guard_test.py | Apache-2.0 |
def testStringRepresentation(self, tree, correct_string):
"""Checks that the string representation of a tree works."""
treedef = tree_util.tree_structure(tree)
print(TREES)
self.assertRegex(str(treedef), correct_string) | Checks that the string representation of a tree works. | testStringRepresentation | python | jax-ml/jax | tests/tree_util_test.py | https://github.com/jax-ml/jax/blob/master/tests/tree_util_test.py | Apache-2.0 |
def f(*args, **kwargs):
"""The function to be transformed.
Scales the positional arguments by a factor.
Takes only one keyword argument, the factor to scale by."""
factor = kwargs.pop('factor', 2) # For PY2
assert not kwargs
return tuple(a * factor for a in args) | The function to be transformed.
Scales the positional arguments by a factor.
Takes only one keyword argument, the factor to scale by. | f | python | jax-ml/jax | tests/util_test.py | https://github.com/jax-ml/jax/blob/master/tests/util_test.py | Apache-2.0 |
def kw_to_positional(f, store, factor, *args, **kwargs):
"""A transformation with auxiliary output.
Turns all keyword parameters into positional ones.
On entry, append the values of the keyword arguments to the positional
arguments. On exit, take a list of results and recreate a dictionary
... | A transformation with auxiliary output.
Turns all keyword parameters into positional ones.
On entry, append the values of the keyword arguments to the positional
arguments. On exit, take a list of results and recreate a dictionary
from the tail of the results. The auxiliary output is the list o... | kw_to_positional | python | jax-ml/jax | tests/util_test.py | https://github.com/jax-ml/jax/blob/master/tests/util_test.py | Apache-2.0 |
def patch_jax_version(version, release_version):
"""
Patch jax.version._version & jax.version._release_version in order to
test the version construction logic.
"""
original_version = jax.version._version
original_release_version = jax.version._release_version
jax.version._version = version
jax.version.... |
Patch jax.version._version & jax.version._release_version in order to
test the version construction logic.
| patch_jax_version | python | jax-ml/jax | tests/version_test.py | https://github.com/jax-ml/jax/blob/master/tests/version_test.py | Apache-2.0 |
def assert_subprocess_call(stdout: bytes | None = None):
"""Run code, asserting that subprocess.Popen *is* called at least once."""
with mock.patch("subprocess.Popen") as mock_Popen:
mock_Popen.return_value.communicate.return_value = (stdout, b"")
yield
mock_Popen.return_value.communicate.assert_called() | Run code, asserting that subprocess.Popen *is* called at least once. | assert_subprocess_call | python | jax-ml/jax | tests/version_test.py | https://github.com/jax-ml/jax/blob/master/tests/version_test.py | Apache-2.0 |
def lower(f):
"""Prints the MLIR IR that results from lowering `f`.
The arguments to `f` are taken to be arrays shaped like `prototypes`."""
inputs = jax.tree.map(np.array, prototypes)
flat_inputs, _ = jax.tree.flatten(inputs)
shape_strs = " ".join([f"{x.dtype.name}[{','.join(map(str, x.shape))}]"
... | Prints the MLIR IR that results from lowering `f`.
The arguments to `f` are taken to be arrays shaped like `prototypes`. | lower | python | jax-ml/jax | tests/filecheck/jax_filecheck_helpers.py | https://github.com/jax-ml/jax/blob/master/tests/filecheck/jax_filecheck_helpers.py | Apache-2.0 |
def test_wgmma_transposed_layout(self, store_transposed):
"""Tests that the result of wgmma can be store transposed using
the WGMMA_TRNASPOSED layout.
"""
dtype = jnp.dtype(jnp.float16)
swizzle_elems = 128 // dtype.itemsize
shape = (128, 128)
@functools.partial(
pl.pallas_call,
... | Tests that the result of wgmma can be store transposed using
the WGMMA_TRNASPOSED layout.
| test_wgmma_transposed_layout | python | jax-ml/jax | tests/pallas/mosaic_gpu_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/mosaic_gpu_test.py | Apache-2.0 |
def test_tma_load_multicast(self, collective_dims, noncollective_dims, collective_dim_size):
"""
1. Broadcast a GMEM slice to SMEM across collective CTAs.
2. Send a SMEM slice from each collective CTA to reconstruct the GMEM slice.
It's not strictly necessary to use every collective CTA, but we ... |
1. Broadcast a GMEM slice to SMEM across collective CTAs.
2. Send a SMEM slice from each collective CTA to reconstruct the GMEM slice.
It's not strictly necessary to use every collective CTA, but we use them
to test that the cluster axes are used correctly.
| test_tma_load_multicast | python | jax-ml/jax | tests/pallas/mosaic_gpu_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/mosaic_gpu_test.py | Apache-2.0 |
def test_scalar_compare(self, params):
"""Test some scalar compares.
We don't really expect that the results would be wrong, but rather we want
to exercise the lowering rules.
"""
self.skip_if_mosaic_gpu()
def kernel(x_ref, y_ref, o_ref):
x = x_ref[0, 0]
y = y_ref[0, 0]
o_ref... | Test some scalar compares.
We don't really expect that the results would be wrong, but rather we want
to exercise the lowering rules.
| test_scalar_compare | python | jax-ml/jax | tests/pallas/ops_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/ops_test.py | Apache-2.0 |
def test_vector_compare(self, params):
"""Test some vector compares.
We don't really expect that the results would be wrong, but rather we want
to exercise the lowering rules.
"""
self.skip_if_mosaic_gpu()
def kernel(x_ref, y_ref, o_ref):
x = x_ref[:]
y = y_ref[:]
one = jnp.o... | Test some vector compares.
We don't really expect that the results would be wrong, but rather we want
to exercise the lowering rules.
| test_vector_compare | python | jax-ml/jax | tests/pallas/ops_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/ops_test.py | Apache-2.0 |
def test_dot_dims_batched_simple_dot_general(self):
"""This test is only meant to exercise a simple batch lowering of dot_general.
It is not meant to be a comprehensive test of dot_general lowering, for that
see pallas_test.py.
"""
if jtu.test_device_matches(["gpu"]):
self.skipTest("TPU only ... | This test is only meant to exercise a simple batch lowering of dot_general.
It is not meant to be a comprehensive test of dot_general lowering, for that
see pallas_test.py.
| test_dot_dims_batched_simple_dot_general | python | jax-ml/jax | tests/pallas/ops_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/ops_test.py | Apache-2.0 |
def test_range_while_loop(self):
"""Tests lowering of a while_loop which can reduce to a fori_loop."""
def kernel(x_ref, r_ref):
@pl.when(pl.program_id(0) == 0)
def _():
r_ref[0, 0] = 0
def cond(carry):
i, j = carry
return i < j
def body(carry):
io, j =... | Tests lowering of a while_loop which can reduce to a fori_loop. | test_range_while_loop | python | jax-ml/jax | tests/pallas/pallas_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/pallas_test.py | Apache-2.0 |
def test_non_range_while_loop(self):
"""Tests lowering of a while_loop which cannot reduce to a fori_loop."""
def kernel(x_ref, r_ref):
@pl.when(pl.program_id(0) == 0)
def _():
r_ref[0, 0] = 0
def cond(state):
i, s = state
return jnp.logical_and(i < 1024, s < 1024)
... | Tests lowering of a while_loop which cannot reduce to a fori_loop. | test_non_range_while_loop | python | jax-ml/jax | tests/pallas/pallas_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/pallas_test.py | Apache-2.0 |
def test_vector_carry_while_loop(self):
"""Tests lowering of a while_loop which carries a vector quantity."""
if jtu.test_device_matches(["gpu"]) and not self.INTERPRET:
self.skipTest("TODO: slice not implemented on GPU")
def kernel(x_ref, r_ref):
def cond(v):
return v[0, 0] < 16
... | Tests lowering of a while_loop which carries a vector quantity. | test_vector_carry_while_loop | python | jax-ml/jax | tests/pallas/pallas_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/pallas_test.py | Apache-2.0 |
def rand(
shape: tuple[int, ...], dtype: np.dtype | jnp.dtype, seed: int = 1234
) -> np.ndarray:
"""A helper function to generate random data for testing."""
rng = np.random.Generator(np.random.Philox(counter=0, key=seed))
if jnp.issubdtype(dtype, jnp.floating):
return rng.normal(size=shape).astype(dtype)... | A helper function to generate random data for testing. | rand | python | jax-ml/jax | tests/pallas/tpu_ops_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_ops_test.py | Apache-2.0 |
def _generate_qkv_simplest(
dtype: jnp.dtype,
) -> tuple[jax.Array, jax.Array, jax.Array, jax.Array, jax.Array]:
"""Generates queries with one query head, kv pages, and attention."""
max_seq_len = 4
seq_lens = jnp.asarray([max_seq_len // 2])
assert seq_lens.shape == (1,)
# q_shape = (batch_size=1, num_q_... | Generates queries with one query head, kv pages, and attention. | _generate_qkv_simplest | python | jax-ml/jax | tests/pallas/tpu_paged_attention_kernel_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_paged_attention_kernel_test.py | Apache-2.0 |
def _generate_qkv_with_two_q_heads(
dtype: jnp.dtype,
) -> tuple[jax.Array, jax.Array, jax.Array, jax.Array, jax.Array]:
"""Generates queries with two query heads, kv pages, and attention."""
max_seq_len = 4
seq_lens = jnp.asarray([max_seq_len])
assert seq_lens.shape == (1,)
# q_shape = (batch_size=1, nu... | Generates queries with two query heads, kv pages, and attention. | _generate_qkv_with_two_q_heads | python | jax-ml/jax | tests/pallas/tpu_paged_attention_kernel_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_paged_attention_kernel_test.py | Apache-2.0 |
def _generate_qkv_with_head_dim_two(
dtype: jnp.dtype,
) -> tuple[jax.Array, jax.Array, jax.Array, jax.Array, jax.Array]:
"""Generates queries, kv pages, and attention with head_dim=2."""
max_seq_len = 4
seq_lens = jnp.asarray([max_seq_len // 2])
assert seq_lens.shape == (1,)
# q_shape = (batch_size=1, n... | Generates queries, kv pages, and attention with head_dim=2. | _generate_qkv_with_head_dim_two | python | jax-ml/jax | tests/pallas/tpu_paged_attention_kernel_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_paged_attention_kernel_test.py | Apache-2.0 |
def test_scratch_input_vmap(self):
"""Test that vmapp-ing a kernel with scratch inputs works correctly."""
# Scratch inputs are only available for PallasTPU. This is why this test
# does not live with the other vmap tests in:
# jax/tests/pallas/pallas_test.py
def add_one_with_scratch(x_ref, o_ref, ... | Test that vmapp-ing a kernel with scratch inputs works correctly. | test_scratch_input_vmap | python | jax-ml/jax | tests/pallas/tpu_pallas_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_pallas_test.py | Apache-2.0 |
def test_grid_shrinking(self):
"""Make sure that grid shrinking does not change the attention output."""
class IdentityMask(mask_lib._ComputableMask):
"""Identity mask that is guaranteed to trigger grid shrinking."""
def __init__(
self,
shape: tuple[int, int],
shard_c... | Make sure that grid shrinking does not change the attention output. | test_grid_shrinking | python | jax-ml/jax | tests/pallas/tpu_splash_attention_kernel_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_splash_attention_kernel_test.py | Apache-2.0 |
def test_chunked_causal_mask(self, make_chunked_mask):
"""Tests the chunked causal mask logic for various shapes and chunk sizes."""
with self.subTest("unit"):
expected = np.array([[1]], dtype=np.bool_)
actual = make_chunked_mask(shape=(1, 1), chunk_size=1)
self.assertArraysEqual(actual, expec... | Tests the chunked causal mask logic for various shapes and chunk sizes. | test_chunked_causal_mask | python | jax-ml/jax | tests/pallas/tpu_splash_attention_mask_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_splash_attention_mask_test.py | Apache-2.0 |
def test_lazy_chunked_causal_mask_chunking(
self,
block_size: tuple[int, int],
shape: tuple[int, int],
chunk_size: int,
):
"""Compares lazy chunked mask evaluation against the dense version block-by-block."""
q_len, kv_len = shape
# Adjust block size if it exceeds shape dimensions
... | Compares lazy chunked mask evaluation against the dense version block-by-block. | test_lazy_chunked_causal_mask_chunking | python | jax-ml/jax | tests/pallas/tpu_splash_attention_mask_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_splash_attention_mask_test.py | Apache-2.0 |
def test_process_invalid_mask(self):
"""Masks with of an all-0 row causes undefined softmax, reject them."""
sequence_length = 32
invalid_mask = np.ones(
(4, sequence_length, sequence_length), dtype=np.bool_
)
invalid_mask[2, 14, :] = False
invalid_mask = mask_lib.MultiHeadMask(
... | Masks with of an all-0 row causes undefined softmax, reject them. | test_process_invalid_mask | python | jax-ml/jax | tests/pallas/tpu_splash_attention_mask_test.py | https://github.com/jax-ml/jax/blob/master/tests/pallas/tpu_splash_attention_mask_test.py | Apache-2.0 |
def validate_data(url,method):
''' Validate HTTP request data and return boolean value'''
validate_url = urllib.parse.urlparse(url)
http_method = ['GET','POST','DEL','OPTIONS','PUT']
if method in http_method and bool(validate_url.scheme) is True:
validate_result = True
else:
validate... | Validate HTTP request data and return boolean value | validate_data | python | flipkart-incubator/Astra | astra.py | https://github.com/flipkart-incubator/Astra/blob/master/astra.py | Apache-2.0 |
def scan_single_api(url, method, headers, body, api, scanid=None):
''' This function deals with scanning a single API. '''
if headers is None or headers == '':
headers = {'Content-Type' : 'application/json'}
try:
# Convert header and body in dict format
if type(headers) is not d... | This function deals with scanning a single API. | scan_single_api | python | flipkart-incubator/Astra | astra.py | https://github.com/flipkart-incubator/Astra/blob/master/astra.py | Apache-2.0 |
def __init__(self):
''' Set the proxy ip, port and Apitoken of OWASP ZAP '''
self.api_logger = logger()
self.dbupdate = Database_update()
self.ip = get_value('config.property','Configuration','ZAP_ip')
self.port = get_value('config.property','Configuration','ZAP_port')
se... | Set the proxy ip, port and Apitoken of OWASP ZAP | __init__ | python | flipkart-incubator/Astra | core/zapscan.py | https://github.com/flipkart-incubator/Astra/blob/master/core/zapscan.py | Apache-2.0 |
def update_db(self,scanid,url,alert,impact,description,solution,messageId):
''' This function gathers all the info of alert and update it into DB '''
message_url = '{0}/JSON/core/view/message/?zapapiformat=JSON&apikey={1}&formMethod=GET&id={2}'.format(self.zap_url,self.apitoken,messageId)
messag... | This function gathers all the info of alert and update it into DB | update_db | python | flipkart-incubator/Astra | core/zapscan.py | https://github.com/flipkart-incubator/Astra/blob/master/core/zapscan.py | Apache-2.0 |
def run_add_system(name, token, org, system, prompt):
"""
Adds a new system to the repo.
"""
repo = get_repo(token=token, org=org, name=name)
try:
repo.create_label(name=system.strip(), color=SYSTEM_LABEL_COLOR)
click.secho("Successfully added new system {}".format(system), fg="green... |
Adds a new system to the repo.
| run_add_system | python | jayfk/statuspage | statuspage/statuspage.py | https://github.com/jayfk/statuspage/blob/master/statuspage/statuspage.py | MIT |
def get_config(repo):
"""
Get the config for the repo, merged with the default config. Returns the default config if
no config file is found.
"""
files = get_files(repo)
config = DEFAULT_CONFIG
if "config.json" in files:
# get the config file, parse JSON and merge it with the default... |
Get the config for the repo, merged with the default config. Returns the default config if
no config file is found.
| get_config | python | jayfk/statuspage | statuspage/statuspage.py | https://github.com/jayfk/statuspage/blob/master/statuspage/statuspage.py | MIT |
def test_update(self):
"""
runner = CliRunner()
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
self.gh.assert_called_with("token")
self.gh().get_user().get_repo.assert_called_with(name="testrepo")
... |
runner = CliRunner()
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
self.gh.assert_called_with("token")
self.gh().get_user().get_repo.assert_called_with(name="testrepo")
self.gh().get_user().get_repo().ge... | test_update | python | jayfk/statuspage | statuspage/tests.py | https://github.com/jayfk/statuspage/blob/master/statuspage/tests.py | MIT |
def test_dont_update_when_nothing_changes(self):
"""
runner = CliRunner()
self.template.content = codecs.encode(b"some foo", "base64")
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
self.gh.assert_called_wi... |
runner = CliRunner()
self.template.content = codecs.encode(b"some foo", "base64")
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
self.gh.assert_called_with("token")
self.gh().get_user().get_repo.assert_cal... | test_dont_update_when_nothing_changes | python | jayfk/statuspage | statuspage/tests.py | https://github.com/jayfk/statuspage/blob/master/statuspage/tests.py | MIT |
def test_update_index_does_not_exist(self):
"""
self.gh().get_user().get_repo().update_file.side_effect = UnknownObjectException(status=404, data="foo")
runner = CliRunner()
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_c... |
self.gh().get_user().get_repo().update_file.side_effect = UnknownObjectException(status=404, data="foo")
runner = CliRunner()
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
self.gh.assert_called_with("token")
... | test_update_index_does_not_exist | python | jayfk/statuspage | statuspage/tests.py | https://github.com/jayfk/statuspage/blob/master/statuspage/tests.py | MIT |
def test_update_non_labeled_issue_not_displayed(self):
"""
self.issue.get_labels.return_value = []
runner = CliRunner()
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
# make sure that get_comments is not ... |
self.issue.get_labels.return_value = []
runner = CliRunner()
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
# make sure that get_comments is not called for the first issue but for the second
self.issue.g... | test_update_non_labeled_issue_not_displayed | python | jayfk/statuspage | statuspage/tests.py | https://github.com/jayfk/statuspage/blob/master/statuspage/tests.py | MIT |
def test_update_non_colaborator_issue_not_displayed(self):
"""
self.issue.user.login = "some-other-dude"
runner = CliRunner()
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
# make sure that get_comments i... |
self.issue.user.login = "some-other-dude"
runner = CliRunner()
result = runner.invoke(update, ["--name", "testrepo", "--token", "token"])
self.assertEqual(result.exit_code, 0)
# make sure that get_comments is not called for the first issue but for the second
self.issue... | test_update_non_colaborator_issue_not_displayed | python | jayfk/statuspage | statuspage/tests.py | https://github.com/jayfk/statuspage/blob/master/statuspage/tests.py | MIT |
def backtest():
"""
A simple backtest, which splits the dataset into a train set and test set,
then fits a Random Forest classifier to the train set. We print the precision and accuracy
of the classifier on the test set, then run a backtest comparing this strategy's performance
to passive investment... |
A simple backtest, which splits the dataset into a train set and test set,
then fits a Random Forest classifier to the train set. We print the precision and accuracy
of the classifier on the test set, then run a backtest comparing this strategy's performance
to passive investment in the S&P500.
Ple... | backtest | python | robertmartin8/MachineLearningStocks | backtesting.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/backtesting.py | MIT |
def check_yahoo():
"""
Retrieves the stock ticker from the _KeyStats directory, then downloads the html file from yahoo finance.
:return: a directory named `forward/` filled with the html files for each ticker
"""
# Create the directory where we will store the current data
if not os.path.exists(... |
Retrieves the stock ticker from the _KeyStats directory, then downloads the html file from yahoo finance.
:return: a directory named `forward/` filled with the html files for each ticker
| check_yahoo | python | robertmartin8/MachineLearningStocks | current_data.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/current_data.py | MIT |
def forward():
"""
Creates the forward sample by parsing the current data html files that we downloaded in check_yahoo().
:return: a pandas dataframe containing all of the current data for each ticker.
"""
# Creating an empty dataframe which we will later fill. In addition to the features, we need s... |
Creates the forward sample by parsing the current data html files that we downloaded in check_yahoo().
:return: a pandas dataframe containing all of the current data for each ticker.
| forward | python | robertmartin8/MachineLearningStocks | current_data.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/current_data.py | MIT |
def build_stock_dataset(start=START_DATE, end=END_DATE):
"""
Creates the dataset containing all stock prices
:returns: stock_prices.csv
"""
statspath = "intraQuarter/_KeyStats/"
ticker_list = os.listdir(statspath)
# Required on macOS
if ".DS_Store" in ticker_list:
os.remove(f"{... |
Creates the dataset containing all stock prices
:returns: stock_prices.csv
| build_stock_dataset | python | robertmartin8/MachineLearningStocks | download_historical_prices.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/download_historical_prices.py | MIT |
def build_dataset_iteratively(
idx_start, idx_end, date_start=START_DATE, date_end=END_DATE
):
"""
This is an alternative iterative solution to building the stock dataset, which may be necessary if the
tickerlist is too big.
Instead of downloading all at once, we download ticker by ticker and append... |
This is an alternative iterative solution to building the stock dataset, which may be necessary if the
tickerlist is too big.
Instead of downloading all at once, we download ticker by ticker and append to a dataframe.
This will download data for tickerlist[idx_start:idx_end], which makes this method su... | build_dataset_iteratively | python | robertmartin8/MachineLearningStocks | download_historical_prices.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/download_historical_prices.py | MIT |
def preprocess_price_data():
"""
Currently, the sp500 and stock price datasets we downloaded do not have any data for
days when the market was closed (weekends and public holidays). We need to amend this so that
all rows are included. Doing this now saves a lot of effort when we actually create the
... |
Currently, the sp500 and stock price datasets we downloaded do not have any data for
days when the market was closed (weekends and public holidays). We need to amend this so that
all rows are included. Doing this now saves a lot of effort when we actually create the
keystats dataset, which requires tha... | preprocess_price_data | python | robertmartin8/MachineLearningStocks | parsing_keystats.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/parsing_keystats.py | MIT |
def parse_keystats(sp500_df, stock_df):
"""
We have downloaded a large number of html files, which are snapshots of a ticker at different times,
containing the fundamental data (our features). To extract the key statistics, we use regex.
For supervised machine learning, we also need the data that will f... |
We have downloaded a large number of html files, which are snapshots of a ticker at different times,
containing the fundamental data (our features). To extract the key statistics, we use regex.
For supervised machine learning, we also need the data that will form our dependent variable,
the performance... | parse_keystats | python | robertmartin8/MachineLearningStocks | parsing_keystats.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/parsing_keystats.py | MIT |
def build_data_set():
"""
Reads the keystats.csv file and prepares it for scikit-learn
:return: X_train and y_train numpy arrays
"""
training_data = pd.read_csv("keystats.csv", index_col="Date")
training_data.dropna(axis=0, how="any", inplace=True)
features = training_data.columns[6:]
X... |
Reads the keystats.csv file and prepares it for scikit-learn
:return: X_train and y_train numpy arrays
| build_data_set | python | robertmartin8/MachineLearningStocks | stock_prediction.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/stock_prediction.py | MIT |
def data_string_to_float(number_string):
"""
The result of our regex search is a number stored as a string, but we need a float.
- Some of these strings say things like '25M' instead of 25000000.
- Some have 'N/A' in them.
- Some are negative (have '-' in front of the numbers).
-... |
The result of our regex search is a number stored as a string, but we need a float.
- Some of these strings say things like '25M' instead of 25000000.
- Some have 'N/A' in them.
- Some are negative (have '-' in front of the numbers).
- As an artifact of our regex, some values which ... | data_string_to_float | python | robertmartin8/MachineLearningStocks | utils.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/utils.py | MIT |
def duplicate_error_check(df):
"""
A common symptom of failed parsing is when there are consecutive duplicate values. This function was used
to find the duplicates and tweak the regex. Any remaining duplicates are probably coincidences.
:param df: the dataframe to be checked
:return: Prints out a li... |
A common symptom of failed parsing is when there are consecutive duplicate values. This function was used
to find the duplicates and tweak the regex. Any remaining duplicates are probably coincidences.
:param df: the dataframe to be checked
:return: Prints out a list of the rows containing duplicates, ... | duplicate_error_check | python | robertmartin8/MachineLearningStocks | utils.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/utils.py | MIT |
def status_calc(stock, sp500, outperformance=10):
"""A simple function to classify whether a stock outperformed the S&P500
:param stock: stock price
:param sp500: S&P500 price
:param outperformance: stock is classified 1 if stock price > S&P500 price + outperformance
:return: true/false
"""
... | A simple function to classify whether a stock outperformed the S&P500
:param stock: stock price
:param sp500: S&P500 price
:param outperformance: stock is classified 1 if stock price > S&P500 price + outperformance
:return: true/false
| status_calc | python | robertmartin8/MachineLearningStocks | utils.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/utils.py | MIT |
def test_forward_sample_dimensions():
"""
Check that the forward sample has been built correctly
"""
# Number of features + ['Date', 'Unix', 'Ticker', 'Price', 'stock_p_change', 'SP500', 'SP500_p_change']
df = pd.read_csv('forward_sample.csv')
indexing_columns = ['Date', 'Unix', 'Ticker', 'Price... |
Check that the forward sample has been built correctly
| test_forward_sample_dimensions | python | robertmartin8/MachineLearningStocks | tests/test_datasets.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/tests/test_datasets.py | MIT |
def test_forward_sample_data():
"""
Some quick checks on the forward sample data
"""
df = pd.read_csv('forward_sample.csv')
# For these tests we need to fill in nan values with zero
df.fillna(0, inplace=True)
# Make sure that these features have positive values
positive_features = ['Mar... |
Some quick checks on the forward sample data
| test_forward_sample_data | python | robertmartin8/MachineLearningStocks | tests/test_datasets.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/tests/test_datasets.py | MIT |
def test_stock_prices_dataset():
"""
Check that data from pandas-datareader has been downloaded correctly
"""
df = pd.read_csv("stock_prices.csv", index_col='Date', parse_dates=True)
assert type(df.index) == pd.core.indexes.datetimes.DatetimeIndex
# Make sure that all columns have some price da... |
Check that data from pandas-datareader has been downloaded correctly
| test_stock_prices_dataset | python | robertmartin8/MachineLearningStocks | tests/test_datasets.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/tests/test_datasets.py | MIT |
def def_keystats_dimensions():
"""
This tests that the keystats csv has been built correctly
"""
df = pd.read_csv("keystats.csv", index_col='Date')
indexing_columns = ['Unix', 'Ticker', 'Price',
'stock_p_change', 'SP500', 'SP500_p_change']
n_cols = len(df.columns)
as... |
This tests that the keystats csv has been built correctly
| def_keystats_dimensions | python | robertmartin8/MachineLearningStocks | tests/test_datasets.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/tests/test_datasets.py | MIT |
def test_stock_prediction_dataset():
"""
This tests that the dataset on which we are training our algorithm has been correctly built
"""
df = pd.read_csv("keystats.csv", index_col='Date')
num_rows_with_nan = sum(df.isnull().sum(axis=1) > 0)
X, y = stock_prediction.build_data_set()
assert X.... |
This tests that the dataset on which we are training our algorithm has been correctly built
| test_stock_prediction_dataset | python | robertmartin8/MachineLearningStocks | tests/test_datasets.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/tests/test_datasets.py | MIT |
def test_status_calc():
"""
Test the status_calc function which generates training labels
"""
assert utils.status_calc(50, 20, 12.2) == 1
assert utils.status_calc(12.003, 10, 15) == 0
assert utils.status_calc(-10, -30, 5) == 1
assert utils.status_calc(-31, -30, 15) == 0
assert utils.stat... |
Test the status_calc function which generates training labels
| test_status_calc | python | robertmartin8/MachineLearningStocks | tests/test_utils.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/tests/test_utils.py | MIT |
def test_data_string_to_float():
"""
data_string_to_float() is a function that needs to meet lots of empirical requirements
owing to the idiosyncrasies of Yahoo Finance's HTML. The main jobs are parsing negatives and
abbreviations of big numbers.
"""
assert utils.data_string_to_float("asdfNaN") ... |
data_string_to_float() is a function that needs to meet lots of empirical requirements
owing to the idiosyncrasies of Yahoo Finance's HTML. The main jobs are parsing negatives and
abbreviations of big numbers.
| test_data_string_to_float | python | robertmartin8/MachineLearningStocks | tests/test_utils.py | https://github.com/robertmartin8/MachineLearningStocks/blob/master/tests/test_utils.py | MIT |
def combine_summaries(summaries):
"""Combine a list of summary obtained from the function `summarize`.
The combined summary's format is as follows:
```
"google/gemma-2b": {
"benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5": {
"3cd6ed22e4d49219f300f5055e7... | Combine a list of summary obtained from the function `summarize`.
The combined summary's format is as follows:
```
"google/gemma-2b": {
"benchmark.input_shapes.batch_size=1,benchmark.input_shapes.sequence_length=5": {
"3cd6ed22e4d49219f300f5055e71e3929aba20d7": {
"metric... | combine_summaries | python | huggingface/transformers | benchmark/benchmark.py | https://github.com/huggingface/transformers/blob/master/benchmark/benchmark.py | Apache-2.0 |
def initialise_benchmark(self, metadata: Dict[str, str]) -> int:
"""
Creates a new benchmark, returns the benchmark id
"""
# gpu_name: str, model_id: str
with self.conn.cursor() as cur:
cur.execute(
"INSERT INTO benchmarks (repository, branch, commit_i... |
Creates a new benchmark, returns the benchmark id
| initialise_benchmark | python | huggingface/transformers | benchmark/benchmarks_entrypoint.py | https://github.com/huggingface/transformers/blob/master/benchmark/benchmarks_entrypoint.py | Apache-2.0 |
def collect_device_measurements(self, benchmark_id: int, cpu_util, mem_megabytes, gpu_util, gpu_mem_megabytes):
"""
Collect device metrics, such as CPU & GPU usage. These are "static", as in you cannot pass arbitrary arguments to the function.
"""
with self.conn.cursor() as cur:
... |
Collect device metrics, such as CPU & GPU usage. These are "static", as in you cannot pass arbitrary arguments to the function.
| collect_device_measurements | python | huggingface/transformers | benchmark/benchmarks_entrypoint.py | https://github.com/huggingface/transformers/blob/master/benchmark/benchmarks_entrypoint.py | Apache-2.0 |
def parse_arguments() -> Tuple[str, str, str, str]:
"""
Parse command line arguments for the benchmarking CLI.
"""
parser = argparse.ArgumentParser(description="CLI for benchmarking the huggingface/transformers.")
parser.add_argument(
"repository",
type=str,
help="The reposi... |
Parse command line arguments for the benchmarking CLI.
| parse_arguments | python | huggingface/transformers | benchmark/benchmarks_entrypoint.py | https://github.com/huggingface/transformers/blob/master/benchmark/benchmarks_entrypoint.py | Apache-2.0 |
def all_reduce_grads(model, world_mesh, use_ddp):
"""All reduce gradients across dp_cp if applicable."""
cp_mesh = world_mesh["cp"]
if use_ddp:
# DDP/FSDP takes care of syncing grads
mesh = cp_mesh
else:
mesh = world_mesh["dp", "cp"]._flatten(mesh_dim_name="dp_cp")
if dist.is... | All reduce gradients across dp_cp if applicable. | all_reduce_grads | python | huggingface/transformers | examples/3D_parallel.py | https://github.com/huggingface/transformers/blob/master/examples/3D_parallel.py | Apache-2.0 |
def clip_grad_norm_(
parameters: Iterable[torch.Tensor],
max_norm: float,
norm_type: float = 2.0,
error_if_nonfinite: bool = False,
foreach: bool | None = None,
) -> torch.Tensor:
"""
Clip the gradient norm of an iterable of parameters.
"""
# Filter out parameters with no gradients
... |
Clip the gradient norm of an iterable of parameters.
| clip_grad_norm_ | python | huggingface/transformers | examples/3D_parallel.py | https://github.com/huggingface/transformers/blob/master/examples/3D_parallel.py | Apache-2.0 |
def _prepare_4d_causal_attention_mask_with_cache_position(
attention_mask: torch.Tensor,
sequence_length: int,
target_length: int,
dtype: torch.dtype,
cache_position: torch.Tensor,
batch_size: int,
**kwargs,
):
"""
Creates a causal 4D mask of s... |
Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
`(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
Args:
attention_mask (`torch.Tensor`):
A 2D attention mask of sh... | _prepare_4d_causal_attention_mask_with_cache_position | python | huggingface/transformers | examples/modular-transformers/modeling_dummy.py | https://github.com/huggingface/transformers/blob/master/examples/modular-transformers/modeling_dummy.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.