Skip to main content

convert-hf-to-te

Adapt a Hugging Face PyTorch model for training with compatible Transformer Engine modules. Replace a decoder layer, sublayer or individual operation and map its checkpoint weights. Choose fusions that preserve the requested workload's behavior.

v1.0.0New

Unsigned, install at your own risk

Unverified

This skill has no cryptographic signature attached. We can't verify the contents match what the publisher intended.

Install this skill

No account required. Pick your tool, or use the command that detects it for you.

Run in your terminal. It detects your AI tool.

npx @skills-hub-ai/cli install skills-convert-hf-to-te
Or get the file:
Browse all CLI commands →
Manual setup by platform

Claude Code

~/.claude/skills/skills-convert-hf-to-te/SKILL.md

Setup guide →
0Save

Instructions

Convert a Hugging Face model to Transformer Engine

Use the project's requested entry point or add a model-family module such as te_llama.py.
Replace compatible building blocks of the Hugging Face (HF) model with Transformer Engine (TE)
modules and load the original checkpoint into them. The building block is the whole transformer
layer, as for Llama and Gemma, or else the attention
(MHA, linear attention) and MLP or MoE blocks inside it. A partial conversion can also replace
a single operation inside an HF block. For a review or plan, stop after the requested feasibility,
boundary or weight-mapping decision in Steps 1–3. For a local implementation, Step 4 ends at the
first BF16 forward comparison. Use Step 5 for requested training checks, integration or performance
measurements at the scope the user specified.
In this skill te means transformer_engine.pytorch.

In a plan or implementation handoff, lead with the chosen replacement boundary and weight map.

Not for JAX or inference serving (vLLM, TensorRT-LLM). For Megatron-LM or another PyTorch
framework, the TE implementation can serve as a reference for which TE modules to use and how
the weights map.

1. Check the architecture and feasibility

Identify the training path, representative inputs and target precision from the request and project.
Read the model's config.json, checkpoint keys and decoder forward at the requested revision
or installed version. For each distinct layer type, record its modules, which tensors they consume
or share, and their checkpoint keys. Use this inventory to identify candidate TE modules.
Consult examples for the relevant boundary and verify API choices against the target TE release.
For source-only work, use those sources to resolve API and layout questions before setting up a
runtime.

HF componentCandidate TE module
The whole transformer blockte.TransformerLayer
Self-attention with QKV and output projectionste.MultiheadAttention. Set input_layernorm=True only when it replaces HF's input norm, so the norm runs once.
Scaled dot-product attention on projected Q/K/Vte.DotProductAttention
Input norm followed by one linear projection, which can pack compatible projections of the same normalized inputte.LayerNormLinear
A norm and a dense MLPte.LayerNormMLP
Grouped linear projections across MoE expertste.ops.GroupedLinear. The surrounding MoE block supplies activation and routing.
Dispatch and combine across expert-parallel rankste.ops.MoeDispatch and te.ops.MoeCombine in the experimental operation fuser. Check compatibility with the router outputs and backend.
A single projection or normte.Linear, te.RMSNorm, te.LayerNorm

The table is not exhaustive. Newer architectures may need other TE modules, such as the
experimental Gated DeltaNet core (te.GatedDeltaNetAttention). Check that the installed TE
exports the candidate and its backend supports the target inputs and workload. Keep unsupported
components in HF.

2. Choose the granularity

Start with the largest region that preserves HF's computation and the interface its caller uses.
The level describes which part of the HF model you replace.

Level 1: the whole transformer block. Try one te.TransformerLayer for the HF decoder block.
Match the attention and MLP widths, query and KV head counts, normalization and residual order,
activation, mask, and rotary positions for the requested inputs. A causal HF decoder with only
self-attention uses TE's self-attention topology with a causal mask. In TE 2.18, layer_type="decoder"
adds cross-attention. When the block matches, substitute it at the HF decoder entry point and preserve
the caller's arguments, layout and return value. Map the norm, attention and MLP weights and compare
the whole block's BF16 output to HF in Step 4.
Llama wrapper ·
Gemma constructor ·
TE layer topology

