Repository navigation
Load and fine-tune LongCat-Flash-Lite-Sparse on transformers' longcat_flash - #11620
Conversation
The published checkpoint (LongcatCausalLM) ships no model_type, auto_map or modeling code, so AutoConfig raised "Unrecognized model". Its network is LongCat-Flash-Lite with a DSA-style lightning indexer whose top-k selects every causal key up to index_topk (2048) tokens, which is the dense model. unsloth/models/longcat_lsa.py builds it on the native longcat_flash decoder: the n-gram embedding, key renames for the oe_embed_* tables (both ways, on transformers 4 and 5), deepseek_yarn read as yarn, head_dim from qk_rope_head_dim, routed-only expert stacks on transformers 5, rms_norm_eps on the MLA latent norms and an F32 router as SGLang runs them, and the indexer kept as frozen weights so it round-trips. Sequences past index_topk train dense and warn once. import_fixes answers only AutoConfig's "Unrecognized model" on this config.
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex security review |
…rops, warn on cached length
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
# Conflicts: # unsloth/_gpu_init.py
… resets A cache built during training switched off transformers' packed-sequence mask, so padding-free batches attended across samples; the n-gram also read across packed samples and left padding. Restart it where position_ids restart.
# Conflicts: # unsloth/_gpu_init.py
|
@codex review |
1 similar comment
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 796e3dcf93
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| **kwargs, | ||
| ) | ||
|
|
||
| class LongcatCausalLM(LongcatFlashForCausalLM): |
There was a problem hiding this comment.
Register the model after compiler class replacement
In the normal FastModel load, the AutoConfig fallback calls register_longcat_lsa() and creates this subclass before unsloth_compile_transformers runs. The compiler later replaces the classes exported by transformers.models.longcat_flash.modeling_longcat_flash, but the registered custom class still inherits the original class object, so it misses replacements such as the fused linear cross-entropy forward. With this model's 131072-token vocabulary, training therefore materializes the full logits tensor and can consume substantially more memory or OOM; the custom registration needs to bind to the post-compiler class or provide the equivalent patched forward.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Not reproducible: the compiler patches the class object in transformers.models.longcat_flash.modeling_longcat_flash, which is the exact base LongcatCausalLM inherits (checked via the MRO after a FastLanguageModel load). In a training forward plus backward, lm_head is never called as a module and the returned logits are empty, identical to a native Qwen3-MoE control, so the fused cross entropy path is taken and no full logits tensor is built.
…les across vocab resizes Without position_ids, a left-padded batch read pad ids into the first real tokens' n-grams; derive the restarts from the 2-D attention mask as generate() does. resize_token_embeddings changed vocab_size, which sized the n-gram tables and radix on reload; persist oe_ngram_vocab_size in the config instead.
# Conflicts: # unsloth/_gpu_init.py
|
Codex Review: Didn't find any major issues. 👍 Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
|
pre-commit.ci run |
# Conflicts: # unsloth/_gpu_init.py
# Conflicts: # unsloth/models/vision.py
…_flash (unslothai#11620) * Load LongCat-Flash-Lite-Sparse on transformers' longcat_flash The published checkpoint (LongcatCausalLM) ships no model_type, auto_map or modeling code, so AutoConfig raised "Unrecognized model". Its network is LongCat-Flash-Lite with a DSA-style lightning indexer whose top-k selects every causal key up to index_topk (2048) tokens, which is the dense model. unsloth/models/longcat_lsa.py builds it on the native longcat_flash decoder: the n-gram embedding, key renames for the oe_embed_* tables (both ways, on transformers 4 and 5), deepseek_yarn read as yarn, head_dim from qk_rope_head_dim, routed-only expert stacks on transformers 5, rms_norm_eps on the MLA latent norms and an F32 router as SGLang runs them, and the indexer kept as frozen weights so it round-trips. Sequences past index_topk train dense and warn once. import_fixes answers only AutoConfig's "Unrecognized model" on this config. * LongCat LSA: pass the word embedding output, not the module, to the n-gram embedding * Keep LongCat-Flash MLA q_b_proj / kv_b_proj out of 4-bit quantization * LongCat LSA: carry the n-gram id history through cache reorders and crops, warn on cached length * LongCat LSA: clear the n-gram history on cache reset, refuse inputs_embeds * Give the device-map planner the same architecture skip modules as the 4-bit load * Gate the split-model test on a real CUDA device * Trim comments in LongCat LSA support * LongCat LSA: no cache in training, restart the n-gram on position_ids resets A cache built during training switched off transformers' packed-sequence mask, so padding-free batches attended across samples; the n-gram also read across packed samples and left padding. Restart it where position_ids restart. * LongCat LSA: restart n-grams from the attention mask, keep n-gram tables across vocab resizes Without position_ids, a left-padded batch read pad ids into the first real tokens' n-grams; derive the restarts from the 2-D attention mask as generate() does. resize_token_embeddings changed vocab_size, which sized the n-gram tables and radix on reload; persist oe_ngram_vocab_size in the config instead. * Trim LongCat LSA comments
…#12018) unslothai#11620 registers longcat_flash_lsa into transformers' and peft's _MODEL_TO_CONVERSION_PATTERN with longcat_flash's family when its conversions are set up. In any process where tests/test_longcat_lsa.py has run first, the live map carries that type, and test_the_moe_snapshot_matches_the_installed_transformers fails because the snapshot does not. Whether it fails depends on which xdist worker gets which test. The snapshot now lists it with longcat_flash's family, and a new test checks unsloth's own registration against the snapshot directly, so the pairing is checked in every order.
Problem
meituan-longcat/LongCat-Flash-Lite-Sparseships nomodel_type,auto_mapor modeling code (its config namesLongcatCausalLM), soAutoConfigraises "Unrecognized model ... Should have amodel_typekey" andFastLanguageModelthen fails with "Both AutoConfig and PeftConfig loading failed".The checkpoint is LongCat-Flash-Lite plus a DSA-style lightning indexer. Up to
index_topk(2048) tokens the indexer's top-k selects every causal key, so the network is exactly the denselongcat_flashmodel transformers already ships (SGLang'sdsa_indexersays the same and skips the logits there).Change
unsloth/models/longcat_lsa.pybuilds the checkpoint on the nativelongcat_flashdecoder under a customlongcat_flash_lsamodel type:NgramEmbedding, per-row EOS reset vectorised; ids bit-exact against SGLang's kernel), with theoe_embed_tokens{i}/oe_embed_proj{i}keys renamed both ways on transformers 4 and 5.deepseek_yarnread asyarn,head_dimdefaulted toqk_rope_head_dim,rms_norm_epson the MLA latent norms and an F32 router, as SGLang runs them.LongcatFlashExperts.gate_up_projfor routed plus identity experts while the checkpoint stacks routed only; the stack is sized to the routed experts so the checkpoint loads.index_topktrain dense and warn once.embed_tokensmodule: on a split model accelerate's hook on the n-gram module moves every argument with a.to, which moved the whole token table to the other card (index is on cuda:0, different from other tensors on cuda:1).q_b_proj/kv_b_projin 16-bit forlongcat_flashmodels (vision.pyskip list, next to the Nemotron-H rule). An NF4 round trip of each Linear group in the 16-bit model on the real checkpoint:q_a_projkv_a_proj_with_mqaq_b_proj+kv_b_projo_projWith the two projections kept, a real 4-bit load gives 0.7418 on the same text.
import_fixes.pyonly answersAutoConfig's "Unrecognized model" for this config.Real model
meituan-longcat/LongCat-Flash-Lite-Sparse, bf16 over 2 B200s, next-token loss on a fixed text:routed_scaling_factor(transformers, vLLM, Meituan's HF code; what this runs)The weights were trained with the scaled form, so the native transformers semantics are kept.
LoRA r=16 including the experts, 10 steps, seq 512:
Unrecognized modelBefore the skip-list change the same 4-bit cell ran 2.015, 1.512, 2.188, ...
Fidelity
Against a reference transcribed from SGLang (MLA, deepseek_yarn, the n-gram kernel), written against the raw checkpoint keys:
Tests
tests/test_longcat_lsa.py(12 tests): config recognition, every checkpoint key loading, the SGLang reference forward, n-gram ids, cached decode, the bf16 router and norm eps, the saved layout, PEFT per-expert adapter conversion, the long-sequence warning, a split model keeping the token table where accelerate placed it (GPU, fails on the previous version with the real model's error), and the 4-bit skip rule. transformers 5.17: 12 passed. transformers 4.57.6 / torch 2.6 / TRL 0.22.2 / PEFT 0.18: 10 passed, 1 skipped (no conversion table there), GPU test deselected (that torch has no B200 kernels).Depends on
__init__(yarn_apply_mscalecompiled with fullgraph).Compatibility
transformers 4.57.6 and 5.x (key renames through
key_mappingon 4.x,WeightRenamingon 5.x); TRL 0.22.2 and 1.x; PEFT 0.18 to 0.20. Pure PyTorch, no platform-specific code; the only change to shared code is the 4-bit skip entry, which applies tolongcat_flashmodel types alone.Real checkpoint, llama.cpp-protocol perplexity and 10 step SFT (B200)
meituan-longcat/LongCat-Flash-Lite-Sparse, on-the-fly NF4, with unslothai/unsloth-zoo#1336 and #1351, transformers 5.17: wikitext-2 PPL 9.888 (n_ctx 512, 80 chunks, second half scored), FineTome response-only LoRA r=16 (bs 2 x ga 4, seq 2048) loss 0.986, 0.826, 0.816, 0.736, 0.715, 0.987, 0.627, 0.718, 0.858, 0.453, held-out CE 0.743 to 0.637. Without the zoo PRs the load fails inyarn_apply_mscale(compiled with fullgraph) and then in the 4-bit expert forward.Review fixes
use_cacheis unset during training. The cache switched off transformers' packed-sequence mask (it is only built whenpast_key_values is None), so Unsloth's default padding-free batches attended across samples. Packed and padded runs of a tiny checkpoint now give identical losses and grad norms over 10 steps (sample 2 logits packed vs alone: 7.3 before, 2e-6 after).position_idsrestart (packing, left padding) and, when noposition_idsare passed, where the 2-D attention mask starts each row, asgenerate()derives positions. Left-padded generation and left-padded forwards now match the unpadded ones.oe_ngram_vocab_sizeis stored in the config (defaults to the originalvocab_size), soresize_token_embeddingsfollowed by save and reload keeps the n-gram tables and hash radix.