Skip to content

Add agent skill for converting Hugging Face models to Transformer Engine - #3904

Open
faradawn wants to merge 13 commits into
NVIDIA:mainfrom
faradawn:add-hf-conversion-skill
Open

faradawn wants to merge 13 commits into
NVIDIA:mainfrom
faradawn:add-hf-conversion-skill

Conversation

@faradawn

@faradawn faradawn commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Skill: fusions like LayerNorm+QKV, LayerNorm+MLP, TransformerLayer and GroupedLinear MoE experts, with the checkpoint weight mapping.
Eval: Llama, Gemma and Mixtral

Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
@github-actions github-actions Bot added the community-contribution PRs from external contributor outside the core maintainers, representing community-driven work. label Nov 19, 2026
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
@faradawn
faradawn marked this pull request as ready for review November 19, 2026 23:20
@greptile-apps

greptile-apps Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 3/5

[Low impact] The changes affect an assistant workflow for model-conversion questions, not Transformer Engine runtime behavior.

The PR should not merge until the existing scaled-RoPE and left-padding findings are addressed.

Findings

  1. P1 Scaled RoPE is lost ▶
  2. P1 Left padding changes attention ▶
  3. P2 Incomplete accuracy checks pass ▶
  4. P2 Whole-layer conversion goes unchecked ▶

Summary

Adds a skill for converting Hugging Face models to Transformer Engine.

  • Assistants can build Transformer Engine replacements for Hugging Face models.

Reviews (13) · Last reviewed commit: "Drop the cuBLAS assertion, loosen the BF..." · Reviewed by Greptile

@sbhavani

Copy link
Copy Markdown
Collaborator

Could we consider a weight mapping check? For every source param and destination, reconstruct the HF tensors from the converted weights, and compare them exactly. This should catch missing weights and swapped ordering

Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
@faradawn

Copy link
Copy Markdown
Contributor Author

Hi @sbhavani , I've added a "check_weight_mapping.py" to ensure weight mapping is correct.

Cover models beyond the tutorials: fused norm and projections for mixers
TE's layers cannot express, TE cores for attention and gated delta rule,
MoE experts in blocks of 64 with ScaledSwiGLU and padded routing, and the
cuBLAS grouped GEMM bug. Fix the Llama template for transformers 5 and
for head_dim, and add tested fused-QKV copy code.

check_weight_mapping.py now checks row order, skips entries Hugging Face
does not load and runs faster. Add compare_logits.py, which compares the
TE model with the HF model against HF's own rounding noise, whole or in
slices of layers, and make_subcheckpoint.py.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
faradawn and others added 2 commits November 23, 2026 12:48
Describe the output as a TE-based drop-in replacement for the HF
Transformer layer module, pointing to the Llama and Gemma tutorials.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
Remove the verification scripts, which added maintenance burden, and
rewrite SKILL.md without code snippets: it now starts by matching the
architecture to a reference (the Llama tutorial for dense models, the
Mixtral tutorial for MoE models, BioNeMo Recipes for genomics and
protein models) and points to the functions to reuse by their
signatures. Add an eval for routing a protein model to BioNeMo Recipes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
Comment on lines +99 to +100
- **RoPE base.** `RotaryPositionEmbedding` defaults to base 10000; pass the model's
`rope_theta` as `rotary_base`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Scaled RoPE is lost

The shortened rule drops the requirement to preserve rope_scaling. If a checkpoint uses scaled RoPE, passing only rope_theta as rotary_base builds unscaled frequencies. The dense reference does not add scaling either, so following these instructions changes the model's outputs even when its weights are copied correctly.

Restore the scaling requirement, or keep HF's rotary code when TE cannot match it.

Comment on lines +106 to +107
- **Masks.** Do not pass HF's additive mask to a TE attention block. TE builds the causal mask,
and its masks are boolean with `True` meaning masked out.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P1 Left padding changes attention

The rewrite removes the left-padding warning while still saying not to pass HF's additive mask because TE builds the causal mask. A causal mask only hides future tokens; it does not hide padding before real tokens. With left-padded batches, following this rule without a separate padding path lets real tokens attend to padding and changes the training loss.

Restore the requirement to preserve padding locations through a supported boolean mask or packed input.

Knowledge Base Used: Framework examples and integrations

faradawn and others added 2 commits November 23, 2026 16:12
Address review feedback: the skill now walks through four steps,
checking which HF components TE covers, choosing between replacing the
whole transformer block and replacing attention and MLP separately,
mapping the weights, and implementing (what to fuse, and the design
patterns). Code examples move to references/design-patterns.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
Call the result a TE implementation rather than a recipe, which in TE
means a quantization recipe. State that the building block replaced is
the whole transformer layer or its attention and MLP/MoE blocks, and go
no deeper. Note that the module table is not exhaustive, carry the
sliding window to TE, mention extra dependencies, allow use as a
reference for other PyTorch frameworks, and drop the design-patterns
reference file in favour of the tutorials.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
@faradawn faradawn changed the title Add agent skill for converting Hugging Face models to TE recipes Add agent skill for converting Hugging Face models to Transformer Engine Nov 24, 2026
faradawn and others added 2 commits November 24, 2026 09:23
DeepSeek-V3 checks multi-head latent attention at the attention-block
level, the YaRN softmax scale, group-limited sigmoid routing over 256
experts and dequantization of the FP8 checkpoint. GLM-5 checks that the
DeepSeek Sparse Attention indexer stays HF code, the real MLA head
sizes rather than config.head_dim, and the layer's top-k interface.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
Keep the four steps at the level of general principles and point to the
Llama, Gemma and Mixtral tutorials for details. Collect the settings
that must match the config, the checks and the problems found on
Qwen3.5 into a troubleshooting section, and stop telling agents to pass
config.head_dim as the attention head size, which is wrong for GLM-5.
Align the Qwen3.5 eval with what the skill teaches.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>

