Text Generation
Transformers
Safetensors
English
Chinese
k2_horizon
k2-horizon
0.9b
dense
reasoning
knowledge-distillation
ifm
conversational
custom_code
Instructions to use IFM/K2-Horizon-0.9B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use IFM/K2-Horizon-0.9B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="IFM/K2-Horizon-0.9B", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("IFM/K2-Horizon-0.9B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use IFM/K2-Horizon-0.9B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "IFM/K2-Horizon-0.9B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "IFM/K2-Horizon-0.9B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/IFM/K2-Horizon-0.9B
- SGLang
How to use IFM/K2-Horizon-0.9B 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 "IFM/K2-Horizon-0.9B" \ --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": "IFM/K2-Horizon-0.9B", "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 "IFM/K2-Horizon-0.9B" \ --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": "IFM/K2-Horizon-0.9B", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use IFM/K2-Horizon-0.9B with Docker Model Runner:
docker model run hf.co/IFM/K2-Horizon-0.9B
Upload modeling_k2_horizon.py to rl-mopd
Browse files- modeling_k2_horizon.py +1116 -0
modeling_k2_horizon.py
ADDED
|
@@ -0,0 +1,1116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 2 |
+
# This file was automatically generated from src/transformers/models/qwen3_moe/modular_qwen3_moe.py.
|
| 3 |
+
# Do NOT edit this file manually as any edits will be overwritten by the generation of
|
| 4 |
+
# the file from the modular. If any change should be done, please apply the change to the
|
| 5 |
+
# modular_qwen3_moe.py file directly. One of our CI enforces this.
|
| 6 |
+
# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
|
| 7 |
+
# coding=utf-8
|
| 8 |
+
# Copyright 2025 The Qwen team, Alibaba Group and the HuggingFace Inc. team. All rights reserved.
|
| 9 |
+
#
|
| 10 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 11 |
+
# you may not use this file except in compliance with the License.
|
| 12 |
+
# You may obtain a copy of the License at
|
| 13 |
+
#
|
| 14 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 15 |
+
#
|
| 16 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 17 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 18 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 19 |
+
# See the License for the specific language governing permissions and
|
| 20 |
+
# limitations under the License.
|
| 21 |
+
|
| 22 |
+
from typing import Callable, Optional, Union
|
| 23 |
+
|
| 24 |
+
import math
|
| 25 |
+
import torch
|
| 26 |
+
import torch.nn.functional as F
|
| 27 |
+
from torch import nn
|
| 28 |
+
|
| 29 |
+
from transformers.activations import ACT2FN
|
| 30 |
+
from transformers.cache_utils import Cache, DynamicCache
|
| 31 |
+
from transformers.generation import GenerationMixin
|
| 32 |
+
from transformers.masking_utils import create_causal_mask, create_sliding_window_causal_mask
|
| 33 |
+
from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
|
| 34 |
+
from transformers.modeling_layers import (
|
| 35 |
+
GenericForQuestionAnswering,
|
| 36 |
+
GenericForSequenceClassification,
|
| 37 |
+
GenericForTokenClassification,
|
| 38 |
+
GradientCheckpointingLayer,
|
| 39 |
+
)
|
| 40 |
+
from transformers.modeling_outputs import MoeCausalLMOutputWithPast, MoeModelOutputWithPast
|
| 41 |
+
from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
|
| 42 |
+
from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
|
| 43 |
+
from transformers.processing_utils import Unpack
|
| 44 |
+
from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
|
| 45 |
+
from transformers.utils.generic import maybe_autocast
|
| 46 |
+
from transformers.utils.deprecation import deprecate_kwarg
|
| 47 |
+
from transformers.utils.output_capturing import OutputRecorder
|
| 48 |
+
|
| 49 |
+
from .configuration_k2_horizon import K2HorizonConfig
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def rotate_half(x):
|
| 53 |
+
"""Rotates half the hidden dims of the input."""
|
| 54 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 55 |
+
x2 = x[..., x.shape[-1] // 2:]
|
| 56 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
|
| 60 |
+
"""Applies Rotary Position Embedding to the query and key tensors.
|
| 61 |
+
|
| 62 |
+
Args:
|
| 63 |
+
q (`torch.Tensor`): The query tensor.
|
| 64 |
+
k (`torch.Tensor`): The key tensor.
|
| 65 |
+
cos (`torch.Tensor`): The cosine part of the rotary embedding.
|
| 66 |
+
sin (`torch.Tensor`): The sine part of the rotary embedding.
|
| 67 |
+
position_ids (`torch.Tensor`, *optional*):
|
| 68 |
+
Deprecated and unused.
|
| 69 |
+
unsqueeze_dim (`int`, *optional*, defaults to 1):
|
| 70 |
+
The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
|
| 71 |
+
sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
|
| 72 |
+
that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
|
| 73 |
+
k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
|
| 74 |
+
cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
|
| 75 |
+
the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
|
| 76 |
+
Returns:
|
| 77 |
+
`tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
|
| 78 |
+
"""
|
| 79 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 80 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 81 |
+
q_embed = (q * cos) + (rotate_half(q) * sin)
|
| 82 |
+
k_embed = (k * cos) + (rotate_half(k) * sin)
|
| 83 |
+
return q_embed, k_embed
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
|
| 87 |
+
"""
|
| 88 |
+
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
| 89 |
+
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
| 90 |
+
"""
|
| 91 |
+
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
| 92 |
+
if n_rep == 1:
|
| 93 |
+
return hidden_states
|
| 94 |
+
hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
|
| 95 |
+
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def split_to_interleaved(x):
|
| 99 |
+
# Split halves: x0 x1 x2 x3 ... y0 y1 y2 y3 ...
|
| 100 |
+
# Interleaved: x0 y0 x1 y1 x2 y2 x3 y3 ...
|
| 101 |
+
return x.reshape(*x.shape[:-1], 2, -1).transpose(-1, -2).reshape(*x.shape[:-1], -1)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def interleaved_to_split(x):
|
| 105 |
+
# Interleaved: x0 y0 x1 y1 x2 y2 x3 y3 ...
|
| 106 |
+
# Split halves: x0 x1 x2 x3 ... y0 y1 y2 y3 ...
|
| 107 |
+
return x.reshape(*x.shape[:-1], -1, 2).transpose(-1, -2).reshape(*x.shape[:-1], -1)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def eager_attention_forward(
|
| 111 |
+
module: nn.Module,
|
| 112 |
+
query: torch.Tensor,
|
| 113 |
+
key: torch.Tensor,
|
| 114 |
+
value: torch.Tensor,
|
| 115 |
+
attention_mask: Optional[torch.Tensor],
|
| 116 |
+
scaling: float,
|
| 117 |
+
dropout: float = 0.0,
|
| 118 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 119 |
+
):
|
| 120 |
+
key_states = repeat_kv(key, module.num_key_value_groups)
|
| 121 |
+
value_states = repeat_kv(value, module.num_key_value_groups)
|
| 122 |
+
|
| 123 |
+
attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
|
| 124 |
+
if attention_mask is not None:
|
| 125 |
+
causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
|
| 126 |
+
attn_weights = attn_weights + causal_mask
|
| 127 |
+
|
| 128 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
|
| 129 |
+
attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
|
| 130 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 131 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
| 132 |
+
|
| 133 |
+
return attn_output, attn_weights
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def calc_router_weights(
|
| 137 |
+
router_logits: torch.Tensor,
|
| 138 |
+
router_bias: Optional[torch.Tensor],
|
| 139 |
+
score_func: str,
|
| 140 |
+
top_k: int,
|
| 141 |
+
scaling_factor: Optional[float],
|
| 142 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 143 |
+
"""Return native-XLLM-compatible routing weights and selected experts.
|
| 144 |
+
|
| 145 |
+
XLLM applies router bias only to the values used for top-k selection. The
|
| 146 |
+
selected routes are still weighted by the original router probabilities,
|
| 147 |
+
then optionally normalized and scaled.
|
| 148 |
+
"""
|
| 149 |
+
if score_func == "softmax":
|
| 150 |
+
routing_scores = F.softmax(router_logits, dim=-1, dtype=torch.float32)
|
| 151 |
+
elif score_func == "sigmoid":
|
| 152 |
+
routing_scores = torch.sigmoid(router_logits.to(torch.float32))
|
| 153 |
+
else:
|
| 154 |
+
raise ValueError(f"Unsupported router score function: {score_func}")
|
| 155 |
+
|
| 156 |
+
selection_scores = routing_scores
|
| 157 |
+
if router_bias is not None:
|
| 158 |
+
selection_scores = selection_scores + router_bias.to(selection_scores)
|
| 159 |
+
|
| 160 |
+
selected_indices = torch.topk(selection_scores, top_k, dim=-1).indices
|
| 161 |
+
routing_weights = torch.gather(routing_scores, dim=-1, index=selected_indices)
|
| 162 |
+
if top_k > 1:
|
| 163 |
+
routing_weights = routing_weights / routing_weights.sum(dim=-1, keepdim=True)
|
| 164 |
+
if scaling_factor is not None:
|
| 165 |
+
routing_weights = routing_weights * scaling_factor
|
| 166 |
+
return routing_weights, selected_indices
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def combine_routed_experts(
|
| 170 |
+
hidden_states: torch.Tensor,
|
| 171 |
+
routing_weights: torch.Tensor,
|
| 172 |
+
selected_indices: torch.Tensor,
|
| 173 |
+
experts: nn.ModuleList,
|
| 174 |
+
activation: Optional[Callable[[torch.Tensor], torch.Tensor]] = None,
|
| 175 |
+
) -> torch.Tensor:
|
| 176 |
+
num_tokens, hidden_dim = hidden_states.shape
|
| 177 |
+
final_hidden_states = torch.zeros(
|
| 178 |
+
(num_tokens, experts[0].out_features),
|
| 179 |
+
dtype=hidden_states.dtype,
|
| 180 |
+
device=hidden_states.device,
|
| 181 |
+
)
|
| 182 |
+
expert_mask = torch.nn.functional.one_hot(
|
| 183 |
+
selected_indices, num_classes=len(experts)
|
| 184 |
+
).permute(2, 1, 0)
|
| 185 |
+
|
| 186 |
+
for expert_idx in torch.nonzero(expert_mask.sum(dim=(-1, -2)), as_tuple=False).flatten():
|
| 187 |
+
topk_positions, token_positions = torch.where(expert_mask[int(expert_idx)])
|
| 188 |
+
expert_states = experts[int(expert_idx)](hidden_states[token_positions])
|
| 189 |
+
if activation is not None:
|
| 190 |
+
expert_states = activation(expert_states)
|
| 191 |
+
expert_states = expert_states * routing_weights[token_positions, topk_positions, None].to(expert_states.dtype)
|
| 192 |
+
final_hidden_states.index_add_(0, token_positions, expert_states.to(hidden_states.dtype))
|
| 193 |
+
|
| 194 |
+
return final_hidden_states
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
class K2HorizonAttention(nn.Module):
|
| 198 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
| 199 |
+
|
| 200 |
+
def __init__(self, config: K2HorizonConfig, layer_idx: int):
|
| 201 |
+
super().__init__()
|
| 202 |
+
self.config = config
|
| 203 |
+
self.layer_idx = layer_idx
|
| 204 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 205 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 206 |
+
self.scaling = self.head_dim ** -0.5
|
| 207 |
+
self.attention_dropout = config.attention_dropout
|
| 208 |
+
self.is_causal = True
|
| 209 |
+
|
| 210 |
+
self.rope_head_dim = self.head_dim if config.rope_head_dim is None else config.rope_head_dim
|
| 211 |
+
|
| 212 |
+
self.q_proj = nn.Linear(
|
| 213 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 214 |
+
)
|
| 215 |
+
self.k_proj = nn.Linear(
|
| 216 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 217 |
+
)
|
| 218 |
+
self.v_proj = nn.Linear(
|
| 219 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 220 |
+
)
|
| 221 |
+
self.o_proj = nn.Linear(
|
| 222 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
self.gate_func = config.attention_gate_func
|
| 226 |
+
if self.gate_func is not None:
|
| 227 |
+
self.gate_proj = nn.Linear(
|
| 228 |
+
config.hidden_size,
|
| 229 |
+
config.num_attention_heads * self.head_dim,
|
| 230 |
+
bias=False)
|
| 231 |
+
|
| 232 |
+
if config.query_key_norm:
|
| 233 |
+
self.q_norm = K2HorizonRMSNorm(
|
| 234 |
+
hidden_size=config.num_attention_heads * self.head_dim,
|
| 235 |
+
n_groups=config.num_attention_heads,
|
| 236 |
+
eps=config.rms_norm_eps)
|
| 237 |
+
self.k_norm = K2HorizonRMSNorm(
|
| 238 |
+
hidden_size=config.num_key_value_heads * self.head_dim,
|
| 239 |
+
n_groups=config.num_key_value_heads,
|
| 240 |
+
eps=config.rms_norm_eps)
|
| 241 |
+
|
| 242 |
+
self.sliding_window = getattr(config, "sliding_window", None)
|
| 243 |
+
|
| 244 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 245 |
+
def forward(
|
| 246 |
+
self,
|
| 247 |
+
hidden_states: torch.Tensor,
|
| 248 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 249 |
+
attention_mask: Optional[torch.Tensor],
|
| 250 |
+
past_key_values: Optional[Cache] = None,
|
| 251 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 252 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 253 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 254 |
+
input_shape = hidden_states.shape[:-1]
|
| 255 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 256 |
+
|
| 257 |
+
if self.config.query_key_norm:
|
| 258 |
+
query_states = self.q_norm(self.q_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
|
| 259 |
+
key_states = self.k_norm(self.k_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
|
| 260 |
+
else:
|
| 261 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 262 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 263 |
+
|
| 264 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 265 |
+
|
| 266 |
+
cos, sin = position_embeddings
|
| 267 |
+
if self.rope_head_dim == self.head_dim:
|
| 268 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 269 |
+
else:
|
| 270 |
+
query_states, query_states_ = torch.split(
|
| 271 |
+
split_to_interleaved(query_states),
|
| 272 |
+
split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
|
| 273 |
+
dim=-1)
|
| 274 |
+
|
| 275 |
+
key_states, key_states_ = torch.split(
|
| 276 |
+
split_to_interleaved(key_states),
|
| 277 |
+
split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
|
| 278 |
+
dim=-1)
|
| 279 |
+
|
| 280 |
+
query_states, key_states = apply_rotary_pos_emb(
|
| 281 |
+
interleaved_to_split(query_states),
|
| 282 |
+
interleaved_to_split(key_states),
|
| 283 |
+
cos,
|
| 284 |
+
sin)
|
| 285 |
+
|
| 286 |
+
query_states = interleaved_to_split(torch.cat(
|
| 287 |
+
[split_to_interleaved(query_states), query_states_], dim=-1))
|
| 288 |
+
key_states = interleaved_to_split(torch.cat(
|
| 289 |
+
[split_to_interleaved(key_states), key_states_], dim=-1))
|
| 290 |
+
|
| 291 |
+
if past_key_values is not None:
|
| 292 |
+
# sin and cos are specific to RoPE models; cache_position needed for the static cache
|
| 293 |
+
cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
|
| 294 |
+
key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
| 295 |
+
|
| 296 |
+
attention_interface: Callable = eager_attention_forward
|
| 297 |
+
if self.config._attn_implementation != "eager":
|
| 298 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 299 |
+
|
| 300 |
+
attn_output, attn_weights = attention_interface(
|
| 301 |
+
self,
|
| 302 |
+
query_states,
|
| 303 |
+
key_states,
|
| 304 |
+
value_states,
|
| 305 |
+
attention_mask,
|
| 306 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 307 |
+
scaling=self.scaling,
|
| 308 |
+
sliding_window=self.sliding_window, # diff with Llama
|
| 309 |
+
**kwargs,
|
| 310 |
+
)
|
| 311 |
+
|
| 312 |
+
if self.gate_func is not None:
|
| 313 |
+
gate = self.gate_proj(hidden_states).view(
|
| 314 |
+
input_shape + (-1, self.head_dim))
|
| 315 |
+
if self.gate_func == 'silu':
|
| 316 |
+
gate = F.silu(gate)
|
| 317 |
+
else:
|
| 318 |
+
assert self.gate_func == 'softplus'
|
| 319 |
+
gate = F.softplus(gate, beta=math.log(2))
|
| 320 |
+
|
| 321 |
+
attn_output = attn_output * gate
|
| 322 |
+
|
| 323 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 324 |
+
attn_output = self.o_proj(attn_output)
|
| 325 |
+
return attn_output, attn_weights
|
| 326 |
+
|
| 327 |
+
|
| 328 |
+
def apply_rotary_pos_emb_xllm(q, k, freqs_cis):
|
| 329 |
+
if q.shape[-1] % 2 != 0 or k.shape[-1] % 2 != 0:
|
| 330 |
+
raise ValueError(f"RoPE dimensions must be even, got q={q.shape[-1]} and k={k.shape[-1]}")
|
| 331 |
+
q_ = torch.view_as_complex(q.float().reshape(*q.shape[:-1], -1, 2))
|
| 332 |
+
k_ = torch.view_as_complex(k.float().reshape(*k.shape[:-1], -1, 2))
|
| 333 |
+
if freqs_cis.ndim == 2:
|
| 334 |
+
freqs_cis = freqs_cis.unsqueeze(1)
|
| 335 |
+
elif freqs_cis.ndim == 3:
|
| 336 |
+
freqs_cis = freqs_cis.unsqueeze(2)
|
| 337 |
+
else:
|
| 338 |
+
raise ValueError(f"Unsupported freqs_cis shape: {tuple(freqs_cis.shape)}")
|
| 339 |
+
if freqs_cis.shape[-1] != q_.shape[-1] or freqs_cis.shape[-1] != k_.shape[-1]:
|
| 340 |
+
raise ValueError(
|
| 341 |
+
"RoPE frequency dimension mismatch: "
|
| 342 |
+
f"q_rope_dim={q.shape[-1]}, k_rope_dim={k.shape[-1]}, "
|
| 343 |
+
f"q_complex_dim={q_.shape[-1]}, k_complex_dim={k_.shape[-1]}, "
|
| 344 |
+
f"freqs_complex_dim={freqs_cis.shape[-1]}, freqs_shape={tuple(freqs_cis.shape)}"
|
| 345 |
+
)
|
| 346 |
+
q_embed = torch.view_as_real(q_ * freqs_cis).flatten(-2).to(q.dtype)
|
| 347 |
+
k_embed = torch.view_as_real(k_ * freqs_cis).flatten(-2).to(k.dtype)
|
| 348 |
+
return q_embed, k_embed
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class K2HorizonMoVAAttention(nn.Module):
|
| 352 |
+
"""MoVA attention with routed value experts and optional post-attention gate."""
|
| 353 |
+
|
| 354 |
+
def __init__(self, config: K2HorizonConfig, layer_idx: int):
|
| 355 |
+
super().__init__()
|
| 356 |
+
self.config = config
|
| 357 |
+
self.layer_idx = layer_idx
|
| 358 |
+
self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
|
| 359 |
+
self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
|
| 360 |
+
self.scaling = self.head_dim**-0.5
|
| 361 |
+
self.attention_dropout = config.attention_dropout
|
| 362 |
+
self.is_causal = True
|
| 363 |
+
|
| 364 |
+
self.num_experts_per_tok = config.mova_num_experts_per_tok
|
| 365 |
+
self.router_score_func = config.router_score_func
|
| 366 |
+
self.router_scaling_factor = config.router_scaling_factor
|
| 367 |
+
self.gate_func = config.attention_gate_func
|
| 368 |
+
|
| 369 |
+
self.rope_head_dim = self.head_dim if config.rope_head_dim is None else config.rope_head_dim
|
| 370 |
+
|
| 371 |
+
self.q_proj = nn.Linear(
|
| 372 |
+
config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
|
| 373 |
+
)
|
| 374 |
+
self.k_proj = nn.Linear(
|
| 375 |
+
config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
|
| 376 |
+
)
|
| 377 |
+
self.o_proj = nn.Linear(
|
| 378 |
+
config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
|
| 379 |
+
)
|
| 380 |
+
self.v_router = nn.Linear(
|
| 381 |
+
config.hidden_size,
|
| 382 |
+
config.mova_num_experts,
|
| 383 |
+
bias=config.moe_gate_bias)
|
| 384 |
+
self.v_experts = nn.ModuleList([
|
| 385 |
+
nn.Linear(
|
| 386 |
+
config.hidden_size,
|
| 387 |
+
config.num_key_value_heads * self.head_dim,
|
| 388 |
+
bias=False
|
| 389 |
+
) for _ in range(config.mova_num_experts)
|
| 390 |
+
])
|
| 391 |
+
|
| 392 |
+
if self.gate_func is not None:
|
| 393 |
+
self.gate_proj = nn.Linear(
|
| 394 |
+
config.hidden_size,
|
| 395 |
+
config.num_attention_heads * self.head_dim,
|
| 396 |
+
bias=False)
|
| 397 |
+
|
| 398 |
+
if config.query_key_norm:
|
| 399 |
+
self.q_norm = K2HorizonRMSNorm(
|
| 400 |
+
hidden_size=config.num_attention_heads * self.head_dim,
|
| 401 |
+
n_groups=config.num_attention_heads,
|
| 402 |
+
eps=config.rms_norm_eps,
|
| 403 |
+
)
|
| 404 |
+
self.k_norm = K2HorizonRMSNorm(
|
| 405 |
+
hidden_size=config.num_key_value_heads * self.head_dim,
|
| 406 |
+
n_groups=config.num_key_value_heads,
|
| 407 |
+
eps=config.rms_norm_eps,
|
| 408 |
+
)
|
| 409 |
+
|
| 410 |
+
self.sliding_window = getattr(config, "sliding_window", None)
|
| 411 |
+
|
| 412 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 413 |
+
def forward(
|
| 414 |
+
self,
|
| 415 |
+
hidden_states: torch.Tensor,
|
| 416 |
+
position_embeddings: torch.Tensor,
|
| 417 |
+
attention_mask: Optional[torch.Tensor],
|
| 418 |
+
past_key_values: Optional[Cache] = None,
|
| 419 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 420 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 421 |
+
) -> tuple[torch.Tensor, Optional[torch.Tensor]]:
|
| 422 |
+
input_shape = hidden_states.shape[:-1]
|
| 423 |
+
hidden_shape = (*input_shape, -1, self.head_dim)
|
| 424 |
+
flat_hidden_states = hidden_states.reshape(-1, hidden_states.shape[-1])
|
| 425 |
+
|
| 426 |
+
# Match native MOVAttention router semantics exactly: compute logits with
|
| 427 |
+
# the weight-only linear and apply router bias only to selection scores.
|
| 428 |
+
router_logits = F.linear(flat_hidden_states, self.v_router.weight)
|
| 429 |
+
routing_weights, selected_values = calc_router_weights(
|
| 430 |
+
router_logits=router_logits,
|
| 431 |
+
router_bias=self.v_router.bias,
|
| 432 |
+
score_func=self.router_score_func,
|
| 433 |
+
top_k=self.num_experts_per_tok,
|
| 434 |
+
scaling_factor=self.router_scaling_factor,
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
mixed_value_states = combine_routed_experts(
|
| 438 |
+
hidden_states=flat_hidden_states,
|
| 439 |
+
routing_weights=routing_weights,
|
| 440 |
+
selected_indices=selected_values,
|
| 441 |
+
experts=self.v_experts,
|
| 442 |
+
activation=F.silu)
|
| 443 |
+
|
| 444 |
+
value_states = mixed_value_states.view(hidden_shape).transpose(1, 2)
|
| 445 |
+
|
| 446 |
+
if self.config.query_key_norm:
|
| 447 |
+
query_states = self.q_norm(self.q_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
|
| 448 |
+
key_states = self.k_norm(self.k_proj(hidden_states)).view(hidden_shape).transpose(1, 2)
|
| 449 |
+
else:
|
| 450 |
+
query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 451 |
+
key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 452 |
+
|
| 453 |
+
cos, sin = position_embeddings
|
| 454 |
+
if self.rope_head_dim == self.head_dim:
|
| 455 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 456 |
+
else:
|
| 457 |
+
query_states, query_states_ = torch.split(
|
| 458 |
+
split_to_interleaved(query_states),
|
| 459 |
+
split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
|
| 460 |
+
dim=-1)
|
| 461 |
+
|
| 462 |
+
key_states, key_states_ = torch.split(
|
| 463 |
+
split_to_interleaved(key_states),
|
| 464 |
+
split_size_or_sections=[self.rope_head_dim, self.head_dim - self.rope_head_dim],
|
| 465 |
+
dim=-1)
|
| 466 |
+
|
| 467 |
+
query_states, key_states = apply_rotary_pos_emb(
|
| 468 |
+
interleaved_to_split(query_states),
|
| 469 |
+
interleaved_to_split(key_states),
|
| 470 |
+
cos,
|
| 471 |
+
sin)
|
| 472 |
+
|
| 473 |
+
query_states = interleaved_to_split(torch.cat(
|
| 474 |
+
[split_to_interleaved(query_states), query_states_], dim=-1))
|
| 475 |
+
key_states = interleaved_to_split(torch.cat(
|
| 476 |
+
[split_to_interleaved(key_states), key_states_], dim=-1))
|
| 477 |
+
|
| 478 |
+
if past_key_values is not None:
|
| 479 |
+
cache_kwargs = {"cache_position": cache_position}
|
| 480 |
+
key_states, value_states = past_key_values.update(
|
| 481 |
+
key_states, value_states, self.layer_idx, cache_kwargs
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
attention_interface: Callable = eager_attention_forward
|
| 485 |
+
if self.config._attn_implementation != "eager":
|
| 486 |
+
attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
|
| 487 |
+
|
| 488 |
+
attn_output, attn_weights = attention_interface(
|
| 489 |
+
self,
|
| 490 |
+
query_states,
|
| 491 |
+
key_states,
|
| 492 |
+
value_states,
|
| 493 |
+
attention_mask,
|
| 494 |
+
dropout=0.0 if not self.training else self.attention_dropout,
|
| 495 |
+
scaling=self.scaling,
|
| 496 |
+
sliding_window=self.sliding_window,
|
| 497 |
+
**kwargs,
|
| 498 |
+
)
|
| 499 |
+
|
| 500 |
+
if self.gate_func is not None:
|
| 501 |
+
gate = self.gate_proj(hidden_states).view(input_shape + (-1, self.head_dim))
|
| 502 |
+
if self.gate_func == 'silu':
|
| 503 |
+
gate = F.silu(gate)
|
| 504 |
+
else:
|
| 505 |
+
assert self.gate_func == 'softplus'
|
| 506 |
+
gate = F.softplus(gate, beta=math.log(2))
|
| 507 |
+
|
| 508 |
+
attn_output = attn_output * gate
|
| 509 |
+
|
| 510 |
+
attn_output = attn_output.reshape(*input_shape, -1).contiguous()
|
| 511 |
+
attn_output = self.o_proj(attn_output)
|
| 512 |
+
return attn_output, attn_weights
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
class K2HorizonMLP(nn.Module):
|
| 516 |
+
def __init__(self, config, intermediate_size=None):
|
| 517 |
+
super().__init__()
|
| 518 |
+
self.config = config
|
| 519 |
+
self.hidden_size = config.hidden_size
|
| 520 |
+
self.intermediate_size = intermediate_size if intermediate_size is not None else config.intermediate_size
|
| 521 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 522 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 523 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 524 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 525 |
+
|
| 526 |
+
def forward(self, x):
|
| 527 |
+
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 528 |
+
return down_proj
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
class K2HorizonSparseMoeBlock(nn.Module):
|
| 532 |
+
def __init__(self, config):
|
| 533 |
+
super().__init__()
|
| 534 |
+
self.num_experts = config.num_experts
|
| 535 |
+
self.top_k = config.num_experts_per_tok
|
| 536 |
+
self.norm_topk_prob = config.norm_topk_prob
|
| 537 |
+
self.num_shared_experts = config.num_shared_experts
|
| 538 |
+
self.router_score_func = config.router_score_func
|
| 539 |
+
self.router_scaling_factor = config.router_scaling_factor
|
| 540 |
+
|
| 541 |
+
# gating
|
| 542 |
+
self.gate = nn.Linear(config.hidden_size, config.num_experts, bias=config.moe_gate_bias)
|
| 543 |
+
self.experts = nn.ModuleList(
|
| 544 |
+
[K2HorizonMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
|
| 545 |
+
)
|
| 546 |
+
|
| 547 |
+
if config.num_shared_experts > 0:
|
| 548 |
+
self.shared_experts = K2HorizonMLP(
|
| 549 |
+
config=config,
|
| 550 |
+
intermediate_size=config.moe_intermediate_size * config.num_shared_experts)
|
| 551 |
+
|
| 552 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 553 |
+
""" """
|
| 554 |
+
residuals = hidden_states
|
| 555 |
+
|
| 556 |
+
batch_size, sequence_length, hidden_dim = hidden_states.shape
|
| 557 |
+
hidden_states = hidden_states.view(-1, hidden_dim)
|
| 558 |
+
# router_logits: (batch * sequence_length, n_experts)
|
| 559 |
+
# router_logits = self.gate(hidden_states)
|
| 560 |
+
router_logits = F.linear(hidden_states, self.gate.weight)
|
| 561 |
+
|
| 562 |
+
if self.router_score_func == "softmax":
|
| 563 |
+
routing_weights = F.softmax(router_logits, dim=1, dtype=torch.float)
|
| 564 |
+
else:
|
| 565 |
+
assert self.router_score_func == "sigmoid"
|
| 566 |
+
routing_weights = F.sigmoid(router_logits.to(torch.float32))
|
| 567 |
+
|
| 568 |
+
routing_weights_for_choice = routing_weights
|
| 569 |
+
if self.gate.bias is not None:
|
| 570 |
+
routing_weights_for_choice = routing_weights + self.gate.bias.to(routing_weights.dtype)
|
| 571 |
+
|
| 572 |
+
_, selected_experts = torch.topk(routing_weights_for_choice, self.top_k, dim=-1)
|
| 573 |
+
routing_weights = torch.gather(routing_weights, dim=-1, index=selected_experts)
|
| 574 |
+
|
| 575 |
+
if self.norm_topk_prob: # only diff with mixtral sparse moe block!
|
| 576 |
+
routing_weights /= routing_weights.sum(dim=-1, keepdim=True)
|
| 577 |
+
routing_weights = routing_weights * self.router_scaling_factor
|
| 578 |
+
# we cast back to the input dtype
|
| 579 |
+
routing_weights = routing_weights.to(hidden_states.dtype)
|
| 580 |
+
|
| 581 |
+
final_hidden_states = torch.zeros(
|
| 582 |
+
(batch_size * sequence_length, hidden_dim), dtype=hidden_states.dtype, device=hidden_states.device
|
| 583 |
+
)
|
| 584 |
+
|
| 585 |
+
# One hot encode the selected experts to create an expert mask
|
| 586 |
+
# this will be used to easily index which expert is going to be sollicitated
|
| 587 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_classes=self.num_experts).permute(2, 1, 0)
|
| 588 |
+
|
| 589 |
+
# Loop over all available experts in the model and perform the computation on each expert
|
| 590 |
+
expert_hit = torch.greater(expert_mask.sum(dim=(-1, -2)), 0).nonzero()
|
| 591 |
+
for expert_idx in expert_hit:
|
| 592 |
+
expert_layer = self.experts[expert_idx]
|
| 593 |
+
idx, top_x = torch.where(expert_mask[expert_idx].squeeze(0))
|
| 594 |
+
|
| 595 |
+
# Index the correct hidden states and compute the expert hidden state for
|
| 596 |
+
# the current expert. We need to make sure to multiply the output hidden
|
| 597 |
+
# states by `routing_weights` on the corresponding tokens (top-1 and top-2)
|
| 598 |
+
current_state = hidden_states[None, top_x].reshape(-1, hidden_dim)
|
| 599 |
+
current_hidden_states = expert_layer(current_state) * routing_weights[top_x, idx, None]
|
| 600 |
+
|
| 601 |
+
# However `index_add_` only support torch tensors for indexing so we'll use
|
| 602 |
+
# the `top_x` tensor here.
|
| 603 |
+
final_hidden_states.index_add_(0, top_x, current_hidden_states.to(hidden_states.dtype))
|
| 604 |
+
final_hidden_states = final_hidden_states.reshape(batch_size, sequence_length, hidden_dim)
|
| 605 |
+
|
| 606 |
+
if self.num_shared_experts > 0:
|
| 607 |
+
final_hidden_states = final_hidden_states + self.shared_experts(residuals)
|
| 608 |
+
|
| 609 |
+
return final_hidden_states, router_logits
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
# @use_kernel_forward_from_hub("RMSNorm")
|
| 613 |
+
class K2HorizonRMSNorm(nn.Module):
|
| 614 |
+
def __init__(self, hidden_size: int, n_groups: int, eps=1e-6):
|
| 615 |
+
"""
|
| 616 |
+
K2HorizonRMSNorm is equivalent to T5LayerNorm
|
| 617 |
+
"""
|
| 618 |
+
super().__init__()
|
| 619 |
+
self.n_groups = n_groups
|
| 620 |
+
self.hidden_size = hidden_size
|
| 621 |
+
assert hidden_size % n_groups == 0
|
| 622 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 623 |
+
self.variance_epsilon = eps
|
| 624 |
+
|
| 625 |
+
def forward(self, hidden_states):
|
| 626 |
+
input_dtype = hidden_states.dtype
|
| 627 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 628 |
+
|
| 629 |
+
hidden_states = hidden_states.reshape(*hidden_states.shape[:-1], self.n_groups, -1)
|
| 630 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 631 |
+
|
| 632 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 633 |
+
hidden_states = hidden_states.reshape(*hidden_states.shape[:-2], -1)
|
| 634 |
+
hidden_states = self.weight * hidden_states
|
| 635 |
+
|
| 636 |
+
return hidden_states.to(input_dtype)
|
| 637 |
+
|
| 638 |
+
def extra_repr(self):
|
| 639 |
+
return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
class K2HorizonDecoderLayer(GradientCheckpointingLayer):
|
| 643 |
+
def __init__(self, config: K2HorizonConfig, layer_idx: int):
|
| 644 |
+
super().__init__()
|
| 645 |
+
self.hidden_size = config.hidden_size
|
| 646 |
+
|
| 647 |
+
is_sparse_layer = (layer_idx not in config.mlp_only_layers) and (
|
| 648 |
+
config.num_experts > 0 and (layer_idx + 1) % config.decoder_sparse_step == 0)
|
| 649 |
+
|
| 650 |
+
if is_sparse_layer and config.mova_num_experts > 0:
|
| 651 |
+
self.self_attn = K2HorizonMoVAAttention(config=config, layer_idx=layer_idx)
|
| 652 |
+
else:
|
| 653 |
+
self.self_attn = K2HorizonAttention(config, layer_idx)
|
| 654 |
+
|
| 655 |
+
if is_sparse_layer:
|
| 656 |
+
self.mlp = K2HorizonSparseMoeBlock(config)
|
| 657 |
+
else:
|
| 658 |
+
self.mlp = K2HorizonMLP(config, intermediate_size=config.intermediate_size)
|
| 659 |
+
|
| 660 |
+
assert config.hidden_size % config.layernorm_num_groups == 0
|
| 661 |
+
self.input_layernorm = K2HorizonRMSNorm(
|
| 662 |
+
hidden_size=config.hidden_size,
|
| 663 |
+
n_groups=config.layernorm_num_groups,
|
| 664 |
+
eps=config.rms_norm_eps)
|
| 665 |
+
self.post_attention_layernorm = K2HorizonRMSNorm(
|
| 666 |
+
hidden_size=config.hidden_size,
|
| 667 |
+
n_groups=config.layernorm_num_groups,
|
| 668 |
+
eps=config.rms_norm_eps)
|
| 669 |
+
|
| 670 |
+
@deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
|
| 671 |
+
def forward(
|
| 672 |
+
self,
|
| 673 |
+
hidden_states: torch.Tensor,
|
| 674 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor],
|
| 675 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 676 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 677 |
+
past_key_values: Optional[Cache] = None,
|
| 678 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 679 |
+
**kwargs: Unpack[FlashAttentionKwargs],
|
| 680 |
+
) -> torch.FloatTensor:
|
| 681 |
+
"""
|
| 682 |
+
Args:
|
| 683 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
| 684 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
| 685 |
+
`(batch, sequence_length)` where padding elements are indicated by 0.
|
| 686 |
+
output_attentions (`bool`, *optional*):
|
| 687 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
| 688 |
+
returned tensors for more detail.
|
| 689 |
+
output_router_logits (`bool`, *optional*):
|
| 690 |
+
Whether or not to return the logits of all the routers. They are useful for computing the router loss,
|
| 691 |
+
and should not be returned during inference.
|
| 692 |
+
use_cache (`bool`, *optional*):
|
| 693 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
| 694 |
+
(see `past_key_values`).
|
| 695 |
+
past_key_values (`Cache`, *optional*): cached past key and value projection states
|
| 696 |
+
cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
|
| 697 |
+
Indices depicting the position of the input sequence tokens in the sequence.
|
| 698 |
+
position_embeddings (`tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
|
| 699 |
+
Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
|
| 700 |
+
with `head_dim` being the embedding dimension of each attention head.
|
| 701 |
+
kwargs (`dict`, *optional*):
|
| 702 |
+
Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
|
| 703 |
+
into the model
|
| 704 |
+
"""
|
| 705 |
+
residual = hidden_states
|
| 706 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 707 |
+
|
| 708 |
+
# Self Attention
|
| 709 |
+
hidden_states, _ = self.self_attn(
|
| 710 |
+
hidden_states=hidden_states,
|
| 711 |
+
position_embeddings=position_embeddings,
|
| 712 |
+
attention_mask=attention_mask,
|
| 713 |
+
position_ids=position_ids,
|
| 714 |
+
past_key_values=past_key_values,
|
| 715 |
+
cache_position=cache_position,
|
| 716 |
+
**kwargs,
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
hidden_states = residual + hidden_states
|
| 720 |
+
|
| 721 |
+
# Fully Connected
|
| 722 |
+
residual = hidden_states
|
| 723 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 724 |
+
hidden_states = self.mlp(hidden_states)
|
| 725 |
+
# For the MoE layers, we need to unpack
|
| 726 |
+
if isinstance(hidden_states, tuple):
|
| 727 |
+
hidden_states, _ = hidden_states
|
| 728 |
+
hidden_states = residual + hidden_states
|
| 729 |
+
|
| 730 |
+
return hidden_states
|
| 731 |
+
|
| 732 |
+
|
| 733 |
+
class K2HorizonRotaryEmbedding(nn.Module):
|
| 734 |
+
inv_freq: torch.Tensor # fix linting for `register_buffer`
|
| 735 |
+
|
| 736 |
+
def __init__(self, config: K2HorizonConfig, device=None):
|
| 737 |
+
super().__init__()
|
| 738 |
+
self.max_seq_len_cached = config.max_position_embeddings
|
| 739 |
+
self.original_max_seq_len = config.max_position_embeddings
|
| 740 |
+
|
| 741 |
+
self.config = config
|
| 742 |
+
|
| 743 |
+
self.rope_type = self.config.rope_parameters["rope_type"]
|
| 744 |
+
rope_init_fn: Callable = self.compute_default_rope_parameters
|
| 745 |
+
if self.rope_type != "default":
|
| 746 |
+
rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
|
| 747 |
+
inv_freq, self.attention_scaling = rope_init_fn(self.config, device)
|
| 748 |
+
|
| 749 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 750 |
+
self.register_buffer("original_inv_freq", inv_freq.clone(), persistent=False)
|
| 751 |
+
|
| 752 |
+
@staticmethod
|
| 753 |
+
def compute_default_rope_parameters(
|
| 754 |
+
config: K2HorizonConfig | None = None,
|
| 755 |
+
device: Optional["torch.device"] = None,
|
| 756 |
+
seq_len: int | None = None,
|
| 757 |
+
) -> tuple["torch.Tensor", float]:
|
| 758 |
+
"""
|
| 759 |
+
Computes the inverse frequencies according to the original RoPE implementation
|
| 760 |
+
Args:
|
| 761 |
+
config ([`~transformers.PreTrainedConfig`]):
|
| 762 |
+
The model configuration.
|
| 763 |
+
device (`torch.device`):
|
| 764 |
+
The device to use for initialization of the inverse frequencies.
|
| 765 |
+
seq_len (`int`, *optional*):
|
| 766 |
+
The current sequence length. Unused for this type of RoPE.
|
| 767 |
+
Returns:
|
| 768 |
+
Tuple of (`torch.Tensor`, `float`), containing the inverse frequencies for the RoPE embeddings and the
|
| 769 |
+
post-processing scaling factor applied to the computed cos/sin (unused in this type of RoPE).
|
| 770 |
+
"""
|
| 771 |
+
base = config.rope_parameters["rope_theta"]
|
| 772 |
+
# dim = getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 773 |
+
dim = (
|
| 774 |
+
config.rope_head_dim
|
| 775 |
+
if config.rope_head_dim is not None
|
| 776 |
+
else getattr(config, "head_dim", None) or config.hidden_size // config.num_attention_heads
|
| 777 |
+
)
|
| 778 |
+
|
| 779 |
+
attention_factor = 1.0 # Unused in this type of RoPE
|
| 780 |
+
|
| 781 |
+
# Compute the inverse frequencies
|
| 782 |
+
inv_freq = 1.0 / (
|
| 783 |
+
base ** (torch.arange(0, dim, 2, dtype=torch.int64).to(device=device, dtype=torch.float) / dim)
|
| 784 |
+
)
|
| 785 |
+
return inv_freq, attention_factor
|
| 786 |
+
|
| 787 |
+
@torch.no_grad()
|
| 788 |
+
@dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
|
| 789 |
+
def forward(self, x, position_ids):
|
| 790 |
+
inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
|
| 791 |
+
position_ids_expanded = position_ids[:, None, :].float()
|
| 792 |
+
|
| 793 |
+
device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
|
| 794 |
+
with maybe_autocast(device_type=device_type, enabled=False): # Force float32
|
| 795 |
+
freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
|
| 796 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 797 |
+
cos = emb.cos() * self.attention_scaling
|
| 798 |
+
sin = emb.sin() * self.attention_scaling
|
| 799 |
+
|
| 800 |
+
return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
|
| 801 |
+
|
| 802 |
+
|
| 803 |
+
@auto_docstring
|
| 804 |
+
class K2HorizonPreTrainedModel(PreTrainedModel):
|
| 805 |
+
config: K2HorizonConfig
|
| 806 |
+
base_model_prefix = "model"
|
| 807 |
+
supports_gradient_checkpointing = True
|
| 808 |
+
_no_split_modules = ["K2HorizonDecoderLayer"]
|
| 809 |
+
_skip_keys_device_placement = ["past_key_values"]
|
| 810 |
+
_supports_flash_attn = True
|
| 811 |
+
_supports_sdpa = True
|
| 812 |
+
_supports_flex_attn = True
|
| 813 |
+
_can_compile_fullgraph = False # MoE models don't work with torch.compile (`torch.where(condition)` not supported)
|
| 814 |
+
_supports_attention_backend = True
|
| 815 |
+
_can_record_outputs = {
|
| 816 |
+
"router_logits": OutputRecorder(K2HorizonSparseMoeBlock, index=1),
|
| 817 |
+
"hidden_states": K2HorizonDecoderLayer,
|
| 818 |
+
"attentions": K2HorizonAttention,
|
| 819 |
+
}
|
| 820 |
+
|
| 821 |
+
|
| 822 |
+
@auto_docstring
|
| 823 |
+
class K2HorizonModel(K2HorizonPreTrainedModel):
|
| 824 |
+
def __init__(self, config: K2HorizonConfig):
|
| 825 |
+
super().__init__(config)
|
| 826 |
+
# self.padding_idx = config.pad_token_id
|
| 827 |
+
self.padding_idx = getattr(config, "padding_idx", None)
|
| 828 |
+
self.vocab_size = config.vocab_size
|
| 829 |
+
|
| 830 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 831 |
+
self.layers = nn.ModuleList(
|
| 832 |
+
[K2HorizonDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
|
| 833 |
+
)
|
| 834 |
+
|
| 835 |
+
assert config.hidden_size % config.layernorm_num_groups == 0
|
| 836 |
+
self.norm = K2HorizonRMSNorm(
|
| 837 |
+
hidden_size=config.hidden_size,
|
| 838 |
+
n_groups=config.layernorm_num_groups,
|
| 839 |
+
eps=config.rms_norm_eps)
|
| 840 |
+
|
| 841 |
+
self.rotary_emb = K2HorizonRotaryEmbedding(config=config)
|
| 842 |
+
self.gradient_checkpointing = False
|
| 843 |
+
|
| 844 |
+
# Initialize weights and apply final processing
|
| 845 |
+
self.post_init()
|
| 846 |
+
|
| 847 |
+
@auto_docstring
|
| 848 |
+
def forward(
|
| 849 |
+
self,
|
| 850 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 851 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 852 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 853 |
+
past_key_values: Optional[Cache] = None,
|
| 854 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 855 |
+
use_cache: Optional[bool] = None,
|
| 856 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 857 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 858 |
+
) -> MoeModelOutputWithPast:
|
| 859 |
+
if (input_ids is None) ^ (inputs_embeds is not None):
|
| 860 |
+
raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
|
| 861 |
+
|
| 862 |
+
if use_cache and past_key_values is None:
|
| 863 |
+
past_key_values = DynamicCache(config=self.config)
|
| 864 |
+
|
| 865 |
+
if inputs_embeds is None:
|
| 866 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 867 |
+
|
| 868 |
+
if cache_position is None:
|
| 869 |
+
past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 870 |
+
cache_position = torch.arange(
|
| 871 |
+
past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
|
| 872 |
+
)
|
| 873 |
+
if position_ids is None:
|
| 874 |
+
position_ids = cache_position.unsqueeze(0)
|
| 875 |
+
|
| 876 |
+
mask_function = create_causal_mask if self.config.sliding_window is None else create_sliding_window_causal_mask
|
| 877 |
+
causal_mask = mask_function(
|
| 878 |
+
config=self.config,
|
| 879 |
+
inputs_embeds=inputs_embeds,
|
| 880 |
+
attention_mask=attention_mask,
|
| 881 |
+
past_key_values=past_key_values,
|
| 882 |
+
position_ids=position_ids,
|
| 883 |
+
)
|
| 884 |
+
|
| 885 |
+
hidden_states = inputs_embeds
|
| 886 |
+
|
| 887 |
+
# create position embeddings to be shared across the decoder layers
|
| 888 |
+
position_embeddings = self.rotary_emb(hidden_states, position_ids)
|
| 889 |
+
|
| 890 |
+
for layer_idx, decoder_layer in enumerate(self.layers[: self.config.num_hidden_layers]):
|
| 891 |
+
hidden_states = decoder_layer(
|
| 892 |
+
hidden_states,
|
| 893 |
+
position_embeddings=position_embeddings,
|
| 894 |
+
attention_mask=causal_mask,
|
| 895 |
+
position_ids=position_ids,
|
| 896 |
+
past_key_values=past_key_values,
|
| 897 |
+
use_cache=use_cache,
|
| 898 |
+
cache_position=cache_position,
|
| 899 |
+
**kwargs,
|
| 900 |
+
)
|
| 901 |
+
|
| 902 |
+
hidden_states = self.norm(hidden_states)
|
| 903 |
+
|
| 904 |
+
return MoeModelOutputWithPast( # only diff with Mistral is the output type, we need MoE
|
| 905 |
+
last_hidden_state=hidden_states,
|
| 906 |
+
past_key_values=past_key_values,
|
| 907 |
+
)
|
| 908 |
+
|
| 909 |
+
|
| 910 |
+
def load_balancing_loss_func(
|
| 911 |
+
gate_logits: Union[torch.Tensor, tuple[torch.Tensor], None],
|
| 912 |
+
num_experts: Optional[int] = None,
|
| 913 |
+
top_k=2,
|
| 914 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 915 |
+
) -> Union[torch.Tensor, int]:
|
| 916 |
+
r"""
|
| 917 |
+
Computes auxiliary load balancing loss as in Switch Transformer - implemented in Pytorch.
|
| 918 |
+
|
| 919 |
+
See Switch Transformer (https://huggingface.co/papers/2101.03961) for more details. This function implements the loss
|
| 920 |
+
function presented in equations (4) - (6) of the paper. It aims at penalizing cases where the routing between
|
| 921 |
+
experts is too unbalanced.
|
| 922 |
+
|
| 923 |
+
Args:
|
| 924 |
+
gate_logits:
|
| 925 |
+
Logits from the `gate`, should be a tuple of model.config.num_hidden_layers tensors of
|
| 926 |
+
shape [batch_size X sequence_length, num_experts].
|
| 927 |
+
num_experts:
|
| 928 |
+
Number of experts
|
| 929 |
+
top_k:
|
| 930 |
+
The number of experts to route per-token, can be also interpreted as the `top-k` routing
|
| 931 |
+
parameter.
|
| 932 |
+
attention_mask (`torch.Tensor`, *optional*):
|
| 933 |
+
The attention_mask used in forward function
|
| 934 |
+
shape [batch_size X sequence_length] if not None.
|
| 935 |
+
|
| 936 |
+
Returns:
|
| 937 |
+
The auxiliary loss.
|
| 938 |
+
"""
|
| 939 |
+
if gate_logits is None or not isinstance(gate_logits, tuple):
|
| 940 |
+
return 0
|
| 941 |
+
|
| 942 |
+
if isinstance(gate_logits, tuple):
|
| 943 |
+
compute_device = gate_logits[0].device
|
| 944 |
+
concatenated_gate_logits = torch.cat([layer_gate.to(compute_device) for layer_gate in gate_logits], dim=0)
|
| 945 |
+
|
| 946 |
+
routing_weights = torch.nn.functional.softmax(concatenated_gate_logits, dim=-1)
|
| 947 |
+
|
| 948 |
+
_, selected_experts = torch.topk(routing_weights, top_k, dim=-1)
|
| 949 |
+
|
| 950 |
+
expert_mask = torch.nn.functional.one_hot(selected_experts, num_experts)
|
| 951 |
+
|
| 952 |
+
if attention_mask is None:
|
| 953 |
+
# Compute the percentage of tokens routed to each experts
|
| 954 |
+
tokens_per_expert = torch.mean(expert_mask.float(), dim=0)
|
| 955 |
+
|
| 956 |
+
# Compute the average probability of routing to these experts
|
| 957 |
+
router_prob_per_expert = torch.mean(routing_weights, dim=0)
|
| 958 |
+
else:
|
| 959 |
+
batch_size, sequence_length = attention_mask.shape
|
| 960 |
+
num_hidden_layers = concatenated_gate_logits.shape[0] // (batch_size * sequence_length)
|
| 961 |
+
|
| 962 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of expert_mask
|
| 963 |
+
expert_attention_mask = (
|
| 964 |
+
attention_mask[None, :, :, None, None]
|
| 965 |
+
.expand((num_hidden_layers, batch_size, sequence_length, top_k, num_experts))
|
| 966 |
+
.reshape(-1, top_k, num_experts)
|
| 967 |
+
.to(compute_device)
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
# Compute the percentage of tokens routed to each experts
|
| 971 |
+
tokens_per_expert = torch.sum(expert_mask.float() * expert_attention_mask, dim=0) / torch.sum(
|
| 972 |
+
expert_attention_mask, dim=0
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
# Compute the mask that masks all padding tokens as 0 with the same shape of tokens_per_expert
|
| 976 |
+
router_per_expert_attention_mask = (
|
| 977 |
+
attention_mask[None, :, :, None]
|
| 978 |
+
.expand((num_hidden_layers, batch_size, sequence_length, num_experts))
|
| 979 |
+
.reshape(-1, num_experts)
|
| 980 |
+
.to(compute_device)
|
| 981 |
+
)
|
| 982 |
+
|
| 983 |
+
# Compute the average probability of routing to these experts
|
| 984 |
+
router_prob_per_expert = torch.sum(routing_weights * router_per_expert_attention_mask, dim=0) / torch.sum(
|
| 985 |
+
router_per_expert_attention_mask, dim=0
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
overall_loss = torch.sum(tokens_per_expert * router_prob_per_expert.unsqueeze(0))
|
| 989 |
+
return overall_loss * num_experts
|
| 990 |
+
|
| 991 |
+
|
| 992 |
+
@auto_docstring
|
| 993 |
+
class K2HorizonForCausalLM(K2HorizonPreTrainedModel, GenerationMixin):
|
| 994 |
+
# _tied_weights_keys = ["lm_head.weight"]
|
| 995 |
+
# _tp_plan = {"lm_head": "colwise_rep"}
|
| 996 |
+
# _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
| 997 |
+
|
| 998 |
+
def __init__(self, config):
|
| 999 |
+
super().__init__(config)
|
| 1000 |
+
self.model = K2HorizonModel(config)
|
| 1001 |
+
self.vocab_size = config.vocab_size
|
| 1002 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1003 |
+
self.router_aux_loss_coef = config.router_aux_loss_coef
|
| 1004 |
+
self.num_experts = config.num_experts
|
| 1005 |
+
self.num_experts_per_tok = config.num_experts_per_tok
|
| 1006 |
+
|
| 1007 |
+
# Initialize weights and apply final processing
|
| 1008 |
+
self.post_init()
|
| 1009 |
+
|
| 1010 |
+
@can_return_tuple
|
| 1011 |
+
@auto_docstring
|
| 1012 |
+
def forward(
|
| 1013 |
+
self,
|
| 1014 |
+
input_ids: Optional[torch.LongTensor] = None,
|
| 1015 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1016 |
+
position_ids: Optional[torch.LongTensor] = None,
|
| 1017 |
+
past_key_values: Optional[Cache] = None,
|
| 1018 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
| 1019 |
+
labels: Optional[torch.LongTensor] = None,
|
| 1020 |
+
use_cache: Optional[bool] = None,
|
| 1021 |
+
output_router_logits: Optional[bool] = None,
|
| 1022 |
+
cache_position: Optional[torch.LongTensor] = None,
|
| 1023 |
+
logits_to_keep: Union[int, torch.Tensor] = 0,
|
| 1024 |
+
**kwargs: Unpack[TransformersKwargs],
|
| 1025 |
+
) -> MoeCausalLMOutputWithPast:
|
| 1026 |
+
r"""
|
| 1027 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
| 1028 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
| 1029 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
| 1030 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
| 1031 |
+
|
| 1032 |
+
Example:
|
| 1033 |
+
|
| 1034 |
+
```python
|
| 1035 |
+
>>> from transformers import AutoTokenizer, K2HorizonForCausalLM
|
| 1036 |
+
|
| 1037 |
+
>>> model = K2HorizonForCausalLM.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
|
| 1038 |
+
>>> tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-MoE-15B-A2B")
|
| 1039 |
+
|
| 1040 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
| 1041 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
| 1042 |
+
|
| 1043 |
+
>>> # Generate
|
| 1044 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
| 1045 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
| 1046 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
| 1047 |
+
```"""
|
| 1048 |
+
|
| 1049 |
+
output_router_logits = (
|
| 1050 |
+
output_router_logits if output_router_logits is not None else self.config.output_router_logits
|
| 1051 |
+
)
|
| 1052 |
+
|
| 1053 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
| 1054 |
+
outputs: MoeModelOutputWithPast = self.model(
|
| 1055 |
+
input_ids=input_ids,
|
| 1056 |
+
attention_mask=attention_mask,
|
| 1057 |
+
position_ids=position_ids,
|
| 1058 |
+
past_key_values=past_key_values,
|
| 1059 |
+
inputs_embeds=inputs_embeds,
|
| 1060 |
+
use_cache=use_cache,
|
| 1061 |
+
output_router_logits=output_router_logits,
|
| 1062 |
+
cache_position=cache_position,
|
| 1063 |
+
**kwargs,
|
| 1064 |
+
)
|
| 1065 |
+
|
| 1066 |
+
hidden_states = outputs.last_hidden_state
|
| 1067 |
+
# Only compute necessary logits, and do not upcast them to float if we are not computing the loss
|
| 1068 |
+
slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
|
| 1069 |
+
logits = self.lm_head(hidden_states[:, slice_indices, :])
|
| 1070 |
+
|
| 1071 |
+
loss = None
|
| 1072 |
+
if labels is not None:
|
| 1073 |
+
loss = self.loss_function(logits, labels, self.vocab_size, **kwargs)
|
| 1074 |
+
|
| 1075 |
+
aux_loss = None
|
| 1076 |
+
if output_router_logits:
|
| 1077 |
+
aux_loss = load_balancing_loss_func(
|
| 1078 |
+
outputs.router_logits,
|
| 1079 |
+
self.num_experts,
|
| 1080 |
+
self.num_experts_per_tok,
|
| 1081 |
+
attention_mask,
|
| 1082 |
+
)
|
| 1083 |
+
if labels is not None:
|
| 1084 |
+
loss += self.router_aux_loss_coef * aux_loss.to(loss.device) # make sure to reside in the same device
|
| 1085 |
+
|
| 1086 |
+
return MoeCausalLMOutputWithPast(
|
| 1087 |
+
loss=loss,
|
| 1088 |
+
aux_loss=aux_loss,
|
| 1089 |
+
logits=logits,
|
| 1090 |
+
past_key_values=outputs.past_key_values,
|
| 1091 |
+
hidden_states=outputs.hidden_states,
|
| 1092 |
+
attentions=outputs.attentions,
|
| 1093 |
+
router_logits=outputs.router_logits,
|
| 1094 |
+
)
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
class K2HorizonForSequenceClassification(GenericForSequenceClassification, K2HorizonPreTrainedModel):
|
| 1098 |
+
pass
|
| 1099 |
+
|
| 1100 |
+
|
| 1101 |
+
class K2HorizonForTokenClassification(GenericForTokenClassification, K2HorizonPreTrainedModel):
|
| 1102 |
+
pass
|
| 1103 |
+
|
| 1104 |
+
|
| 1105 |
+
class K2HorizonForQuestionAnswering(GenericForQuestionAnswering, K2HorizonPreTrainedModel):
|
| 1106 |
+
base_model_prefix = "transformer" # For BC, where `transformer` was used instead of `model`
|
| 1107 |
+
|
| 1108 |
+
|
| 1109 |
+
__all__ = [
|
| 1110 |
+
"K2HorizonForCausalLM",
|
| 1111 |
+
"K2HorizonForQuestionAnswering",
|
| 1112 |
+
"K2HorizonModel",
|
| 1113 |
+
"K2HorizonPreTrainedModel",
|
| 1114 |
+
"K2HorizonForSequenceClassification",
|
| 1115 |
+
"K2HorizonForTokenClassification",
|
| 1116 |
+
]
|