test_shape_prop.py 2.08 KB
Newer Older
1
2
import pytest
import torch
3
4
from packaging import version

5
from colossalai.testing.utils import clear_cache_before_run, parameterize
6
from tests.test_analyzer.test_fx.zoo import tm_models, tmm_models
7
8
9
10
11
12

try:
    from colossalai._analyzer._subclasses import MetaTensorMode
    from colossalai._analyzer.fx import symbolic_trace
    from colossalai._analyzer.fx.passes.shape_prop import shape_prop_pass
    from colossalai._analyzer.fx.symbolic_profile import register_shape_impl
13

14
15
16
17
    @register_shape_impl(torch.nn.functional.linear)
    def linear_impl(*args, **kwargs):
        assert True
        return torch.nn.functional.linear(*args, **kwargs)
18

19
20
21
22
23
24
except:
    pass


def _check_gm_validity(gm: torch.fx.GraphModule):
    for node in gm.graph.nodes:
25
        assert node.meta["info"].outputs, f"In {gm.__class__.__name__}, {node} has no output shape."
26
        if node.op in [
27
28
29
            "call_module",  # can apply to params
            "call_function",  # can apply to params
            "call_method",  # can apply to params
30
        ]:
31
            assert hasattr(node.meta["info"], "inputs"), f"In {gm.__class__.__name__}, {node} has no input shape."
32
33


34
@pytest.mark.skipif(version.parse(torch.__version__) < version.parse("1.12.0"), reason="torch version < 12")
35
@clear_cache_before_run()
36
@parameterize("m", tm_models)
37
38
39
40
41
42
43
44
45
46
47
48
def test_torchvision_shape_prop(m):
    with MetaTensorMode():
        model = m()
        data = torch.rand(100, 3, 224, 224)
    meta_args = {
        "x": data,
    }
    gm = symbolic_trace(model, meta_args=meta_args)
    shape_prop_pass(gm, data)
    _check_gm_validity(gm)


49
@pytest.mark.skipif(version.parse(torch.__version__) < version.parse("1.12.0"), reason="torch version < 12")
50
@clear_cache_before_run()
51
@parameterize("m", tmm_models)
52
53
54
55
56
57
58
def test_timm_shape_prop(m):
    with MetaTensorMode():
        model = m()
        data = torch.rand(100, 3, 224, 224)
    meta_args = {
        "x": data,
    }
59

60
61
62
63
64
65
    gm = symbolic_trace(model, meta_args=meta_args)
    shape_prop_pass(gm, data)
    _check_gm_validity(gm)


if __name__ == "__main__":
66
67
    test_torchvision_shape_prop()
    test_timm_shape_prop()