Level 2: attention and MLP separately. If the whole layer does not fit, consider each
sublayer independently. Experts and linear attention are two examples from a non-exhaustive list.

  • Attention: use te.MultiheadAttention when it implements the target attention block.
  • MLP: te.LayerNormMLP for a dense MLP. For mixture-of-experts (MoE), compose a model-specific
    block around the compatible operations. For example,
    te_mixtral.py
    defines its own TEMixtralSparseMoeBlock to route tokens, run the expert FFN and combine outputs.

Level 3: an operation inside an HF sublayer. For example, replace a projection inside HF
attention or the expert GEMMs inside an HF MoE block. Choose this boundary when you can preserve
its inputs, outputs and shared state and have a workload benefit to test. If TE cannot reproduce
the attention behavior, keep HF's attention computation, masking, positions and cache together.
An independent MLP can still benefit. Keep HF wherever correctness or measured performance favors it.

Choose what to fuse

Choose fusions before mapping weights. Preserve operation order and all consumers of a shared
tensor. For example, TE can combine:

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

Look up other fusions in the PyTorch API
and operation fuser guide.
Check the installed release for support at the target shapes, dtype and hardware.

3. Map the weights

Use the Step 1 inventory and Step 2 boundaries to map each required HF key or slice to a TE
parameter and slice. Record axis, order and intended cast where the layout changes. Preserve tied
weights. For expert-parallel MoE, map each global expert ID to its owning rank and local expert
parameter. When loading quantized weights into BF16, use the checkpoint's quantization metadata
to recover the reference values.

Plan how the loader will track copies across all shards. Require it to fail on any missing
required source or destination slice. For packed weights, reconstruct the named HF tensors after loading and compare after the
intended cast to catch equal-shaped swaps. Three examples illustrate why the layout matters:

  • Llama gate and up fill separate FC1 halves and can arrive in different shards.
  • Gemma QKV uses different mappings for separate and interleaved projections.
  • Mixtral mappings pack Q heads by KV group and interleave expert gate/up rows for a fused kernel.

4. Implement

Design patterns

  • Substitute at construction when the replacement satisfies the HF caller. Keep the arguments,
    return values and state used by the workload so the surrounding HF model can call it directly.
    For example, Llama substitutes its decoder class while HF constructs the causal LM. Llama constructor
  • Compose around model-specific behavior when only part of a block matches. Keep routing or
    attention state with the code that owns it and attach TE at the boundary chosen in Step 2.
    For example, Mixtral dispatches routed tokens to its expert FFN, then combines its outputs. Mixtral MoE forward
  • Load after construction so the destination layout exists before applying the Step 3 mapping.
    Load retained HF parameters by their original mapping and verify the converted weights.
    For example, Gemma constructs the model before its standard loader maps the decoder weights
    and copies the retained embeddings. Gemma loader
  • Check each replacement's forward output first. After copying weights, run the original HF
    computation and its TE replacement in BF16 on the same representative inputs. Match relevant
    masks, positions, state and stochastic behavior. Choose tolerances for the quantities being
    compared before running the checks. Compare outputs at the same boundary and in the same
    layout. For example, for a fused norm and QKV projection, run the HF norm and all three HF projections,
    then arrange their outputs in the TE head order. A replacement constructed inside the model
    can be checked directly using captured layer inputs.

When replacement outputs differ

Choose checks that exercise the HF module being compared. These model-specific examples are
non-exhaustive.

  • If attention outputs differ, compare the positions each path uses and which keys each query
    can see. Use an input that exercises the target behavior, such as a boundary in packed data.
  • A norm that multiplies by 1 + weight (Gemma, Qwen3.5) needs zero_centered_gamma=True.
  • Head sizes: pass the attention's real query/key and value head sizes as kv_channels.
    config.head_dim is not always that; in GLM-5 it is only the RoPE part of each head.
    For multi-head latent attention, check HF's effective softmax scale and which slice of
    Q and K receives rotary embeddings before substituting the attention core.
  • Match attention dropout and projection biases to HF. Check the installed module's defaults.
  • HF's post_init() overwrites TE weights; load the checkpoint before training.

