You can provide modality_encoder and modality_decoder to the Transfusion model to automatically handle the transformation between raw modality data (like RGB images) and the latent space used by the transformer.
When using these, ensure modality_default_shape matches the expected shape of the latent representation.
import torch
from torch import nn, randint, randn
from transfusion_pytorch import Transfusion, print_modality_sample
mock_encoder = nn.Conv2d(3, 384, 3, padding = 1)
mock_decoder = nn.Conv2d(384, 3, 3, padding = 1)
model = Transfusion(
num_text_tokens = 12,
dim_latent = 384,
channel_first_latent = True,
modality_default_shape = (4, 4),
modality_encoder = mock_encoder,
modality_decoder = mock_decoder,
transformer = dict(
dim = 512,
depth = 8
)
)
text_and_images = [
[
randint(0, 12, (16,)), # 16 text tokens
randn(3, 8, 8), # (8 x 8) 3 channeled image
randint(0, 12, (8,)), # 8 text tokens
randn(3, 7, 7) # (7 x 7) 3 channeled image
]
]
loss = model(text_and_images)
loss.backward()
one_multimodal_sample = model.sample()
print_modality_sample(one_multimodal_sample)