Run this model with HF Jobs
Run codys12/Hunyuan-A13B-Instruct on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs and TRL to fine-tune https://huggingface.co/codys12/Hunyuan-A13B-Instruct. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/codys12/Hunyuan-A13B-Instruct on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Evaluate on a benchmark
Use HF Jobs to evaluate https://huggingface.co/codys12/Hunyuan-A13B-Instruct. Ask me which benchmark to run, then save the scores and the per-example results to a new dataset repo. Run `hf jobs --help` first to learn the CLI.
Quantize for lower memory use
Use HF Jobs to create a 4-bit version of https://huggingface.co/codys12/Hunyuan-A13B-Instruct. Push it to a new model repo, then reload it from there and report its memory footprint. Run `hf jobs --help` first to learn the CLI.
Instructions to use codys12/Hunyuan-A13B-Instruct with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use codys12/Hunyuan-A13B-Instruct with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="codys12/Hunyuan-A13B-Instruct", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("codys12/Hunyuan-A13B-Instruct", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use codys12/Hunyuan-A13B-Instruct with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "codys12/Hunyuan-A13B-Instruct" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "codys12/Hunyuan-A13B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/codys12/Hunyuan-A13B-Instruct
- SGLang
How to use codys12/Hunyuan-A13B-Instruct with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "codys12/Hunyuan-A13B-Instruct" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "codys12/Hunyuan-A13B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "codys12/Hunyuan-A13B-Instruct" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "codys12/Hunyuan-A13B-Instruct", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use codys12/Hunyuan-A13B-Instruct with Docker Model Runner:
docker model run hf.co/codys12/Hunyuan-A13B-Instruct
Upload modeling_hunyuan.py
Browse files123452 unmodified lines89101112131449 unmodified lines64656667686970183 unmodified lines2542552562572582592605 unmodified lines2662672682692702712 unmodified lines274275276277278279280118 unmodified lines39940040140240340440544 unmodified lines450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591536 unmodified lines1128112911301131113211331134113511361137113811391140114111421143114411455 unmodified lines115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119086 unmodified lines127712781279128012811282172 unmodified lines1455145614571458145914601461123 unmodified lines158515861587158815891590159152 unmodified lines16441645164616471648164998 unmodified lines1748174917501751# coding=utf-8# Copyright 2024 Tencent Inc. All Rights Reserved.#""" PyTorch HunYuan model."""2 unmodified linesfrom typing import List, Optional, Tuple, Unionimport torchtorch.set_default_dtype(torch.float32)from torch import Tensorimport torch.nn.functional as Fimport torch.utils.checkpoint49 unmodified linesdef topkgating(logits: Tensor, topk: int):logits = logits.float()gates = F.softmax(logits, dim=1)expert_capacity = topk * gates.shape[0]num_experts = int(gates.shape[1])# Top-k router probability and corresponding expert indices for each token.# Shape: [tokens_per_group, num_selected_experts].183 unmodified linesself.max_position_embeddings = max_position_embeddingsself.base = baseinv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))inv_freq = inv_freq.bfloat16()self.register_buffer("inv_freq", inv_freq, persistent=False)# Build here to make `torch.jit.trace` work.5 unmodified linesself.max_seq_len_cached = seq_lent = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)freqs = torch.outer(t, self.inv_freq)# Different from paper, but it uses a different permutation in order to obtain the same calculationemb = torch.cat((freqs, freqs), dim=-1).float()2 unmodified linesdef forward(self, x, seq_len=None):# x: [bs, num_attention_heads, seq_len, head_size]if seq_len > self.max_seq_len_cached:self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)return (118 unmodified linesself.layer_idx = layer_idxself.hidden_size = config.hidden_sizeif is_shared_mlp:self.intermediate_size = config.intermediate_size * config.num_shared_expertelse:self.intermediate_size = config.intermediate_sizeself.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)44 unmodified linesif self.moe_topk == 1:gate_output = top1gating(logits, random_routing_dropped_token=self.random_routing_dropped_token)else:gate_output = topkgating(logits, self.moe_topk)return gate_outputclass HunYuanMoE(nn.Module):"""Mixture-of-Experts block with vectorized expert execution and Straight‑Through Estimator (STE) utilities.This implementation removes all Python‑side loops over experts. Expert parameters are **stacked** on‑the‑fly andall experts are executed in a single batched matmul sequence, which allows efficient tensor‑parallel execution(e.g. with DeepSpeed ZeRO‑3) while keeping the state‑dict format unchanged (each expert remains an individualsub‑module for full compatibility with existing checkpoints)."""def __init__(self, config: HunYuanConfig, layer_idx: Optional[int] = None):super().__init__()self.config = configself.layer_idx = layer_idxself.moe_topk = config.moe_topkself.num_experts = config.num_experts# Optional shared MLP branch (mixed MoE + dense)if config.use_mixed_mlp_moe:self.shared_mlp = HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=True)# Routerself.gate = HunYuanTopKGate(config, layer_idx=layer_idx)# Experts kept as individual sub‑modules so that load_state_dict / save_pretrained stay identical.self.experts = nn.ModuleList([HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=False) for _ in range(config.num_experts)])# ---------------------------------------------------------------------# Internal helpers# ---------------------------------------------------------------------def _stack_weights(self):"""Return stacked (batched) expert weights for gate/up/down projections.Shapes:Wg : (E, I, H)Wu : (E, I, H)Wd : (E, H, I) – note transposed compared to nn.Linear's weight so thattorch.matmul(act, Wd.transpose(-2,‑1)) produces (E, C, H)"""Wg = torch.stack([exp.gate_proj.weight for exp in self.experts], dim=0)Wu = torch.stack([exp.up_proj.weight for exp in self.experts], dim=0)Wd = torch.stack([exp.down_proj.weight for exp in self.experts], dim=0)return Wg, Wu, Wd# ---------------------------------------------------------------------# Public API# ---------------------------------------------------------------------def forward(self,hidden_states: torch.Tensor,*,return_router_logits: bool = False,):"""Sparse Top‑k MoE forward pass ("y_sparse") with optional router logits.This is the route used during both training and inference for the *sparse*branch. No Python loops over experts are used.""""bsz, seq_len, hidden_size = hidden_states.shape# Optional dense branch when using mixed MoEif self.config.use_mixed_mlp_moe:hidden_states_mlp = self.shared_mlp(hidden_states)# ---------------- Routing ----------------l_moe, combine_weights, dispatch_mask, _ = self.gate(hidden_states)flat_input = hidden_states.reshape(-1, hidden_size) # (S, H) where S = B*T# dispatch tokens → expertsdispatched_input = torch.einsum("sec,sm->ecm", # (E, C, H)dispatch_mask.to(hidden_states.dtype),flat_input)# ---------------- Expert computation ----------------Wg, Wu, Wd = self._stack_weights()Wg = Wg.to(hidden_states.dtype)Wu = Wu.to(hidden_states.dtype)Wd = Wd.to(hidden_states.dtype)gate_out = torch.einsum("ech,eih->eci", dispatched_input, Wg) # (E, C, I)up_out = torch.einsum("ech,eih->eci", dispatched_input, Wu) # (E, C, I)act_fn = self.experts[0].act_fninterm = act_fn(gate_out) * up_out # (E, C, I)expert_output = torch.matmul(interm, Wd.transpose(-2, -1)) # (E, C, H)# ---------------- Combine ----------------combined_output = torch.einsum("sec,ecm->sm", # (S, H)combine_weights.to(hidden_states.dtype),expert_output)combined_output = combined_output.reshape(bsz, seq_len, hidden_size)if self.config.use_mixed_mlp_moe:combined_output = hidden_states_mlp + combined_outputif return_router_logits:router_logits = self.gate.wg(flat_input).view(bsz, seq_len, self.num_experts)return combined_output, router_logitsreturn combined_output# ---------------------------------------------------------------------# Dense branch – outputs *all* expert activations (no routing)# ---------------------------------------------------------------------@torch.no_grad()def forward_all(self, hidden_states: torch.Tensor):"""Compute every expert on every token ("dense" MoE path).Returns:Tensor of shape (B, T, E, H) – per‑expert hidden states."""bsz, seq_len, hidden_size = hidden_states.shapeflat_input = hidden_states.reshape(-1, hidden_size) # (S, H)Wg, Wu, Wd = self._stack_weights()Wg = Wg.to(hidden_states.dtype)Wu = Wu.to(hidden_states.dtype)Wd = Wd.to(hidden_states.dtype)gate_out = torch.einsum("sh,eih->esi", flat_input, Wg) # (E, S, I)up_out = torch.einsum("sh,eih->esi", flat_input, Wu) # (E, S, I)act_fn = self.experts[0].act_fninterm = act_fn(gate_out) * up_out # (E, S, I)dense_out = torch.matmul(interm, Wd.transpose(-2, -1)) # (E, S, H)dense_out = dense_out.permute(1, 0, 2).contiguous() # (S, E, H)dense_out = dense_out.view(bsz, seq_len, self.num_experts, hidden_size) # (B, T, E, H)if self.config.use_mixed_mlp_moe:hidden_states_mlp = self.shared_mlp(hidden_states) # (B, T, H)dense_out = dense_out + hidden_states_mlp.unsqueeze(2)return dense_outclass HunYuanAttention(nn.Module):"""Multi-headed attention from 'Attention Is All You Need' paper"""536 unmodified lineskv_states: Optional[Tuple[torch.Tensor]] = None,**kwargs,) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:"""Modified to include Straight‑Through Estimator (STE) training logic."""if "padding_mask" in kwargs:warnings.warn("Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use ""`attention_mask` instead.`")# ---------------- Self‑Attention ----------------residual = hidden_stateshidden_states = self.input_layernorm(hidden_states)hidden_states, self_attn_weights, present_key_value, kv_states = self.self_attn(hidden_states=hidden_states,attention_mask=attention_mask,5 unmodified lines**kwargs,)hidden_states = residual + hidden_states# ---------------- MLP / MoE (+STE) ----------------residual = hidden_stateshidden_states = self.post_attention_layernorm(hidden_states)if self.training and isinstance(self.mlp, HunYuanMoE):# Sparse path + router logitsy_sparse, router_logits = self.mlp(hidden_states, return_router_logits=True)# Dense (all‑experts) path – memory‑efficient, no gradwith torch.no_grad():y_all = self.mlp.forward_all(hidden_states) # (B, T, E, H)gate = router_logits.softmax(-1).unsqueeze(-1) # (B, T, E, 1)y_dense = (gate * y_all).sum(-2) # (B, T, H)mlp_out = y_dense + (y_sparse - y_dense).detach()else:mlp_out = self.mlp(hidden_states)hidden_states = residual + mlp_out# ---------------- Outputs ----------------outputs = (hidden_states,)if output_attentions:outputs += (self_attn_weights,)if use_cache:outputs += (present_key_value,)outputs += (kv_states,)return outputsclass HunYuanPreTrainedModel(PreTrainedModel):config_class = HunYuanConfigbase_model_prefix = "model"86 unmodified lines"""class HunYuanModel(HunYuanPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`HunYuanDecoderLayer`]172 unmodified lines)class HunYuanForCausalLM(HunYuanPreTrainedModel):_tied_weights_keys = ["lm_head.weight"]def __init__(self, config: HunYuanConfig):123 unmodified linesif isinstance(past_key_values, Cache):cache_length = past_key_values.get_seq_length()past_length = past_key_values.seen_tokensmax_cache_length = past_key_values.get_max_length()else:cache_length = past_length = past_key_values[0][0].shape[2]max_cache_length = None52 unmodified linesreturn reordered_pastclass HunYuanForSequenceClassification(HunYuanPreTrainedModel):def __init__(self, config):super().__init__(config)98 unmodified linespast_key_values=transformer_outputs.past_key_values,hidden_states=transformer_outputs.hidden_states,attentions=transformer_outputs.attentions,)123456789101112131415162 unmodified lines19202122232449 unmodified lines7475767778798081183 unmodified lines2652662672682692702715 unmodified lines2772782792802812822832 unmodified lines286287288289290291292118 unmodified lines41141241341441541641744 unmodified lines462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527536 unmodified lines1064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510965 unmodified lines1102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114886 unmodified lines1235123612371238123912401241124212431244172 unmodified lines1417141814191420142114221423123 unmodified lines154715481549155015511552155352 unmodified lines16061607160816091610161116121613161416151616161716181619162016211622162316241625162698 unmodified lines172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910# Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.## Licensed under the TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## https://github.com/Tencent/Tencent-Hunyuan-Large/blob/main/License.docx## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.#""" PyTorch HunYuan model."""2 unmodified linesfrom typing import List, Optional, Tuple, Unionimport torchfrom torch import Tensorimport torch.nn.functional as Fimport torch.utils.checkpoint49 unmodified linesdef topkgating(logits: Tensor, topk: int):logits = logits.float()gates = F.softmax(logits, dim=1)# expert_capacity = topk * gates.shape[0]expert_capacity = max(topk, topk * gates.shape[0] // gates.shape[1])num_experts = int(gates.shape[1])# Top-k router probability and corresponding expert indices for each token.# Shape: [tokens_per_group, num_selected_experts].183 unmodified linesself.max_position_embeddings = max_position_embeddingsself.base = baseinv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))# inv_freq = inv_freq.bfloat16()self.register_buffer("inv_freq", inv_freq, persistent=False)# Build here to make `torch.jit.trace` work.5 unmodified linesself.max_seq_len_cached = seq_lent = torch.arange(self.max_seq_len_cached, device=device, dtype=torch.float32)self.inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))freqs = torch.outer(t, self.inv_freq)# Different from paper, but it uses a different permutation in order to obtain the same calculationemb = torch.cat((freqs, freqs), dim=-1).float()2 unmodified linesdef forward(self, x, seq_len=None):# x: [bs, num_attention_heads, seq_len, head_size]if seq_len > self.max_seq_len_cached or self.inv_freq.dtype != torch.float32:self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)return (118 unmodified linesself.layer_idx = layer_idxself.hidden_size = config.hidden_sizeif is_shared_mlp:self.intermediate_size = config.intermediate_size * config.num_shared_expert[0]else:self.intermediate_size = config.intermediate_sizeself.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)44 unmodified linesif self.moe_topk == 1:gate_output = top1gating(logits, random_routing_dropped_token=self.random_routing_dropped_token)else:gate_output = topkgating(logits, self.moe_topk[0])return gate_outputclass HunYuanMoE(nn.Module):def __init__(self, config: HunYuanConfig, layer_idx: Optional[int] = None):super().__init__()self.config = configself.layer_idx = layer_idxself.moe_topk = config.moe_topkself.num_experts = config.num_expertsif config.use_mixed_mlp_moe:self.shared_mlp = HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=True)self.gate = HunYuanTopKGate(config, layer_idx=layer_idx)self.experts = nn.ModuleList([HunYuanMLP(config, layer_idx=layer_idx, is_shared_mlp=False) for _ in range(config.num_experts)])def forward(self, hidden_states):bsz, seq_len, hidden_size = hidden_states.shapeif self.config.use_mixed_mlp_moe:hidden_states_mlp = self.shared_mlp(hidden_states)l_moe, combine_weights, dispatch_mask, exp_counts = self.gate(hidden_states)reshaped_input = hidden_states.reshape(-1, hidden_size)dispatched_input = torch.einsum("sec,sm->ecm", dispatch_mask.type_as(hidden_states), reshaped_input)chunks = dispatched_input.chunk(self.num_experts, dim=0)expert_outputs = []for chunk, expert in zip(chunks, self.experts):expert_outputs.append(expert(chunk))expert_output = torch.cat(expert_outputs, dim=0)combined_output = torch.einsum("sec,ecm->sm", combine_weights.type_as(hidden_states), expert_output)combined_output = combined_output.reshape(bsz, seq_len, hidden_size)if self.config.use_mixed_mlp_moe:output = hidden_states_mlp + combined_outputelse:output = combined_outputreturn outputdef repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:"""This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)"""batch, num_key_value_heads, slen, head_dim = hidden_states.shapeif n_rep == 1:return hidden_stateshidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)class HunYuanAttention(nn.Module):"""Multi-headed attention from 'Attention Is All You Need' paper"""536 unmodified lineskv_states: Optional[Tuple[torch.Tensor]] = None,**kwargs,) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:"""Args:hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`attention_mask (`torch.FloatTensor`, *optional*):attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,query_sequence_length, key_sequence_length)` if default attention is used.output_attentions (`bool`, *optional*):Whether or not to return the attentions tensors of all attention layers. See `attentions` underreturned tensors for more detail.use_cache (`bool`, *optional*):If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding(see `past_key_values`).past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection stateskv_states (`Tuple(torch.FloatTensor)`, *optional*): Used when CLA is enabled,key and value states from past attention blocks"""if "padding_mask" in kwargs:warnings.warn("Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use ""`attention_mask` instead.`")residual = hidden_stateshidden_states = self.input_layernorm(hidden_states)# Self Attentionhidden_states, self_attn_weights, present_key_value, kv_states = self.self_attn(hidden_states=hidden_states,attention_mask=attention_mask,5 unmodified lines**kwargs,)hidden_states = residual + hidden_states# Fully Connectedresidual = hidden_stateshidden_states = self.post_attention_layernorm(hidden_states)hidden_states = self.mlp(hidden_states)hidden_states = residual + hidden_statesoutputs = (hidden_states,)if output_attentions:outputs += (self_attn_weights,)if use_cache:outputs += (present_key_value,)outputs += (kv_states,)return outputsHUNYUAN_START_DOCSTRING = r"""This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods thelibrary implements for all its model (such as downloading or saving, resizing the input embeddings, pruning headsetc.)This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usageand behavior.Parameters:config ([`HunYuanConfig`]):Model configuration class with all the parameters of the model. Initializing with a config file does notload the weights associated with the model, only the configuration. Check out the[`~PreTrainedModel.from_pretrained`] method to load the model weights."""@add_start_docstrings("The bare HunYuan Model outputting raw hidden-states without any specific head on top.",HUNYUAN_START_DOCSTRING,)class HunYuanPreTrainedModel(PreTrainedModel):config_class = HunYuanConfigbase_model_prefix = "model"86 unmodified lines"""@add_start_docstrings("The bare HunYuan Model outputting raw hidden-states without any specific head on top.",HUNYUAN_START_DOCSTRING,)class HunYuanModel(HunYuanPreTrainedModel):"""Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`HunYuanDecoderLayer`]172 unmodified lines)class HunYuanMoEV1ForCausalLM(HunYuanPreTrainedModel):_tied_weights_keys = ["lm_head.weight"]def __init__(self, config: HunYuanConfig):123 unmodified linesif isinstance(past_key_values, Cache):cache_length = past_key_values.get_seq_length()past_length = past_key_values.seen_tokensmax_cache_length = past_key_values.get_max_cache_shape()else:cache_length = past_length = past_key_values[0][0].shape[2]max_cache_length = None52 unmodified linesreturn reordered_past@add_start_docstrings("""The HunYuan Model transformer with a sequence classification head on top (linear layer).[`HunYuanForSequenceClassification`] uses the last token in order to do the classification, as other causal models(e.g. GPT-2) do.Since it does classification on the last token, it requires to know the position of the last token. If a`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. Ifno `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess thepadding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value ineach row of the batch).""",HUNYUAN_START_DOCSTRING,)class HunYuanForSequenceClassification(HunYuanPreTrainedModel):def __init__(self, config):super().__init__(config)98 unmodified linespast_key_values=transformer_outputs.past_key_values,hidden_states=transformer_outputs.hidden_states,attentions=transformer_outputs.attentions,)# ================================================================# Dense/Sparse MoE utilities# These enable dense training (all experts active) with sparse inference,# by fusing the per‑expert parameters into single linear layers and# applying a straight‑through estimator (STE) – gradients flow through the# dense path, while the forward pass matches sparse routing behaviour.# ================================================================import typesclass HunYuanDenseMoE(nn.Module):"""Dense counterpart of :class:`HunYuanMoE`.* The per‑expert linear layers (``gate_proj``, ``up_proj``, ``down_proj``)are concatenated to form three *fused* linear layers.* Forward pass:1. **Dense path** – every expert contributes,weighted by the softmax router probabilities.2. **Sparse path** – only the Top‑K experts (identical to theoriginal sparse MoE) are evaluated.3. **STE** – ``output = dense + (sparse – dense).detach()`` –identical values to sparse inference, dense gradients."""def __init__(self, moe: "HunYuanMoE"):super().__init__()self.config = moe.configself.layer_idx = moe.layer_idxself.num_experts = moe.num_experts# All experts share the same hidden/intermediate sizesself.hidden_size = moe.experts[0].hidden_sizeself.intermediate_size = moe.experts[0].intermediate_size# Router is reused directlyself.gate = moe.gate# ------------------------------------------------------------------# Fuse per‑expert parameters# ------------------------------------------------------------------with torch.no_grad():fused_gate_w = torch.cat([exp.gate_proj.weight for exp in moe.experts], dim=0).clone()fused_up_w = torch.cat([exp.up_proj.weight for exp in moe.experts], dim=0).clone()# down_proj weights are shaped (hidden, intermediate)fused_down_w = torch.cat([exp.down_proj.weight for exp in moe.experts], dim=1).clone()self.fused_gate_proj = nn.Linear(self.hidden_size,self.intermediate_size * self.num_experts,bias=False)self.fused_up_proj = nn.Linear(self.hidden_size,self.intermediate_size * self.num_experts,bias=False)self.fused_down_proj = nn.Linear(self.intermediate_size * self.num_experts,self.hidden_size,bias=False)# Load weightsself.fused_gate_proj.weight.data.copy_(fused_gate_w)self.fused_up_proj.weight.data.copy_(fused_up_w)self.fused_down_proj.weight.data.copy_(fused_down_w)self.act_fn = moe.experts[0].act_fnself.topk = self.gate.moe_topk[0] if isinstance(self.gate.moe_topk, (list, tuple)) else self.gate.moe_topkdef _dense_path(self, x, probs):"""Compute dense mixture – every expert active."""gate_out = self.fused_gate_proj(x) # (T, I*E)up_out = self.fused_up_proj(x) # (T, I*E)interm = self.act_fn(gate_out) * up_out # (T, I*E)# Reshape to (T, E, I)interm = interm.view(-1, self.num_experts, self.intermediate_size)# Weight by softmax router probabilitiesinterm_weighted = interm * probs.unsqueeze(-1) # (T, E, I)# Collapse experts back to vector and project downdense_flat = interm_weighted.reshape(-1, self.intermediate_size * self.num_experts)return self.fused_down_proj(dense_flat) # (T, H)def _sparse_path(self, x, probs):"""Compute sparse Top‑K mixture (matches original inference)."""# Pre‑compute per‑expert activations to avoid repeated forward callsgate_out = self.fused_gate_proj(x) # (T, I*E)up_out = self.fused_up_proj(x) # (T, I*E)interm = self.act_fn(gate_out) * up_out # (T, I*E)interm = interm.view(-1, self.num_experts, self.intermediate_size) # (T,E,I)# Top‑K experts per tokenvalues, indices = torch.topk(probs, self.topk, dim=1) # (T,K)# Gather corresponding intermediate activationsgathered = interm.gather(1, indices.unsqueeze(-1).expand(-1, -1, self.intermediate_size)) # (T,K,I)gathered = gathered * values.unsqueeze(-1) # weight by router prob# Gather matching down-proj weights# fused_down_proj.weight: (H, I*E) -> reshape to (E,I,H)down_w = self.fused_down_proj.weight.view(self.hidden_size,self.num_experts,self.intermediate_size).permute(1,2,0).contiguous() # (E,I,H)selected_w = down_w.index_select(0, indices.reshape(-1)).view(indices.size(0), self.topk,self.intermediate_size, self.hidden_size)# (T,K,I,H)# Compute output: batch matmul over Isparse_out = torch.einsum('t k i, t k i h -> t h', gathered, selected_w)return sparse_out # (T, H)def forward(self, hidden_states):bsz, seq_len, _ = hidden_states.shapex = hidden_states.reshape(-1, self.hidden_size) # T x Hlogits = self.gate.wg(x) # (T,E)probs = torch.softmax(logits, dim=1) # (T,E)dense_out = self._dense_path(x, probs)sparse_out = self._sparse_path(x, probs)out = dense_out + (sparse_out - dense_out).detach() # STEreturn out.view(bsz, seq_len, self.hidden_size)# -----------------------------------------------------------------------# Helper for module replacement# -----------------------------------------------------------------------def _replace_submodule(root: nn.Module, target: str, new_module: nn.Module):"""Replace a (possibly nested) sub‑module.``target`` is the dotted path returned by ``model.named_modules()``."""parts = target.split('.')parent = rootfor p in parts[:-1]:parent = getattr(parent, p)setattr(parent, parts[-1], new_module)# -----------------------------------------------------------------------# Public APIs# -----------------------------------------------------------------------def densify(model: nn.Module):"""Convert all :class:`HunYuanMoE` modules under *model* to:class:`HunYuanDenseMoE`. Operates **in‑place**."""replacements = []for name, module in model.named_modules():if isinstance(module, HunYuanMoE):replacements.append((name, module))for name, sparse_moe in replacements:dense_moe = HunYuanDenseMoE(sparse_moe).to(next(sparse_moe.parameters()).device)_replace_submodule(model, name, dense_moe)return modeldef sparsify(model: nn.Module):"""Rebuild standard sparse :class:`HunYuanMoE` modules from theirfused :class:`HunYuanDenseMoE` form. Operates **in‑place**."""replacements = []for name, module in model.named_modules():if isinstance(module, HunYuanDenseMoE):replacements.append((name, module))for name, dense_moe in replacements:cfg = dense_moe.configsparse_moe = HunYuanMoE(cfg, layer_idx=dense_moe.layer_idx).to(next(dense_moe.parameters()).device)# Copy routersparse_moe.gate.load_state_dict(dense_moe.gate.state_dict())# Slice fused weights back to per‑expertfor idx, expert in enumerate(sparse_moe.experts):start = idx * dense_moe.intermediate_sizeend = (idx + 1) * dense_moe.intermediate_sizeexpert.gate_proj.weight.data.copy_(dense_moe.fused_gate_proj.weight.data[start:end])expert.up_proj.weight.data.copy_(dense_moe.fused_up_proj.weight.data[start:end])expert.down_proj.weight.data.copy_(dense_moe.fused_down_proj.weight.data[:, start:end])_replace_submodule(model, name, sparse_moe)return model
modeling_hunyuan.py+303-144