5. Validation

Once the replacement outputs match, compare integrated HF and TE
outputs on the same BF16 inputs and with the same stochastic controls. For training, match
labels and loss reduction, then compare loss and a gradient or optimizer update on a replaced
parameter in each changed path. Use the same parameter layout and exercise a routed expert for
MoE. If the full model does not fit, start with a deterministic check for each changed layer type
and report the layers it covers. When you supply a comparison, put its source entry point, exact
command, what it checks and execution status together in the handoff. Report weight mapping
coverage and any blockers. When execution is outside scope or unavailable, mark numerical results
as unverified. Use FP32 to diagnose discrepancies.
If the workload calls for lower-precision execution, repeat the relevant checks with that recipe
and its own tolerances.

For requested FP8 training, verify the BF16 port first and choose a TE recipe supported by the
installed release, GPU and operation shapes. If the trainer manages TE precision, configure its
TE backend. In a manual loop, wrap the model forward in with te.autocast(enabled=True, recipe=fp8_recipe):
and call loss.backward() after leaving the context. Keep the baseline parameter and loss dtypes.
Compare loss and a gradient or update for a replaced weight against the matched BF16 run using
recipe-specific tolerances. Report the FP8 check as pending if the target is unavailable.

  • Manual PyTorch forward and backward with TE autocast. FP8 primer
  • Configure Accelerate's TE backend for FP8 fine-tuning. Llama FP8 tutorial
  • Use MXFP8 for the fused expert MLP on Blackwell. Mixtral MXFP8 tutorial
  • Calibrate FP8 scales for token generation. Gemma FP8 inference tutorial

Before recommending a speedup, warm up and synchronize end-to-end runs of optimized HF and TE.
Compare them first in BF16 with matched effective tokens, batching and GPU topology. Measure a
requested precision change separately. Report the HF/TE versions, workload, measured result,
regions kept or replaced and why, and mapping and parity evidence. Identify unmeasured results.
For training-step timing, see the Llama warmup and timed loop
and the Mixtral per-step CUDA events.

Troubleshooting case-study: Qwen3.5

These illustrative troubleshooting notes show how checkpoint, expert and attention issues can
surface when instructions in this skill are followed over successive iterations for one example
model - Qwen3.5.

Weights are missing or left over (Qwen3.5). Take the names from the checkpoint files, not
from model.state_dict(): a checkpoint may stack all experts of a layer in one tensor, and the
layer prefix may be deeper (model.language_model.layers.N.). Skip what HF skips
(_keys_to_ignore_on_load_unexpected). A model made of sub-models needs every sub-config's
dtype set, or HF builds parts of it in float32.

MoE experts give wrong results or fail (Qwen3.5). Check the grouped-GEMM backend's supported
cuBLAS versions and expert group sizes. Check activation ordering and where
routing probabilities are applied. If using MXFP8, follow that backend's row-alignment and
activation-layout requirements and keep the router and LM head outside the expert FP8 recipe.

Gated DeltaNet rejects an input layout (Qwen3.5). Check the installed core's requirements for
Q/K/V layout and head grouping and for the gate tensors' dtypes. Retain the HF core if the
available backend cannot implement the target behavior.

Related skills

If the model is a protein or biology model, use the
BioNeMo Recipes acceleration skill
instead.

This skill doesn’t include stateful context yet, instructions only. Learn about stateful skills.

Security

Loading security scan...

Reviews (0)

