Skip to content

VLM: Onboarding native resolution, native aspect ratio, interleaved VLM training - #1615

Merged
tianyu-l merged 20 commits into
pytorch:mainfrom
lkhphuc:lkhphuc-vlm
Sep 22, 2025
Merged

tianyu-l merged 20 commits into
pytorch:mainfrom
lkhphuc:lkhphuc-vlm

Conversation

@lkhphuc

@lkhphuc lkhphuc commented Aug 21, 2025 •

Copy link
Copy Markdown
Contributor

First PR to onboarding modern VLM training to torchtitan.

Features:

  • Native Aspect Ratio: not limited to square crops.
  • Native Resolution: images in a batch can have different sizes, no more image tiles and thumbnails.
  • Native Interleaved data: training samples can have variable number of images, interleaved with text at different position. You can train more than just a captioning model.

Design

Distributed training usually does not play nice with input of varying shapes. To handle a varying number of images and image sizes, we requires two additional hyperparameters, number of images per batch N and max image patches length L, then we pad the actual image patches to this fixed size.

Screenshot 2025-08-21 at 16 21 57
  • After tok_embedding, we obtain tokens of shape BxS.
  • After encoder, we obtain visual tokens of shape NxL.
  • We extract the valid visual tokens only
  • Then scatter those tokens to their actual positions in the LLM input tokens.

This requires the dataloader to handle the following aspect:

  • Interleave the correct precise numbers of image tokens in the inputs token based on encoder's patch size and input images' size
  • Convert images/videos to 1D sequence of patchs:
    • rearrange(pixels, 'n (t pt) (h ph) (w pw) c -> n (t h w) (pt p pw c)', pt=temporal_ps, ph=patch_size, pw=patch_size)
    • Pad all image patches sequence to a fixed length and return pixel_values.shape == [N, L, D]
  • Return a grid_thw.shape == [N, L, 3] to keep track of the location indicies of each patches in the images. Padding image can be tracked in the same tensors with values -1.

This result in a very simple and general interface to train modern VLM with interleaved data and native resolution & aspect ratio:

  • Depending on data mixtures, we can set dataloader's hyperparameters N, L to have minimal empty image padding (in batch dimension).
  • Use modern pytorch features (Flex Attention, compile etc) for efficient handling of different attention mask per (padding in sequence dimension).
  • Interface nicely with TP, PP, etc

In this PR

  • Minimal interleaved Obelics dataloader with native resolution and aspect ratio.
    • The dataloader is currently very slow, as it need to download images from internet everytime you run. (Same thing for the current imp in the multimodal experiment).
  • Siglip2 model code, mostly based on HF.
  • VLM model code called Llama3Siglip2 connecting the two vision encoder and language decoder.
  • Minimal infra code for debug model to run
Screenshot 2025-08-21 at 15 25 25

Todo:

  • Add support for captioning HF dataset that has images stored inside the dataset (CC12M like Flux exp?) so it's not super slow to load
  • Flex Attention for encoder.
  • Modify Llama3 tokenizer to add special tokens.
  • Script to combine Siglip2 + Llama3 weights and load.
  • Test Siglip2 encoder correctness.
  • Multimodal CE loss to correct for image token bias
  • All the parallelisms DP, CP, TP, PP.

@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Aug 21, 2025

@wwwjn wwwjn left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for making the great PR! I learned a lot from this PR personally. However, I feel like the data preprocessing part in mm_collator_nld.py is a little bit hard to follow and read.

For image preprocessing, it mainly happens inmm_collator_nld.py , and the collator functions contains following steps for images:

  1. Patchify
  2. Generate Grids with coordinations
  3. Padding/ truncate
  4. Assemble as batched outputs

And text preprocessing is mainly handled in mm_dataset.py, which also contains several steps, eg padding with <image> tokens, Tokenization, mask out <image> tokens in label.

I was wondering can we future split the image and text preprocessing function into smaller code pieces, adding tensor shape hints, or even adding examples like experiments/multimodal? In this way, we could increase readability and easy to debug

The VLM modeling parts LGTM, it's clear structured!

Comment thread tests/assets/tokenizer/tokenizer.json Resolved
Comment on lines +242 to +245
# Normalize with OpenAI CLIP mean/std
mean = np.array([0.48145466, 0.4578275, 0.40821073])
std = np.array([0.26862954, 0.26130258, 0.27577711])
img_array = (img_array - mean) / std

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

