PyTorch torch.nn.Bilinear function
PyTorch torch.nn Reference Manual
torch.nn.Bilinear is the bilinear layer in PyTorch.
It applies a bilinear transformation to two inputs and is commonly used for feature fusion.
Function definition
torch.nn.Bilinear(in1_features, out_features, out_features, bias=True)
Formula
y = x1 * W * x2 + b
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
Bilinear layer: two 100-dimensional inputs -> 50-dimensional output
bilinear
=
nn.
Bilinear
(
100
,
100
,
50
)
Two inputs
x1
=
torch.
randn
(
4
,
100
)
x2
=
torch.
randn
(
4
,
100
)
output
=
bilinear
(
x1
,
x2
)
(
"Input 1:"
,
x1.
shape
)
(
"Input 2:"
,
x2.
shape
)
(
"Output:"
,
output.
shape
)
Example 2: Feature fusion
Example
import
torch
import
torch.
nn
as
nn
Bilinear feature fusion (similar to Skip-gram)
class
FusionNet
(
nn.
Module
)
:
def
init
(
self
,
dim
=
128
)
:
super
(
FusionNet
,
self
)
.
init
(
)
self
.
bilinear
=
nn.
Bilinear
(
dim
,
dim
,
dim
)
def
forward
(
self
,
feat1
,
feat2
)
:
return
self
.
bilinear
(
feat1
,
feat2
)
model
=
FusionNet
(
)
f1
=
torch.
randn
(
4
,
128
)
f2
=
torch.
randn
(
4
,
128
)
output
=
model
(
f1
,
f2
)
(
"Fused output:"
,
output.
shape
)
Example 3: Number of parameters
Example
import
torch
import
torch.
nn
as
nn
Bilinear layer parameters
bilinear
=
nn.
Bilinear
(
100
,
100
,
50
)
(
"Number of parameters:"
,
sum
(
p.
numel
(
)
for
p
in
bilinear.
parameters
(
)
)
)
(
"Weight shape:"
,
bilinear.
weight
.
shape
)
(50, 100, 100)
Use Cases
- Feature fusion: Multimodal
- Attention Mechanism
- Interaction modeling
Note: Bilinear layers have a large number of parameters; use them with caution.