Text Generation
Transformers
Safetensors
hybrid_model
custom_code
Terminator-X
mHC
MLA
experimental
research
conversational
Instructions to use Parveshiiii/Terminator-X with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Parveshiiii/Terminator-X with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Parveshiiii/Terminator-X", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Parveshiiii/Terminator-X", trust_remote_code=True, dtype="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps
- vLLM
How to use Parveshiiii/Terminator-X with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Parveshiiii/Terminator-X" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Parveshiiii/Terminator-X", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Parveshiiii/Terminator-X
- SGLang
How to use Parveshiiii/Terminator-X 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 "Parveshiiii/Terminator-X" \ --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": "Parveshiiii/Terminator-X", "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 "Parveshiiii/Terminator-X" \ --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": "Parveshiiii/Terminator-X", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Docker Model Runner
How to use Parveshiiii/Terminator-X with Docker Model Runner:
docker model run hf.co/Parveshiiii/Terminator-X
Upload 5 files
Browse files- config.json +38 -0
- configuration_model.py +72 -0
- generation_config.json +10 -0
- model.safetensors +3 -0
- modelling_model.py +594 -0
config.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architectures": [
|
| 3 |
+
"HybridForCausalLM"
|
| 4 |
+
],
|
| 5 |
+
"attention_dropout": 0.0,
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_model.HybridModelConfig",
|
| 8 |
+
"AutoModelForCausalLM": "modelling_model.HybridForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"bos_token_id": 1,
|
| 11 |
+
"dtype": "float32",
|
| 12 |
+
"eos_token_id": 2,
|
| 13 |
+
"hidden_act": "silu",
|
| 14 |
+
"hidden_size": 64,
|
| 15 |
+
"initializer_range": 0.02,
|
| 16 |
+
"intermediate_size": 128,
|
| 17 |
+
"kv_lora_rank": 16,
|
| 18 |
+
"max_position_embeddings": 2048,
|
| 19 |
+
"mhc_alpha_init": 0.0,
|
| 20 |
+
"mhc_num_streams": 2,
|
| 21 |
+
"mhc_readout_init": "first",
|
| 22 |
+
"mhc_rmsnorm_eps": 1e-06,
|
| 23 |
+
"mhc_sinkhorn_iters": 5,
|
| 24 |
+
"mhc_stream_init": "paper",
|
| 25 |
+
"model_type": "hybrid_model",
|
| 26 |
+
"num_attention_heads": 4,
|
| 27 |
+
"num_hidden_layers": 2,
|
| 28 |
+
"pad_token_id": 0,
|
| 29 |
+
"q_lora_rank": 32,
|
| 30 |
+
"qk_rope_head_dim": 8,
|
| 31 |
+
"rms_norm_eps": 1e-06,
|
| 32 |
+
"rope_theta": 10000.0,
|
| 33 |
+
"sliding_window": 512,
|
| 34 |
+
"tie_word_embeddings": true,
|
| 35 |
+
"transformers_version": "5.3.0",
|
| 36 |
+
"use_cache": true,
|
| 37 |
+
"vocab_size": 4096
|
| 38 |
+
}
|
configuration_model.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
class HybridModelConfig(PretrainedConfig):
|
| 4 |
+
model_type = "hybrid_model"
|
| 5 |
+
keys_to_ignore_at_inference = ["past_key_values"]
|
| 6 |
+
|
| 7 |
+
def __init__(
|
| 8 |
+
self,
|
| 9 |
+
vocab_size=151936,
|
| 10 |
+
hidden_size=768,
|
| 11 |
+
intermediate_size=2048,
|
| 12 |
+
num_hidden_layers=12,
|
| 13 |
+
num_attention_heads=12,
|
| 14 |
+
# MLA compression dims (DeepSeek-style naming)
|
| 15 |
+
kv_lora_rank=192, # KV latent/compression dimension (d_c)
|
| 16 |
+
q_lora_rank=384, # Query latent/compression dimension (d_c1)
|
| 17 |
+
qk_rope_head_dim=32, # RoPE dimension per head (d_rotate)
|
| 18 |
+
hidden_act="silu",
|
| 19 |
+
max_position_embeddings=32768,
|
| 20 |
+
initializer_range=0.02,
|
| 21 |
+
rms_norm_eps=1e-6,
|
| 22 |
+
use_cache=True,
|
| 23 |
+
pad_token_id=0,
|
| 24 |
+
bos_token_id=1,
|
| 25 |
+
eos_token_id=2,
|
| 26 |
+
tie_word_embeddings=False,
|
| 27 |
+
rope_theta=10000.0,
|
| 28 |
+
sliding_window=4096,
|
| 29 |
+
attention_dropout=0.0,
|
| 30 |
+
# MHC (Multi-Head Connections) settings
|
| 31 |
+
mhc_num_streams=4, # number of parallel streams (mhc_n)
|
| 32 |
+
mhc_sinkhorn_iters=20, # Sinkhorn-Knopp iterations (mhc_tmax)
|
| 33 |
+
mhc_alpha_init=0.01,
|
| 34 |
+
mhc_rmsnorm_eps=1e-6,
|
| 35 |
+
mhc_stream_init="paper",
|
| 36 |
+
mhc_readout_init="first",
|
| 37 |
+
**kwargs,
|
| 38 |
+
):
|
| 39 |
+
self.vocab_size = vocab_size
|
| 40 |
+
self.max_position_embeddings = max_position_embeddings
|
| 41 |
+
self.hidden_size = hidden_size
|
| 42 |
+
self.intermediate_size = intermediate_size
|
| 43 |
+
self.num_hidden_layers = num_hidden_layers
|
| 44 |
+
self.num_attention_heads = num_attention_heads
|
| 45 |
+
|
| 46 |
+
self.kv_lora_rank = kv_lora_rank
|
| 47 |
+
self.q_lora_rank = q_lora_rank
|
| 48 |
+
self.qk_rope_head_dim = qk_rope_head_dim
|
| 49 |
+
|
| 50 |
+
self.sliding_window = sliding_window
|
| 51 |
+
|
| 52 |
+
self.hidden_act = hidden_act
|
| 53 |
+
self.initializer_range = initializer_range
|
| 54 |
+
self.rms_norm_eps = rms_norm_eps
|
| 55 |
+
self.use_cache = use_cache
|
| 56 |
+
self.rope_theta = rope_theta
|
| 57 |
+
self.attention_dropout = attention_dropout
|
| 58 |
+
|
| 59 |
+
self.mhc_num_streams = mhc_num_streams
|
| 60 |
+
self.mhc_sinkhorn_iters = mhc_sinkhorn_iters
|
| 61 |
+
self.mhc_alpha_init = mhc_alpha_init
|
| 62 |
+
self.mhc_rmsnorm_eps = mhc_rmsnorm_eps
|
| 63 |
+
self.mhc_stream_init = mhc_stream_init
|
| 64 |
+
self.mhc_readout_init = mhc_readout_init
|
| 65 |
+
|
| 66 |
+
super().__init__(
|
| 67 |
+
pad_token_id=pad_token_id,
|
| 68 |
+
bos_token_id=bos_token_id,
|
| 69 |
+
eos_token_id=eos_token_id,
|
| 70 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 71 |
+
**kwargs,
|
| 72 |
+
)
|
generation_config.json
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": 2,
|
| 5 |
+
"output_attentions": false,
|
| 6 |
+
"output_hidden_states": false,
|
| 7 |
+
"pad_token_id": 0,
|
| 8 |
+
"transformers_version": "5.3.0",
|
| 9 |
+
"use_cache": true
|
| 10 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8998ca5b02181eb4300db14c7ef45fe7a59b1bfd93b4579906f81814a61bbf8f
|
| 3 |
+
size 2423072
|
modelling_model.py
ADDED
|
@@ -0,0 +1,594 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import math
|
| 2 |
+
import torch
|
| 3 |
+
import torch.nn as nn
|
| 4 |
+
import torch.nn.functional as F
|
| 5 |
+
from transformers import PreTrainedModel, GenerationMixin
|
| 6 |
+
from transformers.activations import ACT2FN
|
| 7 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast, BaseModelOutputWithPast
|
| 8 |
+
from typing import Optional, Tuple, List, Union
|
| 9 |
+
import inspect
|
| 10 |
+
from dataclasses import dataclass
|
| 11 |
+
|
| 12 |
+
from configuration_model import HybridModelConfig
|
| 13 |
+
|
| 14 |
+
def precompute_freqs_cis(dim: int, end: int, theta: float = 10000.0):
|
| 15 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].float() / dim))
|
| 16 |
+
t = torch.arange(end, device=freqs.device)
|
| 17 |
+
freqs = torch.outer(t, freqs).float()
|
| 18 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs)
|
| 19 |
+
return freqs_cis
|
| 20 |
+
|
| 21 |
+
def reshape_for_broadcast(freqs_cis: torch.Tensor, x: torch.Tensor):
|
| 22 |
+
ndim = x.ndim
|
| 23 |
+
assert 0 <= 1 < ndim
|
| 24 |
+
assert freqs_cis.shape == (x.shape[1], x.shape[-1])
|
| 25 |
+
shape = [d if i == 1 or i == ndim - 1 else 1 for i, d in enumerate(x.shape)]
|
| 26 |
+
return freqs_cis.view(*shape)
|
| 27 |
+
|
| 28 |
+
def apply_rotary_emb(
|
| 29 |
+
xq: torch.Tensor,
|
| 30 |
+
xk: torch.Tensor,
|
| 31 |
+
q_freqs_cis: torch.Tensor,
|
| 32 |
+
k_freqs_cis: torch.Tensor,
|
| 33 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 34 |
+
xq_ = torch.view_as_complex(xq.float().reshape(*xq.shape[:-1], -1, 2))
|
| 35 |
+
xk_ = torch.view_as_complex(xk.float().reshape(*xk.shape[:-1], -1, 2))
|
| 36 |
+
|
| 37 |
+
q_freqs = reshape_for_broadcast(q_freqs_cis, xq_)
|
| 38 |
+
k_freqs = reshape_for_broadcast(k_freqs_cis, xk_)
|
| 39 |
+
|
| 40 |
+
xq_out = torch.view_as_real(xq_ * q_freqs).flatten(xq.ndim - 1)
|
| 41 |
+
xk_out = torch.view_as_real(xk_ * k_freqs).flatten(xk.ndim - 1)
|
| 42 |
+
|
| 43 |
+
return xq_out.type_as(xq), xk_out.type_as(xk)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class RMSNorm(nn.Module):
|
| 47 |
+
def __init__(self, hidden_size, eps=1e-6):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.weight = nn.Parameter(torch.ones(hidden_size))
|
| 50 |
+
self.variance_epsilon = eps
|
| 51 |
+
|
| 52 |
+
def forward(self, hidden_states):
|
| 53 |
+
input_dtype = hidden_states.dtype
|
| 54 |
+
hidden_states = hidden_states.to(torch.float32)
|
| 55 |
+
variance = hidden_states.pow(2).mean(-1, keepdim=True)
|
| 56 |
+
hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
|
| 57 |
+
return self.weight * hidden_states.to(input_dtype)
|
| 58 |
+
|
| 59 |
+
# ================================
|
| 60 |
+
# MHC (Multi-Head Connections) Implementation
|
| 61 |
+
# ================================
|
| 62 |
+
def sinkhorn_knopp(
|
| 63 |
+
logits: torch.Tensor,
|
| 64 |
+
*,
|
| 65 |
+
tmax: int = 20,
|
| 66 |
+
eps: float = 1e-8,
|
| 67 |
+
clamp_min: float = 0.0,
|
| 68 |
+
) -> torch.Tensor:
|
| 69 |
+
log_m = logits.float()
|
| 70 |
+
log_m = log_m - log_m.amax(dim=(-2, -1), keepdim=True)
|
| 71 |
+
for _ in range(tmax):
|
| 72 |
+
log_m = log_m - torch.logsumexp(log_m, dim=-1, keepdim=True)
|
| 73 |
+
log_m = log_m - torch.logsumexp(log_m, dim=-2, keepdim=True)
|
| 74 |
+
m = torch.exp(log_m)
|
| 75 |
+
if clamp_min is not None and clamp_min > 0:
|
| 76 |
+
m = m.clamp_min(clamp_min)
|
| 77 |
+
m = m / (m.sum(dim=-1, keepdim=True) + eps)
|
| 78 |
+
m = m / (m.sum(dim=-2, keepdim=True) + eps)
|
| 79 |
+
return m
|
| 80 |
+
|
| 81 |
+
@dataclass(frozen=True)
|
| 82 |
+
class MhcMappings:
|
| 83 |
+
h_pre: torch.Tensor
|
| 84 |
+
h_post: torch.Tensor
|
| 85 |
+
h_res: torch.Tensor
|
| 86 |
+
|
| 87 |
+
class MhcProjector(nn.Module):
|
| 88 |
+
def __init__(
|
| 89 |
+
self,
|
| 90 |
+
*,
|
| 91 |
+
n_streams: int,
|
| 92 |
+
hidden_dim: int,
|
| 93 |
+
tmax: int = 20,
|
| 94 |
+
alpha_init: float = 0.01,
|
| 95 |
+
rmsnorm_eps: float = 1e-6,
|
| 96 |
+
):
|
| 97 |
+
super().__init__()
|
| 98 |
+
self.n = int(n_streams)
|
| 99 |
+
self.c = int(hidden_dim)
|
| 100 |
+
self.tmax = int(tmax)
|
| 101 |
+
|
| 102 |
+
flat_dim = self.n * self.c
|
| 103 |
+
self.rmsnorm = RMSNorm(flat_dim, eps=rmsnorm_eps)
|
| 104 |
+
|
| 105 |
+
self.phi_pre = nn.Parameter(torch.empty(flat_dim, self.n))
|
| 106 |
+
self.phi_post = nn.Parameter(torch.empty(flat_dim, self.n))
|
| 107 |
+
self.phi_res = nn.Parameter(torch.empty(flat_dim, self.n * self.n))
|
| 108 |
+
|
| 109 |
+
self.b_pre = nn.Parameter(torch.zeros(self.n))
|
| 110 |
+
self.b_post = nn.Parameter(torch.zeros(self.n))
|
| 111 |
+
self.b_res = nn.Parameter(torch.zeros(self.n, self.n))
|
| 112 |
+
|
| 113 |
+
self.alpha_pre = nn.Parameter(torch.tensor(float(alpha_init)))
|
| 114 |
+
self.alpha_post = nn.Parameter(torch.tensor(float(alpha_init)))
|
| 115 |
+
self.alpha_res = nn.Parameter(torch.tensor(float(alpha_init)))
|
| 116 |
+
|
| 117 |
+
self.reset_parameters()
|
| 118 |
+
|
| 119 |
+
def reset_parameters(self) -> None:
|
| 120 |
+
std = 0.02
|
| 121 |
+
nn.init.normal_(self.phi_pre, mean=0.0, std=std)
|
| 122 |
+
nn.init.normal_(self.phi_post, mean=0.0, std=std)
|
| 123 |
+
nn.init.normal_(self.phi_res, mean=0.0, std=std)
|
| 124 |
+
nn.init.zeros_(self.b_pre)
|
| 125 |
+
nn.init.zeros_(self.b_post)
|
| 126 |
+
nn.init.zeros_(self.b_res)
|
| 127 |
+
|
| 128 |
+
self.init_gpt2_equivalence()
|
| 129 |
+
|
| 130 |
+
@torch.no_grad()
|
| 131 |
+
def init_gpt2_equivalence(self, *, offdiag_bias: float = -20.0, alpha: float = 0.0) -> None:
|
| 132 |
+
self.phi_pre.zero_()
|
| 133 |
+
self.phi_post.zero_()
|
| 134 |
+
self.phi_res.zero_()
|
| 135 |
+
|
| 136 |
+
self.alpha_pre.fill_(alpha)
|
| 137 |
+
self.alpha_post.fill_(alpha)
|
| 138 |
+
self.alpha_res.fill_(alpha)
|
| 139 |
+
|
| 140 |
+
p = 1.0 / float(self.n)
|
| 141 |
+
logit_p = math.log(p / (1.0 - p)) if p not in (0.0, 1.0) else 0.0
|
| 142 |
+
self.b_pre.fill_(logit_p)
|
| 143 |
+
|
| 144 |
+
self.b_post.zero_()
|
| 145 |
+
|
| 146 |
+
self.b_res.fill_(offdiag_bias)
|
| 147 |
+
self.b_res.diagonal().fill_(0.0)
|
| 148 |
+
|
| 149 |
+
def forward(self, x_stream: torch.Tensor) -> MhcMappings:
|
| 150 |
+
b, t, n, c = x_stream.shape
|
| 151 |
+
x_flat = x_stream.reshape(b * t, n * c)
|
| 152 |
+
x_flat = self.rmsnorm(x_flat)
|
| 153 |
+
|
| 154 |
+
h_pre_tilde = self.alpha_pre * (x_flat @ self.phi_pre) + self.b_pre
|
| 155 |
+
h_post_tilde = self.alpha_post * (x_flat @ self.phi_post) + self.b_post
|
| 156 |
+
|
| 157 |
+
h_res_dyn = x_flat @ self.phi_res
|
| 158 |
+
h_res_tilde = self.alpha_res * h_res_dyn.reshape(b * t, n, n) + self.b_res
|
| 159 |
+
|
| 160 |
+
h_pre = torch.sigmoid(h_pre_tilde).reshape(b, t, n)
|
| 161 |
+
h_post = (2.0 * torch.sigmoid(h_post_tilde)).reshape(b, t, n)
|
| 162 |
+
h_res = sinkhorn_knopp(h_res_tilde.reshape(b, t, n, n), tmax=self.tmax)
|
| 163 |
+
|
| 164 |
+
return MhcMappings(h_pre=h_pre, h_post=h_post, h_res=h_res)
|
| 165 |
+
|
| 166 |
+
def stream_weighted_sum(x_stream: torch.Tensor, weights: torch.Tensor) -> torch.Tensor:
|
| 167 |
+
if weights.dtype != x_stream.dtype:
|
| 168 |
+
weights = weights.to(dtype=x_stream.dtype)
|
| 169 |
+
return torch.einsum("btn,btnc->btc", weights, x_stream)
|
| 170 |
+
|
| 171 |
+
def stream_mix(x_stream: torch.Tensor, h_res: torch.Tensor) -> torch.Tensor:
|
| 172 |
+
if h_res.dtype != x_stream.dtype:
|
| 173 |
+
h_res = h_res.to(dtype=x_stream.dtype)
|
| 174 |
+
return torch.einsum("btij,btjc->btic", h_res, x_stream)
|
| 175 |
+
|
| 176 |
+
def stream_write(y: torch.Tensor, h_post: torch.Tensor) -> torch.Tensor:
|
| 177 |
+
if h_post.dtype != y.dtype:
|
| 178 |
+
h_post = h_post.to(dtype=y.dtype)
|
| 179 |
+
return h_post.unsqueeze(-1) * y.unsqueeze(-2)
|
| 180 |
+
|
| 181 |
+
def mhc_update(x_stream: torch.Tensor, *, h_post: torch.Tensor, h_res: torch.Tensor, y: torch.Tensor) -> torch.Tensor:
|
| 182 |
+
return stream_mix(x_stream, h_res) + stream_write(y, h_post)
|
| 183 |
+
|
| 184 |
+
# ================================
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
class HybridMLAAttention(nn.Module):
|
| 188 |
+
def __init__(self, config: HybridModelConfig, layer_idx: int):
|
| 189 |
+
super().__init__()
|
| 190 |
+
self.config = config
|
| 191 |
+
self.layer_idx = layer_idx
|
| 192 |
+
self.d_model = config.hidden_size
|
| 193 |
+
self.num_head = config.num_attention_heads
|
| 194 |
+
self.d_head = self.d_model // self.num_head
|
| 195 |
+
self.d_embed = config.hidden_size
|
| 196 |
+
self.d_c = config.kv_lora_rank
|
| 197 |
+
self.d_c1 = config.q_lora_rank
|
| 198 |
+
self.d_rotate = config.qk_rope_head_dim
|
| 199 |
+
self.dropout_rate = config.attention_dropout
|
| 200 |
+
|
| 201 |
+
self.sliding_window = config.sliding_window if layer_idx % 2 == 0 else None
|
| 202 |
+
|
| 203 |
+
self.DKV_proj = nn.Linear(self.d_embed, self.d_c, bias=False)
|
| 204 |
+
self.DQ_proj = nn.Linear(self.d_embed, self.d_c1, bias=False)
|
| 205 |
+
|
| 206 |
+
self.UQ_proj = nn.Linear(self.d_c1, self.d_model, bias=False)
|
| 207 |
+
self.UK_proj = nn.Linear(self.d_c, self.d_model, bias=False)
|
| 208 |
+
self.UV_proj = nn.Linear(self.d_c, self.d_model, bias=False)
|
| 209 |
+
|
| 210 |
+
self.RQ_proj = nn.Linear(self.d_c1, self.num_head * self.d_rotate, bias=False)
|
| 211 |
+
self.RK_proj = nn.Linear(self.d_embed, self.d_rotate, bias=False)
|
| 212 |
+
|
| 213 |
+
self.o_proj = nn.Linear(self.d_model, self.d_model, bias=False)
|
| 214 |
+
self.dropout = nn.Dropout(p=self.dropout_rate)
|
| 215 |
+
|
| 216 |
+
self.scaler = float(1.0 / math.sqrt(self.d_head + self.d_rotate))
|
| 217 |
+
|
| 218 |
+
def forward(self, hidden_states, attention_mask=None, past_key_value=None, freqs_cis=None, use_cache=False):
|
| 219 |
+
batch_size, seq_len, _ = hidden_states.size()
|
| 220 |
+
start_pos = past_key_value[0].size(1) if past_key_value is not None else 0
|
| 221 |
+
|
| 222 |
+
C_Q = self.DQ_proj(hidden_states)
|
| 223 |
+
Q_state = self.UQ_proj(C_Q)
|
| 224 |
+
Q_rotate = self.RQ_proj(C_Q)
|
| 225 |
+
|
| 226 |
+
C_KV = self.DKV_proj(hidden_states)
|
| 227 |
+
K_rotate = self.RK_proj(hidden_states)
|
| 228 |
+
|
| 229 |
+
if past_key_value is not None:
|
| 230 |
+
C_KV_cache, K_rotate_cache = past_key_value
|
| 231 |
+
C_KV = torch.cat([C_KV_cache, C_KV], dim=1)
|
| 232 |
+
K_rotate = torch.cat([K_rotate_cache, K_rotate], dim=1)
|
| 233 |
+
|
| 234 |
+
present_key_value = (C_KV, K_rotate) if use_cache else None
|
| 235 |
+
actual_kv_len = C_KV.size(1)
|
| 236 |
+
|
| 237 |
+
K_state = self.UK_proj(C_KV)
|
| 238 |
+
V_state = self.UV_proj(C_KV)
|
| 239 |
+
|
| 240 |
+
Q_state = Q_state.view(batch_size, seq_len, self.num_head, self.d_head)
|
| 241 |
+
K_state = K_state.view(batch_size, actual_kv_len, self.num_head, self.d_head)
|
| 242 |
+
V_state = V_state.view(batch_size, actual_kv_len, self.num_head, self.d_head)
|
| 243 |
+
|
| 244 |
+
Q_rotate = Q_rotate.view(batch_size, seq_len, self.num_head, self.d_rotate)
|
| 245 |
+
K_rotate = K_rotate.unsqueeze(2).expand(-1, -1, self.num_head, -1)
|
| 246 |
+
|
| 247 |
+
if freqs_cis is not None:
|
| 248 |
+
q_freqs = freqs_cis[start_pos : start_pos + seq_len]
|
| 249 |
+
k_freqs = freqs_cis[:actual_kv_len]
|
| 250 |
+
Q_rotate, K_rotate = apply_rotary_emb(Q_rotate, K_rotate, q_freqs, k_freqs)
|
| 251 |
+
|
| 252 |
+
Q_state = torch.cat([Q_state, Q_rotate], dim=-1)
|
| 253 |
+
K_state = torch.cat([K_state, K_rotate], dim=-1)
|
| 254 |
+
|
| 255 |
+
Q_state = Q_state * self.scaler
|
| 256 |
+
Q_state = Q_state.transpose(1, 2)
|
| 257 |
+
K_state = K_state.transpose(1, 2)
|
| 258 |
+
V_state = V_state.transpose(1, 2)
|
| 259 |
+
|
| 260 |
+
att_matrix = torch.matmul(Q_state, K_state.transpose(-1, -2))
|
| 261 |
+
|
| 262 |
+
if attention_mask is not None:
|
| 263 |
+
att_matrix = att_matrix + attention_mask
|
| 264 |
+
|
| 265 |
+
if self.sliding_window is not None and actual_kv_len > 1:
|
| 266 |
+
window_mask = torch.ones(seq_len, actual_kv_len, dtype=torch.bool, device=hidden_states.device)
|
| 267 |
+
window_mask = torch.tril(window_mask, diagonal=actual_kv_len - seq_len)
|
| 268 |
+
window_mask = torch.triu(window_mask, diagonal=actual_kv_len - seq_len + 1 - self.sliding_window)
|
| 269 |
+
window_mask = ~window_mask
|
| 270 |
+
att_matrix.masked_fill_(window_mask[None, None, :, :], torch.finfo(att_matrix.dtype).min)
|
| 271 |
+
|
| 272 |
+
att_score = F.softmax(att_matrix, dim=-1, dtype=torch.float32).to(Q_state.dtype)
|
| 273 |
+
att_score = self.dropout(att_score)
|
| 274 |
+
|
| 275 |
+
att_output = torch.matmul(att_score, V_state)
|
| 276 |
+
att_output = att_output.transpose(1, 2).contiguous().view(batch_size, seq_len, self.num_head * self.d_head)
|
| 277 |
+
att_output = self.o_proj(att_output)
|
| 278 |
+
|
| 279 |
+
return att_output, None, present_key_value
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
class HybridMLP(nn.Module):
|
| 283 |
+
def __init__(self, config):
|
| 284 |
+
super().__init__()
|
| 285 |
+
self.hidden_size = config.hidden_size
|
| 286 |
+
self.intermediate_size = config.intermediate_size
|
| 287 |
+
self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 288 |
+
self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
|
| 289 |
+
self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
|
| 290 |
+
self.act_fn = ACT2FN[config.hidden_act]
|
| 291 |
+
|
| 292 |
+
def forward(self, x):
|
| 293 |
+
return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
class HybridDecoderLayer(nn.Module):
|
| 297 |
+
def __init__(self, config: HybridModelConfig, layer_idx: int):
|
| 298 |
+
super().__init__()
|
| 299 |
+
self.hidden_size = config.hidden_size
|
| 300 |
+
self.self_attn = HybridMLAAttention(config=config, layer_idx=layer_idx)
|
| 301 |
+
self.mlp = HybridMLP(config)
|
| 302 |
+
self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 303 |
+
self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 304 |
+
|
| 305 |
+
# MHC modules
|
| 306 |
+
self.mhc_attn = MhcProjector(
|
| 307 |
+
n_streams=config.mhc_num_streams,
|
| 308 |
+
hidden_dim=config.hidden_size,
|
| 309 |
+
tmax=config.mhc_sinkhorn_iters,
|
| 310 |
+
alpha_init=config.mhc_alpha_init,
|
| 311 |
+
rmsnorm_eps=config.mhc_rmsnorm_eps,
|
| 312 |
+
)
|
| 313 |
+
self.mhc_mlp = MhcProjector(
|
| 314 |
+
n_streams=config.mhc_num_streams,
|
| 315 |
+
hidden_dim=config.hidden_size,
|
| 316 |
+
tmax=config.mhc_sinkhorn_iters,
|
| 317 |
+
alpha_init=config.mhc_alpha_init,
|
| 318 |
+
rmsnorm_eps=config.mhc_rmsnorm_eps,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
def forward(self, hidden_states, attention_mask=None, past_key_value=None, freqs_cis=None, use_cache=False):
|
| 322 |
+
# hidden_states is x_stream: [B, T, n_streams, C]
|
| 323 |
+
x_stream = hidden_states
|
| 324 |
+
|
| 325 |
+
# Attention step
|
| 326 |
+
maps_attn = self.mhc_attn(x_stream)
|
| 327 |
+
x_in = stream_weighted_sum(x_stream, maps_attn.h_pre)
|
| 328 |
+
x_in = self.input_layernorm(x_in)
|
| 329 |
+
|
| 330 |
+
attn_out, _, present_key_value = self.self_attn(
|
| 331 |
+
hidden_states=x_in,
|
| 332 |
+
attention_mask=attention_mask,
|
| 333 |
+
past_key_value=past_key_value,
|
| 334 |
+
freqs_cis=freqs_cis,
|
| 335 |
+
use_cache=use_cache,
|
| 336 |
+
)
|
| 337 |
+
x_stream = mhc_update(x_stream, h_post=maps_attn.h_post, h_res=maps_attn.h_res, y=attn_out)
|
| 338 |
+
|
| 339 |
+
# MLP step
|
| 340 |
+
maps_mlp = self.mhc_mlp(x_stream)
|
| 341 |
+
x_in2 = stream_weighted_sum(x_stream, maps_mlp.h_pre)
|
| 342 |
+
x_in2 = self.post_attention_layernorm(x_in2)
|
| 343 |
+
mlp_out = self.mlp(x_in2)
|
| 344 |
+
x_stream = mhc_update(x_stream, h_post=maps_mlp.h_post, h_res=maps_mlp.h_res, y=mlp_out)
|
| 345 |
+
|
| 346 |
+
return x_stream, present_key_value
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class HybridPreTrainedModel(PreTrainedModel):
|
| 350 |
+
config_class = HybridModelConfig
|
| 351 |
+
base_model_prefix = "model"
|
| 352 |
+
supports_gradient_checkpointing = True
|
| 353 |
+
_supports_cache_class = False # use legacy tuple KV cache, not DynamicCache
|
| 354 |
+
|
| 355 |
+
def _init_weights(self, module):
|
| 356 |
+
std = self.config.initializer_range
|
| 357 |
+
if isinstance(module, nn.Linear):
|
| 358 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 359 |
+
if module.bias is not None:
|
| 360 |
+
module.bias.data.zero_()
|
| 361 |
+
elif isinstance(module, nn.Embedding):
|
| 362 |
+
module.weight.data.normal_(mean=0.0, std=std)
|
| 363 |
+
if module.padding_idx is not None:
|
| 364 |
+
module.weight.data[module.padding_idx].zero_()
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class HybridModel(HybridPreTrainedModel):
|
| 368 |
+
def __init__(self, config: HybridModelConfig):
|
| 369 |
+
super().__init__(config)
|
| 370 |
+
self.padding_idx = config.pad_token_id
|
| 371 |
+
self.vocab_size = config.vocab_size
|
| 372 |
+
|
| 373 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
|
| 374 |
+
self.layers = nn.ModuleList([HybridDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)])
|
| 375 |
+
self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 376 |
+
|
| 377 |
+
freqs_cis = precompute_freqs_cis(config.qk_rope_head_dim, config.max_position_embeddings, config.rope_theta)
|
| 378 |
+
self.register_buffer("freqs_cis", freqs_cis, persistent=False)
|
| 379 |
+
|
| 380 |
+
# MHC Readout
|
| 381 |
+
self.mhc_readout_logits = nn.Parameter(torch.zeros(config.mhc_num_streams))
|
| 382 |
+
self._init_readout()
|
| 383 |
+
|
| 384 |
+
self.post_init()
|
| 385 |
+
|
| 386 |
+
def _init_readout(self) -> None:
|
| 387 |
+
with torch.no_grad():
|
| 388 |
+
if self.config.mhc_readout_init == "mean":
|
| 389 |
+
self.mhc_readout_logits.zero_()
|
| 390 |
+
else:
|
| 391 |
+
self.mhc_readout_logits.fill_(-5.0)
|
| 392 |
+
self.mhc_readout_logits[0] = 5.0
|
| 393 |
+
|
| 394 |
+
def _stream_init(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 395 |
+
b, t, c = hidden_states.shape
|
| 396 |
+
n = self.config.mhc_num_streams
|
| 397 |
+
if self.config.mhc_stream_init == "copy":
|
| 398 |
+
return hidden_states.unsqueeze(-2).expand(b, t, n, c).contiguous()
|
| 399 |
+
x_stream = hidden_states.new_zeros((b, t, n, c))
|
| 400 |
+
x_stream[:, :, 0, :] = hidden_states
|
| 401 |
+
return x_stream
|
| 402 |
+
|
| 403 |
+
def _readout(self, x_stream: torch.Tensor) -> torch.Tensor:
|
| 404 |
+
w = torch.softmax(self.mhc_readout_logits, dim=0).to(dtype=x_stream.dtype)
|
| 405 |
+
return torch.einsum("n,btnc->btc", w, x_stream)
|
| 406 |
+
|
| 407 |
+
def forward(
|
| 408 |
+
self,
|
| 409 |
+
input_ids=None,
|
| 410 |
+
attention_mask=None,
|
| 411 |
+
position_ids=None,
|
| 412 |
+
past_key_values=None,
|
| 413 |
+
use_cache=None,
|
| 414 |
+
output_hidden_states=None,
|
| 415 |
+
return_dict=None
|
| 416 |
+
):
|
| 417 |
+
output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
| 418 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
| 419 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 420 |
+
|
| 421 |
+
batch_size, seq_length = input_ids.shape
|
| 422 |
+
|
| 423 |
+
past_key_values_length = 0
|
| 424 |
+
if past_key_values is not None:
|
| 425 |
+
# Convert DynamicCache (or any Cache object) to legacy tuple of tuples
|
| 426 |
+
if not isinstance(past_key_values, tuple):
|
| 427 |
+
if hasattr(past_key_values, "to_legacy_cache"):
|
| 428 |
+
past_key_values = past_key_values.to_legacy_cache()
|
| 429 |
+
else:
|
| 430 |
+
past_key_values = None
|
| 431 |
+
|
| 432 |
+
# An empty tuple means no real cached state yet (first generate() call)
|
| 433 |
+
if past_key_values is not None and len(past_key_values) == 0:
|
| 434 |
+
past_key_values = None
|
| 435 |
+
|
| 436 |
+
if past_key_values is not None:
|
| 437 |
+
past_key_values_length = past_key_values[0][0].shape[1]
|
| 438 |
+
|
| 439 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
| 440 |
+
hidden_states = inputs_embeds
|
| 441 |
+
|
| 442 |
+
kv_seq_len = seq_length + past_key_values_length
|
| 443 |
+
causal_mask = torch.tril(
|
| 444 |
+
torch.ones((seq_length, kv_seq_len), dtype=torch.bool, device=input_ids.device),
|
| 445 |
+
diagonal=past_key_values_length
|
| 446 |
+
)
|
| 447 |
+
|
| 448 |
+
if attention_mask is not None:
|
| 449 |
+
attention_mask_expanded = attention_mask[:, None, None, :] == 1
|
| 450 |
+
else:
|
| 451 |
+
attention_mask_expanded = True
|
| 452 |
+
|
| 453 |
+
mask = causal_mask[None, None, :, :] & attention_mask_expanded
|
| 454 |
+
extended_attention_mask = torch.where(mask, 0.0, torch.finfo(hidden_states.dtype).min)
|
| 455 |
+
|
| 456 |
+
all_present_key_values = () if use_cache else None
|
| 457 |
+
all_hidden_states = () if output_hidden_states else None
|
| 458 |
+
|
| 459 |
+
x_stream = self._stream_init(hidden_states)
|
| 460 |
+
|
| 461 |
+
for i, layer in enumerate(self.layers):
|
| 462 |
+
if output_hidden_states:
|
| 463 |
+
all_hidden_states += (self._readout(x_stream),)
|
| 464 |
+
|
| 465 |
+
past_key_value = past_key_values[i] if past_key_values is not None else None
|
| 466 |
+
x_stream, present_key_value = layer(
|
| 467 |
+
x_stream,
|
| 468 |
+
attention_mask=extended_attention_mask,
|
| 469 |
+
past_key_value=past_key_value,
|
| 470 |
+
freqs_cis=self.freqs_cis,
|
| 471 |
+
use_cache=use_cache,
|
| 472 |
+
)
|
| 473 |
+
if use_cache:
|
| 474 |
+
all_present_key_values += (present_key_value,)
|
| 475 |
+
|
| 476 |
+
hidden_states = self._readout(x_stream)
|
| 477 |
+
hidden_states = self.norm(hidden_states)
|
| 478 |
+
|
| 479 |
+
if output_hidden_states:
|
| 480 |
+
all_hidden_states += (hidden_states,)
|
| 481 |
+
|
| 482 |
+
if not return_dict:
|
| 483 |
+
return tuple(v for v in [hidden_states, all_present_key_values, all_hidden_states] if v is not None)
|
| 484 |
+
|
| 485 |
+
return BaseModelOutputWithPast(
|
| 486 |
+
last_hidden_state=hidden_states,
|
| 487 |
+
past_key_values=all_present_key_values,
|
| 488 |
+
hidden_states=all_hidden_states,
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
|
| 492 |
+
class HybridForCausalLM(HybridPreTrainedModel, GenerationMixin):
|
| 493 |
+
def __init__(self, config):
|
| 494 |
+
super().__init__(config)
|
| 495 |
+
self.model = HybridModel(config)
|
| 496 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 497 |
+
self.post_init()
|
| 498 |
+
|
| 499 |
+
def get_input_embeddings(self):
|
| 500 |
+
return self.model.embed_tokens
|
| 501 |
+
|
| 502 |
+
def set_input_embeddings(self, value):
|
| 503 |
+
self.model.embed_tokens = value
|
| 504 |
+
|
| 505 |
+
def get_output_embeddings(self):
|
| 506 |
+
return self.lm_head
|
| 507 |
+
|
| 508 |
+
def set_output_embeddings(self, new_embeddings):
|
| 509 |
+
self.lm_head = new_embeddings
|
| 510 |
+
|
| 511 |
+
def forward(
|
| 512 |
+
self,
|
| 513 |
+
input_ids=None,
|
| 514 |
+
attention_mask=None,
|
| 515 |
+
position_ids=None,
|
| 516 |
+
past_key_values=None,
|
| 517 |
+
labels=None,
|
| 518 |
+
use_cache=None,
|
| 519 |
+
output_hidden_states=None,
|
| 520 |
+
return_dict=None
|
| 521 |
+
):
|
| 522 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
| 523 |
+
|
| 524 |
+
outputs = self.model(
|
| 525 |
+
input_ids=input_ids,
|
| 526 |
+
attention_mask=attention_mask,
|
| 527 |
+
position_ids=position_ids,
|
| 528 |
+
past_key_values=past_key_values,
|
| 529 |
+
use_cache=use_cache,
|
| 530 |
+
output_hidden_states=output_hidden_states,
|
| 531 |
+
return_dict=return_dict
|
| 532 |
+
)
|
| 533 |
+
|
| 534 |
+
hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state
|
| 535 |
+
logits = self.lm_head(hidden_states)
|
| 536 |
+
|
| 537 |
+
loss = None
|
| 538 |
+
if labels is not None:
|
| 539 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 540 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 541 |
+
loss_fct = nn.CrossEntropyLoss()
|
| 542 |
+
loss = loss_fct(shift_logits.view(-1, self.config.vocab_size), shift_labels.view(-1))
|
| 543 |
+
|
| 544 |
+
if not return_dict:
|
| 545 |
+
output = (logits,) + outputs[1:]
|
| 546 |
+
return (loss,) + output if loss is not None else output
|
| 547 |
+
|
| 548 |
+
return CausalLMOutputWithPast(
|
| 549 |
+
loss=loss,
|
| 550 |
+
logits=logits,
|
| 551 |
+
past_key_values=outputs.past_key_values if return_dict else None,
|
| 552 |
+
hidden_states=outputs.hidden_states if return_dict else None,
|
| 553 |
+
)
|
| 554 |
+
|
| 555 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs):
|
| 556 |
+
if past_key_values is not None:
|
| 557 |
+
if hasattr(past_key_values, "get_seq_length"):
|
| 558 |
+
past_length = past_key_values.get_seq_length()
|
| 559 |
+
else:
|
| 560 |
+
past_length = past_key_values[0][0].shape[1]
|
| 561 |
+
if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
|
| 562 |
+
input_ids = input_ids[:, -1:]
|
| 563 |
+
elif past_length < input_ids.shape[1]:
|
| 564 |
+
input_ids = input_ids[:, past_length:]
|
| 565 |
+
|
| 566 |
+
position_ids = kwargs.get("position_ids", None)
|
| 567 |
+
if attention_mask is not None and position_ids is None:
|
| 568 |
+
position_ids = attention_mask.long().cumsum(-1) - 1
|
| 569 |
+
position_ids.masked_fill_(attention_mask == 0, 1)
|
| 570 |
+
if past_key_values:
|
| 571 |
+
position_ids = position_ids[:, -input_ids.shape[1] :]
|
| 572 |
+
|
| 573 |
+
model_inputs = {"input_ids": input_ids}
|
| 574 |
+
model_inputs.update(
|
| 575 |
+
{
|
| 576 |
+
"position_ids": position_ids,
|
| 577 |
+
"past_key_values": past_key_values,
|
| 578 |
+
"use_cache": kwargs.get("use_cache"),
|
| 579 |
+
"attention_mask": attention_mask,
|
| 580 |
+
}
|
| 581 |
+
)
|
| 582 |
+
return model_inputs
|
| 583 |
+
|
| 584 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 585 |
+
reordered_past = ()
|
| 586 |
+
for layer_past in past_key_values:
|
| 587 |
+
reordered_past += (
|
| 588 |
+
tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
|
| 589 |
+
)
|
| 590 |
+
return reordered_past
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
HybridModelConfig.register_for_auto_class()
|
| 594 |
+
HybridForCausalLM.register_for_auto_class("AutoModelForCausalLM")
|