summaryrefslogtreecommitdiff
path: root/test/test_gpu.py
blob: 615c2a7c3ea02c6b34561277db1e319e5c254cbe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""Tests for module gpu for gpu acceleration """

# Author: Remi Flamary <remi.flamary@unice.fr>
#
# License: MIT License

import numpy as np
import ot
import time
import pytest

try:  # test if cudamat installed
    import ot.gpu
    nogpu = False
except ImportError:
    nogpu = True


@pytest.mark.skipif(nogpu, reason="No GPU available")
def test_gpu_sinkhorn():

    rng = np.random.RandomState(0)

    def describe_res(r):
        print("min:{:.3E}, max::{:.3E}, mean::{:.3E}, std::{:.3E}".format(
            np.min(r), np.max(r), np.mean(r), np.std(r)))

    for n_samples in [50, 100, 500, 1000]:
        print(n_samples)
        a = rng.rand(n_samples // 4, 100)
        b = rng.rand(n_samples, 100)
        time1 = time.time()
        transport = ot.da.OTDA_sinkhorn()
        transport.fit(a, b)
        G1 = transport.G
        time2 = time.time()
        transport = ot.gpu.da.OTDA_sinkhorn()
        transport.fit(a, b)
        G2 = transport.G
        time3 = time.time()
        print("Normal sinkhorn, time: {:6.2f} sec ".format(time2 - time1))
        describe_res(G1)
        print("   GPU sinkhorn, time: {:6.2f} sec ".format(time3 - time2))
        describe_res(G2)

        np.testing.assert_allclose(G1, G2, rtol=1e-5, atol=1e-5)


@pytest.mark.skipif(nogpu, reason="No GPU available")
def test_gpu_sinkhorn_lpl1():

    rng = np.random.RandomState(0)

    def describe_res(r):
        print("min:{:.3E}, max:{:.3E}, mean:{:.3E}, std:{:.3E}"
              .format(np.min(r), np.max(r), np.mean(r), np.std(r)))

    for n_samples in [50, 100, 500]:
        print(n_samples)
        a = rng.rand(n_samples // 4, 100)
        labels_a = np.random.randint(10, size=(n_samples // 4))
        b = rng.rand(n_samples, 100)
        time1 = time.time()
        transport = ot.da.OTDA_lpl1()
        transport.fit(a, labels_a, b)
        G1 = transport.G
        time2 = time.time()
        transport = ot.gpu.da.OTDA_lpl1()
        transport.fit(a, labels_a, b)
        G2 = transport.G
        time3 = time.time()
        print("Normal sinkhorn lpl1, time: {:6.2f} sec ".format(
            time2 - time1))
        describe_res(G1)
        print("   GPU sinkhorn lpl1, time: {:6.2f} sec ".format(
            time3 - time2))
        describe_res(G2)

        np.testing.assert_allclose(G1, G2, rtol=1e-5, atol=1e-5)