Text Generation
Transformers
Safetensors
English
gptx2
causal-lm
custom-code
gpt-x2
long-context
grouped-query-attention
gqa
rope
yarn
symplectic-rope
metric-rope
cixopt
swiglu
rmsnorm
custom_code
Instructions to use reaperdoesntknow/GPT-X2-125M-CIx-Long-Context with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use reaperdoesntknow/GPT-X2-125M-CIx-Long-Context with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="reaperdoesntknow/GPT-X2-125M-CIx-Long-Context", trust_remote_code=True)# pip install -U transformers accelerate # Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("reaperdoesntknow/GPT-X2-125M-CIx-Long-Context", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use reaperdoesntknow/GPT-X2-125M-CIx-Long-Context with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "reaperdoesntknow/GPT-X2-125M-CIx-Long-Context" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "reaperdoesntknow/GPT-X2-125M-CIx-Long-Context", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/reaperdoesntknow/GPT-X2-125M-CIx-Long-Context
- SGLang
How to use reaperdoesntknow/GPT-X2-125M-CIx-Long-Context 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 "reaperdoesntknow/GPT-X2-125M-CIx-Long-Context" \ --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": "reaperdoesntknow/GPT-X2-125M-CIx-Long-Context", "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 "reaperdoesntknow/GPT-X2-125M-CIx-Long-Context" \ --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": "reaperdoesntknow/GPT-X2-125M-CIx-Long-Context", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use reaperdoesntknow/GPT-X2-125M-CIx-Long-Context with Docker Model Runner:
docker model run hf.co/reaperdoesntknow/GPT-X2-125M-CIx-Long-Context
Upload 2 files
Browse files- configuration_gptx2.py +119 -0
- modeling_gptx2.py +1599 -0
configuration_gptx2.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
"""GPT-X2 HuggingFace model implementation with optional Symplectic Metric-RoPE Governor.
|
| 3 |
+
|
| 4 |
+
This file is intended for checkpoint-compatible surgery on pretrained GPT-X2
|
| 5 |
+
weights, including long-context variants that have already been extended to
|
| 6 |
+
32k context and further trained. The governor is identity-safe at init:
|
| 7 |
+
zero metric projections produce exact standard/YaRN RoPE phases.
|
| 8 |
+
|
| 9 |
+
Key properties:
|
| 10 |
+
- compatible with original GPT-X2 parameter names for base modules
|
| 11 |
+
- optional global + per-block Hamiltonian clocks
|
| 12 |
+
- position-id aware RoPE for left padding, cache generation, and 32k context
|
| 13 |
+
- beam-search safe clock-state reordering
|
| 14 |
+
- safer bf16 behavior for A100 training
|
| 15 |
+
- CIxOpt parameter-group helper that keeps governor params on precise Adam path
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
from torch.nn import functional as F
|
| 25 |
+
from torch.optim import Optimizer
|
| 26 |
+
|
| 27 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
| 28 |
+
from transformers.cache_utils import DynamicCache
|
| 29 |
+
from transformers.generation.utils import GenerationMixin
|
| 30 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# =============================================================================
|
| 34 |
+
# Config
|
| 35 |
+
# =============================================================================
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class GPTX2Config(PretrainedConfig):
|
| 39 |
+
model_type = "gptx2"
|
| 40 |
+
|
| 41 |
+
def __init__(
|
| 42 |
+
self,
|
| 43 |
+
vocab_size: int = 32768,
|
| 44 |
+
hidden_size: int = 576,
|
| 45 |
+
num_hidden_layers: int = 30,
|
| 46 |
+
num_attention_heads: int = 9,
|
| 47 |
+
num_key_value_heads: int = 3,
|
| 48 |
+
head_dim: int = 64,
|
| 49 |
+
intermediate_size: int = 1536,
|
| 50 |
+
max_position_embeddings: int = 32768,
|
| 51 |
+
rope_theta: float = 100000.0,
|
| 52 |
+
rope_scaling: Optional[dict] = None,
|
| 53 |
+
rms_norm_eps: float = 1e-6,
|
| 54 |
+
tie_word_embeddings: bool = True,
|
| 55 |
+
z_loss_coeff: float = 0.0,
|
| 56 |
+
logit_l2_coeff: float = 0.0,
|
| 57 |
+
# --- Symplectic Metric-RoPE Governor ---
|
| 58 |
+
use_symplectic_rope: bool = False,
|
| 59 |
+
symplectic_global_k_dim: int = 32,
|
| 60 |
+
symplectic_local_k_dim: int = 16,
|
| 61 |
+
symplectic_global_dt: float = 0.02,
|
| 62 |
+
symplectic_local_dt: float = 0.025,
|
| 63 |
+
symplectic_n_steps: int = 2,
|
| 64 |
+
symplectic_context_scale: float = 0.01,
|
| 65 |
+
symplectic_momentum_inject_scale: float = 0.025,
|
| 66 |
+
metric_grad_scale: float = 0.03,
|
| 67 |
+
metric_mass_global_scale: float = 0.020,
|
| 68 |
+
metric_spin_global_scale: float = 0.050,
|
| 69 |
+
metric_mass_local_scale: float = 0.015,
|
| 70 |
+
metric_spin_local_scale: float = 0.050,
|
| 71 |
+
metric_radial_base: float = 256.0,
|
| 72 |
+
clock_reg_coeff: float = 1.0,
|
| 73 |
+
clock_metric_reg_coeff: float = 1e-4,
|
| 74 |
+
clock_state_reg_coeff: float = 1e-5,
|
| 75 |
+
clock_smooth_reg_coeff: float = 1e-4,
|
| 76 |
+
return_clock_diagnostics: bool = False,
|
| 77 |
+
**kwargs: Any,
|
| 78 |
+
):
|
| 79 |
+
self.vocab_size = int(vocab_size)
|
| 80 |
+
self.hidden_size = int(hidden_size)
|
| 81 |
+
self.num_hidden_layers = int(num_hidden_layers)
|
| 82 |
+
self.num_attention_heads = int(num_attention_heads)
|
| 83 |
+
self.num_key_value_heads = int(num_key_value_heads)
|
| 84 |
+
self.head_dim = int(head_dim)
|
| 85 |
+
self.intermediate_size = int(intermediate_size)
|
| 86 |
+
self.max_position_embeddings = int(max_position_embeddings)
|
| 87 |
+
self.rope_theta = float(rope_theta)
|
| 88 |
+
self.rope_scaling = rope_scaling
|
| 89 |
+
self.rms_norm_eps = float(rms_norm_eps)
|
| 90 |
+
self.z_loss_coeff = float(z_loss_coeff)
|
| 91 |
+
self.logit_l2_coeff = float(logit_l2_coeff)
|
| 92 |
+
|
| 93 |
+
self.use_symplectic_rope = bool(use_symplectic_rope)
|
| 94 |
+
self.symplectic_global_k_dim = int(symplectic_global_k_dim)
|
| 95 |
+
self.symplectic_local_k_dim = int(symplectic_local_k_dim)
|
| 96 |
+
self.symplectic_global_dt = float(symplectic_global_dt)
|
| 97 |
+
self.symplectic_local_dt = float(symplectic_local_dt)
|
| 98 |
+
self.symplectic_n_steps = int(symplectic_n_steps)
|
| 99 |
+
self.symplectic_context_scale = float(symplectic_context_scale)
|
| 100 |
+
self.symplectic_momentum_inject_scale = float(symplectic_momentum_inject_scale)
|
| 101 |
+
self.metric_grad_scale = float(metric_grad_scale)
|
| 102 |
+
self.metric_mass_global_scale = float(metric_mass_global_scale)
|
| 103 |
+
self.metric_spin_global_scale = float(metric_spin_global_scale)
|
| 104 |
+
self.metric_mass_local_scale = float(metric_mass_local_scale)
|
| 105 |
+
self.metric_spin_local_scale = float(metric_spin_local_scale)
|
| 106 |
+
self.metric_radial_base = float(metric_radial_base)
|
| 107 |
+
self.clock_reg_coeff = float(clock_reg_coeff)
|
| 108 |
+
self.clock_metric_reg_coeff = float(clock_metric_reg_coeff)
|
| 109 |
+
self.clock_state_reg_coeff = float(clock_state_reg_coeff)
|
| 110 |
+
self.clock_smooth_reg_coeff = float(clock_smooth_reg_coeff)
|
| 111 |
+
self.return_clock_diagnostics = bool(return_clock_diagnostics)
|
| 112 |
+
|
| 113 |
+
if self.num_attention_heads % self.num_key_value_heads != 0:
|
| 114 |
+
raise ValueError("num_attention_heads must be divisible by num_key_value_heads")
|
| 115 |
+
if self.head_dim * self.num_attention_heads != self.hidden_size:
|
| 116 |
+
raise ValueError("head_dim * num_attention_heads must equal hidden_size")
|
| 117 |
+
|
| 118 |
+
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 119 |
+
|
modeling_gptx2.py
ADDED
|
@@ -0,0 +1,1599 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
"""GPT-X2 HuggingFace model implementation with optional Symplectic Metric-RoPE Governor.
|
| 3 |
+
|
| 4 |
+
This file is intended for checkpoint-compatible surgery on pretrained GPT-X2
|
| 5 |
+
weights, including long-context variants that have already been extended to
|
| 6 |
+
32k context and further trained. The governor is identity-safe at init:
|
| 7 |
+
zero metric projections produce exact standard/YaRN RoPE phases.
|
| 8 |
+
|
| 9 |
+
Key properties:
|
| 10 |
+
- compatible with original GPT-X2 parameter names for base modules
|
| 11 |
+
- optional global + per-block Hamiltonian clocks
|
| 12 |
+
- position-id aware RoPE for left padding, cache generation, and 32k context
|
| 13 |
+
- beam-search safe clock-state reordering
|
| 14 |
+
- safer bf16 behavior for A100 training
|
| 15 |
+
- CIxOpt parameter-group helper that keeps governor params on precise Adam path
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import math
|
| 20 |
+
from typing import Any, Dict, Iterable, List, Optional, Tuple
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
import torch.nn as nn
|
| 24 |
+
from torch.nn import functional as F
|
| 25 |
+
from torch.optim import Optimizer
|
| 26 |
+
|
| 27 |
+
from transformers import PreTrainedModel, PretrainedConfig
|
| 28 |
+
from transformers.cache_utils import DynamicCache
|
| 29 |
+
from transformers.generation.utils import GenerationMixin
|
| 30 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 31 |
+
from configuration_gptx2 import GPTX2Config
|
| 32 |
+
|
| 33 |
+
# =============================================================================
|
| 34 |
+
# Config
|
| 35 |
+
# =============================================================================
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
# =============================================================================
|
| 41 |
+
# General utilities
|
| 42 |
+
# =============================================================================
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _safe_getattr(obj: Any, name: str, default: Any) -> Any:
|
| 46 |
+
return getattr(obj, name, default)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def zero_init_linear(linear: nn.Linear) -> None:
|
| 50 |
+
with torch.no_grad():
|
| 51 |
+
nn.init.zeros_(linear.weight)
|
| 52 |
+
if linear.bias is not None:
|
| 53 |
+
nn.init.zeros_(linear.bias)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def damped_st(x: torch.Tensor, grad_scale: float) -> torch.Tensor:
|
| 57 |
+
"""Forward value is x; backward gradient is multiplied by grad_scale."""
|
| 58 |
+
grad_scale = float(grad_scale)
|
| 59 |
+
if grad_scale >= 1.0:
|
| 60 |
+
return x
|
| 61 |
+
if grad_scale <= 0.0:
|
| 62 |
+
return x.detach()
|
| 63 |
+
return x.detach() + grad_scale * (x - x.detach())
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _align_attention_mask(
|
| 67 |
+
attention_mask: Optional[torch.Tensor],
|
| 68 |
+
batch_size: int,
|
| 69 |
+
seq_len: int,
|
| 70 |
+
device: torch.device,
|
| 71 |
+
) -> Optional[torch.Tensor]:
|
| 72 |
+
"""Return a [B, seq_len] key mask aligned to the key sequence length."""
|
| 73 |
+
if attention_mask is None:
|
| 74 |
+
return None
|
| 75 |
+
mask = attention_mask.to(device=device)
|
| 76 |
+
if mask.dim() != 2 or mask.size(0) != batch_size:
|
| 77 |
+
return mask
|
| 78 |
+
if mask.size(1) == seq_len:
|
| 79 |
+
return mask
|
| 80 |
+
if mask.size(1) > seq_len:
|
| 81 |
+
return mask[:, -seq_len:]
|
| 82 |
+
|
| 83 |
+
pad = torch.ones(batch_size, seq_len - mask.size(1), device=device, dtype=mask.dtype)
|
| 84 |
+
return torch.cat([pad, mask], dim=1)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _current_token_mask(
|
| 88 |
+
attention_mask: Optional[torch.Tensor],
|
| 89 |
+
batch_size: int,
|
| 90 |
+
current_len: int,
|
| 91 |
+
device: torch.device,
|
| 92 |
+
) -> Optional[torch.Tensor]:
|
| 93 |
+
return _align_attention_mask(attention_mask, batch_size, current_len, device)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def masked_sequence_mean(
|
| 97 |
+
x: torch.Tensor,
|
| 98 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 99 |
+
) -> torch.Tensor:
|
| 100 |
+
"""Mean over currently materialized sequence positions while ignoring padding."""
|
| 101 |
+
batch_size, seq_len, _ = x.shape
|
| 102 |
+
mask = _current_token_mask(attention_mask, batch_size, seq_len, x.device)
|
| 103 |
+
|
| 104 |
+
if mask is None or mask.dim() != 2:
|
| 105 |
+
return x.mean(dim=1)
|
| 106 |
+
|
| 107 |
+
weights = mask.to(dtype=x.dtype).unsqueeze(-1)
|
| 108 |
+
denom = weights.sum(dim=1).clamp_min(1.0)
|
| 109 |
+
return (x * weights).sum(dim=1) / denom
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def safe_lm_cross_entropy(logits: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
| 113 |
+
"""Cross-entropy that remains finite when all labels are ignored."""
|
| 114 |
+
shift_logits = logits[..., :-1, :].contiguous().float()
|
| 115 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 116 |
+
valid = shift_labels.ne(-100)
|
| 117 |
+
|
| 118 |
+
if not bool(valid.any()):
|
| 119 |
+
return shift_logits.sum() * 0.0
|
| 120 |
+
|
| 121 |
+
return F.cross_entropy(shift_logits[valid], shift_labels[valid])
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def make_position_ids(
|
| 125 |
+
input_ids: torch.Tensor,
|
| 126 |
+
attention_mask: Optional[torch.Tensor],
|
| 127 |
+
past_len: int,
|
| 128 |
+
) -> torch.Tensor:
|
| 129 |
+
"""Build RoPE position ids that are left-padding and cache aware.
|
| 130 |
+
|
| 131 |
+
For generation, HF usually supplies a full attention_mask of length
|
| 132 |
+
past + current. We cumsum over that full mask and then slice the current
|
| 133 |
+
token window. For unmasked calls, positions are absolute cache positions.
|
| 134 |
+
"""
|
| 135 |
+
batch_size, current_len = input_ids.shape
|
| 136 |
+
device = input_ids.device
|
| 137 |
+
|
| 138 |
+
if attention_mask is not None and attention_mask.dim() == 2 and attention_mask.size(0) == batch_size:
|
| 139 |
+
mask = attention_mask.to(device=device)
|
| 140 |
+
pos = mask.long().cumsum(dim=-1) - 1
|
| 141 |
+
pos = pos.clamp_min(0)
|
| 142 |
+
|
| 143 |
+
if pos.size(1) >= current_len:
|
| 144 |
+
return pos[:, -current_len:]
|
| 145 |
+
|
| 146 |
+
return torch.arange(
|
| 147 |
+
past_len,
|
| 148 |
+
past_len + current_len,
|
| 149 |
+
device=device,
|
| 150 |
+
dtype=torch.long,
|
| 151 |
+
).unsqueeze(0).expand(batch_size, current_len)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
# =============================================================================
|
| 155 |
+
# CIxOpt
|
| 156 |
+
# =============================================================================
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
class CIxOpt(Optimizer):
|
| 160 |
+
"""Heterogeneous optimizer.
|
| 161 |
+
|
| 162 |
+
Large matrix params use sign-momentum updates; smaller or precision-sensitive
|
| 163 |
+
params use Adam-style second moments. Per-param-group sign_threshold can be
|
| 164 |
+
raised to force the precise Adam branch for governor/clock parameters.
|
| 165 |
+
"""
|
| 166 |
+
|
| 167 |
+
def __init__(
|
| 168 |
+
self,
|
| 169 |
+
params: Iterable,
|
| 170 |
+
lr: float = 1e-4,
|
| 171 |
+
betas: Tuple[float, float] = (0.9, 0.99),
|
| 172 |
+
eps: float = 1e-8,
|
| 173 |
+
weight_decay: float = 0.01,
|
| 174 |
+
*,
|
| 175 |
+
sign_threshold: int = 4096,
|
| 176 |
+
sign_min_ndim: int = 2,
|
| 177 |
+
grad_centralize: bool = True,
|
| 178 |
+
centralize_min_ndim: int = 2,
|
| 179 |
+
caution: bool = True,
|
| 180 |
+
caution_normalize: bool = False,
|
| 181 |
+
decay_min_ndim: int = 2,
|
| 182 |
+
activation_decay: bool = False,
|
| 183 |
+
decay_floor: float = 0.1,
|
| 184 |
+
decay_ceiling: float = 3.0,
|
| 185 |
+
activation_ema_beta: Optional[float] = 0.95,
|
| 186 |
+
state_dtype: torch.dtype = torch.float32,
|
| 187 |
+
foreach: bool = True,
|
| 188 |
+
):
|
| 189 |
+
if lr < 0.0:
|
| 190 |
+
raise ValueError(f"Invalid lr: {lr}")
|
| 191 |
+
if not 0.0 <= betas[0] < 1.0:
|
| 192 |
+
raise ValueError(f"Invalid beta1: {betas[0]}")
|
| 193 |
+
if not 0.0 <= betas[1] < 1.0:
|
| 194 |
+
raise ValueError(f"Invalid beta2: {betas[1]}")
|
| 195 |
+
if eps < 0.0:
|
| 196 |
+
raise ValueError(f"Invalid eps: {eps}")
|
| 197 |
+
if sign_threshold < 0:
|
| 198 |
+
raise ValueError(f"Invalid sign_threshold: {sign_threshold}")
|
| 199 |
+
|
| 200 |
+
defaults = dict(
|
| 201 |
+
lr=lr,
|
| 202 |
+
betas=betas,
|
| 203 |
+
eps=eps,
|
| 204 |
+
weight_decay=weight_decay,
|
| 205 |
+
sign_threshold=sign_threshold,
|
| 206 |
+
sign_min_ndim=sign_min_ndim,
|
| 207 |
+
grad_centralize=grad_centralize,
|
| 208 |
+
centralize_min_ndim=centralize_min_ndim,
|
| 209 |
+
caution=caution,
|
| 210 |
+
caution_normalize=caution_normalize,
|
| 211 |
+
decay_min_ndim=decay_min_ndim,
|
| 212 |
+
activation_decay=activation_decay,
|
| 213 |
+
decay_floor=decay_floor,
|
| 214 |
+
decay_ceiling=decay_ceiling,
|
| 215 |
+
activation_ema_beta=activation_ema_beta,
|
| 216 |
+
state_dtype=state_dtype,
|
| 217 |
+
foreach=foreach,
|
| 218 |
+
)
|
| 219 |
+
super().__init__(params, defaults)
|
| 220 |
+
|
| 221 |
+
@staticmethod
|
| 222 |
+
def _centralize_gradient(grad: torch.Tensor, min_ndim: int = 2) -> torch.Tensor:
|
| 223 |
+
if grad.ndim >= min_ndim:
|
| 224 |
+
reduce_dims = tuple(range(1, grad.ndim))
|
| 225 |
+
return grad - grad.mean(dim=reduce_dims, keepdim=True)
|
| 226 |
+
return grad
|
| 227 |
+
|
| 228 |
+
def _is_sign_param(self, p: torch.Tensor, group: dict) -> bool:
|
| 229 |
+
return p.numel() > group["sign_threshold"] and p.ndim >= group["sign_min_ndim"]
|
| 230 |
+
|
| 231 |
+
def _should_decay(self, p: torch.Tensor, group: dict) -> bool:
|
| 232 |
+
return group["weight_decay"] != 0.0 and p.ndim >= group["decay_min_ndim"]
|
| 233 |
+
|
| 234 |
+
def _decay_multiplier(self, state: dict, group: dict) -> float:
|
| 235 |
+
if not group["activation_decay"]:
|
| 236 |
+
return 1.0
|
| 237 |
+
freq = max(0.0, min(1.0, float(state.get("activation_freq", 1.0))))
|
| 238 |
+
floor = group["decay_floor"]
|
| 239 |
+
ceiling = group["decay_ceiling"]
|
| 240 |
+
return max(floor, min(ceiling, ceiling - (ceiling - floor) * freq))
|
| 241 |
+
|
| 242 |
+
@torch.no_grad()
|
| 243 |
+
def step(self, closure=None):
|
| 244 |
+
loss = None
|
| 245 |
+
|
| 246 |
+
if closure is not None:
|
| 247 |
+
with torch.enable_grad():
|
| 248 |
+
loss = closure()
|
| 249 |
+
|
| 250 |
+
for group in self.param_groups:
|
| 251 |
+
if group["foreach"]:
|
| 252 |
+
self._step_foreach(group)
|
| 253 |
+
else:
|
| 254 |
+
self._step_sequential(group)
|
| 255 |
+
|
| 256 |
+
return loss
|
| 257 |
+
|
| 258 |
+
def _step_sequential(self, group: dict) -> None:
|
| 259 |
+
lr = group["lr"]
|
| 260 |
+
beta1, beta2 = group["betas"]
|
| 261 |
+
eps = group["eps"]
|
| 262 |
+
state_dtype = group["state_dtype"]
|
| 263 |
+
|
| 264 |
+
for p in group["params"]:
|
| 265 |
+
if p.grad is None:
|
| 266 |
+
continue
|
| 267 |
+
|
| 268 |
+
grad = p.grad.detach()
|
| 269 |
+
if group["grad_centralize"]:
|
| 270 |
+
grad = self._centralize_gradient(grad, min_ndim=group["centralize_min_ndim"])
|
| 271 |
+
if grad.dtype != state_dtype:
|
| 272 |
+
grad = grad.to(dtype=state_dtype)
|
| 273 |
+
|
| 274 |
+
state = self.state[p]
|
| 275 |
+
if "step" not in state:
|
| 276 |
+
state["step"] = 0
|
| 277 |
+
state["exp_avg"] = torch.zeros_like(p, dtype=state_dtype)
|
| 278 |
+
if not self._is_sign_param(p, group):
|
| 279 |
+
state["exp_avg_sq"] = torch.zeros_like(p, dtype=state_dtype)
|
| 280 |
+
if group["activation_decay"]:
|
| 281 |
+
state["activation_freq"] = 1.0
|
| 282 |
+
|
| 283 |
+
state["step"] += 1
|
| 284 |
+
step = state["step"]
|
| 285 |
+
exp_avg = state["exp_avg"]
|
| 286 |
+
|
| 287 |
+
if self._should_decay(p, group):
|
| 288 |
+
decay_mult = self._decay_multiplier(state, group)
|
| 289 |
+
p.mul_(1.0 - lr * group["weight_decay"] * decay_mult)
|
| 290 |
+
|
| 291 |
+
if self._is_sign_param(p, group):
|
| 292 |
+
update = exp_avg.mul(beta1).add(grad, alpha=1.0 - beta1)
|
| 293 |
+
sign_update = update.sign()
|
| 294 |
+
|
| 295 |
+
if group["caution"] and step > 1:
|
| 296 |
+
mask = sign_update * exp_avg.sign() > 0
|
| 297 |
+
if mask.any():
|
| 298 |
+
sign_update.mul_(mask.to(dtype=sign_update.dtype))
|
| 299 |
+
if group["caution_normalize"]:
|
| 300 |
+
active_frac = mask.to(torch.float32).mean().item()
|
| 301 |
+
sign_update.mul_(min(1.0 / max(active_frac, 1e-8), 10.0))
|
| 302 |
+
else:
|
| 303 |
+
sign_update.zero_()
|
| 304 |
+
|
| 305 |
+
p.add_(sign_update.to(dtype=p.dtype), alpha=-lr)
|
| 306 |
+
exp_avg.mul_(beta2).add_(grad, alpha=1.0 - beta2)
|
| 307 |
+
else:
|
| 308 |
+
exp_avg_sq = state["exp_avg_sq"]
|
| 309 |
+
exp_avg.mul_(beta1).add_(grad, alpha=1.0 - beta1)
|
| 310 |
+
exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2)
|
| 311 |
+
|
| 312 |
+
bc1 = 1.0 - beta1**step
|
| 313 |
+
bc2 = 1.0 - beta2**step
|
| 314 |
+
denom = (exp_avg_sq.sqrt() / math.sqrt(bc2)).add_(eps)
|
| 315 |
+
update = (exp_avg / denom).to(dtype=p.dtype)
|
| 316 |
+
p.add_(update, alpha=-(lr / bc1))
|
| 317 |
+
|
| 318 |
+
def _step_foreach(self, group: dict) -> None:
|
| 319 |
+
lr = group["lr"]
|
| 320 |
+
beta1, beta2 = group["betas"]
|
| 321 |
+
eps = group["eps"]
|
| 322 |
+
state_dtype = group["state_dtype"]
|
| 323 |
+
|
| 324 |
+
sign_p: List[torch.Tensor] = []
|
| 325 |
+
sign_grads: List[torch.Tensor] = []
|
| 326 |
+
sign_exp_avg: List[torch.Tensor] = []
|
| 327 |
+
sign_steps: List[int] = []
|
| 328 |
+
|
| 329 |
+
adam_p: List[torch.Tensor] = []
|
| 330 |
+
adam_grads: List[torch.Tensor] = []
|
| 331 |
+
adam_exp_avg: List[torch.Tensor] = []
|
| 332 |
+
adam_exp_avg_sq: List[torch.Tensor] = []
|
| 333 |
+
adam_steps: List[int] = []
|
| 334 |
+
|
| 335 |
+
for p in group["params"]:
|
| 336 |
+
if p.grad is None:
|
| 337 |
+
continue
|
| 338 |
+
|
| 339 |
+
grad = p.grad.detach()
|
| 340 |
+
if group["grad_centralize"]:
|
| 341 |
+
grad = self._centralize_gradient(grad, min_ndim=group["centralize_min_ndim"])
|
| 342 |
+
if grad.dtype != state_dtype:
|
| 343 |
+
grad = grad.to(dtype=state_dtype)
|
| 344 |
+
|
| 345 |
+
state = self.state[p]
|
| 346 |
+
if "step" not in state:
|
| 347 |
+
state["step"] = 0
|
| 348 |
+
state["exp_avg"] = torch.zeros_like(p, dtype=state_dtype)
|
| 349 |
+
if not self._is_sign_param(p, group):
|
| 350 |
+
state["exp_avg_sq"] = torch.zeros_like(p, dtype=state_dtype)
|
| 351 |
+
if group["activation_decay"]:
|
| 352 |
+
state["activation_freq"] = 1.0
|
| 353 |
+
|
| 354 |
+
state["step"] += 1
|
| 355 |
+
|
| 356 |
+
if self._should_decay(p, group):
|
| 357 |
+
decay_mult = self._decay_multiplier(state, group)
|
| 358 |
+
p.mul_(1.0 - lr * group["weight_decay"] * decay_mult)
|
| 359 |
+
|
| 360 |
+
if self._is_sign_param(p, group):
|
| 361 |
+
sign_p.append(p)
|
| 362 |
+
sign_grads.append(grad)
|
| 363 |
+
sign_exp_avg.append(state["exp_avg"])
|
| 364 |
+
sign_steps.append(state["step"])
|
| 365 |
+
else:
|
| 366 |
+
adam_p.append(p)
|
| 367 |
+
adam_grads.append(grad)
|
| 368 |
+
adam_exp_avg.append(state["exp_avg"])
|
| 369 |
+
adam_exp_avg_sq.append(state["exp_avg_sq"])
|
| 370 |
+
adam_steps.append(state["step"])
|
| 371 |
+
|
| 372 |
+
if sign_p:
|
| 373 |
+
updates = torch._foreach_mul(sign_exp_avg, beta1)
|
| 374 |
+
torch._foreach_add_(updates, sign_grads, alpha=1.0 - beta1)
|
| 375 |
+
sign_updates = [u.sign() for u in updates]
|
| 376 |
+
|
| 377 |
+
if group["caution"]:
|
| 378 |
+
for i, step_val in enumerate(sign_steps):
|
| 379 |
+
if step_val <= 1:
|
| 380 |
+
continue
|
| 381 |
+
mask = sign_updates[i] * sign_exp_avg[i].sign() > 0
|
| 382 |
+
if mask.any():
|
| 383 |
+
sign_updates[i].mul_(mask.to(dtype=sign_updates[i].dtype))
|
| 384 |
+
if group["caution_normalize"]:
|
| 385 |
+
active_frac = mask.to(torch.float32).mean().item()
|
| 386 |
+
sign_updates[i].mul_(min(1.0 / max(active_frac, 1e-8), 10.0))
|
| 387 |
+
else:
|
| 388 |
+
sign_updates[i].zero_()
|
| 389 |
+
|
| 390 |
+
sign_updates = [u.to(dtype=p.dtype) for u, p in zip(sign_updates, sign_p)]
|
| 391 |
+
torch._foreach_add_(sign_p, sign_updates, alpha=-lr)
|
| 392 |
+
|
| 393 |
+
torch._foreach_mul_(sign_exp_avg, beta2)
|
| 394 |
+
torch._foreach_add_(sign_exp_avg, sign_grads, alpha=1.0 - beta2)
|
| 395 |
+
|
| 396 |
+
if adam_p:
|
| 397 |
+
torch._foreach_mul_(adam_exp_avg, beta1)
|
| 398 |
+
torch._foreach_add_(adam_exp_avg, adam_grads, alpha=1.0 - beta1)
|
| 399 |
+
|
| 400 |
+
torch._foreach_mul_(adam_exp_avg_sq, beta2)
|
| 401 |
+
torch._foreach_addcmul_(adam_exp_avg_sq, adam_grads, adam_grads, value=1.0 - beta2)
|
| 402 |
+
|
| 403 |
+
for i, p_node in enumerate(adam_p):
|
| 404 |
+
step = adam_steps[i]
|
| 405 |
+
bc1 = 1.0 - beta1**step
|
| 406 |
+
bc2 = 1.0 - beta2**step
|
| 407 |
+
denom = (adam_exp_avg_sq[i].sqrt() / math.sqrt(bc2)).add_(eps)
|
| 408 |
+
update = (adam_exp_avg[i] / denom).to(dtype=p_node.dtype)
|
| 409 |
+
p_node.add_(update, alpha=-(lr / bc1))
|
| 410 |
+
|
| 411 |
+
def register_param_names(self, named_parameters: Iterable[Tuple[str, torch.Tensor]]) -> None:
|
| 412 |
+
name_map = {id(p): name for name, p in named_parameters}
|
| 413 |
+
for group in self.param_groups:
|
| 414 |
+
for p in group["params"]:
|
| 415 |
+
name = name_map.get(id(p))
|
| 416 |
+
if name is not None:
|
| 417 |
+
self.state[p]["name"] = name
|
| 418 |
+
|
| 419 |
+
def update_activation_frequencies(
|
| 420 |
+
self,
|
| 421 |
+
frequencies: Dict[str, float],
|
| 422 |
+
*,
|
| 423 |
+
exact: bool = True,
|
| 424 |
+
contains: bool = False,
|
| 425 |
+
ema_beta: Optional[float] = None,
|
| 426 |
+
) -> int:
|
| 427 |
+
count = 0
|
| 428 |
+
|
| 429 |
+
for name, freq in frequencies.items():
|
| 430 |
+
clamped_freq = max(0.0, min(1.0, float(freq)))
|
| 431 |
+
|
| 432 |
+
for group in self.param_groups:
|
| 433 |
+
beta = group.get("activation_ema_beta", None) if ema_beta is None else ema_beta
|
| 434 |
+
|
| 435 |
+
for p in group["params"]:
|
| 436 |
+
state = self.state[p]
|
| 437 |
+
p_name = state.get("name")
|
| 438 |
+
if p_name is None:
|
| 439 |
+
continue
|
| 440 |
+
|
| 441 |
+
match = (exact and p_name == name) or (contains and name in p_name)
|
| 442 |
+
if not match:
|
| 443 |
+
continue
|
| 444 |
+
|
| 445 |
+
if beta is None or "activation_freq" not in state:
|
| 446 |
+
state["activation_freq"] = clamped_freq
|
| 447 |
+
else:
|
| 448 |
+
old = float(state.get("activation_freq", 1.0))
|
| 449 |
+
state["activation_freq"] = beta * old + (1.0 - beta) * clamped_freq
|
| 450 |
+
|
| 451 |
+
count += 1
|
| 452 |
+
|
| 453 |
+
return count
|
| 454 |
+
|
| 455 |
+
|
| 456 |
+
def build_cix_param_groups(
|
| 457 |
+
model: nn.Module,
|
| 458 |
+
*,
|
| 459 |
+
base_lr: float = 1e-4,
|
| 460 |
+
weight_decay: float = 0.01,
|
| 461 |
+
governor_lr_mult: float = 0.25,
|
| 462 |
+
norm_lr_mult: float = 1.0,
|
| 463 |
+
force_governor_adam: bool = True,
|
| 464 |
+
) -> List[Dict[str, Any]]:
|
| 465 |
+
"""Create stable param groups for CIxOpt.
|
| 466 |
+
|
| 467 |
+
The clock/governor modules are intentionally placed on the precise Adam
|
| 468 |
+
path by raising sign_threshold. This avoids sign-updating newly initialized
|
| 469 |
+
metric controllers while the pretrained base model is adapting.
|
| 470 |
+
"""
|
| 471 |
+
base_decay: List[nn.Parameter] = []
|
| 472 |
+
base_nodecay: List[nn.Parameter] = []
|
| 473 |
+
governor: List[nn.Parameter] = []
|
| 474 |
+
seen: set[int] = set()
|
| 475 |
+
|
| 476 |
+
governor_markers = (
|
| 477 |
+
"global_clock",
|
| 478 |
+
"global_metric_proj",
|
| 479 |
+
"local_clock",
|
| 480 |
+
"local_metric_proj",
|
| 481 |
+
)
|
| 482 |
+
norm_markers = ("norm", "ln_", "rms")
|
| 483 |
+
|
| 484 |
+
for name, param in model.named_parameters():
|
| 485 |
+
if not param.requires_grad or id(param) in seen:
|
| 486 |
+
continue
|
| 487 |
+
seen.add(id(param))
|
| 488 |
+
|
| 489 |
+
if any(marker in name for marker in governor_markers):
|
| 490 |
+
governor.append(param)
|
| 491 |
+
elif param.ndim < 2 or name.endswith(".bias") or any(marker in name.lower() for marker in norm_markers):
|
| 492 |
+
base_nodecay.append(param)
|
| 493 |
+
else:
|
| 494 |
+
base_decay.append(param)
|
| 495 |
+
|
| 496 |
+
groups: List[Dict[str, Any]] = []
|
| 497 |
+
|
| 498 |
+
if base_decay:
|
| 499 |
+
groups.append(
|
| 500 |
+
{
|
| 501 |
+
"params": base_decay,
|
| 502 |
+
"lr": base_lr,
|
| 503 |
+
"weight_decay": weight_decay,
|
| 504 |
+
}
|
| 505 |
+
)
|
| 506 |
+
|
| 507 |
+
if base_nodecay:
|
| 508 |
+
groups.append(
|
| 509 |
+
{
|
| 510 |
+
"params": base_nodecay,
|
| 511 |
+
"lr": base_lr * norm_lr_mult,
|
| 512 |
+
"weight_decay": 0.0,
|
| 513 |
+
}
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
if governor:
|
| 517 |
+
gov_group: Dict[str, Any] = {
|
| 518 |
+
"params": governor,
|
| 519 |
+
"lr": base_lr * governor_lr_mult,
|
| 520 |
+
"weight_decay": 0.0,
|
| 521 |
+
"grad_centralize": False,
|
| 522 |
+
}
|
| 523 |
+
if force_governor_adam:
|
| 524 |
+
gov_group["sign_threshold"] = 10**18
|
| 525 |
+
groups.append(gov_group)
|
| 526 |
+
|
| 527 |
+
return groups
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
# =============================================================================
|
| 531 |
+
# Normalization
|
| 532 |
+
# =============================================================================
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
class RMSNorm(nn.Module):
|
| 536 |
+
def __init__(self, dim: int, eps: float = 1e-6):
|
| 537 |
+
super().__init__()
|
| 538 |
+
self.eps = float(eps)
|
| 539 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 540 |
+
|
| 541 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 542 |
+
y = x.float()
|
| 543 |
+
y = y * torch.rsqrt(y.pow(2).mean(dim=-1, keepdim=True) + self.eps)
|
| 544 |
+
y = y * self.weight.float()
|
| 545 |
+
return y.to(dtype=x.dtype)
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
# =============================================================================
|
| 549 |
+
# RoPE and YaRN helpers
|
| 550 |
+
# =============================================================================
|
| 551 |
+
|
| 552 |
+
|
| 553 |
+
def _normalize_rope_scaling(rope_scaling: Any) -> Optional[dict]:
|
| 554 |
+
if rope_scaling is None:
|
| 555 |
+
return None
|
| 556 |
+
if isinstance(rope_scaling, (tuple, list)) and len(rope_scaling) == 1 and isinstance(rope_scaling[0], dict):
|
| 557 |
+
return rope_scaling[0]
|
| 558 |
+
if isinstance(rope_scaling, dict):
|
| 559 |
+
return rope_scaling
|
| 560 |
+
return None
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
def _yarn_get_mscale(scale: float, mscale: float = 1.0) -> float:
|
| 564 |
+
if scale <= 1.0:
|
| 565 |
+
return 1.0
|
| 566 |
+
return 0.1 * mscale * math.log(scale) + 1.0
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def _yarn_find_correction_dim(
|
| 570 |
+
num_rotations: float,
|
| 571 |
+
dim: int,
|
| 572 |
+
base: float = 10000.0,
|
| 573 |
+
max_position_embeddings: int = 2048,
|
| 574 |
+
) -> float:
|
| 575 |
+
return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def _yarn_find_correction_range(
|
| 579 |
+
low_rot: float,
|
| 580 |
+
high_rot: float,
|
| 581 |
+
dim: int,
|
| 582 |
+
base: float = 10000.0,
|
| 583 |
+
max_position_embeddings: int = 2048,
|
| 584 |
+
) -> Tuple[int, int]:
|
| 585 |
+
low = math.floor(_yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings))
|
| 586 |
+
high = math.ceil(_yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings))
|
| 587 |
+
return max(low, 0), min(high, dim - 1)
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def _yarn_linear_ramp_mask(low: int, high: int, dim: int, device: torch.device) -> torch.Tensor:
|
| 591 |
+
if low == high:
|
| 592 |
+
high += 1
|
| 593 |
+
x = (torch.arange(dim, dtype=torch.float32, device=device) - low) / float(high - low)
|
| 594 |
+
return torch.clamp(x, 0.0, 1.0)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def build_rope_inv_freq(
|
| 598 |
+
head_dim: int,
|
| 599 |
+
theta: float = 100000.0,
|
| 600 |
+
device: Optional[torch.device] = None,
|
| 601 |
+
rope_scaling: Optional[dict] = None,
|
| 602 |
+
max_position_embeddings: int = 32768,
|
| 603 |
+
) -> Tuple[torch.Tensor, float]:
|
| 604 |
+
"""Build RoPE inverse frequencies, optionally with YaRN scaling."""
|
| 605 |
+
device = device or torch.device("cpu")
|
| 606 |
+
idx = torch.arange(0, head_dim, 2, dtype=torch.float32, device=device)
|
| 607 |
+
inv_freq_base = 1.0 / (float(theta) ** (idx / float(head_dim)))
|
| 608 |
+
attention_scaling = 1.0
|
| 609 |
+
|
| 610 |
+
rope_scaling = _normalize_rope_scaling(rope_scaling)
|
| 611 |
+
if not rope_scaling:
|
| 612 |
+
return inv_freq_base, attention_scaling
|
| 613 |
+
|
| 614 |
+
rope_type = rope_scaling.get("rope_type", rope_scaling.get("type", None))
|
| 615 |
+
if rope_type != "yarn":
|
| 616 |
+
return inv_freq_base, attention_scaling
|
| 617 |
+
|
| 618 |
+
factor = float(rope_scaling.get("factor", 1.0))
|
| 619 |
+
if factor <= 1.0:
|
| 620 |
+
return inv_freq_base, attention_scaling
|
| 621 |
+
|
| 622 |
+
beta_fast = float(rope_scaling.get("beta_fast", 32.0))
|
| 623 |
+
beta_slow = float(rope_scaling.get("beta_slow", 1.0))
|
| 624 |
+
original_max_position_embeddings = int(
|
| 625 |
+
rope_scaling.get("original_max_position_embeddings", max_position_embeddings)
|
| 626 |
+
)
|
| 627 |
+
extrapolation_factor = float(rope_scaling.get("extrapolation_factor", 1.0))
|
| 628 |
+
|
| 629 |
+
inv_freq_interpolation = inv_freq_base / factor
|
| 630 |
+
inv_freq_extrapolation = inv_freq_base
|
| 631 |
+
|
| 632 |
+
low, high = _yarn_find_correction_range(
|
| 633 |
+
beta_fast,
|
| 634 |
+
beta_slow,
|
| 635 |
+
head_dim,
|
| 636 |
+
float(theta),
|
| 637 |
+
original_max_position_embeddings,
|
| 638 |
+
)
|
| 639 |
+
|
| 640 |
+
inv_freq_mask = (
|
| 641 |
+
1.0 - _yarn_linear_ramp_mask(low, high, head_dim // 2, device)
|
| 642 |
+
) * extrapolation_factor
|
| 643 |
+
inv_freq = inv_freq_interpolation * (1.0 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
|
| 644 |
+
|
| 645 |
+
mscale = float(rope_scaling.get("mscale", 1.0))
|
| 646 |
+
mscale_all_dim = float(rope_scaling.get("mscale_all_dim", 0.0))
|
| 647 |
+
|
| 648 |
+
if mscale_all_dim:
|
| 649 |
+
attention_scaling = _yarn_get_mscale(factor, mscale) / _yarn_get_mscale(factor, mscale_all_dim)
|
| 650 |
+
else:
|
| 651 |
+
attention_scaling = _yarn_get_mscale(factor, mscale)
|
| 652 |
+
|
| 653 |
+
if rope_scaling.get("mscale", None) == 1.0 and rope_scaling.get("mscale_all_dim", None) == 1.0:
|
| 654 |
+
attention_scaling = 1.0
|
| 655 |
+
|
| 656 |
+
return inv_freq, attention_scaling
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def precompute_freqs_cis(
|
| 660 |
+
head_dim: int,
|
| 661 |
+
seq_len: int,
|
| 662 |
+
theta: float = 100000.0,
|
| 663 |
+
device: Optional[torch.device] = None,
|
| 664 |
+
rope_scaling: Optional[dict] = None,
|
| 665 |
+
max_position_embeddings: int = 32768,
|
| 666 |
+
) -> torch.Tensor:
|
| 667 |
+
device = device or torch.device("cpu")
|
| 668 |
+
seq_len = max(int(seq_len), 1)
|
| 669 |
+
|
| 670 |
+
inv_freq, attention_scaling = build_rope_inv_freq(
|
| 671 |
+
head_dim=head_dim,
|
| 672 |
+
theta=theta,
|
| 673 |
+
device=device,
|
| 674 |
+
rope_scaling=rope_scaling,
|
| 675 |
+
max_position_embeddings=max_position_embeddings,
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
+
t = torch.arange(seq_len, dtype=torch.float32, device=device)
|
| 679 |
+
phase = torch.outer(t, inv_freq)
|
| 680 |
+
magnitude = torch.ones_like(phase) * float(attention_scaling)
|
| 681 |
+
return torch.polar(magnitude, phase)
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def apply_rotary_emb(q: torch.Tensor, k: torch.Tensor, freqs_cis: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 685 |
+
"""Apply RoPE.
|
| 686 |
+
|
| 687 |
+
Supports:
|
| 688 |
+
freqs_cis [T, D/2]
|
| 689 |
+
freqs_cis [B, T, D/2]
|
| 690 |
+
"""
|
| 691 |
+
q_complex = torch.view_as_complex(q.float().reshape(*q.shape[:-1], -1, 2))
|
| 692 |
+
k_complex = torch.view_as_complex(k.float().reshape(*k.shape[:-1], -1, 2))
|
| 693 |
+
|
| 694 |
+
if freqs_cis.dim() == 2:
|
| 695 |
+
freqs_cis = freqs_cis.unsqueeze(0).unsqueeze(0)
|
| 696 |
+
elif freqs_cis.dim() == 3:
|
| 697 |
+
freqs_cis = freqs_cis.unsqueeze(1)
|
| 698 |
+
else:
|
| 699 |
+
raise ValueError(f"freqs_cis must be [T, D/2] or [B, T, D/2], got shape {tuple(freqs_cis.shape)}")
|
| 700 |
+
|
| 701 |
+
q_out = torch.view_as_real(q_complex * freqs_cis).flatten(-2)
|
| 702 |
+
k_out = torch.view_as_real(k_complex * freqs_cis).flatten(-2)
|
| 703 |
+
return q_out.to(dtype=q.dtype), k_out.to(dtype=k.dtype)
|
| 704 |
+
|
| 705 |
+
|
| 706 |
+
def compute_metric_warped_freqs_cis(
|
| 707 |
+
head_dim: int,
|
| 708 |
+
seq_len: int,
|
| 709 |
+
theta_base: float,
|
| 710 |
+
mass_delta: torch.Tensor,
|
| 711 |
+
spin_delta: torch.Tensor,
|
| 712 |
+
device: torch.device,
|
| 713 |
+
rope_scaling: Optional[dict] = None,
|
| 714 |
+
max_position_embeddings: int = 32768,
|
| 715 |
+
radial_base: float = 256.0,
|
| 716 |
+
) -> torch.Tensor:
|
| 717 |
+
"""Identity-safe Kerr-inspired RoPE phase warp.
|
| 718 |
+
|
| 719 |
+
mass_delta = 0 and spin_delta = 0 produce exact standard/YaRN RoPE.
|
| 720 |
+
"""
|
| 721 |
+
seq_len = max(int(seq_len), 1)
|
| 722 |
+
|
| 723 |
+
inv_freq, attention_scaling = build_rope_inv_freq(
|
| 724 |
+
head_dim=head_dim,
|
| 725 |
+
theta=theta_base,
|
| 726 |
+
device=device,
|
| 727 |
+
rope_scaling=rope_scaling,
|
| 728 |
+
max_position_embeddings=max_position_embeddings,
|
| 729 |
+
)
|
| 730 |
+
|
| 731 |
+
t = torch.arange(seq_len, dtype=torch.float32, device=device)
|
| 732 |
+
base_phase = t.unsqueeze(-1) * inv_freq.unsqueeze(0)
|
| 733 |
+
|
| 734 |
+
denom = max(seq_len - 1, 1)
|
| 735 |
+
x = t / float(denom)
|
| 736 |
+
radial = 1.0 / (1.0 + t / float(radial_base))
|
| 737 |
+
|
| 738 |
+
mass_delta = mass_delta.float().to(device)
|
| 739 |
+
spin_delta = spin_delta.float().to(device)
|
| 740 |
+
|
| 741 |
+
dilation = 1.0 + mass_delta * radial
|
| 742 |
+
drag = spin_delta * x.square()
|
| 743 |
+
|
| 744 |
+
phase = base_phase * dilation.unsqueeze(-1) + drag.unsqueeze(-1)
|
| 745 |
+
magnitude = torch.ones_like(phase) * float(attention_scaling)
|
| 746 |
+
return torch.polar(magnitude, phase)
|
| 747 |
+
|
| 748 |
+
|
| 749 |
+
# =============================================================================
|
| 750 |
+
# Symplectic Metric-RoPE Governor
|
| 751 |
+
# =============================================================================
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class SymplecticClock(nn.Module):
|
| 755 |
+
"""Hamiltonian phase-space clock using semi-implicit symplectic Euler."""
|
| 756 |
+
|
| 757 |
+
def __init__(
|
| 758 |
+
self,
|
| 759 |
+
k_dim: int,
|
| 760 |
+
embed_dim: int,
|
| 761 |
+
dt: float = 0.025,
|
| 762 |
+
n_steps: int = 2,
|
| 763 |
+
context_scale: float = 0.01,
|
| 764 |
+
momentum_inject_scale: float = 0.025,
|
| 765 |
+
):
|
| 766 |
+
super().__init__()
|
| 767 |
+
self.k_dim = int(k_dim)
|
| 768 |
+
self.embed_dim = int(embed_dim)
|
| 769 |
+
self.dt = float(dt)
|
| 770 |
+
self.n_steps = int(n_steps)
|
| 771 |
+
self.context_scale = float(context_scale)
|
| 772 |
+
self.momentum_inject_scale = float(momentum_inject_scale)
|
| 773 |
+
|
| 774 |
+
self.raw_h_diag = nn.Parameter(torch.full((2 * self.k_dim,), -3.0))
|
| 775 |
+
|
| 776 |
+
self.context_to_force = nn.Sequential(
|
| 777 |
+
nn.Linear(self.embed_dim, 2 * self.k_dim),
|
| 778 |
+
nn.SiLU(),
|
| 779 |
+
nn.Linear(2 * self.k_dim, 2 * self.k_dim),
|
| 780 |
+
)
|
| 781 |
+
self.delta_to_p = nn.Linear(self.embed_dim, self.k_dim, bias=False)
|
| 782 |
+
|
| 783 |
+
self.register_buffer(
|
| 784 |
+
"z_state",
|
| 785 |
+
torch.zeros(1, 2 * self.k_dim, dtype=torch.float32),
|
| 786 |
+
persistent=False,
|
| 787 |
+
)
|
| 788 |
+
self.reset_parameters()
|
| 789 |
+
|
| 790 |
+
def reset_parameters(self) -> None:
|
| 791 |
+
for module in self.context_to_force:
|
| 792 |
+
if isinstance(module, nn.Linear):
|
| 793 |
+
nn.init.xavier_uniform_(module.weight)
|
| 794 |
+
if module.bias is not None:
|
| 795 |
+
nn.init.zeros_(module.bias)
|
| 796 |
+
|
| 797 |
+
final = self.context_to_force[-1]
|
| 798 |
+
if isinstance(final, nn.Linear):
|
| 799 |
+
with torch.no_grad():
|
| 800 |
+
final.weight.mul_(1e-3)
|
| 801 |
+
if final.bias is not None:
|
| 802 |
+
final.bias.zero_()
|
| 803 |
+
|
| 804 |
+
zero_init_linear(self.delta_to_p)
|
| 805 |
+
|
| 806 |
+
def h_diag(self) -> torch.Tensor:
|
| 807 |
+
return F.softplus(self.raw_h_diag.float()) + 1e-5
|
| 808 |
+
|
| 809 |
+
def reset_state(self, batch_size: int, device: torch.device) -> None:
|
| 810 |
+
self.z_state = torch.zeros(batch_size, 2 * self.k_dim, device=device, dtype=torch.float32)
|
| 811 |
+
|
| 812 |
+
def reorder_state(self, beam_idx: torch.LongTensor) -> None:
|
| 813 |
+
if self.z_state is None:
|
| 814 |
+
return
|
| 815 |
+
idx = beam_idx.to(device=self.z_state.device)
|
| 816 |
+
if self.z_state.size(0) == idx.numel():
|
| 817 |
+
self.z_state = self.z_state.index_select(0, idx)
|
| 818 |
+
|
| 819 |
+
def _symplectic_step(self, z: torch.Tensor, context: torch.Tensor) -> torch.Tensor:
|
| 820 |
+
z = z.float()
|
| 821 |
+
context_fp32 = context.float()
|
| 822 |
+
theta, p = z.split(self.k_dim, dim=-1)
|
| 823 |
+
|
| 824 |
+
h = self.h_diag().unsqueeze(0)
|
| 825 |
+
h_theta, h_p = h.split(self.k_dim, dim=-1)
|
| 826 |
+
|
| 827 |
+
force_dtype = self.context_to_force[0].weight.dtype
|
| 828 |
+
force = self.context_to_force(context_fp32.to(dtype=force_dtype)).float()
|
| 829 |
+
force = self.context_scale * force
|
| 830 |
+
f_theta, f_p = force.split(self.k_dim, dim=-1)
|
| 831 |
+
|
| 832 |
+
dH_dtheta = h_theta * theta + f_theta
|
| 833 |
+
p_new = p - self.dt * dH_dtheta
|
| 834 |
+
|
| 835 |
+
dH_dp_new = h_p * p_new + f_p
|
| 836 |
+
theta_new = theta + self.dt * dH_dp_new
|
| 837 |
+
|
| 838 |
+
return torch.cat([theta_new, p_new], dim=-1)
|
| 839 |
+
|
| 840 |
+
def evolve(
|
| 841 |
+
self,
|
| 842 |
+
context: torch.Tensor,
|
| 843 |
+
reset: bool = False,
|
| 844 |
+
residual_delta: Optional[torch.Tensor] = None,
|
| 845 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 846 |
+
batch_size = context.shape[0]
|
| 847 |
+
device = context.device
|
| 848 |
+
|
| 849 |
+
if reset or self.z_state.shape[0] != batch_size or self.z_state.device != device:
|
| 850 |
+
self.reset_state(batch_size, device)
|
| 851 |
+
|
| 852 |
+
z = self.z_state
|
| 853 |
+
for _ in range(self.n_steps):
|
| 854 |
+
z = self._symplectic_step(z, context)
|
| 855 |
+
|
| 856 |
+
if residual_delta is not None:
|
| 857 |
+
theta, p = z.split(self.k_dim, dim=-1)
|
| 858 |
+
delta_dtype = self.delta_to_p.weight.dtype
|
| 859 |
+
dp = self.delta_to_p(residual_delta.float().to(dtype=delta_dtype)).float()
|
| 860 |
+
dp = self.momentum_inject_scale * torch.tanh(dp)
|
| 861 |
+
p = p + dp
|
| 862 |
+
z = torch.cat([theta, p], dim=-1)
|
| 863 |
+
|
| 864 |
+
self.z_state = z.detach()
|
| 865 |
+
theta, p = z.split(self.k_dim, dim=-1)
|
| 866 |
+
return theta, p
|
| 867 |
+
|
| 868 |
+
|
| 869 |
+
def clock_feature(z: torch.Tensor) -> torch.Tensor:
|
| 870 |
+
"""Stable feature from [B, D], valid for B=1 generation."""
|
| 871 |
+
z = z.float()
|
| 872 |
+
mean = z.mean(dim=0)
|
| 873 |
+
energy = z.square().mean(dim=0)
|
| 874 |
+
return mean + 0.25 * energy
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
def project_metric_delta(
|
| 878 |
+
metric_proj: nn.Linear,
|
| 879 |
+
z: torch.Tensor,
|
| 880 |
+
mass_scale: float = 0.020,
|
| 881 |
+
spin_scale: float = 0.050,
|
| 882 |
+
grad_scale: float = 0.03,
|
| 883 |
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
| 884 |
+
feat = clock_feature(z)
|
| 885 |
+
proj_dtype = metric_proj.weight.dtype
|
| 886 |
+
raw = metric_proj(feat.to(dtype=proj_dtype)).float()
|
| 887 |
+
|
| 888 |
+
dm_raw, da_raw = raw[0], raw[1]
|
| 889 |
+
dm = float(mass_scale) * torch.tanh(dm_raw)
|
| 890 |
+
da = float(spin_scale) * torch.tanh(da_raw)
|
| 891 |
+
|
| 892 |
+
return damped_st(dm, grad_scale), damped_st(da, grad_scale)
|
| 893 |
+
|
| 894 |
+
|
| 895 |
+
def clock_regularization(
|
| 896 |
+
dm_global: torch.Tensor,
|
| 897 |
+
da_global: torch.Tensor,
|
| 898 |
+
local_metric_values: List[Tuple[torch.Tensor, torch.Tensor]],
|
| 899 |
+
clock_states: List[torch.Tensor],
|
| 900 |
+
lambda_metric: float = 1e-4,
|
| 901 |
+
lambda_state: float = 1e-5,
|
| 902 |
+
lambda_smooth: float = 1e-4,
|
| 903 |
+
) -> torch.Tensor:
|
| 904 |
+
device = dm_global.device
|
| 905 |
+
loss = torch.zeros((), device=device, dtype=torch.float32)
|
| 906 |
+
|
| 907 |
+
lambda_metric = float(lambda_metric)
|
| 908 |
+
lambda_state = float(lambda_state)
|
| 909 |
+
lambda_smooth = float(lambda_smooth)
|
| 910 |
+
|
| 911 |
+
loss = loss + lambda_metric * (dm_global.float().square() + da_global.float().square())
|
| 912 |
+
|
| 913 |
+
for dm_l, da_l in local_metric_values:
|
| 914 |
+
loss = loss + lambda_metric * (dm_l.float().square() + da_l.float().square())
|
| 915 |
+
|
| 916 |
+
for z in clock_states:
|
| 917 |
+
loss = loss + lambda_state * z.float().square().mean()
|
| 918 |
+
|
| 919 |
+
if len(local_metric_values) > 1:
|
| 920 |
+
dms = torch.stack([v[0].float() for v in local_metric_values])
|
| 921 |
+
das = torch.stack([v[1].float() for v in local_metric_values])
|
| 922 |
+
loss = loss + lambda_smooth * (
|
| 923 |
+
(dms[1:] - dms[:-1]).square().mean()
|
| 924 |
+
+ (das[1:] - das[:-1]).square().mean()
|
| 925 |
+
)
|
| 926 |
+
|
| 927 |
+
return loss
|
| 928 |
+
|
| 929 |
+
|
| 930 |
+
# =============================================================================
|
| 931 |
+
# Transformer modules
|
| 932 |
+
# =============================================================================
|
| 933 |
+
|
| 934 |
+
|
| 935 |
+
class GPTX2Attention(nn.Module):
|
| 936 |
+
def __init__(self, config: GPTX2Config, layer_idx: int):
|
| 937 |
+
super().__init__()
|
| 938 |
+
self.layer_idx = int(layer_idx)
|
| 939 |
+
self.n_head = int(config.num_attention_heads)
|
| 940 |
+
self.n_kv_heads = int(config.num_key_value_heads)
|
| 941 |
+
self.head_dim = int(config.head_dim)
|
| 942 |
+
self.n_rep = self.n_head // self.n_kv_heads
|
| 943 |
+
|
| 944 |
+
self.q_proj = nn.Linear(config.hidden_size, self.n_head * self.head_dim, bias=False)
|
| 945 |
+
self.k_proj = nn.Linear(config.hidden_size, self.n_kv_heads * self.head_dim, bias=False)
|
| 946 |
+
self.v_proj = nn.Linear(config.hidden_size, self.n_kv_heads * self.head_dim, bias=False)
|
| 947 |
+
self.o_proj = nn.Linear(self.n_head * self.head_dim, config.hidden_size, bias=False)
|
| 948 |
+
self.o_proj.NANOGPT_SCALE_INIT = 1
|
| 949 |
+
|
| 950 |
+
self.q_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 951 |
+
self.k_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps)
|
| 952 |
+
|
| 953 |
+
def _build_attention_mask(
|
| 954 |
+
self,
|
| 955 |
+
attention_mask: Optional[torch.Tensor],
|
| 956 |
+
batch_size: int,
|
| 957 |
+
query_len: int,
|
| 958 |
+
key_len: int,
|
| 959 |
+
device: torch.device,
|
| 960 |
+
) -> Optional[torch.Tensor]:
|
| 961 |
+
"""Build SDPA bool mask. True means visible."""
|
| 962 |
+
causal_mask = None
|
| 963 |
+
if query_len > 1:
|
| 964 |
+
causal_mask = torch.ones(query_len, key_len, dtype=torch.bool, device=device)
|
| 965 |
+
causal_mask = causal_mask.tril(diagonal=key_len - query_len)
|
| 966 |
+
|
| 967 |
+
if attention_mask is None:
|
| 968 |
+
if causal_mask is None:
|
| 969 |
+
return None
|
| 970 |
+
return causal_mask[None, None, :, :]
|
| 971 |
+
|
| 972 |
+
aligned_mask = _align_attention_mask(attention_mask, batch_size, key_len, device)
|
| 973 |
+
if aligned_mask is None or aligned_mask.dim() != 2:
|
| 974 |
+
return None
|
| 975 |
+
|
| 976 |
+
key_pad = aligned_mask.to(torch.bool)[:, None, None, :]
|
| 977 |
+
|
| 978 |
+
if causal_mask is not None:
|
| 979 |
+
attn_mask = key_pad & causal_mask[None, None, :, :]
|
| 980 |
+
else:
|
| 981 |
+
attn_mask = key_pad.expand(batch_size, 1, query_len, key_len)
|
| 982 |
+
|
| 983 |
+
empty_rows = ~attn_mask.any(dim=-1, keepdim=True)
|
| 984 |
+
if bool(empty_rows.any()):
|
| 985 |
+
attn_mask = attn_mask | empty_rows.expand_as(attn_mask)
|
| 986 |
+
|
| 987 |
+
return attn_mask
|
| 988 |
+
|
| 989 |
+
def forward(
|
| 990 |
+
self,
|
| 991 |
+
x: torch.Tensor,
|
| 992 |
+
freqs_cis: torch.Tensor,
|
| 993 |
+
past_key_value: Optional[DynamicCache] = None,
|
| 994 |
+
use_cache: bool = False,
|
| 995 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 996 |
+
) -> torch.Tensor:
|
| 997 |
+
batch_size, query_len, _ = x.size()
|
| 998 |
+
|
| 999 |
+
q = self.q_proj(x).view(batch_size, query_len, self.n_head, self.head_dim).transpose(1, 2)
|
| 1000 |
+
k = self.k_proj(x).view(batch_size, query_len, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 1001 |
+
v = self.v_proj(x).view(batch_size, query_len, self.n_kv_heads, self.head_dim).transpose(1, 2)
|
| 1002 |
+
|
| 1003 |
+
q = self.q_norm(q)
|
| 1004 |
+
k = self.k_norm(k)
|
| 1005 |
+
q, k = apply_rotary_emb(q, k, freqs_cis)
|
| 1006 |
+
|
| 1007 |
+
if past_key_value is not None:
|
| 1008 |
+
k, v = past_key_value.update(k, v, self.layer_idx)
|
| 1009 |
+
|
| 1010 |
+
key_len = k.size(2)
|
| 1011 |
+
|
| 1012 |
+
k = (
|
| 1013 |
+
k.unsqueeze(2)
|
| 1014 |
+
.expand(batch_size, self.n_kv_heads, self.n_rep, key_len, self.head_dim)
|
| 1015 |
+
.reshape(batch_size, self.n_head, key_len, self.head_dim)
|
| 1016 |
+
)
|
| 1017 |
+
v = (
|
| 1018 |
+
v.unsqueeze(2)
|
| 1019 |
+
.expand(batch_size, self.n_kv_heads, self.n_rep, key_len, self.head_dim)
|
| 1020 |
+
.reshape(batch_size, self.n_head, key_len, self.head_dim)
|
| 1021 |
+
)
|
| 1022 |
+
|
| 1023 |
+
attn_mask = self._build_attention_mask(
|
| 1024 |
+
attention_mask=attention_mask,
|
| 1025 |
+
batch_size=batch_size,
|
| 1026 |
+
query_len=query_len,
|
| 1027 |
+
key_len=key_len,
|
| 1028 |
+
device=x.device,
|
| 1029 |
+
)
|
| 1030 |
+
|
| 1031 |
+
y = F.scaled_dot_product_attention(
|
| 1032 |
+
q,
|
| 1033 |
+
k,
|
| 1034 |
+
v,
|
| 1035 |
+
attn_mask=attn_mask,
|
| 1036 |
+
is_causal=False,
|
| 1037 |
+
)
|
| 1038 |
+
|
| 1039 |
+
y = y.transpose(1, 2).contiguous().view(batch_size, query_len, self.n_head * self.head_dim)
|
| 1040 |
+
return self.o_proj(y)
|
| 1041 |
+
|
| 1042 |
+
|
| 1043 |
+
class GPTX2SwiGLUMLP(nn.Module):
|
| 1044 |
+
def __init__(self, config: GPTX2Config):
|
| 1045 |
+
super().__init__()
|
| 1046 |
+
self.w_gate = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 1047 |
+
self.w_up = nn.Linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 1048 |
+
self.w_down = nn.Linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 1049 |
+
self.w_down.NANOGPT_SCALE_INIT = 1
|
| 1050 |
+
|
| 1051 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 1052 |
+
return self.w_down(F.silu(self.w_gate(x)) * self.w_up(x))
|
| 1053 |
+
|
| 1054 |
+
|
| 1055 |
+
class GPTX2Block(nn.Module):
|
| 1056 |
+
def __init__(self, config: GPTX2Config, layer_idx: int):
|
| 1057 |
+
super().__init__()
|
| 1058 |
+
self.layer_idx = int(layer_idx)
|
| 1059 |
+
self.config = config
|
| 1060 |
+
self.ln_1 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 1061 |
+
self.attn = GPTX2Attention(config, layer_idx)
|
| 1062 |
+
self.ln_2 = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 1063 |
+
self.mlp = GPTX2SwiGLUMLP(config)
|
| 1064 |
+
|
| 1065 |
+
self.use_symplectic_rope = bool(_safe_getattr(config, "use_symplectic_rope", False))
|
| 1066 |
+
|
| 1067 |
+
if self.use_symplectic_rope:
|
| 1068 |
+
local_k = int(_safe_getattr(config, "symplectic_local_k_dim", 16))
|
| 1069 |
+
self.local_clock = SymplecticClock(
|
| 1070 |
+
k_dim=local_k,
|
| 1071 |
+
embed_dim=config.hidden_size,
|
| 1072 |
+
dt=float(_safe_getattr(config, "symplectic_local_dt", 0.025)),
|
| 1073 |
+
n_steps=int(_safe_getattr(config, "symplectic_n_steps", 2)),
|
| 1074 |
+
context_scale=float(_safe_getattr(config, "symplectic_context_scale", 0.01)),
|
| 1075 |
+
momentum_inject_scale=float(_safe_getattr(config, "symplectic_momentum_inject_scale", 0.025)),
|
| 1076 |
+
)
|
| 1077 |
+
self.local_metric_proj = nn.Linear(2 * local_k, 2)
|
| 1078 |
+
|
| 1079 |
+
def reset_clock_state(self, batch_size: int, device: torch.device) -> None:
|
| 1080 |
+
if hasattr(self, "local_clock"):
|
| 1081 |
+
self.local_clock.reset_state(batch_size, device)
|
| 1082 |
+
|
| 1083 |
+
def reorder_clock_state(self, beam_idx: torch.LongTensor) -> None:
|
| 1084 |
+
if hasattr(self, "local_clock"):
|
| 1085 |
+
self.local_clock.reorder_state(beam_idx)
|
| 1086 |
+
|
| 1087 |
+
def forward(
|
| 1088 |
+
self,
|
| 1089 |
+
x: torch.Tensor,
|
| 1090 |
+
freqs_cis: Optional[torch.Tensor] = None,
|
| 1091 |
+
past_key_value: Optional[DynamicCache] = None,
|
| 1092 |
+
use_cache: bool = False,
|
| 1093 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1094 |
+
freqs_cis_fn: Optional[Any] = None,
|
| 1095 |
+
global_modulation: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
|
| 1096 |
+
reset_clock: bool = False,
|
| 1097 |
+
metric_grad_scale: float = 0.03,
|
| 1098 |
+
return_clock_info: bool = False,
|
| 1099 |
+
):
|
| 1100 |
+
if freqs_cis_fn is None or not self.use_symplectic_rope:
|
| 1101 |
+
x = x + self.attn(
|
| 1102 |
+
self.ln_1(x),
|
| 1103 |
+
freqs_cis,
|
| 1104 |
+
past_key_value=past_key_value if use_cache else None,
|
| 1105 |
+
use_cache=use_cache,
|
| 1106 |
+
attention_mask=attention_mask,
|
| 1107 |
+
)
|
| 1108 |
+
x = x + self.mlp(self.ln_2(x))
|
| 1109 |
+
if return_clock_info:
|
| 1110 |
+
return x, None
|
| 1111 |
+
return x
|
| 1112 |
+
|
| 1113 |
+
residual_pre = x
|
| 1114 |
+
pre_context = masked_sequence_mean(x, attention_mask)
|
| 1115 |
+
|
| 1116 |
+
theta_local, p_local = self.local_clock.evolve(pre_context, reset=reset_clock)
|
| 1117 |
+
z_local = torch.cat([theta_local, p_local], dim=-1)
|
| 1118 |
+
|
| 1119 |
+
if global_modulation is None:
|
| 1120 |
+
raise ValueError("global_modulation is required when using symplectic RoPE")
|
| 1121 |
+
|
| 1122 |
+
dm_global, da_global = global_modulation
|
| 1123 |
+
|
| 1124 |
+
dm_local, da_local = project_metric_delta(
|
| 1125 |
+
self.local_metric_proj,
|
| 1126 |
+
z_local,
|
| 1127 |
+
mass_scale=float(_safe_getattr(self.config, "metric_mass_local_scale", 0.015)),
|
| 1128 |
+
spin_scale=float(_safe_getattr(self.config, "metric_spin_local_scale", 0.050)),
|
| 1129 |
+
grad_scale=metric_grad_scale,
|
| 1130 |
+
)
|
| 1131 |
+
|
| 1132 |
+
dm_block = dm_global + dm_local
|
| 1133 |
+
da_block = da_global + da_local
|
| 1134 |
+
block_freqs_cis = freqs_cis_fn(dm_block, da_block)
|
| 1135 |
+
|
| 1136 |
+
x = x + self.attn(
|
| 1137 |
+
self.ln_1(x),
|
| 1138 |
+
block_freqs_cis,
|
| 1139 |
+
past_key_value=past_key_value if use_cache else None,
|
| 1140 |
+
use_cache=use_cache,
|
| 1141 |
+
attention_mask=attention_mask,
|
| 1142 |
+
)
|
| 1143 |
+
x = x + self.mlp(self.ln_2(x))
|
| 1144 |
+
|
| 1145 |
+
residual_delta = masked_sequence_mean(x - residual_pre, attention_mask)
|
| 1146 |
+
|
| 1147 |
+
# Runtime memory update only. It should affect future cached decoding
|
| 1148 |
+
# steps, not burn graph memory during training.
|
| 1149 |
+
with torch.no_grad():
|
| 1150 |
+
self.local_clock.evolve(
|
| 1151 |
+
pre_context.detach(),
|
| 1152 |
+
reset=False,
|
| 1153 |
+
residual_delta=residual_delta.detach(),
|
| 1154 |
+
)
|
| 1155 |
+
|
| 1156 |
+
info = {
|
| 1157 |
+
"pre_context": pre_context,
|
| 1158 |
+
"residual_delta": residual_delta,
|
| 1159 |
+
"z_local": z_local,
|
| 1160 |
+
"dm_local": dm_local,
|
| 1161 |
+
"da_local": da_local,
|
| 1162 |
+
}
|
| 1163 |
+
|
| 1164 |
+
if return_clock_info:
|
| 1165 |
+
return x, info
|
| 1166 |
+
return x
|
| 1167 |
+
|
| 1168 |
+
|
| 1169 |
+
# =============================================================================
|
| 1170 |
+
# Model
|
| 1171 |
+
# =============================================================================
|
| 1172 |
+
|
| 1173 |
+
|
| 1174 |
+
class GPTX2PreTrainedModel(PreTrainedModel):
|
| 1175 |
+
config_class = GPTX2Config
|
| 1176 |
+
base_model_prefix = "transformer"
|
| 1177 |
+
supports_gradient_checkpointing = False
|
| 1178 |
+
|
| 1179 |
+
def _init_weights(self, module: nn.Module) -> None:
|
| 1180 |
+
std = 0.02
|
| 1181 |
+
if hasattr(module, "NANOGPT_SCALE_INIT"):
|
| 1182 |
+
std *= (2 * self.config.num_hidden_layers) ** -0.5
|
| 1183 |
+
|
| 1184 |
+
if isinstance(module, nn.Linear):
|
| 1185 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=std)
|
| 1186 |
+
if module.bias is not None:
|
| 1187 |
+
torch.nn.init.zeros_(module.bias)
|
| 1188 |
+
elif isinstance(module, nn.Embedding):
|
| 1189 |
+
torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 1190 |
+
|
| 1191 |
+
|
| 1192 |
+
class GPTX2ForCausalLM(GPTX2PreTrainedModel, GenerationMixin):
|
| 1193 |
+
_tied_weights_keys = ["lm_head.weight"]
|
| 1194 |
+
|
| 1195 |
+
def __init__(self, config: GPTX2Config):
|
| 1196 |
+
super().__init__(config)
|
| 1197 |
+
self.config = config
|
| 1198 |
+
self.use_symplectic_rope = bool(_safe_getattr(config, "use_symplectic_rope", False))
|
| 1199 |
+
|
| 1200 |
+
self.transformer = nn.ModuleDict(
|
| 1201 |
+
dict(
|
| 1202 |
+
wte=nn.Embedding(config.vocab_size, config.hidden_size),
|
| 1203 |
+
h=nn.ModuleList([GPTX2Block(config, i) for i in range(config.num_hidden_layers)]),
|
| 1204 |
+
ln_f=RMSNorm(config.hidden_size, eps=config.rms_norm_eps),
|
| 1205 |
+
)
|
| 1206 |
+
)
|
| 1207 |
+
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 1208 |
+
|
| 1209 |
+
if config.tie_word_embeddings:
|
| 1210 |
+
self.lm_head.weight = self.transformer["wte"].weight
|
| 1211 |
+
|
| 1212 |
+
if self.use_symplectic_rope:
|
| 1213 |
+
global_k = int(_safe_getattr(config, "symplectic_global_k_dim", 32))
|
| 1214 |
+
self.global_clock = SymplecticClock(
|
| 1215 |
+
k_dim=global_k,
|
| 1216 |
+
embed_dim=config.hidden_size,
|
| 1217 |
+
dt=float(_safe_getattr(config, "symplectic_global_dt", 0.02)),
|
| 1218 |
+
n_steps=int(_safe_getattr(config, "symplectic_n_steps", 2)),
|
| 1219 |
+
context_scale=float(_safe_getattr(config, "symplectic_context_scale", 0.01)),
|
| 1220 |
+
momentum_inject_scale=float(_safe_getattr(config, "symplectic_momentum_inject_scale", 0.025)),
|
| 1221 |
+
)
|
| 1222 |
+
self.global_metric_proj = nn.Linear(2 * global_k, 2)
|
| 1223 |
+
|
| 1224 |
+
self._embd_scale = math.sqrt(config.hidden_size)
|
| 1225 |
+
self._freqs_cis_cache: Optional[torch.Tensor] = None
|
| 1226 |
+
self._last_clock_stats: Optional[Dict[str, torch.Tensor]] = None
|
| 1227 |
+
|
| 1228 |
+
self.post_init()
|
| 1229 |
+
self._reset_symplectic_init()
|
| 1230 |
+
|
| 1231 |
+
def _reset_symplectic_init(self) -> None:
|
| 1232 |
+
"""Restore identity-safe initialization after HF post_init touches new modules."""
|
| 1233 |
+
if not self.use_symplectic_rope:
|
| 1234 |
+
return
|
| 1235 |
+
|
| 1236 |
+
self.global_clock.reset_parameters()
|
| 1237 |
+
zero_init_linear(self.global_metric_proj)
|
| 1238 |
+
|
| 1239 |
+
for block in self.transformer["h"]:
|
| 1240 |
+
if hasattr(block, "local_clock"):
|
| 1241 |
+
block.local_clock.reset_parameters()
|
| 1242 |
+
if hasattr(block, "local_metric_proj"):
|
| 1243 |
+
zero_init_linear(block.local_metric_proj)
|
| 1244 |
+
|
| 1245 |
+
def reset_clock_states(self, batch_size: int, device: torch.device) -> None:
|
| 1246 |
+
if not self.use_symplectic_rope:
|
| 1247 |
+
return
|
| 1248 |
+
|
| 1249 |
+
self.global_clock.reset_state(batch_size, device)
|
| 1250 |
+
for block in self.transformer["h"]:
|
| 1251 |
+
block.reset_clock_state(batch_size, device)
|
| 1252 |
+
|
| 1253 |
+
def _reorder_cache(self, past_key_values, beam_idx):
|
| 1254 |
+
"""Keep DynamicCache and Hamiltonian clock states in the same beam order."""
|
| 1255 |
+
if past_key_values is not None:
|
| 1256 |
+
if hasattr(past_key_values, "reorder_cache"):
|
| 1257 |
+
past_key_values.reorder_cache(beam_idx)
|
| 1258 |
+
elif hasattr(past_key_values, "batch_select_indices"):
|
| 1259 |
+
past_key_values.batch_select_indices(beam_idx)
|
| 1260 |
+
|
| 1261 |
+
if self.use_symplectic_rope:
|
| 1262 |
+
self.global_clock.reorder_state(beam_idx)
|
| 1263 |
+
for block in self.transformer["h"]:
|
| 1264 |
+
block.reorder_clock_state(beam_idx)
|
| 1265 |
+
|
| 1266 |
+
return past_key_values
|
| 1267 |
+
|
| 1268 |
+
def get_input_embeddings(self):
|
| 1269 |
+
return self.transformer["wte"]
|
| 1270 |
+
|
| 1271 |
+
def set_input_embeddings(self, value):
|
| 1272 |
+
self.transformer["wte"] = value
|
| 1273 |
+
|
| 1274 |
+
def get_output_embeddings(self):
|
| 1275 |
+
return self.lm_head
|
| 1276 |
+
|
| 1277 |
+
def set_output_embeddings(self, new_embeddings):
|
| 1278 |
+
self.lm_head = new_embeddings
|
| 1279 |
+
|
| 1280 |
+
def prepare_inputs_for_generation(
|
| 1281 |
+
self,
|
| 1282 |
+
input_ids,
|
| 1283 |
+
past_key_values=None,
|
| 1284 |
+
attention_mask=None,
|
| 1285 |
+
position_ids=None,
|
| 1286 |
+
cache_position=None,
|
| 1287 |
+
**kwargs,
|
| 1288 |
+
):
|
| 1289 |
+
if past_key_values is not None:
|
| 1290 |
+
try:
|
| 1291 |
+
past_len = past_key_values.get_seq_length()
|
| 1292 |
+
except TypeError:
|
| 1293 |
+
past_len = past_key_values.get_seq_length(0)
|
| 1294 |
+
if past_len > 0:
|
| 1295 |
+
input_ids = input_ids[:, -1:]
|
| 1296 |
+
|
| 1297 |
+
if position_ids is None and attention_mask is not None:
|
| 1298 |
+
pos = attention_mask.long().cumsum(dim=-1) - 1
|
| 1299 |
+
pos = pos.clamp_min(0)
|
| 1300 |
+
position_ids = pos[:, -input_ids.shape[1]:]
|
| 1301 |
+
|
| 1302 |
+
return {
|
| 1303 |
+
"input_ids": input_ids,
|
| 1304 |
+
"attention_mask": attention_mask,
|
| 1305 |
+
"position_ids": position_ids,
|
| 1306 |
+
"past_key_values": past_key_values,
|
| 1307 |
+
"use_cache": True,
|
| 1308 |
+
"cache_position": cache_position,
|
| 1309 |
+
}
|
| 1310 |
+
|
| 1311 |
+
def _get_freqs_cis_by_position(self, position_ids: torch.Tensor, device: torch.device) -> torch.Tensor:
|
| 1312 |
+
max_pos = int(position_ids.detach().max().item()) + 1
|
| 1313 |
+
max_pos = max(max_pos, 1)
|
| 1314 |
+
|
| 1315 |
+
cache = self._freqs_cis_cache
|
| 1316 |
+
if cache is None or cache.device != device or cache.size(0) < max_pos:
|
| 1317 |
+
cache = precompute_freqs_cis(
|
| 1318 |
+
head_dim=self.config.head_dim,
|
| 1319 |
+
seq_len=max_pos,
|
| 1320 |
+
theta=self.config.rope_theta,
|
| 1321 |
+
device=device,
|
| 1322 |
+
rope_scaling=_safe_getattr(self.config, "rope_scaling", None),
|
| 1323 |
+
max_position_embeddings=int(_safe_getattr(self.config, "max_position_embeddings", 32768)),
|
| 1324 |
+
)
|
| 1325 |
+
self._freqs_cis_cache = cache
|
| 1326 |
+
|
| 1327 |
+
return cache[position_ids]
|
| 1328 |
+
|
| 1329 |
+
def _build_clock_freqs_fn(self, position_ids: torch.Tensor, device: torch.device):
|
| 1330 |
+
max_pos = int(position_ids.detach().max().item()) + 1
|
| 1331 |
+
max_pos = max(max_pos, 1)
|
| 1332 |
+
|
| 1333 |
+
def freqs_cis_fn(dm: torch.Tensor, da: torch.Tensor) -> torch.Tensor:
|
| 1334 |
+
table = compute_metric_warped_freqs_cis(
|
| 1335 |
+
head_dim=self.config.head_dim,
|
| 1336 |
+
seq_len=max_pos,
|
| 1337 |
+
theta_base=self.config.rope_theta,
|
| 1338 |
+
mass_delta=dm,
|
| 1339 |
+
spin_delta=da,
|
| 1340 |
+
device=device,
|
| 1341 |
+
rope_scaling=_safe_getattr(self.config, "rope_scaling", None),
|
| 1342 |
+
max_position_embeddings=int(_safe_getattr(self.config, "max_position_embeddings", 32768)),
|
| 1343 |
+
radial_base=float(_safe_getattr(self.config, "metric_radial_base", 256.0)),
|
| 1344 |
+
)
|
| 1345 |
+
return table[position_ids]
|
| 1346 |
+
|
| 1347 |
+
return freqs_cis_fn
|
| 1348 |
+
|
| 1349 |
+
def _make_clock_diagnostics(
|
| 1350 |
+
self,
|
| 1351 |
+
dm_global: torch.Tensor,
|
| 1352 |
+
da_global: torch.Tensor,
|
| 1353 |
+
local_metric_values: List[Tuple[torch.Tensor, torch.Tensor]],
|
| 1354 |
+
clock_states: List[torch.Tensor],
|
| 1355 |
+
) -> Dict[str, torch.Tensor]:
|
| 1356 |
+
with torch.no_grad():
|
| 1357 |
+
if local_metric_values:
|
| 1358 |
+
dm_local = torch.stack([v[0].detach().float() for v in local_metric_values])
|
| 1359 |
+
da_local = torch.stack([v[1].detach().float() for v in local_metric_values])
|
| 1360 |
+
else:
|
| 1361 |
+
dm_local = torch.zeros(1, device=dm_global.device)
|
| 1362 |
+
da_local = torch.zeros(1, device=dm_global.device)
|
| 1363 |
+
|
| 1364 |
+
if clock_states:
|
| 1365 |
+
state_norm = torch.stack([z.detach().float().norm() for z in clock_states]).mean()
|
| 1366 |
+
else:
|
| 1367 |
+
state_norm = torch.zeros((), device=dm_global.device)
|
| 1368 |
+
|
| 1369 |
+
return {
|
| 1370 |
+
"dm_global": dm_global.detach(),
|
| 1371 |
+
"da_global": da_global.detach(),
|
| 1372 |
+
"dm_local_mean": dm_local.mean(),
|
| 1373 |
+
"dm_local_abs_mean": dm_local.abs().mean(),
|
| 1374 |
+
"da_local_mean": da_local.mean(),
|
| 1375 |
+
"da_local_abs_mean": da_local.abs().mean(),
|
| 1376 |
+
"clock_state_norm_mean": state_norm,
|
| 1377 |
+
}
|
| 1378 |
+
|
| 1379 |
+
def get_clock_diagnostics(self, as_float: bool = True):
|
| 1380 |
+
stats = self._last_clock_stats
|
| 1381 |
+
if stats is None:
|
| 1382 |
+
return None
|
| 1383 |
+
if not as_float:
|
| 1384 |
+
return stats
|
| 1385 |
+
|
| 1386 |
+
out = {}
|
| 1387 |
+
for key, value in stats.items():
|
| 1388 |
+
if torch.is_tensor(value):
|
| 1389 |
+
out[key] = float(value.detach().cpu())
|
| 1390 |
+
else:
|
| 1391 |
+
out[key] = value
|
| 1392 |
+
return out
|
| 1393 |
+
|
| 1394 |
+
def forward(
|
| 1395 |
+
self,
|
| 1396 |
+
input_ids: torch.Tensor,
|
| 1397 |
+
attention_mask: Optional[torch.Tensor] = None,
|
| 1398 |
+
labels: Optional[torch.Tensor] = None,
|
| 1399 |
+
past_key_values: Optional[DynamicCache] = None,
|
| 1400 |
+
use_cache: bool = False,
|
| 1401 |
+
position_ids: Optional[torch.Tensor] = None,
|
| 1402 |
+
cache_position: Optional[torch.Tensor] = None,
|
| 1403 |
+
**kwargs: Any,
|
| 1404 |
+
) -> CausalLMOutputWithPast:
|
| 1405 |
+
batch_size, current_len = input_ids.size()
|
| 1406 |
+
|
| 1407 |
+
if use_cache and past_key_values is None:
|
| 1408 |
+
past_key_values = DynamicCache()
|
| 1409 |
+
|
| 1410 |
+
if past_key_values is not None:
|
| 1411 |
+
try:
|
| 1412 |
+
past_len = past_key_values.get_seq_length()
|
| 1413 |
+
except TypeError:
|
| 1414 |
+
past_len = past_key_values.get_seq_length(0)
|
| 1415 |
+
else:
|
| 1416 |
+
past_len = 0
|
| 1417 |
+
|
| 1418 |
+
if position_ids is None:
|
| 1419 |
+
position_ids = make_position_ids(input_ids, attention_mask, past_len)
|
| 1420 |
+
else:
|
| 1421 |
+
position_ids = position_ids.to(device=input_ids.device)
|
| 1422 |
+
|
| 1423 |
+
x = self.transformer["wte"](input_ids) * self._embd_scale
|
| 1424 |
+
|
| 1425 |
+
local_metric_values: List[Tuple[torch.Tensor, torch.Tensor]] = []
|
| 1426 |
+
clock_states: List[torch.Tensor] = []
|
| 1427 |
+
clock_reg: Optional[torch.Tensor] = None
|
| 1428 |
+
|
| 1429 |
+
if not self.use_symplectic_rope:
|
| 1430 |
+
freqs_cis = self._get_freqs_cis_by_position(position_ids, input_ids.device)
|
| 1431 |
+
for block in self.transformer["h"]:
|
| 1432 |
+
x = block(
|
| 1433 |
+
x,
|
| 1434 |
+
freqs_cis=freqs_cis,
|
| 1435 |
+
past_key_value=past_key_values if use_cache else None,
|
| 1436 |
+
use_cache=use_cache,
|
| 1437 |
+
attention_mask=attention_mask,
|
| 1438 |
+
)
|
| 1439 |
+
self._last_clock_stats = None
|
| 1440 |
+
|
| 1441 |
+
else:
|
| 1442 |
+
reset_clocks = past_len == 0
|
| 1443 |
+
metric_grad_scale = float(_safe_getattr(self.config, "metric_grad_scale", 0.03))
|
| 1444 |
+
|
| 1445 |
+
global_context = masked_sequence_mean(x, attention_mask)
|
| 1446 |
+
theta_g, p_g = self.global_clock.evolve(global_context, reset=reset_clocks)
|
| 1447 |
+
z_g = torch.cat([theta_g, p_g], dim=-1)
|
| 1448 |
+
clock_states.append(z_g)
|
| 1449 |
+
|
| 1450 |
+
dm_global, da_global = project_metric_delta(
|
| 1451 |
+
self.global_metric_proj,
|
| 1452 |
+
z_g,
|
| 1453 |
+
mass_scale=float(_safe_getattr(self.config, "metric_mass_global_scale", 0.020)),
|
| 1454 |
+
spin_scale=float(_safe_getattr(self.config, "metric_spin_global_scale", 0.050)),
|
| 1455 |
+
grad_scale=metric_grad_scale,
|
| 1456 |
+
)
|
| 1457 |
+
|
| 1458 |
+
freqs_cis_fn = self._build_clock_freqs_fn(position_ids=position_ids, device=input_ids.device)
|
| 1459 |
+
block_residual_pairs: List[Tuple[torch.Tensor, torch.Tensor]] = []
|
| 1460 |
+
|
| 1461 |
+
for block in self.transformer["h"]:
|
| 1462 |
+
x, info = block(
|
| 1463 |
+
x,
|
| 1464 |
+
freqs_cis_fn=freqs_cis_fn,
|
| 1465 |
+
past_key_value=past_key_values if use_cache else None,
|
| 1466 |
+
use_cache=use_cache,
|
| 1467 |
+
attention_mask=attention_mask,
|
| 1468 |
+
global_modulation=(dm_global, da_global),
|
| 1469 |
+
reset_clock=reset_clocks,
|
| 1470 |
+
metric_grad_scale=metric_grad_scale,
|
| 1471 |
+
return_clock_info=True,
|
| 1472 |
+
)
|
| 1473 |
+
|
| 1474 |
+
if info is not None:
|
| 1475 |
+
local_metric_values.append((info["dm_local"], info["da_local"]))
|
| 1476 |
+
clock_states.append(info["z_local"])
|
| 1477 |
+
block_residual_pairs.append((info["pre_context"], info["residual_delta"]))
|
| 1478 |
+
|
| 1479 |
+
if block_residual_pairs:
|
| 1480 |
+
mean_pre = torch.stack([pair[0] for pair in block_residual_pairs], dim=0).mean(dim=0)
|
| 1481 |
+
mean_delta = torch.stack([pair[1] for pair in block_residual_pairs], dim=0).mean(dim=0)
|
| 1482 |
+
|
| 1483 |
+
with torch.no_grad():
|
| 1484 |
+
self.global_clock.evolve(
|
| 1485 |
+
mean_pre.detach(),
|
| 1486 |
+
reset=False,
|
| 1487 |
+
residual_delta=mean_delta.detach(),
|
| 1488 |
+
)
|
| 1489 |
+
|
| 1490 |
+
clock_reg = clock_regularization(
|
| 1491 |
+
dm_global=dm_global,
|
| 1492 |
+
da_global=da_global,
|
| 1493 |
+
local_metric_values=local_metric_values,
|
| 1494 |
+
clock_states=clock_states,
|
| 1495 |
+
lambda_metric=float(_safe_getattr(self.config, "clock_metric_reg_coeff", 1e-4)),
|
| 1496 |
+
lambda_state=float(_safe_getattr(self.config, "clock_state_reg_coeff", 1e-5)),
|
| 1497 |
+
lambda_smooth=float(_safe_getattr(self.config, "clock_smooth_reg_coeff", 1e-4)),
|
| 1498 |
+
)
|
| 1499 |
+
|
| 1500 |
+
self._last_clock_stats = self._make_clock_diagnostics(
|
| 1501 |
+
dm_global=dm_global,
|
| 1502 |
+
da_global=da_global,
|
| 1503 |
+
local_metric_values=local_metric_values,
|
| 1504 |
+
clock_states=clock_states,
|
| 1505 |
+
)
|
| 1506 |
+
|
| 1507 |
+
x = self.transformer["ln_f"](x)
|
| 1508 |
+
logits = self.lm_head(x)
|
| 1509 |
+
|
| 1510 |
+
loss = None
|
| 1511 |
+
if labels is not None:
|
| 1512 |
+
loss = safe_lm_cross_entropy(logits, labels)
|
| 1513 |
+
|
| 1514 |
+
z_coeff = float(_safe_getattr(self.config, "z_loss_coeff", 0.0))
|
| 1515 |
+
if z_coeff > 0.0:
|
| 1516 |
+
log_z = torch.logsumexp(logits.float(), dim=-1)
|
| 1517 |
+
loss = loss + z_coeff * log_z.square().mean()
|
| 1518 |
+
|
| 1519 |
+
logit_l2_coeff = float(_safe_getattr(self.config, "logit_l2_coeff", 0.0))
|
| 1520 |
+
if logit_l2_coeff > 0.0:
|
| 1521 |
+
loss = loss + logit_l2_coeff * logits.float().square().mean()
|
| 1522 |
+
|
| 1523 |
+
clock_reg_coeff = float(_safe_getattr(self.config, "clock_reg_coeff", 0.0))
|
| 1524 |
+
if clock_reg is not None and clock_reg_coeff > 0.0:
|
| 1525 |
+
loss = loss + clock_reg_coeff * clock_reg
|
| 1526 |
+
|
| 1527 |
+
return CausalLMOutputWithPast(
|
| 1528 |
+
loss=loss,
|
| 1529 |
+
logits=logits,
|
| 1530 |
+
past_key_values=past_key_values if use_cache else None,
|
| 1531 |
+
)
|
| 1532 |
+
|
| 1533 |
+
|
| 1534 |
+
# =============================================================================
|
| 1535 |
+
# Convenience construction helpers
|
| 1536 |
+
# =============================================================================
|
| 1537 |
+
|
| 1538 |
+
|
| 1539 |
+
def enable_symplectic_rope_for_config(
|
| 1540 |
+
config: GPTX2Config,
|
| 1541 |
+
*,
|
| 1542 |
+
cautious: bool = True,
|
| 1543 |
+
max_position_embeddings: Optional[int] = 32768,
|
| 1544 |
+
) -> GPTX2Config:
|
| 1545 |
+
"""Mutate and return a config with the governor enabled.
|
| 1546 |
+
|
| 1547 |
+
Use this before constructing/loading the model when adding the governor to
|
| 1548 |
+
an existing checkpoint. Missing governor weights will initialize safely.
|
| 1549 |
+
"""
|
| 1550 |
+
config.use_symplectic_rope = True
|
| 1551 |
+
|
| 1552 |
+
if max_position_embeddings is not None:
|
| 1553 |
+
config.max_position_embeddings = int(max_position_embeddings)
|
| 1554 |
+
|
| 1555 |
+
if cautious:
|
| 1556 |
+
config.metric_grad_scale = 0.01
|
| 1557 |
+
config.metric_mass_global_scale = 0.005
|
| 1558 |
+
config.metric_spin_global_scale = 0.010
|
| 1559 |
+
config.metric_mass_local_scale = 0.003
|
| 1560 |
+
config.metric_spin_local_scale = 0.010
|
| 1561 |
+
config.clock_reg_coeff = 1.0
|
| 1562 |
+
config.clock_metric_reg_coeff = 1e-4
|
| 1563 |
+
config.clock_state_reg_coeff = 1e-5
|
| 1564 |
+
config.clock_smooth_reg_coeff = 1e-4
|
| 1565 |
+
|
| 1566 |
+
return config
|
| 1567 |
+
|
| 1568 |
+
|
| 1569 |
+
def make_cix_optimizer(
|
| 1570 |
+
model: nn.Module,
|
| 1571 |
+
*,
|
| 1572 |
+
lr: float = 1e-4,
|
| 1573 |
+
weight_decay: float = 0.01,
|
| 1574 |
+
governor_lr_mult: float = 0.25,
|
| 1575 |
+
betas: Tuple[float, float] = (0.9, 0.99),
|
| 1576 |
+
eps: float = 1e-8,
|
| 1577 |
+
foreach: bool = True,
|
| 1578 |
+
) -> CIxOpt:
|
| 1579 |
+
groups = build_cix_param_groups(
|
| 1580 |
+
model,
|
| 1581 |
+
base_lr=lr,
|
| 1582 |
+
weight_decay=weight_decay,
|
| 1583 |
+
governor_lr_mult=governor_lr_mult,
|
| 1584 |
+
force_governor_adam=True,
|
| 1585 |
+
)
|
| 1586 |
+
|
| 1587 |
+
opt = CIxOpt(
|
| 1588 |
+
groups,
|
| 1589 |
+
lr=lr,
|
| 1590 |
+
betas=betas,
|
| 1591 |
+
eps=eps,
|
| 1592 |
+
weight_decay=weight_decay,
|
| 1593 |
+
foreach=foreach,
|
| 1594 |
+
state_dtype=torch.float32,
|
| 1595 |
+
grad_centralize=True,
|
| 1596 |
+
caution=True,
|
| 1597 |
+
)
|
| 1598 |
+
opt.register_param_names(model.named_parameters())
|
| 1599 |
+
return opt
|