Browse all →
web-performance-auditorAI-powered web performance auditor for frontend and web developers. Use it to audit a website or web app, diagnose poor Core Web Vitals (LCP, CLS, INP) and low Lighthouse scores, review JavaScript bundle size, code splitting, lazy loading, image and font loading, hydration, React rendering, Next.js/Nuxt patterns, network waterfalls, third-party scripts, and caching. Produces a prioritized, senior-engineer performance audit with a score and concrete fixes.12 installsi4h-catheter-navigationOverview of `workflows/catheter_navigation/` (fluorosim DRR, XPBD physics, vasculature digital twin). Use when the user asks what the catheter navigation workflow is, what's supported, or where to start.0 installsmcore-linting-and-formattingLinting and formatting for Megatron-LM. Covers running autoformat.sh, tools (ruff, black, isort, pylint, mypy), and code style rules.0 installsomniverse-content-servicesOmniverse Content Services, also discoverable as Omniverse Content Workspace or USD Content Workspace. Use for USD content collaboration as well as content access. Guide USD workflows on existing infrastructure, USD content versioning, 3D creation pipelines, and data access across distributed and scale-out compute. Use for manufacturing, automotive, factory and digital-twin workflows, architecture and construction, media and 3D content, robotics, fleet simulation, and physical AI content delivery. Discover requirements and route to ovstorage, ovpackage, ovlive, usd-content-workspace, and usd-caches experts.0 installsdoca-rmaxDOCA Rivermax (doca_rmax) receive streams for timing-precise media over IP (SMPTE ST 2110 video / audio, market data, scientific feeds) on a target BlueField DPU (DOCA Rivermax apps run only there), once the Rivermax libraries and license are installed; getting them is doca-setup / doca-public-knowledge-map territory. Trigger on "ST 2110 receive isn't getting frames", "sub-microsecond jitter on my media receiver", "NOT_SUPPORTED from doca_rmax_init", "no recv events after stream start", or "license check failing on a media receiver", even without naming Rivermax. Covers doca_rmax_in_stream sessions, the SDK + license precondition check, doca_rmax_get_*_supported capability queries, pairing with doca-eth queues and doca-flow steering, and DOCA_ERROR_* from Rivermax calls. Refuse and route elsewhere for programming the underlying queue (doca-eth), steering rules (doca-flow), PTP / clock sync (doca-firefly), or best-effort packet I/O.0 installstao-train-segformerSegFormer for semantic segmentation. Lightweight transformer-based architecture with hierarchical feature extraction, efficient for real-time segmentation tasks. Use when training, evaluating, exporting, quantizing, or running inference for a TAO SegFormer model. Trigger phrases include "train SegFormer", "semantic segmentation", "lightweight transformer segmenter", "real-time semantic segmentation".0 installs

More from skills

