0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Pytorch】LinearとConv1dってどっちが速いの?

Posted at

結論

基本的にはLinearのほうが速い。

調べること

LinearとConv1dはどちらが速いのかざっくり調べる

コード

Linear

class LinearNet(nn.Module):

    def __init__(self, dim):
        super().__init__()
        self.layer = nn.ModuleList([nn.Linear(dim, dim) for _ in range(5)])

    def forward(self, x):
        for l in self.layer:
            x = l(x)
        return x


start = time.time()
for _ in range(1000):
    l(xl)
print('Linear time: ', time.time() - start)

Conv1d

class Conv1dNet(nn.Module):

    def __init__(self, dim):
        super().__init__()
        self.layer = nn.ModuleList([nn.Conv1d(dim, dim, 1) for _ in range(5)])

    def forward(self, x):
        for l in self.layer:
            x = l(x)
        return x


start = time.time()
for _ in range(1000):
    c(xc)
print('Conv1d time: ', time.time() - start)

検証と結果

以下、LinearNetで計算するtensorのshapeをsl、Conv1dNetで計算するtensorのshapeをscとする

sl = (100, 256), sc = (100, 256, 1)

Linear time: 0.1228024959564209
Conv1d time: 1.3837506771087646

sl = (100, 1, 256), sc = (100, 256, 1)

Linear time: 0.17534923553466797
Conv1d time: 1.3661222457885742

sl = (100, 1024, 256), sc = (100, 256, 1024)

Linear time: 12.256186962127686
Conv1d time: 15.45792818069458

sl = (500, 256), sc = (500, 256, 1)

Linear time: 0.1238257884979248
Conv1d time: 3.9731435775756836

sl = (100, 512), sc = (100, 512, 1)

Linear time: 0.12459373474121094
Conv1d time: 4.35028600692749

まとめ

1次元のデータを扱うときはLinearを使ったほうが速い。
バッチサイズと計算する次元が増えるほどその傾向が顕著。
しかし、計算しない次元が大きくなるとその差は縮まっていく。検証していないが、おそらくある点で越すだろうと予測される

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?