n00b question: why we use CLIP mean/std to normalize the dataset? Is it a common practice?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is dependent on the pretrained vision encoder. We hardcoded it here because Siglip2 is trained with this normalization.
Ideally it should be part of the model_args because it depends on the model, and we access it here. However the current API does not expose model_args to the build_dataloader function. Should we expose it?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previously we want to separate dataloader and model because they are unrelated, and tokenizer are the bridge between these two for text inputs. From the diagram and the code, seems that for image inputs, the VisionTransformer + projector works equivalently as bridge between Llama model and dataloader. As we only support Siglip2 encoder now, we can hardcode is and I think we shouldn't expose model_args to build_dataloader now

btw do we need to load pre-trained VisionTransformer weight iduring pre-training? Or during pre-training, it is trained together with the main llama model?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes we will load both pretrained siglip2 and llama3. "VLM pretraining" usually refers to starting with separately pretrained vision encoder and text decoder, only the projector connecting them are randomly init.

Comment thread torchtitan/experiments/vlm/README.md Resolved
Comment thread torchtitan/experiments/vlm/README.md Resolved
Comment thread torchtitan/experiments/vlm/README.md Resolved
Co-authored-by: Jiani Wang <[email protected]>

@lkhphuc lkhphuc left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for your detailed review Jiani. We have substantially refactor the dataloader part as your suggestion, as well as make some modification to make it more robust.

Now we can run both interleaved Obelics dataset and CC12M captioning dataset. The CC12M dataset from HF have images included in the dataset itself, so should run substantially faster once it's downloaded.
We include both here still to demonstrate the generality of the approach, we can handle both interleave and captioning data with no code or model change.

We also include the Sample Packing features to the dataloader. This is analogous to "document packing" in Llama3 training, and only pack the LLM samples ("<|image|> text text... <|eos|> text <|image|>"). The vision encoder still operates on images with shape NxLxD where each n in N is a single image.

Image

Co-Authored-By: Ankit Singh <[email protected]>

@wwwjn wwwjn left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the nice refactor! I really enjoying reading and reviewing the PR. Add more comments with minor issues, please address them before we merge.

cc @tianyu-l

Comment thread torchtitan/experiments/vlm/README.md Resolved
Comment thread torchtitan/experiments/vlm/README.md Resolved
Comment thread torchtitan/experiments/vlm/README.md Resolved


# HACK: couldn't figure out how to modify the HF tokenizer's json
# to make these attribute accesible. Ideally these should be accesible from the tokenizer itself.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

cc @H-Huang who developed our new tokenizer in torchtitan

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this not handled by having these fields in tokenizer_config.json? Need @H-Huang 's feedback.
torchtune is having a specialized tokenizer files for such model
https://github.com/pytorch/torchtune/blob/main/torchtune/models/llama4/_tokenizer.py#L59
If needed we should do special treatment, e.g. either doing special treatment for every vlm model, or creating a subclass of text tokenizer, or directly add the treatment in text tokenizer https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/tokenizer.py#L38

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lkhphuc Can you try using get_added_tokens_decoder(), you should be able to see the special tokens and their IDs. If this works I don't think we need to add this config.

Example:

