transfusion-pytorch

repository·main·Indexed 23 days ago

https://github.com/lucidrains/transfusion-pytorch

A PyTorch implementation of the Transfusion model, which utilizes a single multi-modal transformer to predict the next text token and perform flow matching for continuous modalities such as images. The library includes the Transfusion model class, support for modality encoders and decoders, and utilities for multimodal data loading and sampling.

Tokens
3.9K
Snippets
4
Records
23
Agent score
80%

What's inside transfusion-pytorch

  1. Format input data for Transfusion

    main

    The model accepts a list of sequences. Each sequence is a list containing interleaved text and modality tensors.

    Data Types:

    • Text: Represented by torch.long tensors.
    • Modalities: Represented by torch.float tensors.

    Multi-modality indexing: When using multiple modalities, you can pass a tuple (modality_index, Tensor) for float tensors to specify which modality the tensor belongs to. The modality_index corresponds to the index in the dim_latent tuple provided during initialization.

  2. Install transfusion-pytorch

    main

    Install the package using pip:

    $ pip install transfusion-pytorch

    To run the included training examples, install with the [examples] extra:

    $ pip install .[examples]

    If you encounter issues with safetensors, ensure the following dependencies are installed and up to date:

    $ pip install -U diffusers transformers accelerate scipy ftfy safetensors
  3. Train and sample from Transfusion

    main

    To train the model, pass the formatted input list to the model instance to compute the loss, then perform backpropagation.

    To generate new content after training:

    • Use model.sample() to generate a multi-modal sample.
    • Use model.generate_text_only(text_tokens, length) for text-only generation (useful for language-first pretraining).
    • Use print_modality_sample(sample) to inspect/print modality samples.
  4. Calculate total loss including text, flow, and reconstruction

    main

    When return_loss=True is passed to the model, it computes a composite loss function:

    1. Text Loss: Autoregressive cross-entropy loss on text tokens (using ignore_index for non-text positions).
    2. Flow Loss: MSE loss between the predicted flow and the target flow (calculated from the noised modality).
    3. Velocity Consistency Loss (Optional): If need_velocity_matching is active, it penalizes differences between the current flow and an EMA model's flow to 'straighten' the flow trajectories.
    4. Reconstruction Loss (Optional): If has_recon_loss is enabled, it calculates MSE between the reconstructed modality and the original target.

    The final loss is a weighted sum of these components, controlled by text_loss_weight, flow_loss_weight, velocity_consistency_loss_weight, and reconstruction_loss_weight.

  5. Define Modality Samples and Types

    main

    In Transfusion, data is represented as ModalitySamples. A sample is a list containing text tokens (as torch.long tensors) and modalities (as torch.float tensors or tuples).

    When using tuples for modalities, the format is (modality_type, tensor).

    Key type definitions:

    • ModalitySample: list[Int[''] | Int['_'] | Float['...'] | tuple[int, Float['...']]]
    • ModalityTokenTransform: str | Callable | None
    • RawModalityPositions: list[list[tuple[int, int, int]]] (representing [type, offset, length] for each modality).
  6. How the Transfusion model processes multimodal sequences

    main

    The model uses a joint transformer and flow-matching system. It intersperses text tokens with modality tokens in a single sequence.

    The sequence structure for a modality includes:

    1. Meta Information: A meta_id followed by a character-tokenized string representing the modality's shape (e.g., '3,224,224').
    2. Start of Modality (SOM): A special som_id token.
    3. Modality Content: The actual latent tokens (often flattened or packed).
    4. End of Modality (EOM): A special eom_id token.

    Positional Embeddings:

    • Text: Uses standard rotary embeddings derived from the sequence position.
    • Modalities: Can use Axial Positional Embeddings if add_pos_emb is enabled. These are factorized embeddings that account for the multi-dimensional structure (like height/width) of the modality latents.
  7. Data Formats for Modalities and Text

    main

    The Transfusion model handles two primary types of data in its input sequences:

    1. Text: Represented as torch.long tensors. These are treated as discrete tokens.
    2. Modalities (e.g., images, audio): Represented as torch.float tensors.

    When passing modalities, you can provide them as raw tensors or as a tuple (modality_type, modality_tensor). If a torch.float tensor is provided without a tuple, it is implicitly treated as modality type 0.

    Key constraints:

    • Text tensors must be 1D (torch.long).
    • Modality tensors must match the dimensions and latent channel size specified in the model's modality configuration.
  8. How the Transfusion model handles modalities

    main

    Transfusion treats text and continuous modalities (like images) as part of a single sequence.

    1. Text: Represented by discrete tokens. The model uses standard causal transformer attention.
    2. Modalities: Represented by continuous latents. The model uses Flow Matching to generate these latents.
    3. Transitions: The model uses special tokens to signal the start and end of modalities:
      • [som] (Start of Modality): Triggers the transition from text decoding to continuous flow sampling.
      • [eom] (End of Modality): Signals the end of the continuous sequence, returning the model to text decoding.
    4. Shape Prediction: Before generating a modality, the model predicts a 'meta string' (via a character tokenizer) that describes the target shape (e.g., "256,256"). This shape is then used to initialize the noise for the flow matching process.
  9. Use modality encoders and decoders for images

    main

    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)
  10. Initialize the Transfusion model

    main

    The Transfusion class implements a multi-modal model that combines next-token prediction (for text) and flow matching (for modalities like images).

    Key arguments for Transfusion:

    • num_text_tokens: Vocabulary size for text tokens.
    • dim_latent: Latent dimension(s). Can be a single int for one modality or a tuple[int, ...] for multiple modalities.
    • modality_default_shape: Fallback shape for modalities if the language model does not produce a valid shape. Can be a single tuple or a tuple of tuples for multiple modalities.
    • transformer: A dictionary of configuration for the transformer backbone (e.g., dim, depth).
    • modality_encoder / modality_decoder: (Optional) Modules to automatically handle encoding/decoding of modalities (e.g., images).
    • channel_first_latent: (Optional) Boolean to indicate if latents are channel-first.
    from transfusion_pytorch import Transfusion
    
    model = Transfusion(
        num_text_tokens = 256,
        dim_latent = 384,
        modality_default_shape = (4,),
        transformer = dict(
            dim = 512,
            depth = 8
        )
    )
  11. Access modality-specific configuration with `get_modality_info()`

    main

    To inspect or manipulate the specific components of a particular modality (e.g., its encoder, decoder, or dimension settings), use get_modality_info(modality_type). This returns a ModalityInfo object containing:

    • encoder: The Module used to encode the modality.
    • decoder: The Module used to decode the modality.
    • latent_to_model: Projection from latent space to transformer dimension.
    • model_to_latent: Projection from transformer dimension to latent space.
    • add_pos_emb: Boolean indicating if axial positional embeddings are used.
    • pos_emb_mlp: The MLP used to generate axial positional embeddings.
    • num_dim: The number of dimensions for the modality.
    • dim_latent: The dimensionality of the latent space.
    • default_shape: The fallback shape for this modality.
    • som_id / eom_id: The start and end tokens for this modality type.