Add MiniCPM3#41116
Conversation
|
cc @ArthurZucker for text models |
|
@ArthurZucker please check this out! I've tested with MiniCPM3-4B and it worked well. |
|
@ArthurZucker I've tested MiniCPM3-4B and our in-house model for the case |
8db4a1c to
90563c4
Compare
|
End-to-end check on import torch
from transformers import AutoTokenizer, MiniCPM3ForCausalLM
tokenizer = AutoTokenizer.from_pretrained("openbmb/MiniCPM3-4B")
model = MiniCPM3ForCausalLM.from_pretrained(
"openbmb/MiniCPM3-4B",
dtype=torch.float16,
device_map="auto",
attn_implementation="eager",
).eval()
messages = [{"role": "user", "content": "Tell me a fun fact about the Eiffel Tower."}]
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
inputs = tokenizer(text, return_tensors="pt").to(model.device)
out = model.generate(**inputs, max_new_tokens=80, do_sample=False)
print(tokenizer.decode(out[0], skip_special_tokens=True))Output: |
|
@aliyevaladddin Sorry I missed your email earlier. I just rebased this PR, would be happy to add you as coauthor since your message got me to come back to it. |
Adds support for the OpenBMB MiniCPM3 architecture (e.g. `openbmb/MiniCPM3-4B`). MiniCPM3 combines Multi-head Latent Attention (MLA) from DeepSeek-V2 with a standard SwiGLU MLP and three scalar scaling factors that govern signal flow: - `scale_emb` scales input embeddings. - `scale_depth / sqrt(num_hidden_layers)` scales residual connections. - `hidden_size / dim_model_base` scales hidden states before the language-model head. The implementation follows the modular pattern, deriving the config and model from `LlamaConfig` / `LlamaModel`. The MLA attention keeps the cos/sin rotary convention used by the original implementation, registered classes are wired into the auto mappings, and `tokenizer_auto` is updated so the upstream tokenizer falls back to the tokenizers backend. Verified with `openbmb/MiniCPM3-4B` end-to-end: weights load without missing/mismatched keys and greedy generation produces a coherent reply via `attn_implementation="eager"`. Co-authored-by: Aladdin Aliyev <[email protected]>
`scale_depth=1.0` and `dim_model_base=1` make the residual and logit scalings collapse, which prevented the small tester model from training and broke the `test_training_overfit` CI job. Mirror the original MiniCPM3 defaults: when not provided, `scale_depth` falls back to `sqrt(num_hidden_layers)` and `dim_model_base` falls back to `hidden_size`, so both factors become exact no-ops. Drop the explicit overrides in `MiniCPM3ModelTester` so the small test config inherits the new defaults. The real `openbmb/MiniCPM3-4B` config is unaffected: it sets all three scalars explicitly. Co-authored-by: Aladdin Aliyev <[email protected]>
595b8b9 to
58bb454
Compare
|
@ArthurZucker @Cyrilvallez when you have a moment, would appreciate a review on this. Thanks! |
|
Thanks for the rebase, @bzantium! I'm honored to be added as a co-author. I'm really excited to see MiniCPM3 support getting closer to being merged. Let me know if there's anything else I can help with regarding testing or further updates! |
|
Will try to take a look today 🤗 |
vasqu
left a comment
There was a problem hiding this comment.
Some initial comments from my side 🫡
- MiniCPM3Attention now inherits DeepseekV2Attention and overrides only forward (cos/sin RoPE instead of DeepSeek-V2's complex rotary), removing the duplicated MLA __init__. Forward output is numerically identical. - Drop config fields that match LlamaConfig defaults; keep only the ones that differ plus the MLA/scaling extras. - Remove the validate_architecture override so the standard Llama divisibility check applies, matching dsv2/dsv3. - Precompute the residual depth scaling per layer; expose the logit scaling as a config property; add comments highlighting the diffs from Llama (embedding, residual, logit scalings). - Bump copyright years to 2026; use AutoModelForCausalLM in the docs example; drop the MoE-oriented test_all_params_have_gradient flag. - Rework integration tests to the value-based Expectations pattern (expected logits/text to be filled from a CI reference run).
…1115 # Conflicts: # docs/source/en/_toctree.yml # src/transformers/models/auto/modeling_auto.py
|
View the CircleCI Test Summary for this PR: https://huggingface.co/spaces/transformers-community/circle-ci-viz?pr=41116&sha=42b80e |
Update the date line to the current "published in HF papers on ... and contributed to ..." format expected by utils/add_dates.py, fixing the check_repository_consistency failure.
vasqu
left a comment
There was a problem hiding this comment.
Just some small comments but overall lgtm. Let me update the CI tomorrow then after you fixed the last comments 🫡
|
We also need to sync with main and fix CI please |
…tion values - Default config to the openbmb/MiniCPM3-4B checkpoint values (scale_emb=12, scale_depth=1.4, dim_model_base=256); no-op scaling only when set to None. - Drop redundant keys_to_ignore_at_inference (inherited from LlamaConfig). - Move embedding scaling into MiniCPM3ScaledWordEmbedding so input_ids and inputs_embeds paths stay consistent (fixes inputs_embeds-vs-input_ids tests). - Remove redundant self_attn assignment in the decoder layer (modular renames it). - Highlight the MLA RoPE diff vs DeepSeek-V2/V3 with a comment. - Fill integration test Expectations with verified A100 (bf16) reference values.
|
The This gate only runs for fork PRs, and the failure comment notes that a maintainer can manually approve CI when a finding is a false positive. Could you approve CI when you get a chance? All 11 other changed files pass the allowlist. Thanks! |
MiniCPM3 uses MLA (inherited from DeepSeek-V2), so the query/key head dim (qk_nope + qk_rope) differs from the value head dim. PyTorch's flash kernel requires q, k, v to share the same last dim, so SDPA cannot dispatch on flash. Skip the test as DeepSeek-V3 already does for the same reason.
|
Thank you for your contribution 🤗! CI Security Gate — automatic approval blockedThis PR was not automatically approved for CI because the security gate failed. Possible reasons:
See the workflow run for the exact violations. A maintainer can review and manually approve CI if a finding is a false positive. |
vasqu
left a comment
There was a problem hiding this comment.
LGTM, the logits differ quite a bit from 8 to 8.6 so just wanna make sure if you can check that I didnt break anything
|
gentle ping @bzantium |
|
[For maintainers] Suggested jobs to run (before merge) run-slow: auto, minicpm3 |
|
@vasqu Thanks for the careful check! I verified on an A100 (compute capability 8.0, same hardware the bf16 reproduction (A100, cc 8.0): So your refactor (inheriting On the 8 vs 8.6 gap: both buckets run bf16 (the config The bf16 vs fp32 gap reaches about 0.34, which is larger than the 8.0 vs 8.6 gap of about 0.08. Most importantly, the argmax token is 11213 in bf16 and fp32 alike, so the actual prediction is stable across precision and only the near zero logit tail moves. Net: your |
|
run-slow: minicpm3 |
|
Just sanity checking but should be good to go then 🫡 |
|
This comment contains models: ["models/minicpm3"] |
|
The docs for this PR live here. All of your documentation changes will be reflected on that endpoint. The docs are available until 30 days after the last update. |
|
Nice thanks for sticking through and gz on the merge 🤗 |
|
Finaly! |
What does this PR do?
Adds native support for the MiniCPM3 architecture from OpenBMB
(
openbmb/MiniCPM3-4B).MiniCPM3 combines:
scale_emb— multiplier on input embeddings.scale_depth / sqrt(num_hidden_layers)— multiplier on residual connections.hidden_size / dim_model_base— divisor on hidden states before the LM head.When
scale_depth/dim_model_baseare not provided, they default to no-op values (sqrt(num_hidden_layers)andhidden_sizerespectively).Implemented as a single
modular_minicpm3.pyderiving fromLlamaConfig/LlamaModel, with a customMiniCPM3Attentionfor MLA. The model reuses the upstreamLlamaTokenizer(no new tokenizer files);minicpm3is added toMODELS_WITH_INCORRECT_HUB_TOKENIZER_CLASSso the auto loader falls back toTokenizersBackend.AutoConfig/AutoModel/AutoModelForCausalLM/AutoModelForSequenceClassificationmappings, docs, and tests are wired up.Fixes #41115.
A second, more recent PR (#45613) covers the same model. This PR (#41116) is the original; the implementations differ on the RoPE convention (this one preserves the original cos/sin RoPE; #45613 uses DeepSeek-V2's complex RoPE) and on a few config defaults.
AI assistance was used during the rebase/refactor; the changes have been reviewed and tested locally end-to-end (see follow-up comment for the example run on
openbmb/MiniCPM3-4B).Before submitting
Pull Request section?
to it if that's the case. — Add Model Architecture for MiniCPM3 #41115
Who can review?
@ArthurZucker @Cyrilvallez