{0: AddedToken("[PAD]", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
 100: AddedToken("[UNK]", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
 101: AddedToken("[CLS]", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
 102: AddedToken("[SEP]", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True),
 103: AddedToken("[MASK]", rstrip=False, lstrip=False, single_word=False, normalized=False, special=True)}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks. I will look into using this.

@lkhphuc lkhphuc left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank @wwwjn. I've addressed some comments and will leave the other for future PRs if that's ok.
Big thanks to @Griffintaur for doing all the dataloader work.

Comment thread torchtitan/experiments/vlm/README.md Resolved

@wwwjn wwwjn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! A quick note for myself - 2 TODO items:

  1. Double check if Linear layers in Siglip2 model needs bias term
  2. Remove the eos_id being passed into model to calculate FlexAttention Mask.

I'm ok with these 2 items being addressed in the following PRs, as long as we keep track of them

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks a lot for the work! Sorry I left many comments.

One big concern for me is on the FSDP2 gradient treatment correctness with ignore_idx.

Also at some point we should add CI testing for this model, similar to https://github.com/pytorch/torchtitan/blob/main/torchtitan/experiments/flux/tests/integration_tests.py

Comment thread torchtitan/experiments/vlm/__init__.py Resolved
Comment thread torchtitan/experiments/vlm/__init__.py Resolved
Comment thread torchtitan/experiments/vlm/__init__.py Resolved
Comment thread torchtitan/experiments/vlm/__init__.py Resolved
Comment thread torchtitan/experiments/vlm/__init__.py Resolved
Comment on lines +38 to +41
# Sort samples by length for better packing
samples = sorted(
self.sample_buffer, key=lambda x: len(x["input_ids"]), reverse=True
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need more comment here:
I think this is just greedy packing which has linear complexity but may not always provide optimal packing results?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A qq: Why sort by length is considered "better"?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed greedy packing is not the optimal.
Since we don't use it internally, here we just start with the most simple packing possible to demonstrate the generality of the vlm approach.

Recently huggingface wrote a blog post about this point https://huggingface.co/blog/mmdp#stage-4-packing-smarter-with-knapsacks
I think this could be iterate upon later.

self.batch_size = batch_size

# Initialize buffers
self.sample_buffer: deque = deque(maxlen=buffer_size)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what is buffer_size? Its definition is not very clear from job_config.py
also, does maxlen matter? below you are explicitly guarding on buffer_size anyway

"""Add a sample to the buffer."""
self.sample_buffer.append(sample)

if len(self.sample_buffer) >= self.buffer_size:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If buffer_size purely a heuristic? If I set buffer_size to be larger than it needs to be, then it's possible that I have many samples in sample_buffer but has_batch_ready just return False.

In practice how should one decide the size?

If we don't introduce this intermediate buffer, then we can always do pack-as-a-full-sample-is-ready. From what I read the benefit is really supporting

Sort samples by length for better packing

but the greedy algorithm doesn't look optimal to me.



@dataclass
class Training:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think all these fields are related to vision data processing, shall we put them in their own config class? It will make function calling interface simpler, too.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I changed the name to Data, but there are some fields not really about data such as patch size. I still put it here since I need it in the build tokenizer, but build tokenizer does not have access to model args.

"""Vision encoder batch size (N)"""
max_patches_per_image: int = 256
"""Vision encoder sequence length (L)"""
patch_size: int = 16

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe noob question:
If we are doing fine-tuning, should these fields be configurable from run-to-run, or should they stick to what the model was trained on?

In other words:
If things are very different from pre-training, would the fine-tuning quality drop a lot?

By pretraining vs. finetuning, I really mean early phase of training vs. late phases.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the fields about dataloader (N, L) it's really depends on your specific data mixture and compute budget.
For example,

  • if you warmup with short captioning, usually the image resolution (L here) can be quite small, and there is 1 image per captioning sample, so you can set num images N = LLM batch size B.
  • But if you decay with long and detailed captioning or interleaved, you would want to set higher L & S (i.e higher image resolution and sequence length), and thus have to reduce N and B.
    So quality would rather depends on your data and training dynamic, and N, L are just for maximizing training effiency.

For field like patch_size and spatial_merge_size, since they are carried over from pretrained vision encoder and controls the parameter's shape, changing them would drastically change model behaviour.
So yes they should stay the same across all VLM pretraining stages.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For field like patch_size and spatial_merge_size, since they are carried over from pretrained vision encoder and controls the parameter's shape, changing them would drastically change model behaviour.
So yes they should stay the same across all VLM pretraining stages.

If so, should they be part of ModelArgs and be part of checkpoint? If a checkpoint doesn't provide these fields, then finetuning / continued pretraining is blocked.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, patch size and spatial merge size (just added) is part of of model args.
I replicated it here in the job config since I don't have access to model_args in the build_dataloader function.

patches = torch.stack(patch_list)
grids = torch.stack(grid_list)

# Pad to max_images_per_batch with empty images

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we have to do this? I could understand the L and D part, but is a varying N problematic?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good question. This is indeed not needed now, but a key insight to enable clean integration with Pipeline parallel.
Since PP do a microbatch splitting of inputs_BS tokens along B, we will also need to split pixel_values_NLD along N.
Padding along N will make the splitted microbatches have the corrects text and images.

Sorry if confusing, I will expalin in more details for the PP PR.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see. I had though there is no clear mapping between B rows and N row.
According to what you said for PP, I'm guessing you will introduce some sort of rigid structure, e.g. "each row of B corresponds to x rows of N where x is fixed"?

Maybe a related question: in CP how are you going to deal with mapping images to the split text?

tianyu-l pushed a commit that referenced this pull request Sep 16, 2025
As suggested in the comment
[here](#1615 (comment))
for PR #1615 , I refactored all the dataset config instance to a common
one in `torchtitan/datasets/__init__.py`, with a common name
`sample_processor`.
Doing it here to make it easier to review and limit scope of the other
PR.
self.out_proj = nn.Linear(self.dim, self.dim)

self.attn = build_attention(
use_flex_attn=True, attn_mask_type=args.attn_mask_type

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I have several questions here:

  1. IIRC you told me for image embedding, the mask should not be "everything attends to everything else" instead of causal? But here you are using causal.
  2. What about the decode part, should the image also attend within the image tokens? Or should we just use (block) causal. Could you explain a bit why?
  3. Given today's torchtitan FlexAttn infra, it relies on the attn_mask_type as the key to differentiate masks. If both encoder and decode use the same type, say causal then I think there will be collision. We should refactor this to allow for general use case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC you told me for image embedding, the mask should not be "everything attends to everything else" instead of causal? But here you are using causal.

For vision encoder, yes, image tokens should attend to each other. But this PR has not address that part yet. I planned to do it in a separate PR later. This flex attn here is just a placeholder for now. sorry for confusion.

What about the decode part, should the image also attend within the image tokens? Or should we just use (block) causal. Could you explain a bit why?

There is no VLM papers (that I know of) use image-block + text-causal mask. So use causal decoder should works just fine. I think the reason is historically it's very inefficient since Flash Attention doesn't support it.
In my exp, "image-block + text-causal" should works just as well or better, and we can leverage Flex Attention to do that. I could try to upstream the flex attention part for this as well if you're interested.

Given today's torchtitan FlexAttn infra, it relies on the attn_mask_type as the key to differentiate masks. If both encoder and decode use the same type, say causal then I think there will be collision. We should refactor this to allow for general use case.

Good point. I haven't considered that.

@lkhphuc lkhphuc left a comment •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

THanks for the detailed reviews. I addressed some comments, and planned to address the other in the follow up PRs to avoid balooning this first PR.
I will look into cleaning up the tokenizer's special tokens part, and the remaining comments later.

"""Vision encoder batch size (N)"""
max_patches_per_image: int = 256
"""Vision encoder sequence length (L)"""
patch_size: int = 16

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the fields about dataloader (N, L) it's really depends on your specific data mixture and compute budget.
For example,

  • if you warmup with short captioning, usually the image resolution (L here) can be quite small, and there is 1 image per captioning sample, so you can set num images N = LLM batch size B.
  • But if you decay with long and detailed captioning or interleaved, you would want to set higher L & S (i.e higher image resolution and sequence length), and thus have to reduce N and B.
    So quality would rather depends on your data and training dynamic, and N, L are just for maximizing training effiency.

For field like patch_size and spatial_merge_size, since they are carried over from pretrained vision encoder and controls the parameter's shape, changing them would drastically change model behaviour.
So yes they should stay the same across all VLM pretraining stages.



# HACK: couldn't figure out how to modify the HF tokenizer's json
# to make these attribute accesible. Ideally these should be accesible from the tokenizer itself.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks. I will look into using this.

Comment on lines +38 to +41
# Sort samples by length for better packing
samples = sorted(
self.sample_buffer, key=lambda x: len(x["input_ids"]), reverse=True
)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Indeed greedy packing is not the optimal.
Since we don't use it internally, here we just start with the most simple packing possible to demonstrate the generality of the vlm approach.

Recently huggingface wrote a blog post about this point https://huggingface.co/blog/mmdp#stage-4-packing-smarter-with-knapsacks
I think this could be iterate upon later.

labels = labels[:, :seq_len]

# Convert padding tokens to ignore_idx in labels
labels[labels == padding_idx] = ignore_idx

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I planned to address it later to keep this PR MVP for running, without too many VLM-specific detail.
This will be handled in the loss function.

self.out_proj = nn.Linear(self.dim, self.dim)

self.attn = build_attention(
use_flex_attn=True, attn_mask_type=args.attn_mask_type

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

IIRC you told me for image embedding, the mask should not be "everything attends to everything else" instead of causal? But here you are using causal.

For vision encoder, yes, image tokens should attend to each other. But this PR has not address that part yet. I planned to do it in a separate PR later. This flex attn here is just a placeholder for now. sorry for confusion.

What about the decode part, should the image also attend within the image tokens? Or should we just use (block) causal. Could you explain a bit why?

There is no VLM papers (that I know of) use image-block + text-causal mask. So use causal decoder should works just fine. I think the reason is historically it's very inefficient since Flash Attention doesn't support it.
In my exp, "image-block + text-causal" should works just as well or better, and we can leverage Flex Attention to do that. I could try to upstream the flex attention part for this as well if you're interested.

Given today's torchtitan FlexAttn infra, it relies on the attn_mask_type as the key to differentiate masks. If both encoder and decode use the same type, say causal then I think there will be collision. We should refactor this to allow for general use case.

Good point. I haven't considered that.

pixel_masks_NL: torch.BoolTensor,
grid_hw: torch.LongTensor,
):
init_attention_mask(pixel_masks_NL, eos_id=self.eos_id)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

currently just a placeholder. It will be done properly in a flex attention PR.

@tianyu-l

Copy link
Copy Markdown
Contributor

@lkhphuc Thanks for addressing comments! Great to know that you had planned to tackle most questions.

I will look into cleaning up the tokenizer's special tokens part, and the remaining comments later.

If you could address the tokenizer one (as it involves many LoC lol), we can merge this PR.

@lkhphuc

lkhphuc commented Sep 19, 2025 •

Copy link
Copy Markdown
Contributor Author

I reverted to modified the tests/assets/tokenizer/ files for now.
For the special tokens, I put them in a dataclass and construct it with the actual values fetch from the tokenizer. With this, if the tokenizer does not have some special tokens required, the dataclass construction will throws error.

I also return that SpecialTokens class as part of extra_inputs from the dataloader, so it can be used by the model during forward pass without intrusive changes to train.py

For the Llama3Siglip2ModelArgs, I keep it to subclassing Llama3 model args instead of putting it as child, as that were giving me some error during update_from_job_config due to side effect. Plus, this makes the model args parallel to the model, as Llama3Siglip2 is a subclass of Llama3 as well.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: maybe we should put these utils files into a folder, e.g. datasets/utils/text.py. Doesn't have to be done in this PR tho.



@dataclass
class SpecialTokens:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For the special tokens, I put them in a dataclass and construct it with the actual values fetch from the tokenizer. With this, if the tokenizer does not have some special tokens required, the dataclass construction will throws error.

Sorry I'm still confused by why we need this data class -- is it because we'd like to access these fields directly from tokenizer, but they are not there per https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/tokenizer.py#L58-L61?

I think we should extend the base tokenizer class to have a multimodal subclass, instead of passing this dataclass around.
cc @H-Huang to confirm on the right design.

I'm OK with landing this for now, but please follow up with the inheritance solution.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lkhphuc I think we should have this dataclass as part of the Tokenizer, when we create the tokenizer we should initialize these special tokens if they are provided as part of the config, otherwise leave it to an unset value. Then we access these tokens are part of the tokenizer instance.

@lkhphuc

lkhphuc commented Sep 20, 2025

Copy link
Copy Markdown
Contributor Author

Tests failed seems not related because we haven't add any tests for experiment/vlm?!
All stems from CUDA assert error on Llama3 RMSNorm, DeepSeek and one with float8.

@tianyu-l

Copy link
Copy Markdown
Contributor

@lkhphuc
hmm not sure what happened, as other tests are passing https://github.com/pytorch/torchtitan/actions

Could you rebase and try again?

@lkhphuc

lkhphuc commented Sep 20, 2025

Copy link
Copy Markdown
Contributor Author

It's because the tokenizer vocab size is 2001, while the llama3 and deepseekv3 debugmodel vocab_size is 2000, leads to index error on embedding.
I increased them to 2048 and tests passed locally. Hope that's OK.

@tianyu-l tianyu-l left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lkhphuc

lkhphuc commented Sep 22, 2025

Copy link
Copy Markdown
Contributor Author

My bad. Changed them all to 2048.

@tianyu-l
tianyu-l merged commit c9cb304 into pytorch:main Sep 22, 2025
@lkhphuc
lkhphuc deleted the lkhphuc-vlm branch September 22, 2025 11:31
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
As discussed
[here](pytorch#1615 (comment))
and
[here](pytorch#1615 (comment)),
I create this PR to limit the scope of the other PR pytorch#1615 .

When subclassing a torchtitan's model for training, the call to
`self.init_weights()` inside model `__init__` could have side effect.
Solution is to delete this line because in practice it currently has no
effect, we explicitly called `m.init_weights(buffer_device)` in
`train.py` already.
Flux model already doesn't do it.
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
As suggested in the comment
[here](pytorch#1615 (comment))
for PR pytorch#1615 , I refactored all the dataset config instance to a common
one in `torchtitan/datasets/__init__.py`, with a common name
`sample_processor`.
Doing it here to make it easier to review and limit scope of the other
PR.
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 13, 2026
…LM training (pytorch#1615)

First PR to onboarding modern VLM training to torchtitan.

## Features:
- Native Aspect Ratio: not limited to square crops.
- Native Resolution: images in a batch can have different sizes, no more
image tiles and thumbnails.
- Native Interleaved data: training samples can have variable number of
images, interleaved with text at different position. You can train more
than just a captioning model.

## Design

Distributed training usually does not play nice with input of varying
shapes. To handle a varying number of images and image sizes, we
requires two additional hyperparameters, number of images per batch `N`
and max image patches length `L`, then we pad the actual image patches
to this fixed size.

<img width="1398" height="840" alt="Screenshot 2025-08-21 at 16 21 57"
src="https://github.com/user-attachments/assets/63fcbbc1-c587-4a63-8246-411cb72f5789"
/>

- After `tok_embedding`, we obtain tokens of shape `BxS`.
- After `encoder`, we obtain visual tokens of shape `NxL`.
- We extract the valid visual tokens only 
- Then scatter those tokens to their actual positions in the LLM input
tokens.

This requires the dataloader to handle the following aspect:
- Interleave the correct precise numbers of image tokens in the inputs
token based on encoder's patch size and input images' size
- Convert images/videos to 1D sequence of patchs:
- `rearrange(pixels, 'n (t pt) (h ph) (w pw) c -> n (t h w) (pt p pw
c)', pt=temporal_ps, ph=patch_size, pw=patch_size)`
- Pad all image patches sequence to a fixed length and return
`pixel_values.shape == [N, L, D]`
- Return a `grid_thw.shape == [N, L, 3]` to keep track of the location
indicies of each patches in the images. Padding image can be tracked in
the same tensors with values `-1`.
  
This result in a very simple and general interface to train modern VLM
with interleaved data and native resolution & aspect ratio:
- Depending on data mixtures, we can set dataloader's hyperparameters
`N, L` to have minimal empty image padding (in batch dimension).
- Use modern pytorch features (Flex Attention, compile etc) for
efficient handling of different attention mask per (padding in sequence
dimension).
- Interface nicely with TP, PP, etc

## In this PR
- Minimal interleaved Obelics dataloader with native resolution and
aspect ratio.
- The dataloader is currently very slow, as it need to download images
from internet everytime you run. (Same thing for the current imp in the
`multimodal` experiment).
- Siglip2 model code, mostly based on HF.
- VLM model code called `Llama3Siglip2` connecting the two vision
encoder and language decoder.
- Minimal infra code for debug model to run

<img width="1672" height="1303" alt="Screenshot 2025-08-21 at 15 25 25"
src="https://github.com/user-attachments/assets/c5c70ae2-04cf-4459-90d7-77d045291b88"
/>


## Todo:
- [x] Add support for captioning HF dataset that has images stored
inside the dataset (CC12M like Flux exp?) so it's not super slow to load
- Flex Attention for encoder.
- Modify Llama3 tokenizer to add special tokens.
- Script to combine Siglip2 + Llama3 weights and load. 
- Test Siglip2 encoder correctness.
- Multimodal CE loss to correct for image token bias
- All the parallelisms DP, CP, TP, PP.

---------

Co-authored-by: Jiani Wang <[email protected]>
Co-authored-by: Ankit Singh <[email protected]>
Co-authored-by: tianyu-l <[email protected]>
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
As discussed
[here](pytorch#1615 (comment))
and
[here](pytorch#1615 (comment)),
I create this PR to limit the scope of the other PR pytorch#1615 .

When subclassing a torchtitan's model for training, the call to
`self.init_weights()` inside model `__init__` could have side effect.
Solution is to delete this line because in practice it currently has no
effect, we explicitly called `m.init_weights(buffer_device)` in
`train.py` already.
Flux model already doesn't do it.
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
As suggested in the comment
[here](pytorch#1615 (comment))
for PR pytorch#1615 , I refactored all the dataset config instance to a common
one in `torchtitan/datasets/__init__.py`, with a common name
`sample_processor`.
Doing it here to make it easier to review and limit scope of the other
PR.
xrsrke pushed a commit to NousResearch/torchtitan that referenced this pull request Feb 25, 2026
…LM training (pytorch#1615)

First PR to onboarding modern VLM training to torchtitan.

## Features:
- Native Aspect Ratio: not limited to square crops.
- Native Resolution: images in a batch can have different sizes, no more
image tiles and thumbnails.
- Native Interleaved data: training samples can have variable number of
images, interleaved with text at different position. You can train more
than just a captioning model.

## Design

Distributed training usually does not play nice with input of varying
shapes. To handle a varying number of images and image sizes, we
requires two additional hyperparameters, number of images per batch `N`
and max image patches length `L`, then we pad the actual image patches
to this fixed size.

<img width="1398" height="840" alt="Screenshot 2025-08-21 at 16 21 57"
src="https://github.com/user-attachments/assets/63fcbbc1-c587-4a63-8246-411cb72f5789"
/>

- After `tok_embedding`, we obtain tokens of shape `BxS`.
- After `encoder`, we obtain visual tokens of shape `NxL`.
- We extract the valid visual tokens only 
- Then scatter those tokens to their actual positions in the LLM input
tokens.

This requires the dataloader to handle the following aspect:
- Interleave the correct precise numbers of image tokens in the inputs
token based on encoder's patch size and input images' size
- Convert images/videos to 1D sequence of patchs:
- `rearrange(pixels, 'n (t pt) (h ph) (w pw) c -> n (t h w) (pt p pw
c)', pt=temporal_ps, ph=patch_size, pw=patch_size)`
- Pad all image patches sequence to a fixed length and return
`pixel_values.shape == [N, L, D]`
- Return a `grid_thw.shape == [N, L, 3]` to keep track of the location
indicies of each patches in the images. Padding image can be tracked in
the same tensors with values `-1`.
  
This result in a very simple and general interface to train modern VLM
with interleaved data and native resolution & aspect ratio:
- Depending on data mixtures, we can set dataloader's hyperparameters
`N, L` to have minimal empty image padding (in batch dimension).
- Use modern pytorch features (Flex Attention, compile etc) for
efficient handling of different attention mask per (padding in sequence
dimension).
- Interface nicely with TP, PP, etc

## In this PR
- Minimal interleaved Obelics dataloader with native resolution and
aspect ratio.
- The dataloader is currently very slow, as it need to download images
from internet everytime you run. (Same thing for the current imp in the
`multimodal` experiment).
- Siglip2 model code, mostly based on HF.
- VLM model code called `Llama3Siglip2` connecting the two vision
encoder and language decoder.
- Minimal infra code for debug model to run

<img width="1672" height="1303" alt="Screenshot 2025-08-21 at 15 25 25"
src="https://github.com/user-attachments/assets/c5c70ae2-04cf-4459-90d7-77d045291b88"
/>


## Todo:
- [x] Add support for captioning HF dataset that has images stored
inside the dataset (CC12M like Flux exp?) so it's not super slow to load
- Flex Attention for encoder.
- Modify Llama3 tokenizer to add special tokens.
- Script to combine Siglip2 + Llama3 weights and load. 
- Test Siglip2 encoder correctness.
- Multimodal CE loss to correct for image token bias
- All the parallelisms DP, CP, TP, PP.

---------

Co-authored-by: Jiani Wang <[email protected]>
Co-authored-by: Ankit Singh <[email protected]>
Co-authored-by: tianyu-l <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants