Example #1
0
def test_aliasing_list():
    from myia.compile.backends import LoadingError, load_backend
    try:
        load_backend('pytorch')
    except LoadingError:
        pytest.skip('PyTorch not available')

    def g(xs, y):
        res = 0
        for x in xs:
            res = res + x
        return sum(res)

    @myia(backend='pytorch', alias_tracker=ndarray_aliasable)
    def f(xs, y):
        return grad(g)(xs, y)

    o = np.ones((1, 3))

    a = o * 3
    b = o * 4
    c = o * 5
    d = o * 6
    e = o * 7

    res1 = f([a, b, c, d], e)
    for x in res1:
        np.testing.assert_allclose(x, o)

    with pytest.raises(MyiaInputTypeError):
        print(f([a, b, c, a], e))

    with pytest.raises(MyiaInputTypeError):
        print(f([a, b, c, d], a))
Example #2
0
 def __init__(self, backend, backend_options):
     try:
         load_backend(backend)
     except LoadingError as e:
         pytest.skip(f"Can't load {backend}: {e.__cause__}")
     self.pip = standard_pipeline.configure({
         'compile.backend':
         backend,
         'compile.backend_options':
         backend_options
     }).make()
Example #3
0
def test_backend_error():
    from myia.compile.backends import _backends, register_backend
    name = '__testing_name000_'

    def f():
        raise ValueError('test')

    register_backend(name, f)

    with pytest.raises(LoadingError):
        load_backend(name)

    del _backends[name]
Example #4
0
def test_backend_error():
    from myia.compile.backends import _backends, register_backend

    name = "__testing_name000_"

    def format():
        return {}

    def f():
        raise ValueError("test")

    register_backend(name, f, format)

    with pytest.raises(LoadingError):
        load_backend(name)

    del _backends[name]
Example #5
0
 def __init__(self, backend, backend_options):
     try:
         self.backend = load_backend(backend, backend_options)
     except LoadingError as e:
         pytest.skip(f"Can't load {backend}: {e.__cause__}")
     self.pip = standard_pipeline.configure({
         'resources.backend.name':
         backend,
         'resources.backend.options':
         backend_options
     }).make()
Example #6
0
        def wrapper_fn(*args, **kwargs):

            if primitives:
                backend = kwargs["backend"]
                bck = load_backend(backend)
                for prim_group in primitives:
                    if not bck.supports_prim_group(prim_group):
                        pytest.skip(
                            f"Backend {backend} does not support {prim_group}")

            return fn(*args, **kwargs)
Example #7
0
def test_load_backend_unknown():
    with pytest.raises(UnknownBackend):
        load_backend('_fake_name_')
Example #8
0
from dataclasses import dataclass

import pytest

from myia import myia
from myia.compile.backends import load_backend
from myia.lib import Empty, HandleInstance, core
from myia.operations import cell_get, cell_set, make_cell
from myia.pipeline import standard_pipeline, steps

try:
    load_backend("relay")
except Exception:
    pytestmark = pytest.mark.skip("Requires relay")


upipeline = standard_pipeline.insert_after("parse", resolve=steps.step_resolve)

umyia = myia(
    use_universe=True,
    backend="relay",
    backend_options={"exec_kind": "debug"},
    pipeline=upipeline,
)


def add_one(x):
    # Not universal, but should work from universal function
    return x + 1

Example #9
0
def safe_load(name):
    try:
        return load_backend(name)
    except LoadingError:
        return None
Example #10
0
def _run(
    self,
    fn,
    args,
    result=None,
    abstract=None,
    broad_specs=None,
    validate=True,
    pipeline=standard_pipeline,
    backend=None,
    numpy_compat=False,
    primitives=None,
    **kwargs,
):
    """Test a Myia function.

    Arguments:
        self: auto-passed MyiaFunctionTest object.
        fn: The Myia function to test.
        args: The args for the function.
        result: The expected result, or an exception subclass. If result is
            None, we will call the Python version of the function to compare
            with.
        abstract: The argspec. If None, it will be derived automatically from
            the args.
        broad_specs: For each argument, whether to broaden the type. By
            default, broaden all arguments.
        validate: Whether to run the validation step.
        pipeline: The pipeline to use.
        backend: backends to use. Tuple (backend name, backend options)
        numpy_compat: if True, check if args can be converted to numpy arrays.
        primitives: optional list of primitives or groups of primitives
            (as PrimGroup objects) required for this test.
            If a backend does not support any of given primitives or groups,
            then related test is explicitly skipped.
    """

    if backend:
        backend_name = backend[0]
        backend_options = backend[1]

        if primitives:
            b = load_backend(backend_name, backend_options)
            for p in primitives:
                g = PrimGroup.ensure(p)
                if not b.supports_prim_group(g):
                    pytest.skip(f"Backend {backend_name} does not support {g}")

        pipeline = pipeline.configure({
            "backend.name": backend_name,
            "backend.options": backend_options
        })

    if abstract is None:
        if broad_specs is None:
            broad_specs = (True, ) * len(args)
        argspec = tuple(
            from_value(arg, broaden=bs) for bs, arg in zip(broad_specs, args))
    else:
        argspec = tuple(to_abstract_test(a) for a in abstract)

    if not validate:
        pipeline = pipeline.configure(validator=None)

    def out(args):
        mfn = pipeline(input=fn, argspec=argspec)
        rval = mfn["output"](*args)
        return rval

    if result is None:
        result = fn(*args)

    self.check(out, args, result, **kwargs)

    if numpy_compat:
        args_torch = args
        args = ()
        for _ in args_torch:
            args += (to_numpy(_), )

        if abstract is None:
            if broad_specs is None:
                broad_specs = (True, ) * len(args)
            argspec = tuple(
                from_value(arg, broaden=bs)
                for bs, arg in zip(broad_specs, args))
        else:
            argspec = tuple(to_abstract_test(a) for a in abstract)

        out(args)
Example #11
0
import pytest

from myia import myia
from myia.compile.backends import load_backend
from myia.lib import Empty, HandleInstance, core
from myia.operations import handle, handle_get, handle_set

try:
    load_backend('relay')
except Exception:
    pytestmark = pytest.mark.skip('Requires relay')


def add_one(x):
    # Not universal, but should work from universal function
    return x + 1


@core(use_universe=True)
def increment(h):
    return handle_set(h, add_one(handle_get(h)))


def test_increment():
    @myia(use_universe=True, backend='relay')
    def plus4(x):
        h = handle(x)
        increment(h)
        increment(h)
        increment(h)
        increment(h)