Instructions to use CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B
- SGLang
How to use CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B 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 "CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'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 "CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B with Docker Model Runner:
docker model run hf.co/CodeIsAbstract/HybridTimeScaleModel-Instruct-Tuned-0.1B
Upload model.py with huggingface_hub
Browse files
model.py
ADDED
|
@@ -0,0 +1,450 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
HybridFourierLM β Model Architecture
|
| 3 |
+
=====================================
|
| 4 |
+
Self-contained module that registers the custom config + model with
|
| 5 |
+
HuggingFace `transformers` so that `AutoConfig` / `AutoModelForCausalLM`
|
| 6 |
+
can load checkpoints transparently.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import math
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
from torch.utils.checkpoint import checkpoint
|
| 15 |
+
from transformers import (
|
| 16 |
+
AutoConfig,
|
| 17 |
+
AutoModelForCausalLM,
|
| 18 |
+
GenerationMixin,
|
| 19 |
+
PretrainedConfig,
|
| 20 |
+
PreTrainedModel,
|
| 21 |
+
)
|
| 22 |
+
from transformers.modeling_outputs import CausalLMOutput
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 26 |
+
# Config
|
| 27 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
|
| 29 |
+
class HybridFourierConfig(PretrainedConfig):
|
| 30 |
+
model_type = "hybrid_fourier_lm"
|
| 31 |
+
|
| 32 |
+
def __init__(
|
| 33 |
+
self,
|
| 34 |
+
vocab_size=50304,
|
| 35 |
+
latent_dim=768,
|
| 36 |
+
num_layers=12,
|
| 37 |
+
num_modes=64,
|
| 38 |
+
layer_types=None,
|
| 39 |
+
time_scale=128.0,
|
| 40 |
+
dropout=0.05,
|
| 41 |
+
pad_token_id=0,
|
| 42 |
+
bos_token_id=1,
|
| 43 |
+
eos_token_id=2,
|
| 44 |
+
tie_word_embeddings=True,
|
| 45 |
+
**kwargs,
|
| 46 |
+
):
|
| 47 |
+
self.vocab_size = vocab_size
|
| 48 |
+
self.latent_dim = latent_dim
|
| 49 |
+
self.num_layers = num_layers
|
| 50 |
+
self.num_modes = num_modes
|
| 51 |
+
self.time_scale = time_scale
|
| 52 |
+
self.dropout = dropout
|
| 53 |
+
|
| 54 |
+
if layer_types is None:
|
| 55 |
+
layer_types = [
|
| 56 |
+
"softmax" if (i % 4 == 3) else "linear"
|
| 57 |
+
for i in range(num_layers)
|
| 58 |
+
]
|
| 59 |
+
assert len(layer_types) == num_layers, (
|
| 60 |
+
f"layer_types length ({len(layer_types)}) must equal num_layers ({num_layers})"
|
| 61 |
+
)
|
| 62 |
+
self.layer_types = layer_types
|
| 63 |
+
|
| 64 |
+
super().__init__(
|
| 65 |
+
pad_token_id=pad_token_id,
|
| 66 |
+
bos_token_id=bos_token_id,
|
| 67 |
+
eos_token_id=eos_token_id,
|
| 68 |
+
tie_word_embeddings=tie_word_embeddings,
|
| 69 |
+
**kwargs,
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 74 |
+
# Mixer layers
|
| 75 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 76 |
+
|
| 77 |
+
class LinearFourierMixer(nn.Module):
|
| 78 |
+
def __init__(self, channels, num_modes=64, num_heads=12, time_scale=128, dropout=0.05):
|
| 79 |
+
super().__init__()
|
| 80 |
+
assert channels % num_heads == 0, (
|
| 81 |
+
f"channels ({channels}) must be perfectly divisible by num_heads ({num_heads})"
|
| 82 |
+
)
|
| 83 |
+
self.channels = channels
|
| 84 |
+
self.num_modes = num_modes
|
| 85 |
+
self.num_heads = num_heads
|
| 86 |
+
self.head_dim = channels // num_heads
|
| 87 |
+
self.time_scale = time_scale
|
| 88 |
+
|
| 89 |
+
freq_bands = torch.exp(torch.linspace(math.log(0.0001), math.log(num_modes), num_modes))
|
| 90 |
+
self.num_modes = freq_bands.shape[0]
|
| 91 |
+
self.register_buffer("frequencies", freq_bands)
|
| 92 |
+
|
| 93 |
+
self.q_proj = nn.Linear(channels, self.num_heads * self.num_modes)
|
| 94 |
+
self.k_proj = nn.Linear(channels, self.num_heads * self.num_modes)
|
| 95 |
+
self.v_proj = nn.Linear(channels, channels)
|
| 96 |
+
self.proj_v2 = nn.Linear(channels, channels)
|
| 97 |
+
self.out_proj = nn.Linear(channels, channels)
|
| 98 |
+
self.activation = nn.SiLU()
|
| 99 |
+
self.norm_in = nn.LayerNorm(channels)
|
| 100 |
+
self.norm_out = nn.LayerNorm(channels)
|
| 101 |
+
self.dropout = nn.Dropout(dropout)
|
| 102 |
+
|
| 103 |
+
def forward(self, x, attention_mask=None):
|
| 104 |
+
B, seq_len, C = x.shape
|
| 105 |
+
norm_x = self.norm_in(x)
|
| 106 |
+
|
| 107 |
+
Q = F.elu(self.q_proj(norm_x)).view(B, seq_len, self.num_heads, self.num_modes) + 1.0
|
| 108 |
+
K = F.elu(self.k_proj(norm_x)).view(B, seq_len, self.num_heads, self.num_modes) + 1.0
|
| 109 |
+
|
| 110 |
+
v1 = self.v_proj(norm_x)
|
| 111 |
+
v2 = self.activation(self.proj_v2(norm_x))
|
| 112 |
+
|
| 113 |
+
t = (torch.arange(seq_len, device=x.device, dtype=x.dtype) / self.time_scale).view(-1, 1)
|
| 114 |
+
omega_t = 2 * math.pi * t * self.frequencies.unsqueeze(0)
|
| 115 |
+
U = torch.cos(omega_t).unsqueeze(0).unsqueeze(2)
|
| 116 |
+
V = torch.sin(omega_t).unsqueeze(0).unsqueeze(2)
|
| 117 |
+
|
| 118 |
+
Q_cos = Q * U
|
| 119 |
+
Q_sin = Q * V
|
| 120 |
+
K_cos = K * U
|
| 121 |
+
K_sin = K * V
|
| 122 |
+
|
| 123 |
+
Q_rot = torch.cat([Q_cos, Q_sin], dim=-1)
|
| 124 |
+
K_rot = torch.cat([K_cos, K_sin], dim=-1)
|
| 125 |
+
|
| 126 |
+
# Linear-attention normalization in fp32 for numerical stability
|
| 127 |
+
orig_dtype = Q_rot.dtype
|
| 128 |
+
Q_rot = Q_rot.float()
|
| 129 |
+
K_rot = K_rot.float()
|
| 130 |
+
|
| 131 |
+
if seq_len > 512:
|
| 132 |
+
v1_heads = v1.view(B, seq_len, self.num_heads, self.head_dim)
|
| 133 |
+
out_chunks = []
|
| 134 |
+
chunk_size = 256 if seq_len > 1024 else 512
|
| 135 |
+
for i_start in range(0, seq_len, chunk_size):
|
| 136 |
+
i_end = min(i_start + chunk_size, seq_len)
|
| 137 |
+
Q_chunk = Q_rot[:, i_start:i_end, :, :] # [B, C, H, 2M]
|
| 138 |
+
K_past = K_rot[:, :i_end, :, :] # [B, j_max, H, 2M]
|
| 139 |
+
v1_past = v1_heads[:, :i_end, :, :].float() # [B, j_max, H, D]
|
| 140 |
+
|
| 141 |
+
A_chunk = torch.einsum('b i h m, b j h m -> b h i j', Q_chunk, K_past)
|
| 142 |
+
A_chunk = A_chunk / math.sqrt(self.num_modes * 2)
|
| 143 |
+
|
| 144 |
+
i_abs = torch.arange(i_start, i_end, device=x.device).view(-1, 1)
|
| 145 |
+
j_abs = torch.arange(i_end, device=x.device).view(1, -1)
|
| 146 |
+
causal_mask = (j_abs <= i_abs).to(dtype=A_chunk.dtype)
|
| 147 |
+
A_chunk = A_chunk * causal_mask.unsqueeze(0).unsqueeze(0)
|
| 148 |
+
|
| 149 |
+
if attention_mask is not None:
|
| 150 |
+
pad_mask = attention_mask[:, None, None, :i_end].to(dtype=A_chunk.dtype)
|
| 151 |
+
A_chunk = A_chunk * pad_mask
|
| 152 |
+
|
| 153 |
+
row_denom = torch.abs(A_chunk.sum(dim=-1, keepdim=True)) + 1.0
|
| 154 |
+
A_chunk = A_chunk / row_denom
|
| 155 |
+
|
| 156 |
+
v1_chunk = torch.einsum('b h i j, b j h d -> b i h d', A_chunk, v1_past)
|
| 157 |
+
out_chunks.append(v1_chunk.to(orig_dtype))
|
| 158 |
+
v1_token_mixed = torch.cat(out_chunks, dim=1).reshape(B, seq_len, C)
|
| 159 |
+
v1_token_mixed = self.dropout(v1_token_mixed)
|
| 160 |
+
if attention_mask is not None:
|
| 161 |
+
v1_token_mixed = torch.nan_to_num(v1_token_mixed, nan=0.0, posinf=0.0, neginf=0.0)
|
| 162 |
+
v1_token_mixed = v1_token_mixed * attention_mask.unsqueeze(-1).to(dtype=v1_token_mixed.dtype)
|
| 163 |
+
else:
|
| 164 |
+
A = torch.einsum('b i h m, b j h m -> b h i j', Q_rot, K_rot)
|
| 165 |
+
A = A / math.sqrt(self.num_modes * 2)
|
| 166 |
+
|
| 167 |
+
causal_mask = torch.tril(torch.ones(seq_len, seq_len, device=x.device, dtype=A.dtype))
|
| 168 |
+
A = A * causal_mask.unsqueeze(0).unsqueeze(0)
|
| 169 |
+
|
| 170 |
+
if attention_mask is not None:
|
| 171 |
+
pad_mask = attention_mask[:, None, None, :].to(dtype=A.dtype)
|
| 172 |
+
A = A * pad_mask
|
| 173 |
+
|
| 174 |
+
row_denom = torch.abs(A.sum(dim=-1, keepdim=True)) + 1.0
|
| 175 |
+
A = A / row_denom
|
| 176 |
+
A = A.to(orig_dtype)
|
| 177 |
+
|
| 178 |
+
v1_heads = v1.view(B, seq_len, self.num_heads, self.head_dim)
|
| 179 |
+
v1_token_mixed = torch.einsum('b h i j, b j h d -> b i h d', A, v1_heads)
|
| 180 |
+
v1_token_mixed = v1_token_mixed.reshape(B, seq_len, C)
|
| 181 |
+
v1_token_mixed = self.dropout(v1_token_mixed)
|
| 182 |
+
if attention_mask is not None:
|
| 183 |
+
v1_token_mixed = torch.nan_to_num(v1_token_mixed, nan=0.0, posinf=0.0, neginf=0.0)
|
| 184 |
+
v1_token_mixed = v1_token_mixed * attention_mask.unsqueeze(-1).to(dtype=v1_token_mixed.dtype)
|
| 185 |
+
|
| 186 |
+
v3 = v1_token_mixed * v2
|
| 187 |
+
return self.norm_out(self.out_proj(v3)) + x
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class SoftmaxFourierMixer(nn.Module):
|
| 191 |
+
def __init__(self, channels, num_modes=64, num_heads=12, time_scale=128.0, dropout=0.05):
|
| 192 |
+
super().__init__()
|
| 193 |
+
assert channels % num_heads == 0, (
|
| 194 |
+
f"channels ({channels}) must be perfectly divisible by num_heads ({num_heads})"
|
| 195 |
+
)
|
| 196 |
+
self.channels = channels
|
| 197 |
+
self.num_modes = num_modes
|
| 198 |
+
self.num_heads = num_heads
|
| 199 |
+
self.head_dim = channels // num_heads
|
| 200 |
+
self.time_scale = time_scale
|
| 201 |
+
|
| 202 |
+
freq_bands = torch.exp(torch.linspace(math.log(0.0001), math.log(num_modes), num_modes))
|
| 203 |
+
self.num_modes = freq_bands.shape[0]
|
| 204 |
+
self.register_buffer("frequencies", freq_bands)
|
| 205 |
+
|
| 206 |
+
self.q_proj = nn.Linear(channels, self.num_heads * self.num_modes)
|
| 207 |
+
self.k_proj = nn.Linear(channels, self.num_heads * self.num_modes)
|
| 208 |
+
self.v_proj = nn.Linear(channels, channels)
|
| 209 |
+
self.proj_v2 = nn.Linear(channels, channels)
|
| 210 |
+
self.out_proj = nn.Linear(channels, channels)
|
| 211 |
+
self.activation = nn.SiLU()
|
| 212 |
+
self.norm_in = nn.LayerNorm(channels)
|
| 213 |
+
self.norm_out = nn.LayerNorm(channels)
|
| 214 |
+
self.dropout = nn.Dropout(dropout)
|
| 215 |
+
|
| 216 |
+
def forward(self, x, attention_mask=None):
|
| 217 |
+
B, seq_len, C = x.shape
|
| 218 |
+
norm_x = self.norm_in(x)
|
| 219 |
+
|
| 220 |
+
Q = self.q_proj(norm_x).view(B, seq_len, self.num_heads, self.num_modes)
|
| 221 |
+
K = self.k_proj(norm_x).view(B, seq_len, self.num_heads, self.num_modes)
|
| 222 |
+
|
| 223 |
+
v1 = self.v_proj(norm_x)
|
| 224 |
+
v2 = self.activation(self.proj_v2(norm_x))
|
| 225 |
+
|
| 226 |
+
t = (torch.arange(seq_len, device=x.device, dtype=x.dtype) / self.time_scale).view(-1, 1)
|
| 227 |
+
omega_t = 2 * math.pi * t * self.frequencies.unsqueeze(0)
|
| 228 |
+
U = torch.cos(omega_t).unsqueeze(0).unsqueeze(2)
|
| 229 |
+
V = torch.sin(omega_t).unsqueeze(0).unsqueeze(2)
|
| 230 |
+
|
| 231 |
+
Q_cos = Q * U
|
| 232 |
+
Q_sin = Q * V
|
| 233 |
+
K_cos = K * U
|
| 234 |
+
K_sin = K * V
|
| 235 |
+
|
| 236 |
+
Q_rot = torch.cat([Q_cos, Q_sin], dim=-1)
|
| 237 |
+
K_rot = torch.cat([K_cos, K_sin], dim=-1)
|
| 238 |
+
|
| 239 |
+
v1_heads = v1.view(B, seq_len, self.num_heads, self.head_dim)
|
| 240 |
+
|
| 241 |
+
# Actual softmax attention via SDPA (B, H, L, 2M)
|
| 242 |
+
Q_b = Q_rot.transpose(1, 2)
|
| 243 |
+
K_b = K_rot.transpose(1, 2)
|
| 244 |
+
V_b = v1_heads.transpose(1, 2)
|
| 245 |
+
|
| 246 |
+
# PyTorch's MPS backend has a known bug/crash in C++ kernel
|
| 247 |
+
# (`-[__NSPlaceholderDictionary initWithObjects:forKeys:count:]`)
|
| 248 |
+
# when calling F.scaled_dot_product_attention on certain shapes or when
|
| 249 |
+
# attn_mask and is_causal are combined. We use explicit math attention
|
| 250 |
+
# on MPS (or fallback if SDPA fails) to guarantee stability across all PyTorch versions.
|
| 251 |
+
if x.device.type == "mps" or seq_len > 512:
|
| 252 |
+
scale = 1.0 / math.sqrt(Q_b.size(-1))
|
| 253 |
+
if seq_len > 256:
|
| 254 |
+
out_chunks = []
|
| 255 |
+
chunk_size = 256 if seq_len > 1024 else 512
|
| 256 |
+
for i_start in range(0, seq_len, chunk_size):
|
| 257 |
+
i_end = min(i_start + chunk_size, seq_len)
|
| 258 |
+
Q_chunk = Q_b[:, :, i_start:i_end, :] # [B, H, C, 2M]
|
| 259 |
+
K_past = K_b[:, :, :i_end, :] # [B, H, 2M, j_max]
|
| 260 |
+
V_past = V_b[:, :, :i_end, :] # [B, H, j_max, D]
|
| 261 |
+
|
| 262 |
+
scores_chunk = torch.matmul(Q_chunk, K_past.transpose(-2, -1)) * scale
|
| 263 |
+
|
| 264 |
+
i_abs = torch.arange(i_start, i_end, device=x.device).view(-1, 1)
|
| 265 |
+
j_abs = torch.arange(i_end, device=x.device).view(1, -1)
|
| 266 |
+
causal_mask = (j_abs <= i_abs)
|
| 267 |
+
scores_chunk = scores_chunk.masked_fill(~causal_mask.unsqueeze(0).unsqueeze(0), float("-inf"))
|
| 268 |
+
|
| 269 |
+
if attention_mask is not None:
|
| 270 |
+
pad_mask = attention_mask[:, None, None, :i_end].to(dtype=torch.bool)
|
| 271 |
+
scores_chunk = scores_chunk.masked_fill(~pad_mask, float("-inf"))
|
| 272 |
+
|
| 273 |
+
attn_weights = F.softmax(scores_chunk, dim=-1)
|
| 274 |
+
out_chunk = torch.matmul(attn_weights, V_past) # [B, H, C, D]
|
| 275 |
+
out_chunks.append(out_chunk)
|
| 276 |
+
v1_token_mixed = torch.cat(out_chunks, dim=2)
|
| 277 |
+
else:
|
| 278 |
+
scores = torch.matmul(Q_b, K_b.transpose(-2, -1)) * scale
|
| 279 |
+
causal_mask = torch.tril(torch.ones(seq_len, seq_len, device=x.device, dtype=torch.bool))
|
| 280 |
+
scores = scores.masked_fill(~causal_mask.unsqueeze(0).unsqueeze(0), float("-inf"))
|
| 281 |
+
if attention_mask is not None:
|
| 282 |
+
pad_mask = attention_mask[:, None, None, :].to(dtype=torch.bool)
|
| 283 |
+
scores = scores.masked_fill(~pad_mask, float("-inf"))
|
| 284 |
+
attn_weights = F.softmax(scores, dim=-1)
|
| 285 |
+
v1_token_mixed = torch.matmul(attn_weights, V_b)
|
| 286 |
+
else:
|
| 287 |
+
attn_mask = None
|
| 288 |
+
if attention_mask is not None:
|
| 289 |
+
attn_mask = attention_mask[:, None, None, :].to(dtype=Q_b.dtype)
|
| 290 |
+
attn_mask = (1.0 - attn_mask) * torch.finfo(Q_b.dtype).min
|
| 291 |
+
|
| 292 |
+
try:
|
| 293 |
+
v1_token_mixed = F.scaled_dot_product_attention(
|
| 294 |
+
Q_b, K_b, V_b,
|
| 295 |
+
attn_mask=attn_mask,
|
| 296 |
+
is_causal=True,
|
| 297 |
+
)
|
| 298 |
+
except Exception:
|
| 299 |
+
scale = 1.0 / math.sqrt(Q_b.size(-1))
|
| 300 |
+
scores = torch.matmul(Q_b, K_b.transpose(-2, -1)) * scale
|
| 301 |
+
causal_mask = torch.tril(torch.ones(seq_len, seq_len, device=x.device, dtype=torch.bool))
|
| 302 |
+
scores = scores.masked_fill(~causal_mask.unsqueeze(0).unsqueeze(0), float("-inf"))
|
| 303 |
+
if attention_mask is not None:
|
| 304 |
+
pad_mask = attention_mask[:, None, None, :].to(dtype=torch.bool)
|
| 305 |
+
scores = scores.masked_fill(~pad_mask, float("-inf"))
|
| 306 |
+
attn_weights = F.softmax(scores, dim=-1)
|
| 307 |
+
v1_token_mixed = torch.matmul(attn_weights, V_b)
|
| 308 |
+
|
| 309 |
+
v1_token_mixed = v1_token_mixed.transpose(1, 2).reshape(B, seq_len, C)
|
| 310 |
+
v1_token_mixed = self.dropout(v1_token_mixed)
|
| 311 |
+
if attention_mask is not None:
|
| 312 |
+
v1_token_mixed = torch.nan_to_num(v1_token_mixed, nan=0.0, posinf=0.0, neginf=0.0)
|
| 313 |
+
v1_token_mixed = v1_token_mixed * attention_mask.unsqueeze(-1).to(dtype=v1_token_mixed.dtype)
|
| 314 |
+
|
| 315 |
+
v3 = v1_token_mixed * v2
|
| 316 |
+
return self.norm_out(self.out_proj(v3)) + x
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 320 |
+
# Transformer block
|
| 321 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 322 |
+
|
| 323 |
+
class HybridSpectralBlock(nn.Module):
|
| 324 |
+
def __init__(self, latent_dim, num_modes=64, is_softmax=False,
|
| 325 |
+
time_scale=128.0, dropout=0.05, num_heads=None):
|
| 326 |
+
super().__init__()
|
| 327 |
+
self.is_softmax = is_softmax
|
| 328 |
+
num_heads = num_heads if num_heads is not None else max(1, latent_dim // 64)
|
| 329 |
+
|
| 330 |
+
if is_softmax:
|
| 331 |
+
self.mixer = SoftmaxFourierMixer(latent_dim, num_modes, num_heads, time_scale, dropout)
|
| 332 |
+
else:
|
| 333 |
+
self.mixer = LinearFourierMixer(latent_dim, num_modes, num_heads, time_scale, dropout)
|
| 334 |
+
|
| 335 |
+
self.ffn = nn.Sequential(
|
| 336 |
+
nn.LayerNorm(latent_dim),
|
| 337 |
+
nn.Linear(latent_dim, 4 * latent_dim),
|
| 338 |
+
nn.GELU(),
|
| 339 |
+
nn.Linear(4 * latent_dim, latent_dim),
|
| 340 |
+
nn.Dropout(dropout),
|
| 341 |
+
)
|
| 342 |
+
self.gradient_checkpointing = False
|
| 343 |
+
|
| 344 |
+
def forward(self, x, attention_mask=None):
|
| 345 |
+
z = self.mixer(x, attention_mask=attention_mask)
|
| 346 |
+
return z + self.ffn(z)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 350 |
+
# Full model
|
| 351 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 352 |
+
|
| 353 |
+
class HybridFourierPreTrainedModel(PreTrainedModel):
|
| 354 |
+
config_class = HybridFourierConfig
|
| 355 |
+
base_model_prefix = "hybrid_fourier"
|
| 356 |
+
supports_gradient_checkpointing = True
|
| 357 |
+
_no_split_modules = ["HybridSpectralBlock"]
|
| 358 |
+
_tied_weights_keys = {"lm_head.weight": "embedding.weight"}
|
| 359 |
+
|
| 360 |
+
def _init_weights(self, module):
|
| 361 |
+
if isinstance(module, nn.Linear):
|
| 362 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 363 |
+
if module.bias is not None:
|
| 364 |
+
torch.nn.init.zeros_(module.bias)
|
| 365 |
+
elif isinstance(module, nn.Embedding):
|
| 366 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 367 |
+
elif isinstance(module, nn.LayerNorm):
|
| 368 |
+
torch.nn.init.zeros_(module.bias)
|
| 369 |
+
torch.nn.init.ones_(module.weight)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
class HybridFourierLM(HybridFourierPreTrainedModel, GenerationMixin):
|
| 373 |
+
def __init__(self, config):
|
| 374 |
+
super().__init__(config)
|
| 375 |
+
self.config = config
|
| 376 |
+
|
| 377 |
+
self.embedding = nn.Embedding(config.vocab_size, config.latent_dim,
|
| 378 |
+
padding_idx=config.pad_token_id)
|
| 379 |
+
|
| 380 |
+
blocks = []
|
| 381 |
+
for layer_type in config.layer_types:
|
| 382 |
+
blocks.append(HybridSpectralBlock(
|
| 383 |
+
config.latent_dim,
|
| 384 |
+
config.num_modes,
|
| 385 |
+
is_softmax=(layer_type == "softmax"),
|
| 386 |
+
time_scale=config.time_scale,
|
| 387 |
+
dropout=config.dropout,
|
| 388 |
+
))
|
| 389 |
+
self.mixers = nn.ModuleList(blocks)
|
| 390 |
+
|
| 391 |
+
self.ln_f = nn.LayerNorm(config.latent_dim)
|
| 392 |
+
self.lm_head = nn.Linear(config.latent_dim, config.vocab_size, bias=False)
|
| 393 |
+
|
| 394 |
+
self.post_init()
|
| 395 |
+
|
| 396 |
+
def get_input_embeddings(self):
|
| 397 |
+
return self.embedding
|
| 398 |
+
|
| 399 |
+
def set_input_embeddings(self, value):
|
| 400 |
+
self.embedding = value
|
| 401 |
+
|
| 402 |
+
def get_output_embeddings(self):
|
| 403 |
+
return self.lm_head
|
| 404 |
+
|
| 405 |
+
def set_output_embeddings(self, new_embedding):
|
| 406 |
+
self.lm_head = new_embedding
|
| 407 |
+
|
| 408 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None,
|
| 409 |
+
past_key_values=None, use_cache=None, inputs_embeds=None, **kwargs):
|
| 410 |
+
if inputs_embeds is None:
|
| 411 |
+
z = self.embedding(input_ids)
|
| 412 |
+
else:
|
| 413 |
+
z = inputs_embeds
|
| 414 |
+
|
| 415 |
+
for mixer in self.mixers:
|
| 416 |
+
if getattr(self, "gradient_checkpointing", False) and self.training:
|
| 417 |
+
z = checkpoint(mixer, z, attention_mask, use_reentrant=False)
|
| 418 |
+
else:
|
| 419 |
+
z = mixer(z, attention_mask=attention_mask)
|
| 420 |
+
|
| 421 |
+
z = self.ln_f(z)
|
| 422 |
+
logits = self.lm_head(z)
|
| 423 |
+
|
| 424 |
+
loss = None
|
| 425 |
+
if labels is not None:
|
| 426 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 427 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 428 |
+
loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
|
| 429 |
+
loss = loss_fct(
|
| 430 |
+
shift_logits.view(-1, shift_logits.size(-1)),
|
| 431 |
+
shift_labels.view(-1),
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
return CausalLMOutput(loss=loss, logits=logits)
|
| 435 |
+
|
| 436 |
+
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
|
| 437 |
+
attention_mask=None, **kwargs):
|
| 438 |
+
return {
|
| 439 |
+
"input_ids": input_ids,
|
| 440 |
+
"attention_mask": attention_mask,
|
| 441 |
+
"use_cache": False,
|
| 442 |
+
}
|
| 443 |
+
|
| 444 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 445 |
+
return past_key_values
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# ββ Register with AutoClasses ββββββββββββββββββββββββββββββββββββββββ
|
| 449 |
+
AutoConfig.register("hybrid_fourier_lm", HybridFourierConfig)
|
| 450 |
+
AutoModelForCausalLM.register(HybridFourierConfig, HybridFourierLM)
|