Repository navigation
Add Music Flamingo #43538
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Add Music Flamingo #43538
Changes from all commits
Commits
Show all changes
92 commits
Select commit
Hold shift + click to select a range
caf33f1
Music flamingo
lashahub b69a9d1
Fix pos embeddings
lashahub b4acc17
Merge branch 'huggingface:main' into main
lashahub cf1e9bc
Method arg docstrings
lashahub 44e801b
Add tests & docs
lashahub f0956e3
Merge branch 'huggingface:main' into main
lashahub c973445
Fix AF3 dtype bug
lashahub e3a17fb
Fix the MF performance issue
lashahub 627dee8
Fix pos embeddings
lashahub e9df30d
Merge branch 'main' of https://github.com/lashahub/transformers
lashahub 4c48132
Fix embeddings & format
lashahub d67c114
Remove external deps
lashahub aedd341
Update processor token names
lashahub 87d55a9
Cleanup
lashahub be22746
Simplify RotaryEmbedding to lang-only
lashahub e5b4677
Reuse AF3 config classes
lashahub d7e0bcb
Trim+rename rotary embedding
lashahub 74af4fa
Call parent _init_weights first and drop rotary einsum
lashahub d622368
Precompute rotary cache at init
lashahub cab3937
Use modular processor pattern for MusicFlamingo
lashahub 9dd94a0
Remove audio-only inference example
lashahub 767a1d5
Refactor Audio Feature Casting Path
lashahub 9119660
Clarify private source repo
lashahub fc8ab3a
Clean up modular
lashahub 5159745
Move config to modular
lashahub 4aae4ff
Formatting
lashahub ffef7db
Remove dummy
lashahub 90148ed
Derive musicflamingo timing and rotary config
lashahub 87cb03f
Llama style rotary embeddings
lashahub 5abac95
Added reproducer comments
lashahub f4a1b68
Expose _init_weights for modular.
ebezzam 3b9290f
Satisfy repo checks
ebezzam 82ab1ef
Align MusicFlamingo rotary with Llama style
lashahub e993dea
Move MusicFlamingo _init_weights to encoder
lashahub 2d88557
Keep old behavior
lashahub 27024f1
Move MusicFlamingo rotary settings into encoder rope_parameters
lashahub 10797b9
Use AutoConfig in AF3/MF
lashahub f49014f
Align MusicFlamingo RoTE with Llama RoPE conventions
lashahub f465d3d
Update outdated fixtures
lashahub 4224af5
init_weights without changing others
ebezzam 2cbf219
FIx import
ebezzam a25c8a6
Remove backward compat
lashahub 3ed73a8
Merge branch 'main' into modular-mf
lashahub f2e7d3f
Regenerate modeling for MF
lashahub 445cd24
Fix AF3 batch inference bug
lashahub fc25c48
Simplify config and nit.
ebezzam 664e7b1
Conform more to transformers convention, e.g. removing unused code pa…
ebezzam bbca79a
Add another possible AF3 prefix.
ebezzam 69c9bee
Merge branch 'main' into modular-mf
ebezzam 17846d9
Use auto_docstring and update docstrings.
ebezzam 24fbaa7
Nits
ebezzam e25d377
Nit for review
ebezzam c99fc0a
Shift RoTE to main model so that encoder can be directly used from AF3.
ebezzam 9bb0c53
Refactoring nit.
ebezzam e9528a6
Fix init
lashahub 13af64d
Fix some failing tests
lashahub a34e981
Fix AF3 & MF and add batching tests
lashahub 702eb27
Fix audio embedding masking (bad post length)
ebezzam a32520c
Nits and remove since same as GLM was bug in post length computation
ebezzam 7750bb5
Simplify MF as AF3, and style checks.
ebezzam 74417f6
Merge branch 'main' into modular-mf
ebezzam 54bfecc
New config after merge and modular update.
ebezzam 2f2b552
Merge branch 'main' into modular-mf
ebezzam 612840f
Address music flamingo tests, and some cleanup.
ebezzam 2c3e583
style check
ebezzam a20e163
Regenerate config.
ebezzam fdb849a
Update fixtures.
ebezzam 057ad88
Nits
ebezzam 0442a67
Merge branch 'modular-mf' of github.com:lashahub/transformers into mo…
ebezzam 7f04d2d
Nit
ebezzam 66ce201
Merge branch 'huggingface:main' into modular-mf
lashahub 7e06d27
Improve RoTE config
lashahub d423510
Refine MusicFlamingo rotary time handling
lashahub e79475b
Simplification, and update AF3 processor for better modular
ebezzam 6a1add4
Fix torch export
ebezzam e05b767
Simplify modular, including upstreaming input_ids input to get_audio_…
ebezzam edcffef
Remove upstreaming of input_ids to get_audio_features, and remove aud…
ebezzam e986996
Switch to MoonshineRotaryEmbedding, and cleanup.
ebezzam ad76e28
Remove hardcoded MusicFlamingo partial_rotary_factor
lashahub 8e0dc3b
Update fixtures
lashahub a46aa1c
Compile re.sub
ebezzam 836da94
Merge branch 'modular-mf' of github.com:lashahub/transformers into mo…
ebezzam 1089477
Update src/transformers/models/musicflamingo/modular_musicflamingo.py
ebezzam 2ea5574
Update src/transformers/models/musicflamingo/modular_musicflamingo.py
ebezzam 999737e
Style
ebezzam 1533bec
Merge branch 'main' into modular-mf
ebezzam 6857af9
Update fixtures.
ebezzam cd693fc
Merge branch 'main' into modular-mf
ebezzam 35fc31f
Conditional torch import for processor.
ebezzam a62e7d9
Merge branch 'modular-mf' of github.com:lashahub/transformers into mo…
ebezzam d0d18f2
Merge branch 'main' into modular-mf
ebezzam 47fa938
Merge branch 'main' into modular-mf
ebezzam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,290 @@ | ||
| <!--Copyright 2026 The HuggingFace Team. All rights reserved. | ||
|
|
||
| Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with | ||
| the License. You may obtain a copy of the License at | ||
|
|
||
| http://www.apache.org/licenses/LICENSE-2.0 | ||
|
|
||
| Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
| an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
| specific language governing permissions and limitations under the License. | ||
|
|
||
| ⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be | ||
| rendered properly in your Markdown viewer. | ||
|
|
||
| --> | ||
|
|
||
| *This model was released on 2025-11-03 and added to Hugging Face Transformers on 2026-03-30.* | ||
|
|
||
| # Music Flamingo | ||
|
|
||
| <div class="flex flex-wrap space-x-1"> | ||
| <img alt="PyTorch" src="https://img.shields.io/badge/PyTorch-DE3412?style=flat&logo=pytorch&logoColor=white"> | ||
| <img alt="FlashAttention" src="https://img.shields.io/badge/%E2%9A%A1%EF%B8%8E%20FlashAttention-eae0c8?style=flat"> | ||
| <img alt="SDPA" src="https://img.shields.io/badge/SDPA-DE3412?style=flat&logo=pytorch&logoColor=white"> | ||
| </div> | ||
|
|
||
| ## Overview | ||
|
|
||
| Music Flamingo is a fully open large audio–language model designed for robust understanding and reasoning over music. It builds upon the [Audio Flamingo 3](./audioflamingo3.md) architecture by including **Rotary Time Embeddings (RoTE)**, which injects temporal position information to enable the model to handle audio sequences up to 20 minutes (1200 seconds). | ||
|
|
||
| The model checkpoint is available at: [nvidia/music-flamingo-2601-hf](https://huggingface.co/nvidia/music-flamingo-2601-hf) | ||
|
|
||
| Highlights: | ||
|
|
||
| - Unified audio encoder across speech, sound, and music. | ||
| - **Rotary Time Embeddings (RoTE)** for enhanced temporal modeling, enabling support for **up to 20 minutes of audio**. | ||
| - **Extended long-audio support via windowing and post-pool alignment (up to 20 minutes maximum).** The model processes audio in 30-second windows with a hard limit of 40 windows (20 minutes total). Audio longer than 20 minutes will be truncated. | ||
| - Special sound boundary tokens (`<|sound_bos|>` and `<|sound_eos|>`) for improved audio sequence modeling. | ||
| - Deterministic fusion that preserves sequence length by replacing audio placeholder tokens with audio embeddings. | ||
|
|
||
| This model was contributed by [Lasha Koroshinadze](https://huggingface.co/lashahub) and [Eric Bezzam](https://huggingface.co/bezzam). | ||
|
|
||
| ### Paper | ||
|
|
||
| [Music Flamingo: Scaling Music Understanding in Audio Language Models](https://huggingface.co/papers/2511.10289) | ||
| S. Ghosh, A. Goel, L. Koroshinadze, S. Lee, Z. Kong, J. F. Santos, R. Duraiswami, D. Manocha, W. Ping, M. Shoeybi, B. Catanzaro | ||
| NVIDIA and University of Maryland | ||
| Project: https://research.nvidia.com/labs/adlr/MF/ | ||
|
|
||
| ## Usage | ||
|
|
||
| ### Audio Instruct Mode | ||
|
|
||
| The model supports audio-text instructions, including multi-turn interactions, all processed in batches. | ||
|
|
||
| ➡️ audio + text instruction | ||
|
|
||
| ```python | ||
| from transformers import MusicFlamingoForConditionalGeneration, AutoProcessor | ||
|
|
||
| model_id = "nvidia/music-flamingo-2601-hf" | ||
| processor = AutoProcessor.from_pretrained(model_id) | ||
| model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto") | ||
|
|
||
| conversation = [ | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| {"type": "text", "text": "Describe this track in full detail - tell me the genre, tempo, and key, then dive into the instruments, production style, and overall mood it creates."}, | ||
| {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3"}, | ||
| ], | ||
| } | ||
| ] | ||
|
|
||
| inputs = processor.apply_chat_template( | ||
| conversation, | ||
| tokenize=True, | ||
| add_generation_prompt=True, | ||
| return_dict=True, | ||
| ).to(model.device) | ||
| inputs["input_features"] = inputs["input_features"].to(model.dtype) | ||
|
|
||
| outputs = model.generate(**inputs, max_new_tokens=500) | ||
|
|
||
| decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True) | ||
| print(decoded_outputs) | ||
| ``` | ||
|
|
||
| ➡️ multi-turn: | ||
|
|
||
| ```python | ||
| from transformers import MusicFlamingoForConditionalGeneration, AutoProcessor | ||
|
|
||
| model_id = "nvidia/music-flamingo-2601-hf" | ||
| processor = AutoProcessor.from_pretrained(model_id) | ||
| model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto") | ||
|
|
||
| conversation = [ | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| { | ||
| "type": "text", | ||
| "text": "Write a rich caption that blends the technical details (genre, BPM, key, chords, mix) with how the song feels emotionally and dynamically as it unfolds.", | ||
| }, | ||
| {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3"}, | ||
| ], | ||
| }, | ||
| { | ||
| "role": "assistant", | ||
| "content": [{"type": "text", "text": "This energetic Eurodance anthem at 150 BPM in E major combines bright synth arpeggios with a punchy four-on-the-floor beat..."}], | ||
| }, | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| {"type": "text", "text": "What instruments stand out the most?"}, | ||
| ], | ||
| }, | ||
| ] | ||
|
|
||
| inputs = processor.apply_chat_template( | ||
| conversation, | ||
| tokenize=True, | ||
| add_generation_prompt=True, | ||
| return_dict=True, | ||
| ).to(model.device) | ||
| inputs["input_features"] = inputs["input_features"].to(model.dtype) | ||
|
|
||
| outputs = model.generate(**inputs, max_new_tokens=500) | ||
|
|
||
| decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True) | ||
| print(decoded_outputs) | ||
| ``` | ||
|
|
||
| ➡️ batched inference! | ||
|
|
||
| ```python | ||
| from transformers import MusicFlamingoForConditionalGeneration, AutoProcessor | ||
|
|
||
| model_id = "nvidia/music-flamingo-2601-hf" | ||
| processor = AutoProcessor.from_pretrained(model_id) | ||
| model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto") | ||
|
|
||
| conversations = [ | ||
| [ | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| {"type": "text", "text": "Describe this track in full detail - tell me the genre, tempo, and key, then dive into the instruments, production style, and overall mood it creates."}, | ||
| { | ||
| "type": "audio", | ||
| "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3", | ||
| }, | ||
| ], | ||
| } | ||
| ], | ||
| [ | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| { | ||
| "type": "text", | ||
| "text": "Generate a structured lyric sheet from the input music.", | ||
| }, | ||
| {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_2.mp3"}, | ||
| ], | ||
| } | ||
| ], | ||
| ] | ||
|
|
||
| inputs = processor.apply_chat_template( | ||
| conversations, | ||
| tokenize=True, | ||
| add_generation_prompt=True, | ||
| return_dict=True, | ||
| ).to(model.device) | ||
| inputs["input_features"] = inputs["input_features"].to(model.dtype) | ||
|
|
||
| outputs = model.generate(**inputs, max_new_tokens=500) | ||
|
|
||
| decoded_outputs = processor.batch_decode(outputs[:, inputs.input_ids.shape[1]:], skip_special_tokens=True) | ||
| print(decoded_outputs) | ||
| ``` | ||
|
|
||
| ➡️ Training: | ||
|
|
||
| ```python | ||
| from transformers import MusicFlamingoForConditionalGeneration, AutoProcessor | ||
|
|
||
| model_id = "nvidia/music-flamingo-2601-hf" | ||
| processor = AutoProcessor.from_pretrained(model_id) | ||
| model = MusicFlamingoForConditionalGeneration.from_pretrained(model_id, device_map="auto") | ||
| model.train() | ||
|
|
||
| conversation = [ | ||
| [ | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| {"type": "text", "text": "Break the track down like a critic - list its tempo, key, and chordal motion, then explain the textures, dynamics, and emotional impact of the performance."}, | ||
| {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_1.mp3"}, | ||
| ], | ||
| }, | ||
| { | ||
| "role": "assistant", | ||
| "content": [{"type": "text", "text": "This Eurodance track operates at 150 BPM in E major, with harmonic movement centering on the I-vi-IV-V family. The production features layered synth arpeggios, a four-on-the-floor kick pattern, and a mezzo-soprano lead vocal with bright timbre. Dynamically, the track builds through verses into an anthemic chorus with full synth orchestration and backing vocals, creating an uplifting, euphoric atmosphere characteristic of late 2000s dance-pop."}], | ||
| } | ||
| ], | ||
| [ | ||
| { | ||
| "role": "user", | ||
| "content": [ | ||
| { | ||
| "type": "text", | ||
| "text": "Describe this song from both a technical and artistic lens: mention tempo, harmony, and instrumentation, but also mood, lyrical themes, and structure.", | ||
| }, | ||
| {"type": "audio", "path": "https://huggingface.co/datasets/nvidia/AudioSkills/resolve/main/assets/song_2.mp3"}, | ||
| ], | ||
| }, | ||
| { | ||
| "role": "assistant", | ||
| "content": [{"type": "text", "text": "This electronic pop track combines upbeat production with playful lyrical themes centered around late-night pizza cravings. The structure follows a verse-chorus format with recurring melodic motifs and rhythmic patterns that emphasize the celebratory, lighthearted mood of the piece."}], | ||
| } | ||
|
|
||
| ] | ||
| ] | ||
|
|
||
| inputs = processor.apply_chat_template( | ||
| conversation, | ||
| tokenize=True, | ||
| add_generation_prompt=True, | ||
| return_dict=True, | ||
| output_labels=True, | ||
| ).to(model.device) | ||
| inputs["input_features"] = inputs["input_features"].to(model.dtype) | ||
|
|
||
| loss = model(**inputs).loss | ||
| loss.backward() | ||
| ``` | ||
|
|
||
| ## How the model works | ||
|
|
||
| ### Architecture | ||
|
|
||
| * **Audio Encoder** | ||
| Whisper-style feature extractor + encoder → average-pool over time (stride 2) → LayerNorm. | ||
| Produces per-frame hidden states at the post-pool rate. | ||
|
|
||
| * **Rotary Time Embeddings (RoTE)** | ||
| Applied to the encoder output to inject temporal position information, enabling the model to handle audio sequences up to 20 minutes (1200 seconds). RoTE uses 2D axial rotary embeddings for batch and time dimensions with time-based angle modulation. | ||
|
|
||
| * **MusicFlamingoMultiModalProjector** | ||
| A small MLP that maps encoder features to the language model's hidden size. | ||
|
|
||
| * **MusicFlamingoForConditionalGeneration** | ||
| A causal language model that accepts text embeddings where each audio placeholder token slot is replaced, in place, by an audio frame embedding. Uses special boundary tokens (`<|sound_bos|>` and `<|sound_eos|>`) to mark audio sequences. No sequence-length change is introduced by fusion. | ||
|
|
||
| ### Processor-level alignment | ||
|
|
||
| 1. Each raw waveform is split into fixed-length windows based on the feature extractor’s `chunk_length` (seconds) and `sampling_rate` (Hz). | ||
| 2. For each window, the processor computes the number of post-pool frames `post_pool_len` that the encoder will output (matching the conv/pool schedule). | ||
| 3. The processor expands the audio placeholder token by the total number of post-pool frames across all windows. | ||
| 4. The model later replaces those token positions with the corresponding projected audio embeddings. | ||
|
|
||
| ## Long audio and windowing | ||
|
|
||
| **Important: Maximum audio length is 20 minutes.** Audio longer than this will be truncated. | ||
|
|
||
| * The default setup processes 30-second windows at 16 kHz mono. | ||
| * **The processor enforces a hard limit of 40 windows per sample, resulting in a maximum of 20 minutes of audio (40 windows × 30 seconds).** | ||
| * Rotary Time Embeddings (RoTE) provide position information for sequences up to 20 minutes (1200 seconds). | ||
| * For each window: | ||
|
|
||
| * `mel_len` is the padded mel length. | ||
| * A conv stack reduces time as `conv_output_len = (mel_len - 1) // 2 + 1`. | ||
| * Post-pool frames per window: `post_pool_len = (conv_output_len - 2) // 2 + 1`. | ||
| * An audio placeholder token is expanded to the sum of `post_pool_len` across all windows. | ||
|
|
||
| ## MusicFlamingoConfig | ||
|
|
||
| [[autodoc]] MusicFlamingoConfig | ||
|
|
||
| ## MusicFlamingoProcessor | ||
|
|
||
| [[autodoc]] MusicFlamingoProcessor | ||
|
|
||
| ## MusicFlamingoForConditionalGeneration | ||
|
|
||
| [[autodoc]] MusicFlamingoForConditionalGeneration | ||
| - forward | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.