Skip to content

Load and fine-tune LongCat-Flash-Lite-Sparse on transformers' longcat_flash - #11620

Merged
shimmyshimmer merged 16 commits into
mainfrom
longcat-flash-lite-sparse
Sep 25, 2026
Merged

shimmyshimmer merged 16 commits into
mainfrom
longcat-flash-lite-sparse

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Sep 23, 2026 •

Copy link
Copy Markdown
Member

Problem

meituan-longcat/LongCat-Flash-Lite-Sparse ships no model_type, auto_map or modeling code (its config names LongcatCausalLM), so AutoConfig raises "Unrecognized model ... Should have a model_type key" and FastLanguageModel then 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 dense longcat_flash model transformers already ships (SGLang's dsa_indexer says the same and skips the logits there).

Change

unsloth/models/longcat_lsa.py builds the checkpoint on the native longcat_flash decoder under a custom longcat_flash_lsa model type:

  • The n-gram embedding (Lite's NgramEmbedding, per-row EOS reset vectorised; ids bit-exact against SGLang's kernel), with the oe_embed_tokens{i} / oe_embed_proj{i} keys renamed both ways on transformers 4 and 5.
  • deepseek_yarn read as yarn, head_dim defaulted to qk_rope_head_dim, rms_norm_eps on the MLA latent norms and an F32 router, as SGLang runs them.
  • transformers 5 sizes LongcatFlashExperts.gate_up_proj for routed plus identity experts while the checkpoint stacks routed only; the stack is sized to the routed experts so the checkpoint loads.
  • The indexer weights load as frozen parameters with no forward use and are saved back. Sequences past index_topk train dense and warn once.
  • The n-gram embedding takes the word embedding output, not the embed_tokens module: 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).
  • 4-bit keeps q_b_proj / kv_b_proj in 16-bit for longcat_flash models (vision.py skip list, next to the Nemotron-H rule). An NF4 round trip of each Linear group in the 16-bit model on the real checkpoint:
group quantized to NF4 loss
none (16-bit) 0.6954
q_a_proj 0.7035
kv_a_proj_with_mqa 0.7356
q_b_proj + kv_b_proj 2.7255
o_proj 0.6909
dense MLPs 0.6993
n-gram projections 0.6875
all of the above 3.3717 (a real 4-bit load gave 3.34)

With the two projections kept, a real 4-bit load gives 0.7418 on the same text.

import_fixes.py only answers AutoConfig'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:

identity (zero) expert output loss
scaled by routed_scaling_factor (transformers, vLLM, Meituan's HF code; what this runs) 0.6954
unscaled (SGLang) 0.7599

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:

precision main this branch
16-bit, 2 B200s FAIL, Unrecognized model PASS, 0.590, 0.966, 0.730, 0.473, 0.786, 0.610, 0.944, 0.764, 0.703, 1.034
4-bit, 1 B200 FAIL, same PASS, 0.655, 1.045, 0.923, 0.709, 0.832, 0.700, 1.003, 0.772, 0.729, 1.100

Before 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:

  • Tiny model built from the real config, fp32 logits: max abs diff 1.6e-5 on transformers 5.17, 5.0.0 and 4.57.6. The SGLang zero-expert variant differs by 3.5, so the check discriminates.
  • Real weights, layer 0 plus the final norm (range-read), fp32: relative L2 1.5e-6.
  • Cached decode matches the full forward to 6e-6. Every checkpoint key loads with no missing, unexpected or mismatched keys; saving writes the published layout.

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

Compatibility

transformers 4.57.6 and 5.x (key renames through key_mapping on 4.x, WeightRenaming on 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 to longcat_flash model 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 in yarn_apply_mscale (compiled with fullgraph) and then in the 4-bit expert forward.

Review fixes

  • Padding-free training: the model no longer builds a KV cache when use_cache is unset during training. The cache switched off transformers' packed-sequence mask (it is only built when past_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).
  • The n-gram embedding restarts where position_ids restart (packing, left padding) and, when no position_ids are passed, where the 2-D attention mask starts each row, as generate() derives positions. Left-padded generation and left-padded forwards now match the unpadded ones.
  • oe_ngram_vocab_size is stored in the config (defaults to the original vocab_size), so resize_token_embeddings followed by save and reload keeps the n-gram tables and hash radix.
  • Tiny-model parity against plain transformers + PEFT (fp32, 10 steps, LoRA r=16): max loss difference 0.005, max grad-norm difference 0.084.

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.
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-09-25T20:03:25.379367Z 1dd50e0 New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 23, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 23, 2026
chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: e9da7a5ff0

ℹ️ 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".

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: 96c81f188a

ℹ️ 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".

# Conflicts:
#	unsloth/_gpu_init.py
@danielhanchen danielhanchen self-assigned this Sep 25, 2026
… 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
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@unslothai unslothai deleted a comment from danielhanchen Sep 25, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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):

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 7b0bd236e7

ℹ️ 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".

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 25, 2026
@unslothai unslothai deleted a comment from shimmyshimmer Sep 25, 2026
@unslothai unslothai deleted a comment from shimmyshimmer Sep 25, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

pre-commit.ci run

# Conflicts:
#	unsloth/_gpu_init.py
# Conflicts:
#	unsloth/models/vision.py
@shimmyshimmer
shimmyshimmer merged commit cccba44 into main Sep 25, 2026
33 of 36 checks passed
@shimmyshimmer
shimmyshimmer deleted the longcat-flash-lite-sparse branch September 25, 2026 20:18
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…_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
shaojun pushed a commit to shaojun/unsloth that referenced this pull request Sep 29, 2026
…#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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants