コード例 #1
0
def test_badoptimization_opt_err():
    # This variant of test_badoptimization() replace the working code
    # with a new apply node that will raise an error.
    @gof.local_optimizer([aesara.tensor.add])
    def insert_bigger_b_add(node):
        if node.op == aesara.tensor.add:
            inputs = list(node.inputs)
            if inputs[-1].owner is None:
                inputs[-1] = aesara.tensor.concatenate(
                    (inputs[-1], inputs[-1]))
                return [node.op(*inputs)]
        return False

    @gof.local_optimizer([aesara.tensor.add])
    def insert_bad_dtype(node):
        if node.op == aesara.tensor.add:
            inputs = list(node.inputs)
            if inputs[-1].owner is None:

                return [node.outputs[0].astype("float32")]
        return False

    edb = gof.EquilibriumDB()
    edb.register("insert_bigger_b_add", insert_bigger_b_add, "all")
    opt = edb.query("+all")
    edb2 = gof.EquilibriumDB()
    edb2.register("insert_bad_dtype", insert_bad_dtype, "all")
    opt2 = edb2.query("+all")

    a = aesara.tensor.dvector()
    b = aesara.tensor.dvector()

    f = aesara.function([a, b], a + b, mode=debugmode.DebugMode(optimizer=opt))
    with pytest.raises(ValueError, match=r"insert_bigger_b_add"):
        f(
            [1.0, 2.0, 3.0],
            [2, 3, 4],
        )

    # Test that opt that do an illegal change still get the error from gof.
    with pytest.raises(aesara.gof.toolbox.BadOptimization,
                       match=r"insert_bad_dtype") as einfo:
        with aesara.change_flags(on_opt_error="raise"):
            f2 = aesara.function(
                [a, b],
                a + b,
                mode=debugmode.DebugMode(optimizer=opt2, stability_patience=1),
            )
        f2(
            [1.0, 2.0, 3.0],
            [2, 3, 4],
        )

    # Test that we can reraise the error with an extended message
    with pytest.raises(aesara.gof.toolbox.BadOptimization):
        e = einfo.value
        new_e = e.__class__("TTT" + str(e))
        exc_type, exc_value, exc_trace = sys.exc_info()
        exc_value = new_e
        raise exc_value.with_traceback(exc_trace)
コード例 #2
0
    def _get_func(self):
        """
        Return a function that makes a value from an integer.

        The integer value is assumed to be a valid pointer for the
        type and no check is done to ensure that.
        """
        from aesara.scalar import get_scalar_type

        if self._fn is None:
            with change_flags(compute_test_value="off"):
                v = get_scalar_type("int64")()
                self._fn = aesara.function(
                    [v],
                    _make_cdata(self)(v),
                    mode=aesara.Mode(optimizer=None),
                    profile=False,
                )
        return self._fn
コード例 #3
0
def test_overflow_cpu():
    # run with THEANO_FLAGS=mode=FAST_RUN,device=cpu,floatX=float32
    rng = MRG_RandomStreams(np.random.randint(1234))
    fct = rng.uniform
    with change_flags(compute_test_value="off"):
        # should raise error as the size overflows
        sizes = [
            (2**31, ),
            (2**32, ),
            (
                2**15,
                2**16,
            ),
            (2, 2**15, 2**15),
        ]
        rng_mrg_overflow(sizes, fct, config.mode, should_raise_error=True)
    # should not raise error
    sizes = [(2**5, ), (2**5, 2**5), (2**5, 2**5, 2**5)]
    rng_mrg_overflow(sizes, fct, config.mode, should_raise_error=False)
    # should support int32 sizes
    sizes = [(np.int32(2**10), ),
             (np.int32(2), np.int32(2**10), np.int32(2**10))]
    rng_mrg_overflow(sizes, fct, config.mode, should_raise_error=False)