A component with no TE module (a causal convolution, a gated output norm, a custom router) stays
HF code. A genomics or protein language model (for example ESM-2) is covered by the
[BioNeMo Recipes acceleration skill](https://github.com/NVIDIA-BioNeMo/bionemo-recipes/blob/19ee43214fec23e87916efd468eaa62df47dba3e/skills/bionemo-recipes-acceleration/SKILL.md):

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.

We should probably add a reference section to this skill for things like this: there might be more such sister skills in the future


| HF component | TE module |
|---|---|
| The whole pre-norm block: `x + attn(norm(x))`, then `x + mlp(norm(x))` | `te.TransformerLayer` |

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.

Keep it more abstract - a module that encapsulates a flavor of Attention and a flavor of MLP and is completely compatible a target HuggingFace model's Transformer Layer e.g. Llama, Gemma, etc.

(`class TEGemmaDecoderLayer(te.TransformerLayer)`) do.

**Level 2: attention and MLP separately.** When the block has something `te.TransformerLayer`
cannot express, such as experts or linear attention, replace the attention and the MLP each 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.

We should also indicate that this is a non-exhaustive list

Comment on lines +74 to +86
**Level 2: attention and MLP separately.** When the block has something `te.TransformerLayer`
cannot express, such as experts or linear attention, replace the attention and the MLP each with
TE modules:

- Attention: `te.MultiheadAttention` when it fits; otherwise `te.LayerNormLinear` for the norm
and input projections, a TE core attention, `te.Linear` for the output projection, and HF code
for what lies between.
- MLP: `te.LayerNormMLP` for a dense MLP. For mixture-of-experts (MoE), write an MoE layer
around grouped GEMMs, as
[`te_mixtral.py`](https://github.com/NVIDIA/TransformerEngine/blob/main/docs/examples/te_mixtral/te_mixtral.py)
does in `class TEMixtralSparseMoeBlock(nn.Module)`.

A block that neither level covers stays HF code.

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.

Need to probably rephrase this while showing the proper hierarchy. It mentions the individual pieces from Level 2 but that counts as Level 3.

Comment on lines +90 to +93
Every checkpoint weight of a replaced block needs a destination in the TE modules, and every TE
parameter a source; make the loader fail on a weight left over on either side. Follow
`replace_params(hf_state_dict, te_state_dict, config)` in `te_llama.py` and
`replace_params_bf16` in `docs/examples/te_mixtral/hf_to_te_weights.py`.

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.

Is there a structure one could follow here too? We could add more information about how to approach the weight mapping e.g. during architecture and feature search, we could create a map/graph of the modules and the weights it contains. It's possible that the boundaries of the modules in HF vs TE are different so the second phase (checking the granularity) would help in defining the boundaries. Both of those could provide information on mapping. There might be additional things to watch out for e.g. how to approach a few quirks already faced in te_llama.py/te_gemma.py/te_mixtral.py.

Also, make all the links be full paths.

Comment on lines +99 to +103
Choose fusions that keep the math identical and ideally improve performance, for example:

- a norm with the QKV projection: `te.LayerNormLinear`, or `te.MultiheadAttention` with
`input_layernorm=True`;
- a norm with the MLP: `te.LayerNormMLP`.

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.

There might be more fusions here, find those from the documentation or mention where one can find those. Also, part of this also overlaps with weight mapping, so choosing fusions actuall belongs to phase 2.

Comment on lines +107 to +111
Follow the three existing TE implementations: `te_llama.py`, `te_gemma.py` and
`docs/examples/te_mixtral/`. They show how to swap HF's decoder layer class while HF builds the
model (`replace_decoder(te_decoder_cls)`), load the checkpoint
(`from_pretrained_local(cls, pretrained_model_name_or_path, *args, config, **kwargs)`), map the
weights, and keep the layer interface the installed `transformers` model loop expects.

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.

While this is helpful, is it possible to distill the design patterns in broad terms here?

Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
Comment on lines +4 to +6
{
"id": "transformer-engine-convert-hf-005",
"prompt": "Convert Qwen3.5-35B-A3B to Transformer Engine.",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Whole-layer conversion goes unchecked

Removing the Llama, Gemma and Mixtral cases leaves no evaluation of the skill's preferred whole-layer conversion path or fine-tuning under te.autocast. Both remaining conversion cases explicitly reject TransformerLayer, so an agent that always chooses separate blocks or skips FP8 training checks can pass every evaluation. Restore at least one dense-model fine-tuning case to keep those paths covered.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

Signed-off-by: Faradawn Yang <73060648+faradawn@users.noreply.github.com>
"The 256 experts run through GroupedLinear in blocks of at most 64 experts each.",
"Under MXFP8, each expert's rows are padded to a multiple of 128, and the router and the LM head stay out of quantization.",
"Every checkpoint weight of the decoder layers, including the stacked expert tensors and the shared expert, is mapped to the correct Transformer Engine parameter, and the loader fails on a weight left over on either side.",
"The implementation comes with a check that compares its BF16 output with Hugging Face's BF16 output on the same input."

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Incomplete accuracy checks pass

The Qwen evaluation now accepts a BF16-only comparison, although the skill requires a float32 reference to judge BF16 rounding error. An implementation can skip that reference and pass every assertion without meeting the skill's accuracy check. Restore the float32 comparison and the check against HF's own BF16 error.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution PRs from external contributor outside the core maintainers, representing community-driven work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants