Repository navigation
VLM: Onboarding native resolution, native aspect ratio, interleaved VLM training - #1615
Conversation
There was a problem hiding this comment.
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:
- Patchify
- Generate Grids with coordinations
- Padding/ truncate
- 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!
| # 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 |
There was a problem hiding this comment.
n00b question: why we use CLIP mean/std to normalize the dataset? Is it a common practice?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
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.
Co-authored-by: Jiani Wang <[email protected]>
There was a problem hiding this comment.
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.
Co-Authored-By: Ankit Singh <[email protected]>
|
|
||
|
|
||
| # 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. |
There was a problem hiding this comment.
cc @H-Huang who developed our new tokenizer in torchtitan
There was a problem hiding this comment.
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
There was a problem hiding this comment.
@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)}There was a problem hiding this comment.
thanks. I will look into using this.
There was a problem hiding this comment.
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.
wwwjn
left a comment
There was a problem hiding this comment.
LGTM! A quick note for myself - 2 TODO items:
- Double check if Linear layers in Siglip2 model needs
biasterm - 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
left a comment
There was a problem hiding this comment.
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
| # Sort samples by length for better packing | ||
| samples = sorted( | ||
| self.sample_buffer, key=lambda x: len(x["input_ids"]), reverse=True | ||
| ) |
There was a problem hiding this comment.
need more comment here:
I think this is just greedy packing which has linear complexity but may not always provide optimal packing results?
There was a problem hiding this comment.
A qq: Why sort by length is considered "better"?
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
why do we have to do this? I could understand the L and D part, but is a varying N problematic?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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?
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 |
There was a problem hiding this comment.
I have several questions here:
- 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.
- 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?
- Given today's torchtitan FlexAttn infra, it relies on the
attn_mask_typeas the key to differentiate masks. If both encoder and decode use the same type, saycausalthen I think there will be collision. We should refactor this to allow for general use case.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
thanks. I will look into using this.
| # Sort samples by length for better packing | ||
| samples = sorted( | ||
| self.sample_buffer, key=lambda x: len(x["input_ids"]), reverse=True | ||
| ) |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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) |
There was a problem hiding this comment.
currently just a placeholder. It will be done properly in a flex attention PR.
Co-authored-by: tianyu-l <[email protected]>
|
@lkhphuc Thanks for addressing comments! Great to know that you had planned to tackle most questions.
If you could address the tokenizer one (as it involves many LoC lol), we can merge this PR. |
|
I reverted to modified the I also return that SpecialTokens class as part of For the |
There was a problem hiding this comment.
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: |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
@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.
|
Tests failed seems not related because we haven't add any tests for experiment/vlm?! |
|
@lkhphuc Could you rebase and try again? |
|
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. |
tianyu-l
left a comment
There was a problem hiding this comment.
Could you please change all occurrences of vocab_size=2000 to 2048? https://github.com/search?q=repo%3Apytorch%2Ftorchtitan%20vocab_size%3D2000&type=code
c290430 to
47a400f
Compare
|
My bad. Changed them all to 2048. |
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.
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.
…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]>
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.
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.
…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]>
First PR to onboarding modern VLM training to torchtitan.
Features:
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
Nand max image patches lengthL, then we pad the actual image patches to this fixed size.tok_embedding, we obtain tokens of shapeBxS.encoder, we obtain visual tokens of shapeNxL.This requires the dataloader to handle the following aspect:
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)pixel_values.shape == [N, L, D]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:
N, Lto have minimal empty image padding (in batch dimension).In this PR
multimodalexperiment).Llama3Siglip2connecting the two vision encoder and language decoder.Todo: