Text Generation
Transformers
Safetensors
GGUF
English
kail
kaila
decoder-only
causal-lm
gqa
rope
language-model
conversational
custom_code
Instructions to use Kaniskten/Kail_F2 with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Kaniskten/Kail_F2 with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="Kaniskten/Kail_F2", trust_remote_code=True) messages = [ {"role": "user", "content": "Who are you?"}, ] pipe(messages)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("Kaniskten/Kail_F2", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use Kaniskten/Kail_F2 with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf Kaniskten/Kail_F2:Q4_K_M # Run inference directly in the terminal: llama cli -hf Kaniskten/Kail_F2:Q4_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf Kaniskten/Kail_F2:Q4_K_M # Run inference directly in the terminal: llama cli -hf Kaniskten/Kail_F2:Q4_K_M
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf Kaniskten/Kail_F2:Q4_K_M # Run inference directly in the terminal: ./build/bin/llama cli -hf Kaniskten/Kail_F2:Q4_K_M
Use Docker
docker model run hf.co/Kaniskten/Kail_F2:Q4_K_M
- Llama new
- LM Studio
- Jan
- vLLM
How to use Kaniskten/Kail_F2 with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "Kaniskten/Kail_F2" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "Kaniskten/Kail_F2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/Kaniskten/Kail_F2:Q4_K_M
- SGLang
How to use Kaniskten/Kail_F2 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 "Kaniskten/Kail_F2" \ --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": "Kaniskten/Kail_F2", "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 "Kaniskten/Kail_F2" \ --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": "Kaniskten/Kail_F2", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }' - Ollama
How to use Kaniskten/Kail_F2 with Ollama:
ollama run hf.co/Kaniskten/Kail_F2:Q4_K_M
- Unsloth Desktop
- Pi
How to use Kaniskten/Kail_F2 with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf Kaniskten/Kail_F2:Q4_K_M
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "Kaniskten/Kail_F2:Q4_K_M" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use Kaniskten/Kail_F2 with Docker Model Runner:
docker model run hf.co/Kaniskten/Kail_F2:Q4_K_M
- Lemonade
How to use Kaniskten/Kail_F2 with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull Kaniskten/Kail_F2:Q4_K_M
Run and chat with the model
lemonade run user.Kail_F2-Q4_K_M
List all available models
lemonade list
- Hermes Agent
How to use Kaniskten/Kail_F2 with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf Kaniskten/Kail_F2:Q4_K_M
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:9931/v1 hermes config set model.default Kaniskten/Kail_F2:Q4_K_M
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use Kaniskten/Kail_F2 with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf Kaniskten/Kail_F2:Q4_K_M
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:9931/v1 \ --custom-model-id "Kaniskten/Kail_F2:Q4_K_M" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Download modeling_kail.py from Kaniskten/Kail_F2: direct link, hf CLI and curl.
- Browser
- Download file 50.4 kB
-
https://huggingface.co/Kaniskten/Kail_F2/resolve/main/modeling_kail.py
- Command line
-
hf download hf://Kaniskten/Kail_F2/modeling_kail.py
-
curl -L -o modeling_kail.py https://huggingface.co/Kaniskten/Kail_F2/resolve/main/modeling_kail.py
50.4 kB
"""KailA causal language model.
KailA is a decoder-only transformer architecture from Kaniskten
Programming. This module provides the reference implementation packaged
with the released model and is loaded through ``trust_remote_code=True``.
"""
from __future__ import annotations
import logging
import math
from typing import Any, Callable, Dict, List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers import PreTrainedModel
from .configuration_kail import KailAConfig
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Initialization utilities
# ---------------------------------------------------------------------------
def _init_weights(
module: nn.Module,
std: float = 0.02,
mean: float = 0.0,
) -> None:
"""Initialize linear and embedding weights with a normal distribution."""
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, mean=mean, std=std)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=mean, std=std)
def apply_init(model: nn.Module, std: float = 0.02) -> None:
"""Apply weight initialization to every sub-module in *model*."""
model.apply(lambda m: _init_weights(m, std=std))
def reshape_for_scores(x: Tensor, seq_len: int, num_heads: int) -> Tensor:
"""Reshape a projection output ``(B, S, N * D)`` to ``(B, N, S, D)``."""
batch_size, _, _ = x.shape
x = x.view(batch_size, seq_len, num_heads, -1)
return x.transpose(1, 2)
def create_causal_mask(
seq_len: int,
device: Optional[torch.device] = None,
dtype: torch.dtype = torch.float32,
) -> Tensor:
"""Create an upper-triangular causal mask ``(seq_len, seq_len)``."""
return torch.triu(
torch.ones(seq_len, seq_len, device=device, dtype=torch.bool),
diagonal=1,
)
# ---------------------------------------------------------------------------
# Rotary Position Embeddings
# ---------------------------------------------------------------------------
class KailARotaryEmbedding(nn.Module):
"""Rotary Position Embedding (RoPE) module.
Pre-computes cosine and sine tables and applies the rotary transform
to query and key tensors.
"""
def __init__(
self,
dim: int,
max_position_embeddings: int = 8192,
theta: float = 10000.0,
scaling: Optional[Dict[str, Any]] = None,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.theta = theta
self.scaling = scaling
inv_freq = self._compute_inv_freqs(
dim=dim, theta=theta, scaling=scaling, device=device
)
self.register_buffer("inv_freq", inv_freq, persistent=False)
t = torch.arange(
max_position_embeddings, device=device, dtype=torch.float32
)
if scaling is not None and scaling.get("rope_type") == "linear":
t = t / scaling["factor"]
freqs = torch.outer(t, inv_freq)
emb = torch.cat((freqs, freqs), dim=-1) # (max_seq_len, dim)
self.register_buffer("cos_cached", emb.cos().to(dtype=dtype), persistent=False)
self.register_buffer("sin_cached", emb.sin().to(dtype=dtype), persistent=False)
self._tables_ok = not bool(getattr(self.cos_cached, "is_meta", False))
@staticmethod
def _compute_inv_freqs(
dim: int,
theta: float,
scaling: Optional[Dict[str, Any]],
device: Optional[torch.device],
) -> Tensor:
"""Compute the inverse frequency vector for RoPE."""
base_inv_freq = 1.0 / (
theta ** (torch.arange(0, dim, 2, device=device).float() / dim)
)
scaling_type = None
if scaling is not None:
scaling_type = scaling.get("rope_type")
if scaling_type is None and "factor" in scaling:
scaling_type = "linear"
if scaling is not None and scaling_type == "llama3":
factor = float(scaling.get("factor", 1.0))
low_freq_factor = float(scaling.get("low_freq_factor", 1.0))
high_freq_factor = float(scaling.get("high_freq_factor", 1.0))
orig_max = float(scaling.get("original_max_position_embeddings", 8192))
low_wavelen = orig_max / low_freq_factor
high_wavelen = orig_max / high_freq_factor
wavelen = 2.0 * math.pi / base_inv_freq
smooth = (low_wavelen - wavelen) / (low_wavelen - high_wavelen)
smooth = smooth.clamp(min=0.0, max=1.0)
new_freq = (1.0 - smooth) * (base_inv_freq / factor) + smooth * base_inv_freq
return new_freq
return base_inv_freq
def _build_tables(self, device: torch.device, dtype: torch.dtype):
"""Compute fresh cosine/sine tables on *device* at *dtype*."""
inv_freq = self._compute_inv_freqs(
dim=self.dim, theta=self.theta, scaling=self.scaling, device=device
)
t = torch.arange(self.max_position_embeddings, device=device, dtype=torch.float32)
if self.scaling is not None and self.scaling.get("rope_type") == "linear":
t = t / self.scaling["factor"]
freqs = torch.outer(t, inv_freq)
emb = torch.cat((freqs, freqs), dim=-1)
return emb.cos().to(dtype=dtype), emb.sin().to(dtype=dtype)
def _get_tables(self, device: torch.device, dtype: torch.dtype):
"""Return the cached tables, rebuilding them when necessary.
The tables are non-persistent buffers. When a model is loaded with
``from_pretrained`` on the meta device (the default behavior under
``device_map``), they are not materialized and can end up as zeroed
tensors; this rebuilds them on the active device whenever they are
missing, still on the meta device, or corrupted (a valid table must
have ``cos(0) == 1``).
"""
cos = getattr(self, "cos_cached", None)
sin = getattr(self, "sin_cached", None)
valid = (
bool(getattr(self, "_tables_ok", False))
and cos is not None
and sin is not None
and not bool(getattr(cos, "is_meta", False))
and not bool(getattr(sin, "is_meta", False))
and cos.device == device
)
if not valid:
cos, sin = self._build_tables(device, dtype)
self.register_buffer("cos_cached", cos, persistent=False)
self.register_buffer("sin_cached", sin, persistent=False)
self._tables_ok = True
return cos, sin
def forward(
self,
q: Tensor,
k: Tensor,
position_ids: Tensor,
) -> tuple[Tensor, Tensor]:
"""Apply rotary embeddings to queries and keys."""
cos, sin = self._get_tables(q.device, q.dtype)
if position_ids is None:
position_ids = torch.arange(
q.size(2), dtype=torch.long, device=q.device
).unsqueeze(0)
if position_ids.dim() == 1:
position_ids = position_ids.unsqueeze(0)
cos = cos[position_ids].to(dtype=q.dtype).unsqueeze(1) # (B, 1, S, D)
sin = sin[position_ids].to(dtype=q.dtype).unsqueeze(1)
q_out = q * cos + self._rotate_half(q) * sin
k_out = k * cos + self._rotate_half(k) * sin
return q_out, k_out
@staticmethod
def _rotate_half(x: Tensor) -> Tensor:
"""Rotate half of the hidden dimension (RoPE rotation matrix)."""
x1 = x[..., : x.shape[-1] // 2]
x2 = x[..., x.shape[-1] // 2 :]
return torch.cat((-x2, x1), dim=-1)
def extra_repr(self) -> str:
return (
f"dim={self.dim}, max_seq_len={self.max_position_embeddings}, "
f"theta={self.theta}"
)
# ---------------------------------------------------------------------------
# Normalization
# ---------------------------------------------------------------------------
class KailARMSNorm(nn.Module):
"""Root Mean Square Layer Normalization."""
def __init__(
self,
hidden_size: int,
eps: float = 1e-6,
bias: bool = False,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size, dtype=dtype, device=device))
self.bias = nn.Parameter(torch.zeros(hidden_size, dtype=dtype, device=device)) if bias else None
self.eps = eps
def forward(self, x: Tensor) -> Tensor:
variance = x.pow(2).mean(-1, keepdim=True)
x_norm = x * torch.rsqrt(variance + self.eps)
out = x_norm * self.weight
if self.bias is not None:
out = out + self.bias
return out
class KailALayerNorm(nn.Module):
"""Standard Layer Normalization."""
def __init__(
self,
hidden_size: int,
eps: float = 1e-6,
bias: bool = True,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.weight = nn.Parameter(torch.ones(hidden_size, dtype=dtype, device=device))
self.bias = nn.Parameter(torch.zeros(hidden_size, dtype=dtype, device=device)) if bias else None
self.eps = eps
def forward(self, x: Tensor) -> Tensor:
mean = x.mean(-1, keepdim=True)
variance = x.var(-1, keepdim=True, unbiased=False)
x_norm = (x - mean) * torch.rsqrt(variance + self.eps)
out = x_norm * self.weight
if self.bias is not None:
out = out + self.bias
return out
def build_norm(
normalization: str,
hidden_size: int,
eps: float = 1e-6,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> nn.Module:
"""Build a normalization layer by name."""
if normalization == "rms_norm":
return KailARMSNorm(hidden_size, eps=eps, dtype=dtype, device=device)
elif normalization == "layer_norm":
return KailALayerNorm(hidden_size, eps=eps, dtype=dtype, device=device)
raise ValueError(
f"Unsupported normalization '{normalization}'. "
f"Supported: rms_norm, layer_norm."
)
# ---------------------------------------------------------------------------
# Base attention
# ---------------------------------------------------------------------------
class KailAAttention(nn.Module):
"""Grouped-query attention with optional RoPE and KV caching."""
def __init__(
self,
hidden_size: int,
num_attention_heads: int,
num_key_value_heads: int,
head_dim: Optional[int] = None,
max_position_embeddings: int = 8192,
rope_theta: float = 10000.0,
rope_scaling: Optional[dict] = None,
attention_dropout: float = 0.0,
hidden_dropout: float = 0.0,
use_cache: bool = True,
use_sdpa: bool = True,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.hidden_size = hidden_size
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.num_key_value_groups = num_attention_heads // num_key_value_heads
self.head_dim = head_dim or (hidden_size // num_attention_heads)
self.use_cache = use_cache
self.use_sdpa = use_sdpa and hasattr(F, "scaled_dot_product_attention")
self.attention_dropout = attention_dropout
self.hidden_dropout = hidden_dropout
self.q_proj = nn.Linear(
hidden_size,
num_attention_heads * self.head_dim,
bias=False,
dtype=dtype,
device=device,
)
self.k_proj = nn.Linear(
hidden_size,
num_key_value_heads * self.head_dim,
bias=False,
dtype=dtype,
device=device,
)
self.v_proj = nn.Linear(
hidden_size,
num_key_value_heads * self.head_dim,
bias=False,
dtype=dtype,
device=device,
)
self.o_proj = nn.Linear(
num_attention_heads * self.head_dim,
hidden_size,
bias=False,
dtype=dtype,
device=device,
)
self.rotary_emb = KailARotaryEmbedding(
dim=self.head_dim,
max_position_embeddings=max_position_embeddings,
theta=rope_theta,
scaling=rope_scaling,
dtype=dtype,
device=device,
)
def forward(
self,
hidden_states: Tensor,
attention_mask: Optional[Tensor] = None,
position_ids: Optional[Tensor] = None,
past_key_value: Optional[Tuple[Tensor, Tensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: bool = False,
) -> Tuple[Tensor, Optional[Tensor], Optional[Tuple[Tensor, Tensor]]]:
use_cache = use_cache if use_cache is not None else self.use_cache
batch_size, seq_len, _ = hidden_states.shape
q = self.q_proj(hidden_states)
k = self.k_proj(hidden_states)
v = self.v_proj(hidden_states)
q = reshape_for_scores(q, seq_len, self.num_attention_heads)
k = reshape_for_scores(k, seq_len, self.num_key_value_heads)
v = reshape_for_scores(v, seq_len, self.num_key_value_heads)
q, k = self.rotary_emb(q, k, position_ids)
if past_key_value is not None:
k = torch.cat([past_key_value[0], k], dim=2)
v = torch.cat([past_key_value[1], v], dim=2)
past_key_value_out = (k, v) if use_cache else None
if self.num_key_value_groups > 1:
k = k.repeat_interleave(self.num_key_value_groups, dim=1)
v = v.repeat_interleave(self.num_key_value_groups, dim=1)
if self.use_sdpa:
is_causal = attention_mask is None and k.shape[2] == q.shape[2]
attn_output = F.scaled_dot_product_attention(
q,
k,
v,
attn_mask=attention_mask,
dropout_p=self.attention_dropout if self.training else 0.0,
is_causal=is_causal,
)
else:
scale = 1.0 / math.sqrt(self.head_dim)
attn_weights = torch.matmul(q, k.transpose(2, 3)) * scale
if attention_mask is not None:
attn_weights = attn_weights + attention_mask
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(
q.dtype
)
attn_weights = F.dropout(
attn_weights, p=self.attention_dropout, training=self.training
)
attn_output = torch.matmul(attn_weights, v)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(batch_size, seq_len, -1)
attn_output = self.o_proj(attn_output)
attn_output = F.dropout(
attn_output, p=self.hidden_dropout, training=self.training
)
return attn_output, attn_weights if output_attentions else None, past_key_value_out
def extra_repr(self) -> str:
return (
f"num_heads={self.num_attention_heads}, "
f"num_kv_heads={self.num_key_value_heads}, "
f"head_dim={self.head_dim}"
)
# ---------------------------------------------------------------------------
# KailA-specific controllers
# ---------------------------------------------------------------------------
class KailAttentionController(nn.Module):
"""Context-aware attention scaling controller.
Produces a per-head, per-position scale factor that modulates
attention logits:
hidden_states -> Linear(D, D/r) -> SiLU -> Linear(D/r, num_heads)
-> Sigmoid * 2
The output layer is zero-initialized so the scale starts at ~1.0.
"""
def __init__(
self,
hidden_size: int,
num_heads: int,
reduction: int = 4,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
inner_dim = max(hidden_size // reduction, 32)
self.gate = nn.Sequential(
nn.Linear(hidden_size, inner_dim, dtype=dtype, device=device),
nn.SiLU(),
nn.Linear(inner_dim, num_heads, dtype=dtype, device=device),
)
self._zero_init_output()
def _zero_init_output(self) -> None:
"""Zero-initialize the output layer so the initial scale ~= 1.0."""
nn.init.zeros_(self.gate[-1].weight)
if self.gate[-1].bias is not None:
nn.init.zeros_(self.gate[-1].bias)
def forward(self, hidden_states: Tensor) -> Tensor:
scale = self.gate(hidden_states)
scale = torch.sigmoid(scale) * 2.0
return scale.unsqueeze(2)
class KailFeatureRouter(nn.Module):
"""Feature-space router for the gated feed-forward network.
Produces element-wise modulation weights applied to the gate output:
hidden_states -> Linear(D, D/r) -> SiLU -> Linear(D/r, intermediate)
-> Sigmoid * 2
The output layer is zero-initialized so the initial modulation is ~1.0.
"""
def __init__(
self,
hidden_size: int,
intermediate_size: int,
reduction: int = 8,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
inner_dim = max(hidden_size // reduction, 32)
self.router = nn.Sequential(
nn.Linear(hidden_size, inner_dim, dtype=dtype, device=device),
nn.SiLU(),
nn.Linear(inner_dim, intermediate_size, dtype=dtype, device=device),
)
self._zero_init_output()
def _zero_init_output(self) -> None:
"""Zero-initialize the output layer so the initial modulation ~= 1.0."""
nn.init.zeros_(self.router[-1].weight)
if self.router[-1].bias is not None:
nn.init.zeros_(self.router[-1].bias)
def forward(self, hidden_states: Tensor) -> Tensor:
weights = self.router(hidden_states)
weights = torch.sigmoid(weights) * 2.0
return weights
# ---------------------------------------------------------------------------
# KailAttention
# ---------------------------------------------------------------------------
class KailAttention(nn.Module):
"""Grouped-query attention extended with a dynamic scaling controller."""
def __init__(
self,
hidden_size: int,
num_attention_heads: int,
num_key_value_heads: int,
head_dim: Optional[int] = None,
max_position_embeddings: int = 8192,
rope_theta: float = 10000.0,
rope_scaling: Optional[dict] = None,
attention_dropout: float = 0.0,
hidden_dropout: float = 0.0,
use_cache: bool = True,
use_sdpa: bool = True,
controller_reduction: int = 4,
track_stats: bool = False,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.hidden_size = hidden_size
self.num_attention_heads = num_attention_heads
self.num_key_value_heads = num_key_value_heads
self.num_key_value_groups = num_attention_heads // num_key_value_heads
self.head_dim = head_dim or (hidden_size // num_attention_heads)
self.use_cache = use_cache
self.attention_dropout = attention_dropout
self.hidden_dropout = hidden_dropout
self.track_stats = track_stats
self._base_attn = KailAAttention(
hidden_size=hidden_size,
num_attention_heads=num_attention_heads,
num_key_value_heads=num_key_value_heads,
head_dim=head_dim,
max_position_embeddings=max_position_embeddings,
rope_theta=rope_theta,
rope_scaling=rope_scaling,
attention_dropout=attention_dropout,
hidden_dropout=hidden_dropout,
use_cache=use_cache,
use_sdpa=use_sdpa,
dtype=dtype,
device=device,
)
self.controller = KailAttentionController(
hidden_size=hidden_size,
num_heads=num_attention_heads,
reduction=controller_reduction,
dtype=dtype,
device=device,
)
# Learnable per-head temperature (inverse softmax temperature).
self.attn_temperature = nn.Parameter(
torch.ones(num_attention_heads, dtype=dtype, device=device)
)
if track_stats:
self.register_buffer("_entropy_buffer", torch.zeros(1), persistent=False)
self.register_buffer("_max_prob_buffer", torch.zeros(1), persistent=False)
def forward(
self,
hidden_states: Tensor,
attention_mask: Optional[Tensor] = None,
position_ids: Optional[Tensor] = None,
past_key_value: Optional[Tuple[Tensor, Tensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: bool = False,
) -> Tuple[Tensor, Optional[Tensor], Optional[Tuple[Tensor, Tensor]]]:
use_cache = use_cache if use_cache is not None else self.use_cache
batch_size, seq_len, _ = hidden_states.shape
q = self._base_attn.q_proj(hidden_states)
k = self._base_attn.k_proj(hidden_states)
v = self._base_attn.v_proj(hidden_states)
q = reshape_for_scores(q, seq_len, self.num_attention_heads)
k = reshape_for_scores(k, seq_len, self.num_key_value_heads)
v = reshape_for_scores(v, seq_len, self.num_key_value_heads)
q, k = self._base_attn.rotary_emb(q, k, position_ids)
if past_key_value is not None:
k = torch.cat([past_key_value[0], k], dim=2)
v = torch.cat([past_key_value[1], v], dim=2)
past_key_value_out = (k, v) if use_cache else None
if self.num_key_value_groups > 1:
k = k.repeat_interleave(self.num_key_value_groups, dim=1)
v = v.repeat_interleave(self.num_key_value_groups, dim=1)
# Kail-specific: per-head, per-position attention scaling.
attn_scale = self.controller(hidden_states) # (B, S, 1, H)
temp = self.attn_temperature.view(1, 1, 1, -1) # (1, 1, 1, H)
scale = 1.0 / math.sqrt(self.head_dim)
attn_weights = torch.matmul(q, k.transpose(2, 3)) * scale
ctrl_scale = attn_scale.transpose(1, 3) # (B, H, 1, S)
ctrl_scale = ctrl_scale.squeeze(2) # (B, H, S)
attn_weights = attn_weights * ctrl_scale.unsqueeze(-1) * temp.view(1, -1, 1, 1)
if attention_mask is not None:
attn_weights = attn_weights + attention_mask
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
if self.track_stats:
self._update_stats(attn_weights)
attn_weights = F.dropout(
attn_weights, p=self.attention_dropout, training=self.training
)
attn_output = torch.matmul(attn_weights, v)
attn_output = attn_output.transpose(1, 2).contiguous()
attn_output = attn_output.reshape(batch_size, seq_len, -1)
attn_output = self._base_attn.o_proj(attn_output)
attn_output = F.dropout(
attn_output, p=self.hidden_dropout, training=self.training
)
return attn_output, attn_weights if output_attentions else None, past_key_value_out
@torch.no_grad()
def _update_stats(self, attn_weights: Tensor) -> None:
probs = attn_weights.float()
entropy = -(probs * torch.log(probs.clamp(min=1e-10))).sum(-1).mean()
max_prob = probs.max(-1).values.mean()
self._entropy_buffer[0] = entropy.item()
self._max_prob_buffer[0] = max_prob.item()
def get_attention_stats(self) -> Dict[str, float]:
if not self.track_stats:
return {}
return {
"attention_entropy": self._entropy_buffer.item(),
"attention_max_prob": self._max_prob_buffer.item(),
}
def extra_repr(self) -> str:
return (
f"num_heads={self.num_attention_heads}, "
f"num_kv_heads={self.num_key_value_heads}, "
f"head_dim={self.head_dim}"
)
# ---------------------------------------------------------------------------
# Adaptive feed-forward network
# ---------------------------------------------------------------------------
class KailAdaptiveFFN(nn.Module):
"""Adaptive gated feed-forward network with feature routing."""
def __init__(
self,
hidden_size: int,
intermediate_size: int,
activation: str = "silu",
dropout: float = 0.0,
router_reduction: int = 8,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.hidden_size = hidden_size
self.intermediate_size = intermediate_size
self.gate_proj = nn.Linear(
hidden_size, intermediate_size, bias=False, dtype=dtype, device=device
)
self.up_proj = nn.Linear(
hidden_size, intermediate_size, bias=False, dtype=dtype, device=device
)
self.down_proj = nn.Linear(
intermediate_size, hidden_size, bias=False, dtype=dtype, device=device
)
self.act_fn = self._get_activation_fn(activation)
self.dropout = nn.Dropout(dropout)
self.feature_router = KailFeatureRouter(
hidden_size=hidden_size,
intermediate_size=intermediate_size,
reduction=router_reduction,
dtype=dtype,
device=device,
)
@staticmethod
def _get_activation_fn(activation: str):
activations = {
"silu": nn.SiLU(),
"gelu": nn.GELU(approximate="none"),
"relu": nn.ReLU(),
}
if activation not in activations:
raise ValueError(f"Unsupported activation: {activation}")
return activations[activation]
def forward(self, x: Tensor) -> Tensor:
gate = self.act_fn(self.gate_proj(x)) # (B, S, intermediate)
up = self.up_proj(x) # (B, S, intermediate)
router_weights = self.feature_router(x) # (B, S, intermediate)
gate = gate * router_weights
hidden = gate * up
hidden = self.dropout(hidden)
output = self.down_proj(hidden)
return output
def extra_repr(self) -> str:
return (
f"hidden_size={self.hidden_size}, "
f"intermediate_size={self.intermediate_size}"
)
# ---------------------------------------------------------------------------
# Embedding & LM head
# ---------------------------------------------------------------------------
class KailEmbedding(nn.Module):
"""Token embedding for the KailA architecture."""
def __init__(
self,
vocab_size: int,
hidden_size: int,
padding_idx: Optional[int] = 0,
std: float = 0.02,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.vocab_size = vocab_size
self.hidden_size = hidden_size
self.padding_idx = padding_idx
self.std = std
self.weight = nn.Parameter(
torch.empty(vocab_size, hidden_size, dtype=dtype, device=device)
)
nn.init.normal_(self.weight, mean=0.0, std=std)
if self.padding_idx is not None:
with torch.no_grad():
self.weight[self.padding_idx].zero_()
def forward(self, input_ids: Tensor) -> Tensor:
return F.embedding(
input_ids,
self.weight,
padding_idx=self.padding_idx,
)
def extra_repr(self) -> str:
return (
f"vocab_size={self.vocab_size}, hidden_size={self.hidden_size}, "
f"padding_idx={self.padding_idx}"
)
class KailLMHead(nn.Module):
"""Language modeling head for the KailA architecture."""
def __init__(
self,
hidden_size: int,
vocab_size: int,
bias: bool = False,
std: float = 0.02,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.std = std
self.weight = nn.Parameter(
torch.empty(vocab_size, hidden_size, dtype=dtype, device=device)
)
nn.init.normal_(self.weight, mean=0.0, std=std)
if bias:
self.bias = nn.Parameter(torch.zeros(vocab_size, dtype=dtype, device=device))
else:
self.register_parameter("bias", None)
def forward(self, hidden_states: Tensor) -> Tensor:
return F.linear(hidden_states, self.weight, self.bias)
def extra_repr(self) -> str:
return (
f"vocab_size={self.weight.shape[0]}, "
f"hidden_size={self.weight.shape[1]}, bias={self.bias is not None}"
)
# ---------------------------------------------------------------------------
# Decoder block
# ---------------------------------------------------------------------------
class KailABlock(nn.Module):
"""One KailA decoder block with attention controller and feature router."""
def __init__(
self,
config,
dtype=None,
device=None,
layer_idx: Optional[int] = None,
) -> None:
super().__init__()
self.hidden_size = config.hidden_size
self._use_checkpointing = config.gradient_checkpointing
self.layer_idx = layer_idx
self.input_layernorm = build_norm(
config.normalization,
config.hidden_size,
eps=config.norm_eps,
dtype=dtype,
device=device,
)
self.self_attn = KailAttention(
hidden_size=config.hidden_size,
num_attention_heads=config.num_attention_heads,
num_key_value_heads=config.num_key_value_heads,
head_dim=config.head_dim,
max_position_embeddings=config.max_position_embeddings,
rope_theta=config.rope_theta,
rope_scaling=config.rope_scaling,
attention_dropout=config.attention_dropout,
hidden_dropout=config.hidden_dropout,
use_cache=config.use_cache,
use_sdpa=config.use_sdpa,
controller_reduction=config.controller_reduction,
track_stats=getattr(config, "track_attention_stats", False),
dtype=dtype,
device=device,
)
self.post_attention_layernorm = build_norm(
config.normalization,
config.hidden_size,
eps=config.norm_eps,
dtype=dtype,
device=device,
)
self.mlp = KailAdaptiveFFN(
hidden_size=config.hidden_size,
intermediate_size=config.intermediate_size,
activation=config.activation,
dropout=config.dropout,
router_reduction=getattr(config, "router_reduction", 8),
dtype=dtype,
device=device,
)
self.dropout = config.hidden_dropout
def forward(
self,
hidden_states: Tensor,
attention_mask: Optional[Tensor] = None,
position_ids: Optional[Tensor] = None,
past_key_value: Optional[Tuple[Tensor, Tensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: bool = False,
) -> Tuple[Tensor, Optional[Tensor], Optional[Tuple[Tensor, Tensor]]]:
if self._use_checkpointing and self.training:
return self._checkpointed_forward(
hidden_states, attention_mask, position_ids, past_key_value, use_cache
)
return self._standard_forward(
hidden_states, attention_mask, position_ids,
past_key_value, use_cache, output_attentions,
)
def _checkpointed_forward(
self,
hidden_states: Tensor,
attention_mask: Optional[Tensor] = None,
position_ids: Optional[Tensor] = None,
past_key_value: Optional[Tuple[Tensor, Tensor]] = None,
use_cache: Optional[bool] = None,
) -> Tuple[Tensor, Optional[Tensor], Optional[Tuple[Tensor, Tensor]]]:
fn_args = [hidden_states]
if attention_mask is not None:
fn_args.append(attention_mask)
if position_ids is not None:
fn_args.append(position_ids)
def _fn(*args: Tensor) -> Tuple[Tensor, Tensor]:
_h = args[0]
_mask: Optional[Tensor] = None
_pos: Optional[Tensor] = None
idx = 1
if attention_mask is not None:
_mask = args[idx]
idx += 1
if position_ids is not None:
_pos = args[idx]
idx += 1
out, _, _ = self._core_compute(_h, _mask, _pos, None, None, False)
return out, torch.zeros(1, device=_h.device)
hidden_states, _ = torch.utils.checkpoint.checkpoint(
_fn, *fn_args, use_reentrant=False
)
return hidden_states, None, past_key_value
def _core_compute(
self,
hidden_states: Tensor,
attention_mask: Optional[Tensor] = None,
position_ids: Optional[Tensor] = None,
past_key_value: Optional[Tuple[Tensor, Tensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: bool = False,
) -> Tuple[Tensor, Optional[Tensor], Optional[Tuple[Tensor, Tensor]]]:
residual = hidden_states
hidden_states = self.input_layernorm(hidden_states)
hidden_states, attn_weights, past_key_value = self.self_attn(
hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=past_key_value,
use_cache=use_cache,
output_attentions=output_attentions,
)
hidden_states = residual + hidden_states
if self.dropout > 0.0 and self.training:
hidden_states = F.dropout(hidden_states, p=self.dropout, training=True)
residual = hidden_states
hidden_states = self.post_attention_layernorm(hidden_states)
hidden_states = self.mlp(hidden_states)
hidden_states = residual + hidden_states
if self.dropout > 0.0 and self.training:
hidden_states = F.dropout(hidden_states, p=self.dropout, training=True)
return hidden_states, attn_weights, past_key_value
def _standard_forward(
self,
hidden_states: Tensor,
attention_mask: Optional[Tensor] = None,
position_ids: Optional[Tensor] = None,
past_key_value: Optional[Tuple[Tensor, Tensor]] = None,
use_cache: Optional[bool] = None,
output_attentions: bool = False,
) -> Tuple[Tensor, Optional[Tensor], Optional[Tuple[Tensor, Tensor]]]:
return self._core_compute(
hidden_states, attention_mask, position_ids,
past_key_value, use_cache, output_attentions,
)
# ---------------------------------------------------------------------------
# Model
# ---------------------------------------------------------------------------
class KailAModel(nn.Module):
"""KailA decoder-only transformer backbone."""
def __init__(self, config, dtype=None, device=None) -> None:
super().__init__()
self.config = config
self.padding_idx = getattr(config, "pad_token_id", 0)
self.embed_tokens = KailEmbedding(
vocab_size=config.vocab_size,
hidden_size=config.hidden_size,
padding_idx=self.padding_idx,
dtype=dtype,
device=device,
)
self.layers = nn.ModuleList(
[
KailABlock(config, dtype=dtype, device=device, layer_idx=idx)
for idx in range(config.num_layers)
]
)
self.norm = build_norm(
config.normalization,
config.hidden_size,
eps=config.norm_eps,
dtype=dtype,
device=device,
)
self.post_init()
def post_init(self) -> None:
apply_init(self, std=self.config.initializer_range)
def get_input_embeddings(self) -> nn.Module:
return self.embed_tokens
def set_input_embeddings(self, value: nn.Module) -> None:
self.embed_tokens = value
def gradient_checkpointing_enable(self) -> None:
self.config.gradient_checkpointing = True
for layer in self.layers:
layer._use_checkpointing = True
def gradient_checkpointing_disable(self) -> None:
self.config.gradient_checkpointing = False
for layer in self.layers:
layer._use_checkpointing = False
def forward(
self,
input_ids: Optional[Tensor] = None,
attention_mask: Optional[Tensor] = None,
position_ids: Optional[Tensor] = None,
past_key_values: Optional[List[Tuple[Tensor, Tensor]]] = None,
use_cache: Optional[bool] = None,
output_attentions: bool = False,
output_hidden_states: bool = False,
return_dict: bool = True,
**kwargs,
) -> Any:
if return_dict is None:
return_dict = True
batch_size, seq_len = input_ids.shape
if position_ids is None:
if (
past_key_values is not None
and len(past_key_values) > 0
and past_key_values[0] is not None
):
past_len = past_key_values[0][0].shape[2]
else:
past_len = 0
position_ids = (
torch.arange(past_len, past_len + seq_len, device=input_ids.device)
.unsqueeze(0)
.expand(batch_size, -1)
)
hidden_states = self.embed_tokens(input_ids)
if attention_mask is not None:
if attention_mask.dim() == 2:
total_len = attention_mask.shape[1]
if (
past_key_values is not None
and len(past_key_values) > 0
and past_key_values[0] is not None
):
total_len += past_key_values[0][0].shape[2]
causal_mask = create_causal_mask(
seq_len, device=input_ids.device, dtype=hidden_states.dtype
)
pad_mask = attention_mask[:, None, None, :].to(dtype=hidden_states.dtype)
pad_mask = (1.0 - pad_mask) * torch.finfo(hidden_states.dtype).min
attention_mask = causal_mask[:, :total_len].unsqueeze(0).unsqueeze(0)
attention_mask = attention_mask.to(dtype=hidden_states.dtype)
attention_mask = attention_mask * torch.finfo(hidden_states.dtype).min
attention_mask = attention_mask + pad_mask
elif attention_mask.dim() != 4:
raise ValueError(f"Expected 2D or 4D mask, got {attention_mask.dim()}D")
all_hidden_states = [] if output_hidden_states else None
all_attentions = [] if output_attentions else None
new_past_key_values = [] if use_cache else None
for i, layer in enumerate(self.layers):
if output_hidden_states:
all_hidden_states.append(hidden_states)
layer_past = past_key_values[i] if past_key_values is not None else None
hidden_states, attn_weights, new_kv = layer(
hidden_states,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_value=layer_past,
use_cache=use_cache,
output_attentions=output_attentions,
)
if use_cache:
new_past_key_values.append(new_kv)
if output_attentions:
all_attentions.append(attn_weights)
hidden_states = self.norm(hidden_states)
if output_hidden_states:
all_hidden_states.append(hidden_states)
if return_dict:
from transformers.modeling_outputs import BaseModelOutputWithPast
return BaseModelOutputWithPast(
last_hidden_state=hidden_states,
past_key_values=new_past_key_values if use_cache else past_key_values,
hidden_states=all_hidden_states,
attentions=all_attentions,
)
else:
return (
hidden_states,
new_past_key_values if use_cache else past_key_values,
all_hidden_states,
all_attentions,
)
class KailAForCausalLM(PreTrainedModel):
"""KailA model with a language modeling head for causal language modeling."""
config_class = KailAConfig
base_model_prefix = "model"
main_input_name = "input_ids"
supports_gradient_checkpointing = True
_tied_weights_keys: List[str] = []
_no_split_modules = ["KailABlock"]
_keys_to_ignore_on_load_missing: List[str] = []
_keys_to_ignore_on_load_unexpected: List[str] = []
def __init__(self, config, dtype=None, device=None, **kwargs) -> None:
super().__init__(config)
self.model = KailAModel(config, dtype=dtype, device=device)
self.lm_head = KailLMHead(
hidden_size=config.hidden_size,
vocab_size=config.vocab_size,
bias=False,
dtype=dtype,
device=device,
)
if getattr(config, "tie_word_embeddings", False):
self.lm_head.weight = self.model.embed_tokens.weight
self.post_init()
def _init_weights(self, module: nn.Module) -> None:
_init_weights(module, std=self.config.initializer_range)
def get_input_embeddings(self) -> nn.Module:
return self.model.get_input_embeddings()
def set_input_embeddings(self, value: nn.Module) -> None:
self.model.set_input_embeddings(value)
def get_output_embeddings(self) -> nn.Module:
return self.lm_head
def set_output_embeddings(self, new_embeddings: nn.Module) -> None:
self.lm_head = new_embeddings
def gradient_checkpointing_enable(self) -> None:
self.model.gradient_checkpointing_enable()
def gradient_checkpointing_disable(self) -> None:
self.model.gradient_checkpointing_disable()
def prepare_inputs_for_generation(
self,
input_ids: Tensor,
past_key_values: Optional[List[Tuple[Tensor, Tensor]]] = None,
attention_mask: Optional[Tensor] = None,
**kwargs,
) -> Dict[str, Any]:
if past_key_values is not None and len(past_key_values) > 0:
input_ids = input_ids[:, -1:]
position_ids = None
if attention_mask is not None and past_key_values is not None:
position_ids = attention_mask.long().cumsum(-1) - 1
position_ids = position_ids[:, -1:] if past_key_values else position_ids
return {
"input_ids": input_ids,
"attention_mask": attention_mask,
"position_ids": position_ids,
"past_key_values": past_key_values,
"use_cache": True,
}
def forward(
self,
input_ids: Optional[Tensor] = None,
attention_mask: Optional[Tensor] = None,
position_ids: Optional[Tensor] = None,
past_key_values: Optional[List[Tuple[Tensor, Tensor]]] = None,
labels: Optional[Tensor] = None,
use_cache: Optional[bool] = None,
output_attentions: bool = False,
output_hidden_states: bool = False,
return_dict: bool = True,
**kwargs,
) -> Any:
if return_dict is None:
return_dict = True
outputs = self.model(
input_ids=input_ids,
attention_mask=attention_mask,
position_ids=position_ids,
past_key_values=past_key_values,
use_cache=use_cache,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = outputs[0] if not return_dict else outputs.last_hidden_state
logits = self.lm_head(hidden_states)
loss = None
if labels is not None:
shift_logits = logits[..., :-1, :].contiguous()
shift_labels = labels[..., 1:].contiguous()
loss = F.cross_entropy(
shift_logits.view(-1, self.config.vocab_size),
shift_labels.view(-1),
ignore_index=-100,
)
if return_dict:
from transformers.modeling_outputs import CausalLMOutputWithPast
return CausalLMOutputWithPast(
loss=loss,
logits=logits,
past_key_values=outputs.past_key_values,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
else:
return (loss, logits, outputs[1], outputs[2], outputs[3])
@torch.no_grad()
def generate(
self,
input_ids: Tensor,
max_new_tokens: int = 100,
temperature: float = 1.0,
do_sample: bool = True,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
repetition_penalty: float = 1.0,
eos_token_id: Optional[int] = None,
pad_token_id: Optional[int] = None,
**kwargs,
) -> Tensor:
"""Generate text autoregressively from a prompt.
Parameters
----------
input_ids : Tensor
Prompt token IDs ``(B, S)``.
max_new_tokens : int
Maximum number of tokens to generate.
temperature : float
Sampling temperature (``> 0``).
do_sample : bool
Greedy when ``False``, sample when ``True``.
top_k : int | None
Top-k filtering.
top_p : float | None
Nucleus (top-p) sampling.
repetition_penalty : float
Penalty for repeating tokens.
eos_token_id : int | None
End-of-sequence token; generation stops when it is produced.
pad_token_id : int | None
Padding token used to pad incomplete sequences.
Returns
-------
Tensor
Generated token IDs ``(B, S + max_new_tokens)``.
"""
if temperature <= 0.0:
raise ValueError("temperature must be > 0")
batch_size = input_ids.shape[0]
device = input_ids.device
eos_token_id = eos_token_id if eos_token_id is not None else -1
pad_token_id = pad_token_id if pad_token_id is not None else eos_token_id
attention_mask = torch.ones_like(input_ids, device=device)
past_key_values = None
generated = input_ids
for _ in range(max_new_tokens):
model_inputs = self.prepare_inputs_for_generation(
input_ids=generated,
past_key_values=past_key_values,
attention_mask=attention_mask,
)
outputs = self(
**model_inputs,
return_dict=True,
output_attentions=False,
output_hidden_states=False,
)
logits = outputs.logits[:, -1, :] # (B, V)
past_key_values = outputs.past_key_values
if temperature != 1.0:
logits = logits / temperature
if repetition_penalty != 1.0:
for i in range(batch_size):
for token_id in set(generated[i].tolist()):
logits[i, token_id] /= repetition_penalty
if do_sample:
next_token = _sample(logits, top_k=top_k, top_p=top_p)
else:
next_token = logits.argmax(dim=-1, keepdim=True)
generated = torch.cat([generated, next_token], dim=-1)
attention_mask = torch.cat(
[
attention_mask,
torch.ones((batch_size, 1), device=device),
],
dim=-1,
)
if (next_token == eos_token_id).any():
finished = (next_token == eos_token_id).squeeze(-1)
if bool(finished.all()):
break
return generated
def can_generate(self) -> bool:
return True
def _sample(
logits: Tensor,
top_k: Optional[int] = None,
top_p: Optional[float] = None,
filter_value: float = -float("Inf"),
) -> Tensor:
"""Sample a token from the logit distribution."""
if top_k is not None:
values, _ = torch.topk(logits, min(top_k, logits.size(-1)))
threshold = values[..., -1, None]
logits = torch.where(logits < threshold, filter_value, logits)
if top_p is not None:
sorted_logits, sorted_indices = torch.sort(logits, descending=True, dim=-1)
cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)
sorted_indices_to_remove = cumulative_probs > top_p
sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
sorted_indices_to_remove[..., 0] = 0
indices_to_remove = sorted_indices_to_remove.scatter(
-1, sorted_indices, sorted_indices_to_remove
)
logits = logits.masked_fill(indices_to_remove, filter_value)
probs = F.softmax(logits, dim=-1)
return torch.multinomial(probs, num_samples=1)
def _register_for_auto() -> None:
try:
from transformers import AutoModelForCausalLM
KailAConfig.register_for_auto()
AutoModelForCausalLM.register(KailAConfig, KailAForCausalLM, exist_ok=True)
except Exception: # noqa: BLE001
pass
_register_for_auto()
"""KailA causal language model.
KailA is a decoder-only transformer architecture from Kaniskten
Programming. This module provides the reference implementation packaged
with the released model and is loaded through ``trust_remote_code=True``.
"""
from __future__ import annotations
import logging
import math
from typing import Any, Callable, Dict, List, Optional, Tuple
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from transformers import PreTrainedModel
from .configuration_kail import KailAConfig
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Initialization utilities
# ---------------------------------------------------------------------------
def _init_weights(
module: nn.Module,
std: float = 0.02,
mean: float = 0.0,
) -> None:
"""Initialize linear and embedding weights with a normal distribution."""
if isinstance(module, nn.Linear):
nn.init.normal_(module.weight, mean=mean, std=std)
if module.bias is not None:
nn.init.zeros_(module.bias)
elif isinstance(module, nn.Embedding):
nn.init.normal_(module.weight, mean=mean, std=std)
def apply_init(model: nn.Module, std: float = 0.02) -> None:
"""Apply weight initialization to every sub-module in *model*."""
model.apply(lambda m: _init_weights(m, std=std))
def reshape_for_scores(x: Tensor, seq_len: int, num_heads: int) -> Tensor:
"""Reshape a projection output ``(B, S, N * D)`` to ``(B, N, S, D)``."""
batch_size, _, _ = x.shape
x = x.view(batch_size, seq_len, num_heads, -1)
return x.transpose(1, 2)
def create_causal_mask(
seq_len: int,
device: Optional[torch.device] = None,
dtype: torch.dtype = torch.float32,
) -> Tensor:
"""Create an upper-triangular causal mask ``(seq_len, seq_len)``."""
return torch.triu(
torch.ones(seq_len, seq_len, device=device, dtype=torch.bool),
diagonal=1,
)
# ---------------------------------------------------------------------------
# Rotary Position Embeddings
# ---------------------------------------------------------------------------
class KailARotaryEmbedding(nn.Module):
"""Rotary Position Embedding (RoPE) module.
Pre-computes cosine and sine tables and applies the rotary transform
to query and key tensors.
"""
def __init__(
self,
dim: int,
max_position_embeddings: int = 8192,
theta: float = 10000.0,
scaling: Optional[Dict[str, Any]] = None,
dtype: Optional[torch.dtype] = None,
device: Optional[torch.device] = None,
) -> None:
super().__init__()
self.dim = dim
self.max_position_embeddings = max_position_embeddings
self.theta = theta
self.scaling = scaling
inv_freq = self._compute_inv_freqs(
dim=dim, theta=theta, scaling=scaling, device=device
)
self.register_buffer("inv_freq", inv_freq, persistent=False)
t = torch.arange(
max_position_embeddings, device=device, dtype=torch.float32