コード例 #4
0
def test_SwitchingProcess():

    np.random.seed(2023532)

    test_states = np.r_[2, 0, 1, 2, 0, 1]
    test_dists = [
        Constant.dist(0),
        pm.Poisson.dist(100.0),
        pm.Poisson.dist(1000.0)
    ]
    test_dist = SwitchingProcess.dist(test_dists, test_states)
    assert np.array_equal(test_dist.shape, test_states.shape)

    test_sample = test_dist.random()
    assert test_sample.shape == (test_states.shape[0], )
    assert np.all(test_sample[test_states == 0] == 0)
    assert np.all(0 < test_sample[test_states == 1])
    assert np.all(test_sample[test_states == 1] < 1000)
    assert np.all(100 < test_sample[test_states == 2])

    test_mus = np.r_[100, 100, 500, 100, 100, 100]
    test_dists = [
        Constant.dist(0),
        pm.Poisson.dist(test_mus),
        pm.Poisson.dist(10000.0),
    ]
    test_dist = SwitchingProcess.dist(test_dists, test_states)
    assert np.array_equal(test_dist.shape, test_states.shape)

    test_sample = test_dist.random()
    assert test_sample.shape == (test_states.shape[0], )
    assert np.all(200 < test_sample[2] < 600)
    assert np.all(0 < test_sample[5] < 200)
    assert np.all(5000 < test_sample[test_states == 2])

    test_dists = [
        Constant.dist(0),
        pm.Poisson.dist(100.0),
        pm.Poisson.dist(1000.0)
    ]
    test_dist = SwitchingProcess.dist(test_dists, test_states)
    for i in range(len(test_dists)):
        test_logp = test_dist.logp(
            np.tile(test_dists[i].mode.eval(), test_states.shape)).eval()
        assert test_logp[test_states != i].max() < test_logp[test_states ==
                                                             i].min()

    # Try a continuous mixture
    test_states = np.r_[2, 0, 1, 2, 0, 1]
    test_dists = [
        pm.Normal.dist(0.0, 1.0),
        pm.Normal.dist(100.0, 1.0),
        pm.Normal.dist(1000.0, 1.0),
    ]
    test_dist = SwitchingProcess.dist(test_dists, test_states)
    assert np.array_equal(test_dist.shape, test_states.shape)

    test_sample = test_dist.random()
    assert test_sample.shape == (test_states.shape[0], )
    assert np.all(test_sample[test_states == 0] < 10)
    assert np.all(50 < test_sample[test_states == 1])
    assert np.all(test_sample[test_states == 1] < 150)
    assert np.all(900 < test_sample[test_states == 2])

    # Make sure we can use a large number of distributions in the mixture
    test_states = np.ones(50)
    test_dists = [Constant.dist(i) for i in range(50)]
    test_dist = SwitchingProcess.dist(test_dists, test_states)
    assert np.array_equal(test_dist.shape, test_states.shape)

    with pytest.raises(TypeError):
        SwitchingProcess.dist([1], test_states)

    with aesara.change_flags(compute_test_value="off"):
        # Test for the case when a default can't be computed
        test_dist = pm.Poisson.dist(at.scalar())

        # Confirm that there's no default
        with pytest.raises(AttributeError):
            test_dist.default()

        # Let it try to sample using `Distribution.random` and fail
        with pytest.raises(ValueError):
            SwitchingProcess.dist([test_dist], test_states)

    # Evaluate multiple observed state sequences in an extreme case
    test_states = at.imatrix("states")
    test_states.tag.test_value = np.zeros((10, 4)).astype("int32")
    test_dist = SwitchingProcess.dist(
        [Constant.dist(0), Constant.dist(1)], test_states)
    test_obs = np.tile(np.arange(4), (10, 1)).astype("int32")
    test_logp = test_dist.logp(test_obs)
    exp_logp = np.tile(
        np.array([0.0] + [-np.inf] * 3, dtype=aesara.config.floatX), (10, 1))
    assert np.array_equal(test_logp.tag.test_value, exp_logp)
コード例 #5
0
def set_aesara_flags():
    with aesara.change_flags(compute_test_value="raise"):
        yield
コード例 #6
0
def test_validate_input_types_gpuarray_backend():
    with change_flags(compute_test_value="raise"):
        rstate = np.zeros((7, 6), dtype="int32")
        rstate = gpuarray_shared_constructor(rstate)
        rng_mrg.mrg_uniform.new(rstate, ndim=None, dtype="float32", size=(3, ))