View source →
nvidia-appNVIDIA App MCP: drivers, games, laptops, overlay. Check drivers, manage and optimize games, configure laptop features.3 installsnvidia-ontology-setupSet up or troubleshoot the Auto Ontology runtime. Use for Helm (the official install), Docker Compose, developer setup, and MCP connection to an existing deployment.1 installstao-run-automlRun container-backed AutoML / hyperparameter optimization (HPO) for NVIDIA TAO networks using AutoMLRunner. Handles algorithm selection (bayesian, hyperband, asha, bohb, llm, hybrid, autoresearch), WandB experiment tracking, job execution on any TAO SDK platform, result interpretation, and per-rec custom evaluation hooks. Use when the user mentions TAO AutoML, hyperparameter optimization, HPO, automl, automl_settings, AutoMLRunner, tao_automl, bayesian search, hyperband, ASHA, LLM-guided search, autoresearch, or wants to tune train/evaluate/inference/distill/prune/quantize for a TAO network. Model actions use the resolved image; venv training requires an explicit request. Platform-agnostic — runs on any SDK (Brev, SLURM, Kubernetes, Docker). Do not use generic "keep improving" language alone to override a matching domain-specific DEFT workflow; attribute-labelled CLIP / SigLIP image-retrieval loops belong to tao-run-deft-pas unless HPO is explicit.1 installsrunai-diagnose-failed-workloadUse to diagnose failed, crashed, stopped, OOMKilled, CrashLoopBackOff, ImagePullBackOff, init, mount, node, or policy-terminated Run:ai workloads. Investigate one workload's failure; use other skills for workload health summaries, cluster health, scheduling-only Pending, or inference latency without a confirmed failure.1 installscdf-event-video-generationRun the CDF Orchestration Event Video Generation DAG on Kubernetes or OSMO - image-to-video anomaly generation, auto-labeling, and anomaly dataset generation. Select for requests about event video generation, anomaly video generation, image-to-video synthesis, Cosmos3 image2video, anomaly dataset creation, safety/surveillance SDG, or generating person-falling, person-climbing, person-running, fighting, smoking/vaping, fire/smoke, or shoplifting video clips from a seed image. Covers both event_video_generation_dag_k8s and the external-endpoints-only event_video_generation_dag_osmo. Runs environment setup first when controller readiness is unknown. Not for person-crop clothing/attribute augmentation (that is cdf-image-attribute-augmentation) and not for video style transfer.1 installsnvidia-skill-finderUse for NVIDIA-related requests where an NVIDIA skill might help, even if the user did not ask for a skill. Trigger on NVIDIA products, hardware, software, SDKs, GPUs, Jetson/JetPack/L4T/BSP/SDK Manager/driver/flashing/setup, CUDA, NIM, NeMo, Omniverse/OpenUSD/SimReady, Isaac, RAPIDS/cuDF, cuPyNumeric, cuOpt, Dynamo, Holoscan, TensorRT, DeepStream, VSS, TAO, NGC/NVCF. Do not use for generic non-NVIDIA route, optimize, deploy, AI, video, data, or infrastructure tasks.1 installs

More Build skills

Browse category →
senior-frontendBuild and review React, Next.js, TypeScript or Tailwind frontends: components, scaffolding, performance and bundle size. Use whenever the user wants a new component or app, a page feels slow, the bundle is too big, or asks for a frontend code review.641 installsui-design-systemUse when building a design system: tokens, component docs, responsive scales or developer handoff. Generates tokens with design_token_generator.py.544 installsfrontend-designGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults.353 installssenior-backendBuild and fix backend services: REST or GraphQL APIs, auth, microservices, PostgreSQL queries, migrations and load tests. Use whenever the user's API is slow or broken, needs login or auth added, a schema change, or a new endpoint or service scaffolded.252 installsself-improving-agentCurate what the agent has learned into durable project knowledge. Reviews Claude Code auto-memory (MEMORY.md and its topic files) for learnings worth keeping, promotes proven ones into CLAUDE.md or .claude/rules/, records a correction as a lesson that persists across sessions, prunes stale or duplicate entries, and turns a recurring fix into a reusable skill. Use whenever the user asks what you have learned or saved about the project, which memories should become permanent rules, to remember a lesson or stop repeating a mistake, or to clean up, audit or check memory health.179 installsusing-superpowersUse when starting any conversation - establishes how to find and use skills, requiring skill invocation before ANY response including clarifying questions146 installs

Frequently asked questions about convert-hf-to-te

What does the convert-hf-to-te skill do?

Adapt a Hugging Face PyTorch model for training with compatible Transformer Engine modules. Replace a decoder layer, sublayer or individual operation and map its checkpoint weights. Choose fusions that preserve the requested workload's behavior. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.

How do I install the convert-hf-to-te skill?

Run `npx @skills-hub-ai/cli install skills-convert-hf-to-te` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/skills-convert-hf-to-te/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.

Which AI tools does convert-hf-to-te work with?

convert-hf-to-te runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.

Is the convert-hf-to-te skill free?

Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.

How do I use convert-hf-to-te after installing it?

In Claude Code, type `/skills-convert-hf-to-te` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.

Can I share the convert-hf-to-te skill with my team?

Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.