Clean up: Delete 40 training checkpoint directories
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- checkpoint-1000/chat_template.jinja +0 -4
- checkpoint-1000/config.json +0 -62
- checkpoint-1000/configuration_surjo.py +0 -148
- checkpoint-1000/generation_config.json +0 -7
- checkpoint-1000/model.safetensors +0 -3
- checkpoint-1000/modeling_surjo.py +0 -926
- checkpoint-1000/optimizer.bin +0 -3
- checkpoint-1000/optimizer_1.bin +0 -3
- checkpoint-1000/random_states_0.pkl +0 -3
- checkpoint-1000/tokenizer.json +0 -0
- checkpoint-1000/tokenizer_config.json +0 -85
- checkpoint-10000/chat_template.jinja +0 -4
- checkpoint-10000/config.json +0 -62
- checkpoint-10000/configuration_surjo.py +0 -148
- checkpoint-10000/generation_config.json +0 -7
- checkpoint-10000/model.safetensors +0 -3
- checkpoint-10000/modeling_surjo.py +0 -926
- checkpoint-10000/optimizer.bin +0 -3
- checkpoint-10000/optimizer_1.bin +0 -3
- checkpoint-10000/random_states_0.pkl +0 -3
- checkpoint-10000/tokenizer.json +0 -0
- checkpoint-10000/tokenizer_config.json +0 -85
- checkpoint-10500/chat_template.jinja +0 -4
- checkpoint-10500/config.json +0 -62
- checkpoint-10500/configuration_surjo.py +0 -148
- checkpoint-10500/generation_config.json +0 -7
- checkpoint-10500/model.safetensors +0 -3
- checkpoint-10500/modeling_surjo.py +0 -926
- checkpoint-10500/optimizer.bin +0 -3
- checkpoint-10500/optimizer_1.bin +0 -3
- checkpoint-10500/random_states_0.pkl +0 -3
- checkpoint-10500/tokenizer.json +0 -0
- checkpoint-10500/tokenizer_config.json +0 -85
- checkpoint-11000/chat_template.jinja +0 -4
- checkpoint-11000/config.json +0 -62
- checkpoint-11000/configuration_surjo.py +0 -148
- checkpoint-11000/generation_config.json +0 -7
- checkpoint-11000/model.safetensors +0 -3
- checkpoint-11000/modeling_surjo.py +0 -926
- checkpoint-11000/optimizer.bin +0 -3
- checkpoint-11000/optimizer_1.bin +0 -3
- checkpoint-11000/random_states_0.pkl +0 -3
- checkpoint-11000/tokenizer.json +0 -0
- checkpoint-11000/tokenizer_config.json +0 -85
- checkpoint-11500/chat_template.jinja +0 -4
- checkpoint-11500/config.json +0 -62
- checkpoint-11500/configuration_surjo.py +0 -148
- checkpoint-11500/generation_config.json +0 -7
- checkpoint-11500/model.safetensors +0 -3
- checkpoint-11500/modeling_surjo.py +0 -926
checkpoint-1000/chat_template.jinja
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
-
' + message['content'] + '<|im_end|>
|
| 3 |
-
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
-
' }}{% endif %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/config.json
DELETED
|
@@ -1,62 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_use_flash_xsa": true,
|
| 3 |
-
"architectures": [
|
| 4 |
-
"SurjoForCausalLM"
|
| 5 |
-
],
|
| 6 |
-
"attention_bias": false,
|
| 7 |
-
"attention_dropout": 0.0,
|
| 8 |
-
"auto_map": {
|
| 9 |
-
"AutoConfig": "configuration_surjo.SurjoConfig",
|
| 10 |
-
"AutoModel": "modeling_surjo.SurjoForCausalLM",
|
| 11 |
-
"AutoModelForCausalLM": "modeling_surjo.SurjoForCausalLM"
|
| 12 |
-
},
|
| 13 |
-
"coda_layers": 1,
|
| 14 |
-
"dtype": "float32",
|
| 15 |
-
"gdn_allow_neg_eigval": false,
|
| 16 |
-
"gdn_conv_kernel_size": 4,
|
| 17 |
-
"gdn_key_dim": 64,
|
| 18 |
-
"gdn_num_v_heads": 8,
|
| 19 |
-
"gdn_per_xsa": 3,
|
| 20 |
-
"gdn_value_dim": 64,
|
| 21 |
-
"gradient_checkpointing": false,
|
| 22 |
-
"head_dim": 64,
|
| 23 |
-
"hidden_act": "silu",
|
| 24 |
-
"hidden_size": 512,
|
| 25 |
-
"initializer_range": 0.02,
|
| 26 |
-
"intermediate_size": 1536,
|
| 27 |
-
"layer_types": [
|
| 28 |
-
"full_attention",
|
| 29 |
-
"linear_attention",
|
| 30 |
-
"linear_attention",
|
| 31 |
-
"linear_attention",
|
| 32 |
-
"full_attention",
|
| 33 |
-
"linear_attention",
|
| 34 |
-
"linear_attention",
|
| 35 |
-
"linear_attention",
|
| 36 |
-
"full_attention",
|
| 37 |
-
"full_attention"
|
| 38 |
-
],
|
| 39 |
-
"loop_noise_std": 0.02,
|
| 40 |
-
"max_position_embeddings": 2048,
|
| 41 |
-
"model_type": "surjo",
|
| 42 |
-
"num_attention_heads": 8,
|
| 43 |
-
"num_groups": 2,
|
| 44 |
-
"num_hidden_layers": 10,
|
| 45 |
-
"num_key_value_heads": 4,
|
| 46 |
-
"partial_rotary_factor": 1.0,
|
| 47 |
-
"prelude_layers": 1,
|
| 48 |
-
"recurrent_layers": 8,
|
| 49 |
-
"recurrent_passes": 2,
|
| 50 |
-
"rms_norm_eps": 1e-05,
|
| 51 |
-
"rope_parameters": {
|
| 52 |
-
"partial_rotary_factor": 1.0,
|
| 53 |
-
"rope_theta": 10000.0,
|
| 54 |
-
"rope_type": "default"
|
| 55 |
-
},
|
| 56 |
-
"rope_theta": 10000.0,
|
| 57 |
-
"tie_word_embeddings": true,
|
| 58 |
-
"transformers_version": "5.16.1",
|
| 59 |
-
"use_cache": false,
|
| 60 |
-
"vocab_size": 32768,
|
| 61 |
-
"xsa_projection": true
|
| 62 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/configuration_surjo.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""Surjo gen-3 model configuration."""
|
| 5 |
-
|
| 6 |
-
from typing import List, Optional
|
| 7 |
-
from transformers import PretrainedConfig
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
class SurjoConfig(PretrainedConfig):
|
| 11 |
-
r"""Configuration for the Surjo gen-3 hybrid architecture."""
|
| 12 |
-
|
| 13 |
-
model_type = "surjo"
|
| 14 |
-
keys_to_ignore_at_inference = ["past_key_values"]
|
| 15 |
-
|
| 16 |
-
def __init__(
|
| 17 |
-
self,
|
| 18 |
-
vocab_size: int = 50257,
|
| 19 |
-
hidden_size: int = 384,
|
| 20 |
-
intermediate_size: int = 1024,
|
| 21 |
-
num_attention_heads: int = 6,
|
| 22 |
-
num_key_value_heads: int = 2,
|
| 23 |
-
head_dim: int = 64,
|
| 24 |
-
hidden_act: str = "silu",
|
| 25 |
-
max_position_embeddings: int = 2048,
|
| 26 |
-
initializer_range: float = 0.02,
|
| 27 |
-
rms_norm_eps: float = 1e-6,
|
| 28 |
-
tie_word_embeddings: bool = True,
|
| 29 |
-
rope_theta: float = 10000.0,
|
| 30 |
-
attention_dropout: float = 0.0,
|
| 31 |
-
attention_bias: bool = False,
|
| 32 |
-
prelude_layers: int = 1,
|
| 33 |
-
recurrent_layers: int = 8,
|
| 34 |
-
coda_layers: int = 1,
|
| 35 |
-
recurrent_passes: int = 2,
|
| 36 |
-
loop_noise_std: float = 0.02,
|
| 37 |
-
gdn_per_xsa: int = 3,
|
| 38 |
-
gdn_key_dim: Optional[int] = None,
|
| 39 |
-
gdn_value_dim: Optional[int] = None,
|
| 40 |
-
gdn_num_v_heads: Optional[int] = None,
|
| 41 |
-
gdn_conv_kernel_size: int = 4,
|
| 42 |
-
gdn_allow_neg_eigval: bool = False,
|
| 43 |
-
xsa_projection: bool = True,
|
| 44 |
-
rope_parameters: Optional[dict] = None,
|
| 45 |
-
rope_scaling: Optional[dict] = None,
|
| 46 |
-
partial_rotary_factor: float = 1.0,
|
| 47 |
-
gradient_checkpointing: bool = False,
|
| 48 |
-
use_cache: bool = True,
|
| 49 |
-
**kwargs,
|
| 50 |
-
):
|
| 51 |
-
self.vocab_size = vocab_size
|
| 52 |
-
self.hidden_size = hidden_size
|
| 53 |
-
self.intermediate_size = intermediate_size
|
| 54 |
-
self.num_attention_heads = num_attention_heads
|
| 55 |
-
self.num_key_value_heads = num_key_value_heads
|
| 56 |
-
self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads
|
| 57 |
-
self.hidden_act = hidden_act
|
| 58 |
-
self.max_position_embeddings = max_position_embeddings
|
| 59 |
-
self.initializer_range = initializer_range
|
| 60 |
-
self.rms_norm_eps = rms_norm_eps
|
| 61 |
-
self.tie_word_embeddings = tie_word_embeddings
|
| 62 |
-
self.rope_theta = rope_theta
|
| 63 |
-
self.attention_dropout = attention_dropout
|
| 64 |
-
self.attention_bias = attention_bias
|
| 65 |
-
|
| 66 |
-
self.prelude_layers = prelude_layers
|
| 67 |
-
self.recurrent_layers = recurrent_layers
|
| 68 |
-
self.coda_layers = coda_layers
|
| 69 |
-
self.recurrent_passes = recurrent_passes
|
| 70 |
-
self.loop_noise_std = loop_noise_std
|
| 71 |
-
self.gdn_per_xsa = gdn_per_xsa
|
| 72 |
-
|
| 73 |
-
self.gdn_key_dim = gdn_key_dim if gdn_key_dim is not None else self.head_dim
|
| 74 |
-
self.gdn_value_dim = gdn_value_dim if gdn_value_dim is not None else self.head_dim
|
| 75 |
-
self.gdn_num_v_heads = (
|
| 76 |
-
gdn_num_v_heads if gdn_num_v_heads is not None else num_attention_heads
|
| 77 |
-
)
|
| 78 |
-
self.gdn_conv_kernel_size = gdn_conv_kernel_size
|
| 79 |
-
self.gdn_allow_neg_eigval = gdn_allow_neg_eigval
|
| 80 |
-
|
| 81 |
-
self.xsa_projection = xsa_projection
|
| 82 |
-
|
| 83 |
-
if rope_parameters is not None:
|
| 84 |
-
self.rope_parameters = dict(rope_parameters)
|
| 85 |
-
elif rope_scaling is not None:
|
| 86 |
-
self.rope_parameters = dict(rope_scaling)
|
| 87 |
-
else:
|
| 88 |
-
self.rope_parameters = {"rope_type": "default"}
|
| 89 |
-
self.rope_parameters.setdefault("rope_type", "default")
|
| 90 |
-
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
| 91 |
-
if self.rope_parameters.get("rope_type") != "default":
|
| 92 |
-
self.rope_parameters.setdefault("factor", 1.0)
|
| 93 |
-
self.rope_scaling = dict(self.rope_parameters)
|
| 94 |
-
self.partial_rotary_factor = partial_rotary_factor
|
| 95 |
-
|
| 96 |
-
self.gradient_checkpointing = gradient_checkpointing
|
| 97 |
-
self.use_cache = use_cache
|
| 98 |
-
|
| 99 |
-
group = gdn_per_xsa + 1
|
| 100 |
-
if recurrent_layers % group != 0:
|
| 101 |
-
raise ValueError(
|
| 102 |
-
f"recurrent_layers ({recurrent_layers}) must be divisible by "
|
| 103 |
-
f"gdn_per_xsa + 1 = {group}"
|
| 104 |
-
)
|
| 105 |
-
if num_attention_heads % num_key_value_heads != 0:
|
| 106 |
-
raise ValueError(
|
| 107 |
-
f"num_attention_heads ({num_attention_heads}) must be divisible by "
|
| 108 |
-
f"num_key_value_heads ({num_key_value_heads})"
|
| 109 |
-
)
|
| 110 |
-
if (
|
| 111 |
-
self.gdn_num_v_heads < num_attention_heads
|
| 112 |
-
or self.gdn_num_v_heads % num_attention_heads != 0
|
| 113 |
-
):
|
| 114 |
-
raise ValueError(
|
| 115 |
-
f"gdn_num_v_heads ({self.gdn_num_v_heads}) must be >= "
|
| 116 |
-
f"num_attention_heads ({num_attention_heads}) and divisible by it"
|
| 117 |
-
)
|
| 118 |
-
valid_rope_types = {"default", "linear", "dynamic", "yarn", "longrope", "llama3"}
|
| 119 |
-
rt = self.rope_parameters.get("rope_type", "default")
|
| 120 |
-
if rt not in valid_rope_types:
|
| 121 |
-
raise ValueError(f"rope_type must be one of {valid_rope_types}, got {rt}")
|
| 122 |
-
|
| 123 |
-
self.num_groups = recurrent_layers // group
|
| 124 |
-
self.num_hidden_layers = prelude_layers + recurrent_layers + coda_layers
|
| 125 |
-
self.layer_types = self._build_layer_types()
|
| 126 |
-
|
| 127 |
-
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 128 |
-
|
| 129 |
-
def _build_layer_types(self) -> List[str]:
|
| 130 |
-
types = ["full_attention"] * self.prelude_layers
|
| 131 |
-
for _ in range(self.num_groups):
|
| 132 |
-
types.extend(["linear_attention"] * self.gdn_per_xsa)
|
| 133 |
-
types.append("full_attention")
|
| 134 |
-
types.extend(["full_attention"] * self.coda_layers)
|
| 135 |
-
assert len(types) == self.num_hidden_layers
|
| 136 |
-
return types
|
| 137 |
-
|
| 138 |
-
@property
|
| 139 |
-
def surjo_layer_types(self) -> List[str]:
|
| 140 |
-
return ["xsa" if t == "full_attention" else "gdn" for t in self.layer_types]
|
| 141 |
-
|
| 142 |
-
@property
|
| 143 |
-
def effective_num_layers(self) -> int:
|
| 144 |
-
return (
|
| 145 |
-
self.prelude_layers
|
| 146 |
-
+ self.recurrent_layers * self.recurrent_passes
|
| 147 |
-
+ self.coda_layers
|
| 148 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/generation_config.json
DELETED
|
@@ -1,7 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_from_model_config": true,
|
| 3 |
-
"output_attentions": false,
|
| 4 |
-
"output_hidden_states": false,
|
| 5 |
-
"transformers_version": "5.16.1",
|
| 6 |
-
"use_cache": false
|
| 7 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/model.safetensors
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:a5abd20d992673c35432854a3c7b3c0aa29b82981b300637d2e587e1330a57f4
|
| 3 |
-
size 215196728
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/modeling_surjo.py
DELETED
|
@@ -1,926 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""SurjoLabs Surjo Architecture"""
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
from typing import Dict, List, Optional, Tuple
|
| 8 |
-
|
| 9 |
-
import torch
|
| 10 |
-
import torch.nn as nn
|
| 11 |
-
import torch.nn.functional as F
|
| 12 |
-
import torch.utils.checkpoint
|
| 13 |
-
|
| 14 |
-
from transformers import PreTrainedModel
|
| 15 |
-
from transformers.activations import ACT2FN
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
from transformers import GenerationMixin
|
| 19 |
-
except ImportError:
|
| 20 |
-
from transformers.generation import GenerationMixin
|
| 21 |
-
from transformers.modeling_outputs import (
|
| 22 |
-
BaseModelOutputWithPast,
|
| 23 |
-
CausalLMOutputWithPast,
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
from .configuration_surjo import SurjoConfig
|
| 28 |
-
except (ImportError, ValueError):
|
| 29 |
-
from configuration_surjo import SurjoConfig
|
| 30 |
-
|
| 31 |
-
try:
|
| 32 |
-
from fla.modules.fused_linear_cross_entropy import (
|
| 33 |
-
fused_linear_cross_entropy_loss as _fla_flce,
|
| 34 |
-
)
|
| 35 |
-
except ImportError:
|
| 36 |
-
try:
|
| 37 |
-
from fla.modules import fused_linear_cross_entropy_loss as _fla_flce
|
| 38 |
-
except ImportError:
|
| 39 |
-
_fla_flce = None
|
| 40 |
-
|
| 41 |
-
try:
|
| 42 |
-
from fla.modules.norm import rms_norm as _fla_rms_norm
|
| 43 |
-
except ImportError:
|
| 44 |
-
try:
|
| 45 |
-
from fla.modules import rms_norm as _fla_rms_norm
|
| 46 |
-
except ImportError:
|
| 47 |
-
_fla_rms_norm = None
|
| 48 |
-
|
| 49 |
-
try:
|
| 50 |
-
from fla.ops.gdn2 import chunk_gdn2, fused_recurrent_gdn2
|
| 51 |
-
FLA_AVAILABLE = True
|
| 52 |
-
except ImportError:
|
| 53 |
-
chunk_gdn2 = None
|
| 54 |
-
fused_recurrent_gdn2 = None
|
| 55 |
-
FLA_AVAILABLE = False
|
| 56 |
-
|
| 57 |
-
_USE_FLA_FUSED_CE = True
|
| 58 |
-
_USE_FLA_RMS_NORM = False
|
| 59 |
-
|
| 60 |
-
if FLA_AVAILABLE:
|
| 61 |
-
|
| 62 |
-
@torch.compiler.disable
|
| 63 |
-
def _fla_chunk(q, k, v, g, b, w, initial_state=None, output_final_state=False,
|
| 64 |
-
cu_seqlens=None):
|
| 65 |
-
return chunk_gdn2(
|
| 66 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 67 |
-
initial_state=initial_state,
|
| 68 |
-
output_final_state=output_final_state,
|
| 69 |
-
use_qk_l2norm_in_kernel=True,
|
| 70 |
-
cu_seqlens=cu_seqlens,
|
| 71 |
-
)
|
| 72 |
-
|
| 73 |
-
@torch.compiler.disable
|
| 74 |
-
def _fla_recurrent(q, k, v, g, b, w, initial_state=None, output_final_state=False):
|
| 75 |
-
return fused_recurrent_gdn2(
|
| 76 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 77 |
-
initial_state=initial_state,
|
| 78 |
-
output_final_state=output_final_state,
|
| 79 |
-
use_qk_l2norm_in_kernel=True,
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
try:
|
| 83 |
-
from flash_attn import flash_attn_varlen_func
|
| 84 |
-
FLASH_ATTN_AVAILABLE = True
|
| 85 |
-
except ImportError:
|
| 86 |
-
flash_attn_varlen_func = None
|
| 87 |
-
FLASH_ATTN_AVAILABLE = False
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def _mask_padding_states(hidden_states, padding_mask):
|
| 91 |
-
if padding_mask is not None:
|
| 92 |
-
return hidden_states * padding_mask.unsqueeze(-1).to(hidden_states.dtype)
|
| 93 |
-
return hidden_states
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def naive_gdn2_reference(q, k, v, g, b, w, initial_state=None):
|
| 97 |
-
"""fp32 reference for GDN-2."""
|
| 98 |
-
B, T, H, K = q.shape
|
| 99 |
-
V = v.shape[-1]
|
| 100 |
-
S = (
|
| 101 |
-
torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)
|
| 102 |
-
if initial_state is None
|
| 103 |
-
else initial_state.float()
|
| 104 |
-
)
|
| 105 |
-
scale = K ** -0.5
|
| 106 |
-
outs = []
|
| 107 |
-
for t in range(T):
|
| 108 |
-
q_t = F.normalize(q[:, t], dim=-1)
|
| 109 |
-
k_t = F.normalize(k[:, t], dim=-1)
|
| 110 |
-
v_t, g_t, b_t, w_t = v[:, t], g[:, t], b[:, t], w[:, t]
|
| 111 |
-
S = S * torch.exp(g_t).unsqueeze(-1)
|
| 112 |
-
e = b_t * k_t
|
| 113 |
-
r = torch.einsum("bhkv,bhk->bhv", S, e)
|
| 114 |
-
z = w_t * v_t
|
| 115 |
-
S = S + torch.einsum("bhk,bhv->bhkv", k_t, z - r)
|
| 116 |
-
outs.append(scale * torch.einsum("bhkv,bhk->bhv", S, q_t))
|
| 117 |
-
return torch.stack(outs, dim=1), S
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
class SurjoRMSNorm(nn.Module):
|
| 121 |
-
"""FLA Triton RMSNorm when available; else fused ATen F.rms_norm."""
|
| 122 |
-
|
| 123 |
-
def __init__(self, dim: int, eps: float = 1e-6):
|
| 124 |
-
super().__init__()
|
| 125 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 126 |
-
self.eps = eps
|
| 127 |
-
|
| 128 |
-
def forward(self, x):
|
| 129 |
-
if x.dtype != self.weight.dtype:
|
| 130 |
-
x = x.to(self.weight.dtype)
|
| 131 |
-
if _USE_FLA_RMS_NORM and _fla_rms_norm is not None and x.is_cuda:
|
| 132 |
-
return _fla_rms_norm(x, self.weight, None, eps=self.eps)
|
| 133 |
-
return F.rms_norm(x, (x.shape[-1],), self.weight, self.eps)
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class ClampedMLP(nn.Module):
|
| 137 |
-
def __init__(self, config):
|
| 138 |
-
hidden_size = config.hidden_size
|
| 139 |
-
intermediate_size = config.intermediate_size
|
| 140 |
-
super().__init__()
|
| 141 |
-
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 142 |
-
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 143 |
-
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
| 144 |
-
self.act_fn = ACT2FN[config.hidden_act]
|
| 145 |
-
|
| 146 |
-
def forward(self, x):
|
| 147 |
-
return self.down_proj(
|
| 148 |
-
self.act_fn(self.gate_proj(x).clamp(-15.0, 15.0)) * self.up_proj(x)
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
class SurjoRotaryEmbedding(nn.Module):
|
| 153 |
-
"""RoPE with frequencies computed in forward() (no stored buffer)."""
|
| 154 |
-
|
| 155 |
-
def __init__(self, config, device=None):
|
| 156 |
-
super().__init__()
|
| 157 |
-
self.config = config
|
| 158 |
-
self.rope_type = config.rope_parameters.get("rope_type", "default")
|
| 159 |
-
self.max_position_embeddings = config.max_position_embeddings
|
| 160 |
-
self.base = config.rope_parameters.get("rope_theta", config.rope_theta)
|
| 161 |
-
self.factor = config.rope_parameters.get("factor", 1.0)
|
| 162 |
-
self.dim = int(config.head_dim * config.partial_rotary_factor)
|
| 163 |
-
|
| 164 |
-
def _inv_freq(self, device):
|
| 165 |
-
inv = 1.0 / (
|
| 166 |
-
self.base
|
| 167 |
-
** (torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim)
|
| 168 |
-
)
|
| 169 |
-
if self.rope_type == "linear":
|
| 170 |
-
inv = inv / self.factor
|
| 171 |
-
return inv
|
| 172 |
-
|
| 173 |
-
@torch.no_grad()
|
| 174 |
-
def forward(self, position_ids):
|
| 175 |
-
inv = self._inv_freq(position_ids.device)
|
| 176 |
-
freqs = torch.einsum("bt,f->btf", position_ids.float(), inv)
|
| 177 |
-
emb = torch.cat([freqs, freqs], dim=-1)
|
| 178 |
-
return emb.cos(), emb.sin()
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def rotate_half(x):
|
| 182 |
-
x1, x2 = x.chunk(2, dim=-1)
|
| 183 |
-
return torch.cat((-x2, x1), dim=-1)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def apply_rope(q, k, cos, sin):
|
| 187 |
-
cos = cos[:, None, :, :].to(q.dtype)
|
| 188 |
-
sin = sin[:, None, :, :].to(q.dtype)
|
| 189 |
-
q = q * cos + rotate_half(q) * sin
|
| 190 |
-
k = k * cos + rotate_half(k) * sin
|
| 191 |
-
return q, k
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
def apply_rope_flat(q, k, cos, sin):
|
| 195 |
-
"""RoPE on flat varlen tensors. q, k: [total, H, D]; cos, sin: [B, T, D]."""
|
| 196 |
-
total = q.shape[0]
|
| 197 |
-
cos_f = cos.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 198 |
-
sin_f = sin.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 199 |
-
q = q * cos_f + rotate_half(q) * sin_f
|
| 200 |
-
k = k * cos_f + rotate_half(k) * sin_f
|
| 201 |
-
return q, k
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
@torch.compiler.disable
|
| 205 |
-
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen):
|
| 206 |
-
"""FA2 varlen. cu_seqlens device int32; max_seqlen a constant (no sync)."""
|
| 207 |
-
return flash_attn_varlen_func(
|
| 208 |
-
q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen,
|
| 209 |
-
dropout_p=0.0, causal=True,
|
| 210 |
-
)
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
class ShortConvolution(nn.Module):
|
| 214 |
-
def __init__(self, dim: int, kernel_size: int = 4):
|
| 215 |
-
super().__init__()
|
| 216 |
-
self.kernel_size = kernel_size
|
| 217 |
-
self.conv = nn.Conv1d(dim, dim, kernel_size, groups=dim, bias=False)
|
| 218 |
-
|
| 219 |
-
def forward(self, x, cache=None, output_state=False):
|
| 220 |
-
B, T, C = x.shape
|
| 221 |
-
xt = x.transpose(1, 2)
|
| 222 |
-
if T == 1 and cache is not None:
|
| 223 |
-
comb = torch.cat([cache, xt], dim=2)
|
| 224 |
-
w = self.conv.weight.squeeze(1)
|
| 225 |
-
out = F.silu(torch.einsum("bck,ck->bc", comb, w).unsqueeze(-1))
|
| 226 |
-
new = comb[:, :, 1:] if output_state else None
|
| 227 |
-
return out.transpose(1, 2), new
|
| 228 |
-
if cache is not None:
|
| 229 |
-
xt_in = torch.cat([cache, xt], dim=2)
|
| 230 |
-
else:
|
| 231 |
-
xt_in = F.pad(xt, (self.kernel_size - 1, 0))
|
| 232 |
-
out = F.silu(self.conv(xt_in))
|
| 233 |
-
new = xt_in[:, :, -(self.kernel_size - 1):] if output_state else None
|
| 234 |
-
return out.transpose(1, 2), new
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
class SurjoCache:
|
| 238 |
-
def __init__(self):
|
| 239 |
-
self.kv = {}
|
| 240 |
-
self.gdn_state = {}
|
| 241 |
-
self.gdn_conv = {}
|
| 242 |
-
|
| 243 |
-
def get_seq_length(self):
|
| 244 |
-
if not self.kv:
|
| 245 |
-
return 0
|
| 246 |
-
return next(iter(self.kv.values()))[0].shape[2]
|
| 247 |
-
|
| 248 |
-
@staticmethod
|
| 249 |
-
def num_xsa_slots(config):
|
| 250 |
-
return (
|
| 251 |
-
config.prelude_layers
|
| 252 |
-
+ config.num_groups * config.recurrent_passes
|
| 253 |
-
+ config.coda_layers
|
| 254 |
-
)
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
class XSAAttention(nn.Module):
|
| 258 |
-
"""Full attention with XSA value-projection subtraction."""
|
| 259 |
-
|
| 260 |
-
def __init__(self, config, layer_idx: int):
|
| 261 |
-
super().__init__()
|
| 262 |
-
self.layer_idx = layer_idx
|
| 263 |
-
self.num_heads = config.num_attention_heads
|
| 264 |
-
self.num_kv_heads = config.num_key_value_heads
|
| 265 |
-
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 266 |
-
self.head_dim = config.head_dim
|
| 267 |
-
self.xsa_projection = config.xsa_projection
|
| 268 |
-
self.dropout = config.attention_dropout
|
| 269 |
-
self.hidden_size = config.hidden_size
|
| 270 |
-
self.use_flash = getattr(config, "_use_flash_xsa", False)
|
| 271 |
-
self.q_proj = nn.Linear(
|
| 272 |
-
self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
|
| 273 |
-
)
|
| 274 |
-
self.k_proj = nn.Linear(
|
| 275 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 276 |
-
)
|
| 277 |
-
self.v_proj = nn.Linear(
|
| 278 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 279 |
-
)
|
| 280 |
-
self.o_proj = nn.Linear(
|
| 281 |
-
self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias
|
| 282 |
-
)
|
| 283 |
-
self.q_norm = SurjoRMSNorm(self.head_dim)
|
| 284 |
-
self.k_norm = SurjoRMSNorm(self.head_dim)
|
| 285 |
-
|
| 286 |
-
def _xsa_projection_step(self, attn, v):
|
| 287 |
-
dv = (attn.float() * v.float()).sum(dim=-1, keepdim=True)
|
| 288 |
-
vv = (v.float() * v.float()).sum(dim=-1, keepdim=True).clamp_min(1e-4)
|
| 289 |
-
scale = (dv / vv).to(attn.dtype)
|
| 290 |
-
return attn - scale * v
|
| 291 |
-
|
| 292 |
-
def forward(self, hidden_states, attention_mask, cache, slot, use_cache,
|
| 293 |
-
cache_position, cos, sin, cu_seqlens=None):
|
| 294 |
-
B, T, _ = hidden_states.shape
|
| 295 |
-
H, Hkv, D = self.num_heads, self.num_kv_heads, self.head_dim
|
| 296 |
-
|
| 297 |
-
q = self.q_proj(hidden_states).view(B, T, H, D).transpose(1, 2)
|
| 298 |
-
k = self.k_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 299 |
-
v = self.v_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 300 |
-
q = self.q_norm(q)
|
| 301 |
-
k = self.k_norm(k)
|
| 302 |
-
|
| 303 |
-
use_varlen = (
|
| 304 |
-
cu_seqlens is not None
|
| 305 |
-
and cache is None
|
| 306 |
-
and self.use_flash
|
| 307 |
-
and FLASH_ATTN_AVAILABLE
|
| 308 |
-
and hidden_states.is_cuda
|
| 309 |
-
)
|
| 310 |
-
if use_varlen:
|
| 311 |
-
total = B * T
|
| 312 |
-
q_f = q.transpose(1, 2).reshape(total, H, D).to(torch.bfloat16)
|
| 313 |
-
k_f = k.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 314 |
-
v_f = v.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 315 |
-
if Hkv != H:
|
| 316 |
-
k_f = k_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 317 |
-
v_f = v_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 318 |
-
q_f, k_f = apply_rope_flat(q_f, k_f, cos, sin)
|
| 319 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 320 |
-
o_f = _flash_varlen(q_f, k_f, v_f, cu_dev, T)
|
| 321 |
-
attn_out = o_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 322 |
-
v_xsa = v_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 323 |
-
if self.xsa_projection:
|
| 324 |
-
attn_out = self._xsa_projection_step(attn_out, v_xsa)
|
| 325 |
-
out = attn_out.reshape(B, T, H * D)
|
| 326 |
-
return self.o_proj(out)
|
| 327 |
-
|
| 328 |
-
q, k = apply_rope(q, k, cos, sin)
|
| 329 |
-
v_cur = v
|
| 330 |
-
if cache is not None and use_cache:
|
| 331 |
-
if slot in cache.kv:
|
| 332 |
-
pk, pv = cache.kv[slot]
|
| 333 |
-
k = torch.cat([pk, k.to(pk.dtype)], dim=2)
|
| 334 |
-
v = torch.cat([pv, v.to(pv.dtype)], dim=2)
|
| 335 |
-
cache.kv[slot] = (k, v)
|
| 336 |
-
S = k.shape[2]
|
| 337 |
-
if Hkv != H:
|
| 338 |
-
k_e = k.repeat_interleave(self.num_kv_groups, dim=1)
|
| 339 |
-
v_e = v.repeat_interleave(self.num_kv_groups, dim=1)
|
| 340 |
-
v_cur_e = v_cur.repeat_interleave(self.num_kv_groups, dim=1)
|
| 341 |
-
else:
|
| 342 |
-
k_e, v_e, v_cur_e = k, v, v_cur
|
| 343 |
-
|
| 344 |
-
is_causal = False
|
| 345 |
-
mask4 = None
|
| 346 |
-
if attention_mask is not None:
|
| 347 |
-
L = attention_mask.shape[-1]
|
| 348 |
-
if L < S:
|
| 349 |
-
attention_mask = F.pad(attention_mask, (S - L, 0), value=1)
|
| 350 |
-
elif L > S:
|
| 351 |
-
attention_mask = attention_mask[:, -S:]
|
| 352 |
-
neg = torch.finfo(q.dtype).min
|
| 353 |
-
m = attention_mask[:, None, None, :].to(q.dtype)
|
| 354 |
-
if T == S:
|
| 355 |
-
if T > 1:
|
| 356 |
-
causal = torch.ones(T, S, device=q.device, dtype=q.dtype).tril()
|
| 357 |
-
allow = causal[None, None] * m
|
| 358 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 359 |
-
torch.full_like(allow, neg))
|
| 360 |
-
else:
|
| 361 |
-
mask4 = torch.where(m > 0, torch.zeros_like(m),
|
| 362 |
-
torch.full_like(m, neg))
|
| 363 |
-
else:
|
| 364 |
-
if cache_position is None:
|
| 365 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 366 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 367 |
-
causal = kv_pos[None, :] <= cache_position[:, None].to(q.device)
|
| 368 |
-
allow = causal[None, None].to(q.dtype) * m
|
| 369 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 370 |
-
torch.full_like(allow, neg))
|
| 371 |
-
elif cu_seqlens is not None and T > 1:
|
| 372 |
-
neg = torch.finfo(q.dtype).min
|
| 373 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32)
|
| 374 |
-
gpos = torch.arange(B * T, device=q.device)
|
| 375 |
-
doc_id = torch.searchsorted(cu_dev, gpos, right=True) - 1
|
| 376 |
-
doc_id = doc_id.clamp(min=0).view(B, T)
|
| 377 |
-
same = doc_id.unsqueeze(2) == doc_id.unsqueeze(1)
|
| 378 |
-
idx = torch.arange(T, device=q.device)
|
| 379 |
-
causal = idx.unsqueeze(0) <= idx.unsqueeze(1)
|
| 380 |
-
allow = (same & causal).unsqueeze(1)
|
| 381 |
-
mask4 = torch.where(
|
| 382 |
-
allow,
|
| 383 |
-
torch.zeros(B, 1, T, T, dtype=q.dtype, device=q.device),
|
| 384 |
-
torch.full((B, 1, T, T), neg, dtype=q.dtype, device=q.device),
|
| 385 |
-
)
|
| 386 |
-
else:
|
| 387 |
-
if T == S and T > 1:
|
| 388 |
-
is_causal = True
|
| 389 |
-
elif T > 1:
|
| 390 |
-
if cache_position is None:
|
| 391 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 392 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 393 |
-
neg = torch.finfo(q.dtype).min
|
| 394 |
-
causal = torch.zeros(T, S, device=q.device, dtype=q.dtype)
|
| 395 |
-
causal = causal.masked_fill(
|
| 396 |
-
kv_pos[None, :] > cache_position[:, None], neg
|
| 397 |
-
)
|
| 398 |
-
mask4 = causal[None, None, :, :]
|
| 399 |
-
|
| 400 |
-
attn = F.scaled_dot_product_attention(
|
| 401 |
-
q, k_e, v_e, attn_mask=mask4, is_causal=is_causal,
|
| 402 |
-
dropout_p=self.dropout if self.training else 0.0,
|
| 403 |
-
)
|
| 404 |
-
|
| 405 |
-
if self.xsa_projection:
|
| 406 |
-
attn = self._xsa_projection_step(attn, v_cur_e)
|
| 407 |
-
|
| 408 |
-
out = attn.transpose(1, 2).reshape(B, T, H * D)
|
| 409 |
-
return self.o_proj(out)
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
class GDN2Attention(nn.Module):
|
| 413 |
-
"""Gated DeltaNet-2 linear attention."""
|
| 414 |
-
|
| 415 |
-
def __init__(self, config, layer_idx: int):
|
| 416 |
-
super().__init__()
|
| 417 |
-
self.layer_idx = layer_idx
|
| 418 |
-
H = config.num_attention_heads
|
| 419 |
-
Hv = config.gdn_num_v_heads
|
| 420 |
-
self.num_heads = H
|
| 421 |
-
self.num_v_heads = Hv
|
| 422 |
-
self.gva = Hv // H
|
| 423 |
-
self.head_k_dim = config.gdn_key_dim
|
| 424 |
-
self.head_v_dim = config.gdn_value_dim
|
| 425 |
-
self.key_dim = H * self.head_k_dim
|
| 426 |
-
self.value_dim = Hv * self.head_v_dim
|
| 427 |
-
self.conv_kernel = config.gdn_conv_kernel_size
|
| 428 |
-
self.allow_neg_eigval = config.gdn_allow_neg_eigval
|
| 429 |
-
hidden = config.hidden_size
|
| 430 |
-
self.q_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 431 |
-
self.k_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 432 |
-
self.v_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 433 |
-
self.q_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 434 |
-
self.k_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 435 |
-
self.v_conv = ShortConvolution(self.value_dim, self.conv_kernel)
|
| 436 |
-
self.f_proj = nn.Sequential(
|
| 437 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 438 |
-
nn.Linear(self.head_v_dim, self.key_dim, bias=False),
|
| 439 |
-
)
|
| 440 |
-
self.b_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 441 |
-
self.w_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 442 |
-
self.A_log = nn.Parameter(
|
| 443 |
-
torch.log(torch.empty(H, dtype=torch.float32).uniform_(1, 16))
|
| 444 |
-
)
|
| 445 |
-
self.A_log._no_weight_decay = True
|
| 446 |
-
dt = torch.exp(
|
| 447 |
-
torch.rand(self.key_dim, dtype=torch.float32)
|
| 448 |
-
* (math.log(0.1) - math.log(0.001))
|
| 449 |
-
+ math.log(0.001)
|
| 450 |
-
).clamp(min=1e-4)
|
| 451 |
-
self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt)))
|
| 452 |
-
self.dt_bias._no_weight_decay = True
|
| 453 |
-
self.g_proj = nn.Sequential(
|
| 454 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 455 |
-
nn.Linear(self.head_v_dim, self.value_dim, bias=True),
|
| 456 |
-
)
|
| 457 |
-
self.o_norm = SurjoRMSNorm(self.head_v_dim, eps=config.rms_norm_eps)
|
| 458 |
-
self.o_proj = nn.Linear(self.value_dim, hidden, bias=False)
|
| 459 |
-
|
| 460 |
-
def forward(self, hidden_states, attention_mask, gdn_state, conv_state,
|
| 461 |
-
output_state, cu_seqlens=None):
|
| 462 |
-
B, T, _ = hidden_states.shape
|
| 463 |
-
if attention_mask is not None:
|
| 464 |
-
if attention_mask.shape[-1] != T:
|
| 465 |
-
attention_mask = (
|
| 466 |
-
attention_mask[:, -T:] if attention_mask.shape[-1] > T else None
|
| 467 |
-
)
|
| 468 |
-
if attention_mask is not None:
|
| 469 |
-
hidden_states = _mask_padding_states(hidden_states, attention_mask)
|
| 470 |
-
cq = conv_state[0] if conv_state is not None else None
|
| 471 |
-
ck = conv_state[1] if conv_state is not None else None
|
| 472 |
-
cvs = conv_state[2] if conv_state is not None else None
|
| 473 |
-
q, nq = self.q_conv(self.q_proj(hidden_states), cq, output_state)
|
| 474 |
-
k, nk = self.k_conv(self.k_proj(hidden_states), ck, output_state)
|
| 475 |
-
v, nv = self.v_conv(self.v_proj(hidden_states), cvs, output_state)
|
| 476 |
-
g = F.softplus(self.f_proj(hidden_states).float() + self.dt_bias)
|
| 477 |
-
b = self.b_proj(hidden_states).sigmoid()
|
| 478 |
-
w = self.w_proj(hidden_states).sigmoid()
|
| 479 |
-
q = q.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 480 |
-
k = k.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 481 |
-
v = v.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 482 |
-
g = g.view(B, T, self.num_heads, self.head_k_dim)
|
| 483 |
-
b = b.view(B, T, self.num_heads, self.head_k_dim)
|
| 484 |
-
w = w.view(B, T, self.num_v_heads, self.head_v_dim)
|
| 485 |
-
g = -self.A_log.float().exp().view(1, 1, self.num_heads, 1) * g
|
| 486 |
-
if self.allow_neg_eigval:
|
| 487 |
-
b = b * 2.0
|
| 488 |
-
if self.gva > 1:
|
| 489 |
-
q = q.repeat_interleave(self.gva, dim=2)
|
| 490 |
-
k = k.repeat_interleave(self.gva, dim=2)
|
| 491 |
-
g = g.repeat_interleave(self.gva, dim=2)
|
| 492 |
-
b = b.repeat_interleave(self.gva, dim=2)
|
| 493 |
-
init = gdn_state.float() if gdn_state is not None else None
|
| 494 |
-
|
| 495 |
-
if FLA_AVAILABLE and hidden_states.is_cuda:
|
| 496 |
-
if T == 1 and init is not None:
|
| 497 |
-
o, fs = _fla_recurrent(q, k, v, g, b, w, init, output_state)
|
| 498 |
-
elif cu_seqlens is not None:
|
| 499 |
-
total = B * T
|
| 500 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 501 |
-
q_f = q.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 502 |
-
k_f = k.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 503 |
-
v_f = v.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 504 |
-
g_f = g.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 505 |
-
b_f = b.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 506 |
-
w_f = w.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 507 |
-
o, fs = _fla_chunk(q_f, k_f, v_f, g_f, b_f, w_f, init,
|
| 508 |
-
output_state, cu_dev)
|
| 509 |
-
o = o.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 510 |
-
else:
|
| 511 |
-
o, fs = _fla_chunk(q, k, v, g, b, w, init, output_state, None)
|
| 512 |
-
else:
|
| 513 |
-
o, fs = naive_gdn2_reference(q.float(), k.float(), v.float(), g,
|
| 514 |
-
b.float(), w.float(), init)
|
| 515 |
-
|
| 516 |
-
# Cast back to activation precision
|
| 517 |
-
o = o.to(hidden_states.dtype)
|
| 518 |
-
|
| 519 |
-
fs = fs if output_state else None
|
| 520 |
-
gate = self.g_proj(hidden_states).view(B, T, self.num_v_heads, self.head_v_dim)
|
| 521 |
-
o = self.o_norm(o)
|
| 522 |
-
o = o * torch.sigmoid(gate)
|
| 523 |
-
o = o.reshape(B, T, self.value_dim)
|
| 524 |
-
conv_out = (nq, nk, nv) if output_state else None
|
| 525 |
-
return self.o_proj(o), fs, conv_out
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
def _is_xsa(config, li: int) -> bool:
|
| 529 |
-
if li < config.prelude_layers:
|
| 530 |
-
return True
|
| 531 |
-
if li >= config.prelude_layers + config.recurrent_layers:
|
| 532 |
-
return True
|
| 533 |
-
return (li - config.prelude_layers) % (config.gdn_per_xsa + 1) == config.gdn_per_xsa
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
class SurjoDecoderLayer(nn.Module):
|
| 537 |
-
def __init__(self, config, layer_idx: int):
|
| 538 |
-
super().__init__()
|
| 539 |
-
self.layer_idx = layer_idx
|
| 540 |
-
self.layer_type = "xsa" if _is_xsa(config, layer_idx) else "gdn"
|
| 541 |
-
if self.layer_type == "xsa":
|
| 542 |
-
self.self_attn = XSAAttention(config, layer_idx)
|
| 543 |
-
else:
|
| 544 |
-
self.linear_attn = GDN2Attention(config, layer_idx)
|
| 545 |
-
self.mlp = ClampedMLP(config)
|
| 546 |
-
self.input_layernorm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 547 |
-
self.post_attention_layernorm = SurjoRMSNorm(config.hidden_size,
|
| 548 |
-
eps=config.rms_norm_eps)
|
| 549 |
-
|
| 550 |
-
def forward(self, hidden_states, attention_mask=None, cos=None, sin=None,
|
| 551 |
-
cu_seqlens=None):
|
| 552 |
-
h = self.input_layernorm(hidden_states)
|
| 553 |
-
if self.layer_type == "xsa":
|
| 554 |
-
out = self.self_attn(h, attention_mask, None, -1, False, None,
|
| 555 |
-
cos, sin, cu_seqlens)
|
| 556 |
-
else:
|
| 557 |
-
out, _, _ = self.linear_attn(h, attention_mask, None, None, False,
|
| 558 |
-
cu_seqlens)
|
| 559 |
-
hidden_states = hidden_states + out
|
| 560 |
-
h2 = self.post_attention_layernorm(hidden_states)
|
| 561 |
-
return hidden_states + self.mlp(h2)
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
class SurjoPreTrainedModel(PreTrainedModel):
|
| 565 |
-
config_class = SurjoConfig
|
| 566 |
-
base_model_prefix = "model"
|
| 567 |
-
_no_split_modules = ["SurjoDecoderLayer"]
|
| 568 |
-
_supports_flash_attn = False
|
| 569 |
-
_supports_flash_attn_2 = False
|
| 570 |
-
_supports_sdpa = True
|
| 571 |
-
_is_stateful = True
|
| 572 |
-
_can_compile_fullgraph = True
|
| 573 |
-
|
| 574 |
-
def _init_weights(self, module):
|
| 575 |
-
std = self.config.initializer_range
|
| 576 |
-
if isinstance(module, nn.Linear):
|
| 577 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 578 |
-
if module.bias is not None:
|
| 579 |
-
module.bias.data.zero_()
|
| 580 |
-
elif isinstance(module, nn.Embedding):
|
| 581 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 582 |
-
if module.padding_idx is not None:
|
| 583 |
-
module.weight.data[module.padding_idx].zero_()
|
| 584 |
-
elif isinstance(module, GDN2Attention):
|
| 585 |
-
module.A_log.data.copy_(
|
| 586 |
-
torch.log(
|
| 587 |
-
torch.empty(module.num_heads, dtype=torch.float32,
|
| 588 |
-
device=module.A_log.device).uniform_(1, 16)
|
| 589 |
-
)
|
| 590 |
-
)
|
| 591 |
-
dt = torch.exp(
|
| 592 |
-
torch.rand(module.key_dim, dtype=torch.float32,
|
| 593 |
-
device=module.dt_bias.device)
|
| 594 |
-
* (math.log(0.1) - math.log(0.001)) + math.log(0.001)
|
| 595 |
-
).clamp(min=1e-4)
|
| 596 |
-
module.dt_bias.data.copy_(dt + torch.log(-torch.expm1(-dt)))
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
class SurjoModel(SurjoPreTrainedModel):
|
| 600 |
-
def __init__(self, config):
|
| 601 |
-
super().__init__(config)
|
| 602 |
-
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 603 |
-
self.layers = nn.ModuleList(
|
| 604 |
-
[SurjoDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 605 |
-
)
|
| 606 |
-
self.norm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 607 |
-
self.rotary = SurjoRotaryEmbedding(config)
|
| 608 |
-
self.grad_checkpointing = False
|
| 609 |
-
|
| 610 |
-
slot = 0
|
| 611 |
-
self.xsa_slot_map = {}
|
| 612 |
-
self.exec_plan = []
|
| 613 |
-
for li in range(config.prelude_layers):
|
| 614 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 615 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 616 |
-
slot += 1
|
| 617 |
-
for p in range(config.recurrent_passes):
|
| 618 |
-
for g in range(config.num_groups):
|
| 619 |
-
base = config.prelude_layers + g * (config.gdn_per_xsa + 1)
|
| 620 |
-
for j in range(config.gdn_per_xsa):
|
| 621 |
-
self.exec_plan.append((self.layers[base + j], base + j, p, -1))
|
| 622 |
-
li = base + config.gdn_per_xsa
|
| 623 |
-
self.xsa_slot_map[(li, p)] = slot
|
| 624 |
-
self.exec_plan.append((self.layers[li], li, p, slot))
|
| 625 |
-
slot += 1
|
| 626 |
-
for li in range(config.prelude_layers + config.recurrent_layers,
|
| 627 |
-
config.num_hidden_layers):
|
| 628 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 629 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 630 |
-
slot += 1
|
| 631 |
-
self.num_xsa_slots = slot
|
| 632 |
-
self.post_init()
|
| 633 |
-
|
| 634 |
-
def get_input_embeddings(self):
|
| 635 |
-
return self.embed_tokens
|
| 636 |
-
|
| 637 |
-
def set_input_embeddings(self, value):
|
| 638 |
-
self.embed_tokens = value
|
| 639 |
-
|
| 640 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 641 |
-
past_key_values=None, inputs_embeds=None, use_cache=None,
|
| 642 |
-
cache_position=None, return_dict=True,
|
| 643 |
-
output_hidden_states=False, output_attentions=False,
|
| 644 |
-
cu_seqlens=None, **kwargs):
|
| 645 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 646 |
-
past_key_values = None
|
| 647 |
-
if use_cache is None:
|
| 648 |
-
use_cache = past_key_values is not None
|
| 649 |
-
if use_cache and past_key_values is None:
|
| 650 |
-
past_key_values = SurjoCache()
|
| 651 |
-
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 652 |
-
|
| 653 |
-
if past_len > 0:
|
| 654 |
-
if input_ids is not None:
|
| 655 |
-
n_ids = input_ids.shape[1]
|
| 656 |
-
if (attention_mask is not None
|
| 657 |
-
and attention_mask.shape[-1] > n_ids
|
| 658 |
-
and attention_mask.shape[-1] > past_len):
|
| 659 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 660 |
-
input_ids = input_ids[:, -n_new:] if n_new <= n_ids else input_ids
|
| 661 |
-
elif n_ids > past_len:
|
| 662 |
-
input_ids = input_ids[:, past_len:]
|
| 663 |
-
else:
|
| 664 |
-
input_ids = input_ids[:, -1:]
|
| 665 |
-
elif inputs_embeds is not None:
|
| 666 |
-
n_emb = inputs_embeds.shape[1]
|
| 667 |
-
if (attention_mask is not None
|
| 668 |
-
and attention_mask.shape[-1] > n_emb
|
| 669 |
-
and attention_mask.shape[-1] > past_len):
|
| 670 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 671 |
-
inputs_embeds = (inputs_embeds[:, -n_new:] if n_new <= n_emb
|
| 672 |
-
else inputs_embeds)
|
| 673 |
-
elif n_emb > past_len:
|
| 674 |
-
inputs_embeds = inputs_embeds[:, past_len:]
|
| 675 |
-
else:
|
| 676 |
-
inputs_embeds = inputs_embeds[:, -1:]
|
| 677 |
-
|
| 678 |
-
if inputs_embeds is None:
|
| 679 |
-
if input_ids is None:
|
| 680 |
-
raise ValueError("Specify input_ids or inputs_embeds")
|
| 681 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
| 682 |
-
B, T = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 683 |
-
|
| 684 |
-
cache_position = torch.arange(past_len, past_len + T,
|
| 685 |
-
device=inputs_embeds.device)
|
| 686 |
-
if position_ids is not None and position_ids.shape[-1] != T:
|
| 687 |
-
position_ids = None
|
| 688 |
-
if position_ids is None:
|
| 689 |
-
position_ids = cache_position.unsqueeze(0).expand(B, -1)
|
| 690 |
-
cos, sin = self.rotary(position_ids)
|
| 691 |
-
|
| 692 |
-
gdn_states = dict(past_key_values.gdn_state) if past_key_values is not None else {}
|
| 693 |
-
conv_states = dict(past_key_values.gdn_conv) if past_key_values is not None else {}
|
| 694 |
-
|
| 695 |
-
noise_std = self.config.loop_noise_std
|
| 696 |
-
hidden = inputs_embeds
|
| 697 |
-
prev_p = 0
|
| 698 |
-
use_ckpt = self.training and self.grad_checkpointing
|
| 699 |
-
all_hidden_states = () if output_hidden_states else None
|
| 700 |
-
|
| 701 |
-
for (layer, li, p, slot) in self.exec_plan:
|
| 702 |
-
if output_hidden_states:
|
| 703 |
-
all_hidden_states += (hidden,)
|
| 704 |
-
if p != prev_p and p > 0 and self.training and noise_std > 0.0:
|
| 705 |
-
hidden = hidden + torch.randn_like(hidden) * noise_std
|
| 706 |
-
prev_p = p
|
| 707 |
-
|
| 708 |
-
if use_ckpt:
|
| 709 |
-
hidden = torch.utils.checkpoint.checkpoint(
|
| 710 |
-
self._train_layer, layer, hidden, attention_mask, cos, sin,
|
| 711 |
-
cu_seqlens, use_reentrant=False,
|
| 712 |
-
)
|
| 713 |
-
elif use_cache:
|
| 714 |
-
h = layer.input_layernorm(hidden)
|
| 715 |
-
if layer.layer_type == "xsa":
|
| 716 |
-
out = layer.self_attn(h, attention_mask, past_key_values,
|
| 717 |
-
slot, use_cache, cache_position,
|
| 718 |
-
cos, sin, cu_seqlens)
|
| 719 |
-
else:
|
| 720 |
-
gs = gdn_states.get((li, p))
|
| 721 |
-
cs = conv_states.get((li, p))
|
| 722 |
-
out, ngs, ncs = layer.linear_attn(h, attention_mask, gs, cs,
|
| 723 |
-
use_cache, cu_seqlens)
|
| 724 |
-
if ngs is not None:
|
| 725 |
-
gdn_states[(li, p)] = ngs
|
| 726 |
-
if ncs is not None:
|
| 727 |
-
conv_states[(li, p)] = ncs
|
| 728 |
-
hidden = hidden + out
|
| 729 |
-
h2 = layer.post_attention_layernorm(hidden)
|
| 730 |
-
hidden = hidden + layer.mlp(h2)
|
| 731 |
-
else:
|
| 732 |
-
hidden = layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 733 |
-
|
| 734 |
-
hidden = self.norm(hidden)
|
| 735 |
-
if output_hidden_states:
|
| 736 |
-
all_hidden_states += (hidden,)
|
| 737 |
-
|
| 738 |
-
if use_cache and past_key_values is not None:
|
| 739 |
-
past_key_values.gdn_state.update(gdn_states)
|
| 740 |
-
past_key_values.gdn_conv.update(conv_states)
|
| 741 |
-
|
| 742 |
-
if not return_dict:
|
| 743 |
-
out = tuple(v for v in [hidden, past_key_values if use_cache else None,
|
| 744 |
-
all_hidden_states] if v is not None)
|
| 745 |
-
return out
|
| 746 |
-
return BaseModelOutputWithPast(
|
| 747 |
-
last_hidden_state=hidden,
|
| 748 |
-
past_key_values=past_key_values if use_cache else None,
|
| 749 |
-
hidden_states=all_hidden_states,
|
| 750 |
-
attentions=None,
|
| 751 |
-
)
|
| 752 |
-
|
| 753 |
-
def _train_layer(self, layer, hidden, attention_mask, cos, sin, cu_seqlens):
|
| 754 |
-
return layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
class SurjoForCausalLM(SurjoPreTrainedModel, GenerationMixin):
|
| 758 |
-
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 759 |
-
|
| 760 |
-
def __init__(self, config):
|
| 761 |
-
super().__init__(config)
|
| 762 |
-
self.model = SurjoModel(config)
|
| 763 |
-
self.vocab_size = config.vocab_size
|
| 764 |
-
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 765 |
-
self.post_init()
|
| 766 |
-
|
| 767 |
-
def tie_weights(self, **kwargs):
|
| 768 |
-
try:
|
| 769 |
-
super().tie_weights(**kwargs)
|
| 770 |
-
except TypeError:
|
| 771 |
-
pass
|
| 772 |
-
except Exception:
|
| 773 |
-
pass
|
| 774 |
-
if (getattr(self.config, "tie_word_embeddings", False)
|
| 775 |
-
and getattr(self, "model", None) is not None
|
| 776 |
-
and getattr(self, "lm_head", None) is not None):
|
| 777 |
-
self.lm_head.weight = self.model.embed_tokens.weight
|
| 778 |
-
|
| 779 |
-
def save_pretrained(self, *args, **kwargs):
|
| 780 |
-
was_tied = (getattr(self, "lm_head", None) is not None
|
| 781 |
-
and getattr(self, "model", None) is not None
|
| 782 |
-
and self.lm_head.weight is self.model.embed_tokens.weight)
|
| 783 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 784 |
-
self.lm_head.weight = nn.Parameter(
|
| 785 |
-
self.model.embed_tokens.weight.detach().clone(),
|
| 786 |
-
requires_grad=self.model.embed_tokens.weight.requires_grad,
|
| 787 |
-
)
|
| 788 |
-
try:
|
| 789 |
-
return super().save_pretrained(*args, **kwargs)
|
| 790 |
-
finally:
|
| 791 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 792 |
-
self.tie_weights()
|
| 793 |
-
|
| 794 |
-
def get_input_embeddings(self):
|
| 795 |
-
return self.model.embed_tokens
|
| 796 |
-
|
| 797 |
-
def set_input_embeddings(self, value):
|
| 798 |
-
self.model.embed_tokens = value
|
| 799 |
-
|
| 800 |
-
def get_output_embeddings(self):
|
| 801 |
-
return self.lm_head
|
| 802 |
-
|
| 803 |
-
def set_output_embeddings(self, value):
|
| 804 |
-
self.lm_head = value
|
| 805 |
-
|
| 806 |
-
def set_decoder(self, decoder):
|
| 807 |
-
self.model = decoder
|
| 808 |
-
|
| 809 |
-
def get_decoder(self):
|
| 810 |
-
return self.model
|
| 811 |
-
|
| 812 |
-
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, **kwargs):
|
| 813 |
-
self.model.grad_checkpointing = True
|
| 814 |
-
|
| 815 |
-
def gradient_checkpointing_disable(self):
|
| 816 |
-
self.model.grad_checkpointing = False
|
| 817 |
-
|
| 818 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 819 |
-
past_key_values=None, inputs_embeds=None, labels=None,
|
| 820 |
-
use_cache=None, output_hidden_states=None, output_attentions=None,
|
| 821 |
-
return_dict=None, logits_to_keep=0, cache_position=None,
|
| 822 |
-
cu_seqlens=None, **kwargs):
|
| 823 |
-
if logits_to_keep in (None, 0) and kwargs.get("num_logits_to_keep"):
|
| 824 |
-
logits_to_keep = kwargs.pop("num_logits_to_keep")
|
| 825 |
-
return_dict = True if return_dict is None else return_dict
|
| 826 |
-
if use_cache is None:
|
| 827 |
-
use_cache = not (self.training or labels is not None)
|
| 828 |
-
|
| 829 |
-
outputs = self.model(
|
| 830 |
-
input_ids=input_ids, attention_mask=attention_mask,
|
| 831 |
-
position_ids=position_ids, past_key_values=past_key_values,
|
| 832 |
-
inputs_embeds=inputs_embeds, use_cache=use_cache,
|
| 833 |
-
cache_position=cache_position,
|
| 834 |
-
output_hidden_states=output_hidden_states,
|
| 835 |
-
output_attentions=output_attentions,
|
| 836 |
-
cu_seqlens=cu_seqlens,
|
| 837 |
-
**kwargs,
|
| 838 |
-
)
|
| 839 |
-
hidden_states = outputs[0]
|
| 840 |
-
|
| 841 |
-
loss, logits = None, None
|
| 842 |
-
if labels is not None:
|
| 843 |
-
sh = hidden_states[..., :-1, :].contiguous()
|
| 844 |
-
sl = labels[..., 1:].contiguous()
|
| 845 |
-
if _USE_FLA_FUSED_CE and _fla_flce is not None:
|
| 846 |
-
loss = _fla_flce(
|
| 847 |
-
sh.view(-1, sh.shape[-1]),
|
| 848 |
-
sl.view(-1),
|
| 849 |
-
self.lm_head.weight,
|
| 850 |
-
num_chunks=8,
|
| 851 |
-
reduction="mean",
|
| 852 |
-
)
|
| 853 |
-
else:
|
| 854 |
-
n_chunks = max(8, sh.shape[0] // 8)
|
| 855 |
-
tot = hidden_states.new_zeros((), dtype=torch.float32)
|
| 856 |
-
n_tok = 0
|
| 857 |
-
for h_c, l_c in zip(sh.chunk(n_chunks, dim=0), sl.chunk(n_chunks, dim=0)):
|
| 858 |
-
if l_c.numel() == 0:
|
| 859 |
-
continue
|
| 860 |
-
lg = self.lm_head(h_c)
|
| 861 |
-
tot = tot + F.cross_entropy(
|
| 862 |
-
lg.float().view(-1, lg.size(-1)), l_c.view(-1), reduction="sum"
|
| 863 |
-
)
|
| 864 |
-
n_tok += l_c.numel()
|
| 865 |
-
loss = tot / max(n_tok, 1)
|
| 866 |
-
else:
|
| 867 |
-
if isinstance(logits_to_keep, int) and logits_to_keep > 0:
|
| 868 |
-
sl_hidden = hidden_states[:, -logits_to_keep:, :]
|
| 869 |
-
elif torch.is_tensor(logits_to_keep):
|
| 870 |
-
sl_hidden = hidden_states[:, logits_to_keep, :]
|
| 871 |
-
else:
|
| 872 |
-
sl_hidden = hidden_states
|
| 873 |
-
logits = self.lm_head(sl_hidden)
|
| 874 |
-
|
| 875 |
-
if not return_dict:
|
| 876 |
-
out = (logits,) + outputs[1:]
|
| 877 |
-
return (loss,) + out if loss is not None else out
|
| 878 |
-
return CausalLMOutputWithPast(
|
| 879 |
-
loss=loss, logits=logits,
|
| 880 |
-
past_key_values=outputs.past_key_values,
|
| 881 |
-
hidden_states=outputs.hidden_states,
|
| 882 |
-
attentions=outputs.attentions,
|
| 883 |
-
)
|
| 884 |
-
|
| 885 |
-
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
|
| 886 |
-
attention_mask=None, inputs_embeds=None,
|
| 887 |
-
cache_position=None, use_cache=True, **kwargs):
|
| 888 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 889 |
-
past_key_values = None
|
| 890 |
-
has_state = past_key_values is not None and len(past_key_values.kv) > 0
|
| 891 |
-
if has_state:
|
| 892 |
-
input_ids = input_ids[:, -1:]
|
| 893 |
-
if kwargs.get("logits_to_keep") is None:
|
| 894 |
-
kwargs["logits_to_keep"] = 1
|
| 895 |
-
past_len = past_key_values.get_seq_length() if has_state else 0
|
| 896 |
-
cache_position = torch.arange(past_len, past_len + input_ids.shape[1],
|
| 897 |
-
device=input_ids.device)
|
| 898 |
-
model_inputs = {
|
| 899 |
-
"input_ids": input_ids.contiguous(),
|
| 900 |
-
"past_key_values": past_key_values,
|
| 901 |
-
"use_cache": use_cache,
|
| 902 |
-
"cache_position": cache_position,
|
| 903 |
-
"attention_mask": attention_mask,
|
| 904 |
-
}
|
| 905 |
-
model_inputs.update(kwargs)
|
| 906 |
-
return model_inputs
|
| 907 |
-
|
| 908 |
-
def _reorder_cache(self, past_key_values: SurjoCache, beam_idx):
|
| 909 |
-
for slot, (k, v) in past_key_values.kv.items():
|
| 910 |
-
past_key_values.kv[slot] = (k.index_select(0, beam_idx),
|
| 911 |
-
v.index_select(0, beam_idx))
|
| 912 |
-
for key in list(past_key_values.gdn_state.keys()):
|
| 913 |
-
s = past_key_values.gdn_state[key]
|
| 914 |
-
if s is not None:
|
| 915 |
-
past_key_values.gdn_state[key] = s.index_select(0, beam_idx)
|
| 916 |
-
for key in list(past_key_values.gdn_conv.keys()):
|
| 917 |
-
cs = past_key_values.gdn_conv[key]
|
| 918 |
-
if cs is not None:
|
| 919 |
-
past_key_values.gdn_conv[key] = tuple(
|
| 920 |
-
c.index_select(0, beam_idx) if c is not None else None for c in cs
|
| 921 |
-
)
|
| 922 |
-
return past_key_values
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
SurjoConfig.register_for_auto_class()
|
| 926 |
-
SurjoForCausalLM.register_for_auto_class()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/optimizer.bin
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:967151e939f37797c229ea14fa72f92a68435418b62251eb097af6488e532fad
|
| 3 |
-
size 148034507
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/optimizer_1.bin
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:157010ade80de4660d8fe9c541a7e1262cee4c9b3435c396a76abed8ef9c5cde
|
| 3 |
-
size 134405851
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/random_states_0.pkl
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:d40bd742577a21d618dea12387d03f8b61a77aca9c823ed92049267177110e08
|
| 3 |
-
size 14821
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-1000/tokenizer.json
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
checkpoint-1000/tokenizer_config.json
DELETED
|
@@ -1,85 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"backend": "tokenizers",
|
| 3 |
-
"bos_token": "<|bos|>",
|
| 4 |
-
"clean_up_tokenization_spaces": false,
|
| 5 |
-
"eos_token": "<|eos|>",
|
| 6 |
-
"extra_special_tokens": [
|
| 7 |
-
"<|unk|>",
|
| 8 |
-
"<|pad|>",
|
| 9 |
-
"<|bos|>",
|
| 10 |
-
"<|eos|>",
|
| 11 |
-
"<|mask|>",
|
| 12 |
-
"<|im_start|>",
|
| 13 |
-
"<|im_end|>",
|
| 14 |
-
"<|system|>",
|
| 15 |
-
"<|user|>",
|
| 16 |
-
"<|assistant|>",
|
| 17 |
-
"<think>",
|
| 18 |
-
"</think>",
|
| 19 |
-
"<|begin_of_thought|>",
|
| 20 |
-
"<|end_of_thought|>",
|
| 21 |
-
"<answer>",
|
| 22 |
-
"</answer>",
|
| 23 |
-
"<|step|>",
|
| 24 |
-
"<|/step|>",
|
| 25 |
-
"<context>",
|
| 26 |
-
"</context>",
|
| 27 |
-
"<|doc_start|>",
|
| 28 |
-
"<|doc_end|>",
|
| 29 |
-
"<|search|>",
|
| 30 |
-
"<|search_results|>",
|
| 31 |
-
"<|tool_list_start|>",
|
| 32 |
-
"<|tool_list_end|>",
|
| 33 |
-
"<tools>",
|
| 34 |
-
"</tools>",
|
| 35 |
-
"<|tool_call_start|>",
|
| 36 |
-
"<|tool_call_end|>",
|
| 37 |
-
"<|tool_call|>",
|
| 38 |
-
"<|/tool_call|>",
|
| 39 |
-
"<|tool_response_start|>",
|
| 40 |
-
"<|tool_response_end|>",
|
| 41 |
-
"<|tool_response|>",
|
| 42 |
-
"<|/tool_response|>",
|
| 43 |
-
"<|image|>",
|
| 44 |
-
"<|image_pad|>",
|
| 45 |
-
"<|image_placeholder|>",
|
| 46 |
-
"<|audio|>",
|
| 47 |
-
"<|audio_pad|>",
|
| 48 |
-
"<|audio_placeholder|>",
|
| 49 |
-
"<|video|>",
|
| 50 |
-
"<|video_pad|>",
|
| 51 |
-
"<|fim_prefix|>",
|
| 52 |
-
"<|fim_suffix|>",
|
| 53 |
-
"<|fim_middle|>",
|
| 54 |
-
"<|repo_name|>",
|
| 55 |
-
"<|file_separator|>",
|
| 56 |
-
"<|reward|>",
|
| 57 |
-
"<|reserved_0|>",
|
| 58 |
-
"<|reserved_1|>",
|
| 59 |
-
"<|reserved_2|>",
|
| 60 |
-
"<|reserved_3|>",
|
| 61 |
-
"<|reserved_4|>",
|
| 62 |
-
"<|reserved_5|>",
|
| 63 |
-
"<|reserved_6|>",
|
| 64 |
-
"<|reserved_7|>",
|
| 65 |
-
"<|reserved_8|>",
|
| 66 |
-
"<|reserved_9|>",
|
| 67 |
-
"<|reserved_10|>",
|
| 68 |
-
"<|reserved_11|>",
|
| 69 |
-
"<|reserved_12|>",
|
| 70 |
-
"<|reserved_13|>",
|
| 71 |
-
"<|reserved_14|>",
|
| 72 |
-
"<|reserved_15|>",
|
| 73 |
-
"<|reserved_16|>",
|
| 74 |
-
"<|reserved_17|>",
|
| 75 |
-
"<|reserved_18|>",
|
| 76 |
-
"<|reserved_19|>"
|
| 77 |
-
],
|
| 78 |
-
"is_local": false,
|
| 79 |
-
"local_files_only": false,
|
| 80 |
-
"mask_token": "<|mask|>",
|
| 81 |
-
"model_max_length": 10000000,
|
| 82 |
-
"pad_token": "<|pad|>",
|
| 83 |
-
"tokenizer_class": "TokenizersBackend",
|
| 84 |
-
"unk_token": "<|unk|>"
|
| 85 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/chat_template.jinja
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
-
' + message['content'] + '<|im_end|>
|
| 3 |
-
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
-
' }}{% endif %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/config.json
DELETED
|
@@ -1,62 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_use_flash_xsa": true,
|
| 3 |
-
"architectures": [
|
| 4 |
-
"SurjoForCausalLM"
|
| 5 |
-
],
|
| 6 |
-
"attention_bias": false,
|
| 7 |
-
"attention_dropout": 0.0,
|
| 8 |
-
"auto_map": {
|
| 9 |
-
"AutoConfig": "configuration_surjo.SurjoConfig",
|
| 10 |
-
"AutoModel": "modeling_surjo.SurjoForCausalLM",
|
| 11 |
-
"AutoModelForCausalLM": "modeling_surjo.SurjoForCausalLM"
|
| 12 |
-
},
|
| 13 |
-
"coda_layers": 1,
|
| 14 |
-
"dtype": "float32",
|
| 15 |
-
"gdn_allow_neg_eigval": false,
|
| 16 |
-
"gdn_conv_kernel_size": 4,
|
| 17 |
-
"gdn_key_dim": 64,
|
| 18 |
-
"gdn_num_v_heads": 8,
|
| 19 |
-
"gdn_per_xsa": 3,
|
| 20 |
-
"gdn_value_dim": 64,
|
| 21 |
-
"gradient_checkpointing": false,
|
| 22 |
-
"head_dim": 64,
|
| 23 |
-
"hidden_act": "silu",
|
| 24 |
-
"hidden_size": 512,
|
| 25 |
-
"initializer_range": 0.02,
|
| 26 |
-
"intermediate_size": 1536,
|
| 27 |
-
"layer_types": [
|
| 28 |
-
"full_attention",
|
| 29 |
-
"linear_attention",
|
| 30 |
-
"linear_attention",
|
| 31 |
-
"linear_attention",
|
| 32 |
-
"full_attention",
|
| 33 |
-
"linear_attention",
|
| 34 |
-
"linear_attention",
|
| 35 |
-
"linear_attention",
|
| 36 |
-
"full_attention",
|
| 37 |
-
"full_attention"
|
| 38 |
-
],
|
| 39 |
-
"loop_noise_std": 0.02,
|
| 40 |
-
"max_position_embeddings": 2048,
|
| 41 |
-
"model_type": "surjo",
|
| 42 |
-
"num_attention_heads": 8,
|
| 43 |
-
"num_groups": 2,
|
| 44 |
-
"num_hidden_layers": 10,
|
| 45 |
-
"num_key_value_heads": 4,
|
| 46 |
-
"partial_rotary_factor": 1.0,
|
| 47 |
-
"prelude_layers": 1,
|
| 48 |
-
"recurrent_layers": 8,
|
| 49 |
-
"recurrent_passes": 2,
|
| 50 |
-
"rms_norm_eps": 1e-05,
|
| 51 |
-
"rope_parameters": {
|
| 52 |
-
"partial_rotary_factor": 1.0,
|
| 53 |
-
"rope_theta": 10000.0,
|
| 54 |
-
"rope_type": "default"
|
| 55 |
-
},
|
| 56 |
-
"rope_theta": 10000.0,
|
| 57 |
-
"tie_word_embeddings": true,
|
| 58 |
-
"transformers_version": "5.16.1",
|
| 59 |
-
"use_cache": false,
|
| 60 |
-
"vocab_size": 32768,
|
| 61 |
-
"xsa_projection": true
|
| 62 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/configuration_surjo.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""Surjo gen-3 model configuration."""
|
| 5 |
-
|
| 6 |
-
from typing import List, Optional
|
| 7 |
-
from transformers import PretrainedConfig
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
class SurjoConfig(PretrainedConfig):
|
| 11 |
-
r"""Configuration for the Surjo gen-3 hybrid architecture."""
|
| 12 |
-
|
| 13 |
-
model_type = "surjo"
|
| 14 |
-
keys_to_ignore_at_inference = ["past_key_values"]
|
| 15 |
-
|
| 16 |
-
def __init__(
|
| 17 |
-
self,
|
| 18 |
-
vocab_size: int = 50257,
|
| 19 |
-
hidden_size: int = 384,
|
| 20 |
-
intermediate_size: int = 1024,
|
| 21 |
-
num_attention_heads: int = 6,
|
| 22 |
-
num_key_value_heads: int = 2,
|
| 23 |
-
head_dim: int = 64,
|
| 24 |
-
hidden_act: str = "silu",
|
| 25 |
-
max_position_embeddings: int = 2048,
|
| 26 |
-
initializer_range: float = 0.02,
|
| 27 |
-
rms_norm_eps: float = 1e-6,
|
| 28 |
-
tie_word_embeddings: bool = True,
|
| 29 |
-
rope_theta: float = 10000.0,
|
| 30 |
-
attention_dropout: float = 0.0,
|
| 31 |
-
attention_bias: bool = False,
|
| 32 |
-
prelude_layers: int = 1,
|
| 33 |
-
recurrent_layers: int = 8,
|
| 34 |
-
coda_layers: int = 1,
|
| 35 |
-
recurrent_passes: int = 2,
|
| 36 |
-
loop_noise_std: float = 0.02,
|
| 37 |
-
gdn_per_xsa: int = 3,
|
| 38 |
-
gdn_key_dim: Optional[int] = None,
|
| 39 |
-
gdn_value_dim: Optional[int] = None,
|
| 40 |
-
gdn_num_v_heads: Optional[int] = None,
|
| 41 |
-
gdn_conv_kernel_size: int = 4,
|
| 42 |
-
gdn_allow_neg_eigval: bool = False,
|
| 43 |
-
xsa_projection: bool = True,
|
| 44 |
-
rope_parameters: Optional[dict] = None,
|
| 45 |
-
rope_scaling: Optional[dict] = None,
|
| 46 |
-
partial_rotary_factor: float = 1.0,
|
| 47 |
-
gradient_checkpointing: bool = False,
|
| 48 |
-
use_cache: bool = True,
|
| 49 |
-
**kwargs,
|
| 50 |
-
):
|
| 51 |
-
self.vocab_size = vocab_size
|
| 52 |
-
self.hidden_size = hidden_size
|
| 53 |
-
self.intermediate_size = intermediate_size
|
| 54 |
-
self.num_attention_heads = num_attention_heads
|
| 55 |
-
self.num_key_value_heads = num_key_value_heads
|
| 56 |
-
self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads
|
| 57 |
-
self.hidden_act = hidden_act
|
| 58 |
-
self.max_position_embeddings = max_position_embeddings
|
| 59 |
-
self.initializer_range = initializer_range
|
| 60 |
-
self.rms_norm_eps = rms_norm_eps
|
| 61 |
-
self.tie_word_embeddings = tie_word_embeddings
|
| 62 |
-
self.rope_theta = rope_theta
|
| 63 |
-
self.attention_dropout = attention_dropout
|
| 64 |
-
self.attention_bias = attention_bias
|
| 65 |
-
|
| 66 |
-
self.prelude_layers = prelude_layers
|
| 67 |
-
self.recurrent_layers = recurrent_layers
|
| 68 |
-
self.coda_layers = coda_layers
|
| 69 |
-
self.recurrent_passes = recurrent_passes
|
| 70 |
-
self.loop_noise_std = loop_noise_std
|
| 71 |
-
self.gdn_per_xsa = gdn_per_xsa
|
| 72 |
-
|
| 73 |
-
self.gdn_key_dim = gdn_key_dim if gdn_key_dim is not None else self.head_dim
|
| 74 |
-
self.gdn_value_dim = gdn_value_dim if gdn_value_dim is not None else self.head_dim
|
| 75 |
-
self.gdn_num_v_heads = (
|
| 76 |
-
gdn_num_v_heads if gdn_num_v_heads is not None else num_attention_heads
|
| 77 |
-
)
|
| 78 |
-
self.gdn_conv_kernel_size = gdn_conv_kernel_size
|
| 79 |
-
self.gdn_allow_neg_eigval = gdn_allow_neg_eigval
|
| 80 |
-
|
| 81 |
-
self.xsa_projection = xsa_projection
|
| 82 |
-
|
| 83 |
-
if rope_parameters is not None:
|
| 84 |
-
self.rope_parameters = dict(rope_parameters)
|
| 85 |
-
elif rope_scaling is not None:
|
| 86 |
-
self.rope_parameters = dict(rope_scaling)
|
| 87 |
-
else:
|
| 88 |
-
self.rope_parameters = {"rope_type": "default"}
|
| 89 |
-
self.rope_parameters.setdefault("rope_type", "default")
|
| 90 |
-
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
| 91 |
-
if self.rope_parameters.get("rope_type") != "default":
|
| 92 |
-
self.rope_parameters.setdefault("factor", 1.0)
|
| 93 |
-
self.rope_scaling = dict(self.rope_parameters)
|
| 94 |
-
self.partial_rotary_factor = partial_rotary_factor
|
| 95 |
-
|
| 96 |
-
self.gradient_checkpointing = gradient_checkpointing
|
| 97 |
-
self.use_cache = use_cache
|
| 98 |
-
|
| 99 |
-
group = gdn_per_xsa + 1
|
| 100 |
-
if recurrent_layers % group != 0:
|
| 101 |
-
raise ValueError(
|
| 102 |
-
f"recurrent_layers ({recurrent_layers}) must be divisible by "
|
| 103 |
-
f"gdn_per_xsa + 1 = {group}"
|
| 104 |
-
)
|
| 105 |
-
if num_attention_heads % num_key_value_heads != 0:
|
| 106 |
-
raise ValueError(
|
| 107 |
-
f"num_attention_heads ({num_attention_heads}) must be divisible by "
|
| 108 |
-
f"num_key_value_heads ({num_key_value_heads})"
|
| 109 |
-
)
|
| 110 |
-
if (
|
| 111 |
-
self.gdn_num_v_heads < num_attention_heads
|
| 112 |
-
or self.gdn_num_v_heads % num_attention_heads != 0
|
| 113 |
-
):
|
| 114 |
-
raise ValueError(
|
| 115 |
-
f"gdn_num_v_heads ({self.gdn_num_v_heads}) must be >= "
|
| 116 |
-
f"num_attention_heads ({num_attention_heads}) and divisible by it"
|
| 117 |
-
)
|
| 118 |
-
valid_rope_types = {"default", "linear", "dynamic", "yarn", "longrope", "llama3"}
|
| 119 |
-
rt = self.rope_parameters.get("rope_type", "default")
|
| 120 |
-
if rt not in valid_rope_types:
|
| 121 |
-
raise ValueError(f"rope_type must be one of {valid_rope_types}, got {rt}")
|
| 122 |
-
|
| 123 |
-
self.num_groups = recurrent_layers // group
|
| 124 |
-
self.num_hidden_layers = prelude_layers + recurrent_layers + coda_layers
|
| 125 |
-
self.layer_types = self._build_layer_types()
|
| 126 |
-
|
| 127 |
-
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 128 |
-
|
| 129 |
-
def _build_layer_types(self) -> List[str]:
|
| 130 |
-
types = ["full_attention"] * self.prelude_layers
|
| 131 |
-
for _ in range(self.num_groups):
|
| 132 |
-
types.extend(["linear_attention"] * self.gdn_per_xsa)
|
| 133 |
-
types.append("full_attention")
|
| 134 |
-
types.extend(["full_attention"] * self.coda_layers)
|
| 135 |
-
assert len(types) == self.num_hidden_layers
|
| 136 |
-
return types
|
| 137 |
-
|
| 138 |
-
@property
|
| 139 |
-
def surjo_layer_types(self) -> List[str]:
|
| 140 |
-
return ["xsa" if t == "full_attention" else "gdn" for t in self.layer_types]
|
| 141 |
-
|
| 142 |
-
@property
|
| 143 |
-
def effective_num_layers(self) -> int:
|
| 144 |
-
return (
|
| 145 |
-
self.prelude_layers
|
| 146 |
-
+ self.recurrent_layers * self.recurrent_passes
|
| 147 |
-
+ self.coda_layers
|
| 148 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/generation_config.json
DELETED
|
@@ -1,7 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_from_model_config": true,
|
| 3 |
-
"output_attentions": false,
|
| 4 |
-
"output_hidden_states": false,
|
| 5 |
-
"transformers_version": "5.16.1",
|
| 6 |
-
"use_cache": false
|
| 7 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/model.safetensors
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:7446de985a1bc372cc3b96e80543b79a5082dc2d24c3677f34fd994783fb6a95
|
| 3 |
-
size 215196728
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/modeling_surjo.py
DELETED
|
@@ -1,926 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""SurjoLabs Surjo Architecture"""
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
from typing import Dict, List, Optional, Tuple
|
| 8 |
-
|
| 9 |
-
import torch
|
| 10 |
-
import torch.nn as nn
|
| 11 |
-
import torch.nn.functional as F
|
| 12 |
-
import torch.utils.checkpoint
|
| 13 |
-
|
| 14 |
-
from transformers import PreTrainedModel
|
| 15 |
-
from transformers.activations import ACT2FN
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
from transformers import GenerationMixin
|
| 19 |
-
except ImportError:
|
| 20 |
-
from transformers.generation import GenerationMixin
|
| 21 |
-
from transformers.modeling_outputs import (
|
| 22 |
-
BaseModelOutputWithPast,
|
| 23 |
-
CausalLMOutputWithPast,
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
from .configuration_surjo import SurjoConfig
|
| 28 |
-
except (ImportError, ValueError):
|
| 29 |
-
from configuration_surjo import SurjoConfig
|
| 30 |
-
|
| 31 |
-
try:
|
| 32 |
-
from fla.modules.fused_linear_cross_entropy import (
|
| 33 |
-
fused_linear_cross_entropy_loss as _fla_flce,
|
| 34 |
-
)
|
| 35 |
-
except ImportError:
|
| 36 |
-
try:
|
| 37 |
-
from fla.modules import fused_linear_cross_entropy_loss as _fla_flce
|
| 38 |
-
except ImportError:
|
| 39 |
-
_fla_flce = None
|
| 40 |
-
|
| 41 |
-
try:
|
| 42 |
-
from fla.modules.norm import rms_norm as _fla_rms_norm
|
| 43 |
-
except ImportError:
|
| 44 |
-
try:
|
| 45 |
-
from fla.modules import rms_norm as _fla_rms_norm
|
| 46 |
-
except ImportError:
|
| 47 |
-
_fla_rms_norm = None
|
| 48 |
-
|
| 49 |
-
try:
|
| 50 |
-
from fla.ops.gdn2 import chunk_gdn2, fused_recurrent_gdn2
|
| 51 |
-
FLA_AVAILABLE = True
|
| 52 |
-
except ImportError:
|
| 53 |
-
chunk_gdn2 = None
|
| 54 |
-
fused_recurrent_gdn2 = None
|
| 55 |
-
FLA_AVAILABLE = False
|
| 56 |
-
|
| 57 |
-
_USE_FLA_FUSED_CE = True
|
| 58 |
-
_USE_FLA_RMS_NORM = False
|
| 59 |
-
|
| 60 |
-
if FLA_AVAILABLE:
|
| 61 |
-
|
| 62 |
-
@torch.compiler.disable
|
| 63 |
-
def _fla_chunk(q, k, v, g, b, w, initial_state=None, output_final_state=False,
|
| 64 |
-
cu_seqlens=None):
|
| 65 |
-
return chunk_gdn2(
|
| 66 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 67 |
-
initial_state=initial_state,
|
| 68 |
-
output_final_state=output_final_state,
|
| 69 |
-
use_qk_l2norm_in_kernel=True,
|
| 70 |
-
cu_seqlens=cu_seqlens,
|
| 71 |
-
)
|
| 72 |
-
|
| 73 |
-
@torch.compiler.disable
|
| 74 |
-
def _fla_recurrent(q, k, v, g, b, w, initial_state=None, output_final_state=False):
|
| 75 |
-
return fused_recurrent_gdn2(
|
| 76 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 77 |
-
initial_state=initial_state,
|
| 78 |
-
output_final_state=output_final_state,
|
| 79 |
-
use_qk_l2norm_in_kernel=True,
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
try:
|
| 83 |
-
from flash_attn import flash_attn_varlen_func
|
| 84 |
-
FLASH_ATTN_AVAILABLE = True
|
| 85 |
-
except ImportError:
|
| 86 |
-
flash_attn_varlen_func = None
|
| 87 |
-
FLASH_ATTN_AVAILABLE = False
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def _mask_padding_states(hidden_states, padding_mask):
|
| 91 |
-
if padding_mask is not None:
|
| 92 |
-
return hidden_states * padding_mask.unsqueeze(-1).to(hidden_states.dtype)
|
| 93 |
-
return hidden_states
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def naive_gdn2_reference(q, k, v, g, b, w, initial_state=None):
|
| 97 |
-
"""fp32 reference for GDN-2."""
|
| 98 |
-
B, T, H, K = q.shape
|
| 99 |
-
V = v.shape[-1]
|
| 100 |
-
S = (
|
| 101 |
-
torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)
|
| 102 |
-
if initial_state is None
|
| 103 |
-
else initial_state.float()
|
| 104 |
-
)
|
| 105 |
-
scale = K ** -0.5
|
| 106 |
-
outs = []
|
| 107 |
-
for t in range(T):
|
| 108 |
-
q_t = F.normalize(q[:, t], dim=-1)
|
| 109 |
-
k_t = F.normalize(k[:, t], dim=-1)
|
| 110 |
-
v_t, g_t, b_t, w_t = v[:, t], g[:, t], b[:, t], w[:, t]
|
| 111 |
-
S = S * torch.exp(g_t).unsqueeze(-1)
|
| 112 |
-
e = b_t * k_t
|
| 113 |
-
r = torch.einsum("bhkv,bhk->bhv", S, e)
|
| 114 |
-
z = w_t * v_t
|
| 115 |
-
S = S + torch.einsum("bhk,bhv->bhkv", k_t, z - r)
|
| 116 |
-
outs.append(scale * torch.einsum("bhkv,bhk->bhv", S, q_t))
|
| 117 |
-
return torch.stack(outs, dim=1), S
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
class SurjoRMSNorm(nn.Module):
|
| 121 |
-
"""FLA Triton RMSNorm when available; else fused ATen F.rms_norm."""
|
| 122 |
-
|
| 123 |
-
def __init__(self, dim: int, eps: float = 1e-6):
|
| 124 |
-
super().__init__()
|
| 125 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 126 |
-
self.eps = eps
|
| 127 |
-
|
| 128 |
-
def forward(self, x):
|
| 129 |
-
if x.dtype != self.weight.dtype:
|
| 130 |
-
x = x.to(self.weight.dtype)
|
| 131 |
-
if _USE_FLA_RMS_NORM and _fla_rms_norm is not None and x.is_cuda:
|
| 132 |
-
return _fla_rms_norm(x, self.weight, None, eps=self.eps)
|
| 133 |
-
return F.rms_norm(x, (x.shape[-1],), self.weight, self.eps)
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class ClampedMLP(nn.Module):
|
| 137 |
-
def __init__(self, config):
|
| 138 |
-
hidden_size = config.hidden_size
|
| 139 |
-
intermediate_size = config.intermediate_size
|
| 140 |
-
super().__init__()
|
| 141 |
-
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 142 |
-
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 143 |
-
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
| 144 |
-
self.act_fn = ACT2FN[config.hidden_act]
|
| 145 |
-
|
| 146 |
-
def forward(self, x):
|
| 147 |
-
return self.down_proj(
|
| 148 |
-
self.act_fn(self.gate_proj(x).clamp(-15.0, 15.0)) * self.up_proj(x)
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
class SurjoRotaryEmbedding(nn.Module):
|
| 153 |
-
"""RoPE with frequencies computed in forward() (no stored buffer)."""
|
| 154 |
-
|
| 155 |
-
def __init__(self, config, device=None):
|
| 156 |
-
super().__init__()
|
| 157 |
-
self.config = config
|
| 158 |
-
self.rope_type = config.rope_parameters.get("rope_type", "default")
|
| 159 |
-
self.max_position_embeddings = config.max_position_embeddings
|
| 160 |
-
self.base = config.rope_parameters.get("rope_theta", config.rope_theta)
|
| 161 |
-
self.factor = config.rope_parameters.get("factor", 1.0)
|
| 162 |
-
self.dim = int(config.head_dim * config.partial_rotary_factor)
|
| 163 |
-
|
| 164 |
-
def _inv_freq(self, device):
|
| 165 |
-
inv = 1.0 / (
|
| 166 |
-
self.base
|
| 167 |
-
** (torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim)
|
| 168 |
-
)
|
| 169 |
-
if self.rope_type == "linear":
|
| 170 |
-
inv = inv / self.factor
|
| 171 |
-
return inv
|
| 172 |
-
|
| 173 |
-
@torch.no_grad()
|
| 174 |
-
def forward(self, position_ids):
|
| 175 |
-
inv = self._inv_freq(position_ids.device)
|
| 176 |
-
freqs = torch.einsum("bt,f->btf", position_ids.float(), inv)
|
| 177 |
-
emb = torch.cat([freqs, freqs], dim=-1)
|
| 178 |
-
return emb.cos(), emb.sin()
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def rotate_half(x):
|
| 182 |
-
x1, x2 = x.chunk(2, dim=-1)
|
| 183 |
-
return torch.cat((-x2, x1), dim=-1)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def apply_rope(q, k, cos, sin):
|
| 187 |
-
cos = cos[:, None, :, :].to(q.dtype)
|
| 188 |
-
sin = sin[:, None, :, :].to(q.dtype)
|
| 189 |
-
q = q * cos + rotate_half(q) * sin
|
| 190 |
-
k = k * cos + rotate_half(k) * sin
|
| 191 |
-
return q, k
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
def apply_rope_flat(q, k, cos, sin):
|
| 195 |
-
"""RoPE on flat varlen tensors. q, k: [total, H, D]; cos, sin: [B, T, D]."""
|
| 196 |
-
total = q.shape[0]
|
| 197 |
-
cos_f = cos.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 198 |
-
sin_f = sin.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 199 |
-
q = q * cos_f + rotate_half(q) * sin_f
|
| 200 |
-
k = k * cos_f + rotate_half(k) * sin_f
|
| 201 |
-
return q, k
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
@torch.compiler.disable
|
| 205 |
-
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen):
|
| 206 |
-
"""FA2 varlen. cu_seqlens device int32; max_seqlen a constant (no sync)."""
|
| 207 |
-
return flash_attn_varlen_func(
|
| 208 |
-
q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen,
|
| 209 |
-
dropout_p=0.0, causal=True,
|
| 210 |
-
)
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
class ShortConvolution(nn.Module):
|
| 214 |
-
def __init__(self, dim: int, kernel_size: int = 4):
|
| 215 |
-
super().__init__()
|
| 216 |
-
self.kernel_size = kernel_size
|
| 217 |
-
self.conv = nn.Conv1d(dim, dim, kernel_size, groups=dim, bias=False)
|
| 218 |
-
|
| 219 |
-
def forward(self, x, cache=None, output_state=False):
|
| 220 |
-
B, T, C = x.shape
|
| 221 |
-
xt = x.transpose(1, 2)
|
| 222 |
-
if T == 1 and cache is not None:
|
| 223 |
-
comb = torch.cat([cache, xt], dim=2)
|
| 224 |
-
w = self.conv.weight.squeeze(1)
|
| 225 |
-
out = F.silu(torch.einsum("bck,ck->bc", comb, w).unsqueeze(-1))
|
| 226 |
-
new = comb[:, :, 1:] if output_state else None
|
| 227 |
-
return out.transpose(1, 2), new
|
| 228 |
-
if cache is not None:
|
| 229 |
-
xt_in = torch.cat([cache, xt], dim=2)
|
| 230 |
-
else:
|
| 231 |
-
xt_in = F.pad(xt, (self.kernel_size - 1, 0))
|
| 232 |
-
out = F.silu(self.conv(xt_in))
|
| 233 |
-
new = xt_in[:, :, -(self.kernel_size - 1):] if output_state else None
|
| 234 |
-
return out.transpose(1, 2), new
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
class SurjoCache:
|
| 238 |
-
def __init__(self):
|
| 239 |
-
self.kv = {}
|
| 240 |
-
self.gdn_state = {}
|
| 241 |
-
self.gdn_conv = {}
|
| 242 |
-
|
| 243 |
-
def get_seq_length(self):
|
| 244 |
-
if not self.kv:
|
| 245 |
-
return 0
|
| 246 |
-
return next(iter(self.kv.values()))[0].shape[2]
|
| 247 |
-
|
| 248 |
-
@staticmethod
|
| 249 |
-
def num_xsa_slots(config):
|
| 250 |
-
return (
|
| 251 |
-
config.prelude_layers
|
| 252 |
-
+ config.num_groups * config.recurrent_passes
|
| 253 |
-
+ config.coda_layers
|
| 254 |
-
)
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
class XSAAttention(nn.Module):
|
| 258 |
-
"""Full attention with XSA value-projection subtraction."""
|
| 259 |
-
|
| 260 |
-
def __init__(self, config, layer_idx: int):
|
| 261 |
-
super().__init__()
|
| 262 |
-
self.layer_idx = layer_idx
|
| 263 |
-
self.num_heads = config.num_attention_heads
|
| 264 |
-
self.num_kv_heads = config.num_key_value_heads
|
| 265 |
-
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 266 |
-
self.head_dim = config.head_dim
|
| 267 |
-
self.xsa_projection = config.xsa_projection
|
| 268 |
-
self.dropout = config.attention_dropout
|
| 269 |
-
self.hidden_size = config.hidden_size
|
| 270 |
-
self.use_flash = getattr(config, "_use_flash_xsa", False)
|
| 271 |
-
self.q_proj = nn.Linear(
|
| 272 |
-
self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
|
| 273 |
-
)
|
| 274 |
-
self.k_proj = nn.Linear(
|
| 275 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 276 |
-
)
|
| 277 |
-
self.v_proj = nn.Linear(
|
| 278 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 279 |
-
)
|
| 280 |
-
self.o_proj = nn.Linear(
|
| 281 |
-
self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias
|
| 282 |
-
)
|
| 283 |
-
self.q_norm = SurjoRMSNorm(self.head_dim)
|
| 284 |
-
self.k_norm = SurjoRMSNorm(self.head_dim)
|
| 285 |
-
|
| 286 |
-
def _xsa_projection_step(self, attn, v):
|
| 287 |
-
dv = (attn.float() * v.float()).sum(dim=-1, keepdim=True)
|
| 288 |
-
vv = (v.float() * v.float()).sum(dim=-1, keepdim=True).clamp_min(1e-4)
|
| 289 |
-
scale = (dv / vv).to(attn.dtype)
|
| 290 |
-
return attn - scale * v
|
| 291 |
-
|
| 292 |
-
def forward(self, hidden_states, attention_mask, cache, slot, use_cache,
|
| 293 |
-
cache_position, cos, sin, cu_seqlens=None):
|
| 294 |
-
B, T, _ = hidden_states.shape
|
| 295 |
-
H, Hkv, D = self.num_heads, self.num_kv_heads, self.head_dim
|
| 296 |
-
|
| 297 |
-
q = self.q_proj(hidden_states).view(B, T, H, D).transpose(1, 2)
|
| 298 |
-
k = self.k_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 299 |
-
v = self.v_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 300 |
-
q = self.q_norm(q)
|
| 301 |
-
k = self.k_norm(k)
|
| 302 |
-
|
| 303 |
-
use_varlen = (
|
| 304 |
-
cu_seqlens is not None
|
| 305 |
-
and cache is None
|
| 306 |
-
and self.use_flash
|
| 307 |
-
and FLASH_ATTN_AVAILABLE
|
| 308 |
-
and hidden_states.is_cuda
|
| 309 |
-
)
|
| 310 |
-
if use_varlen:
|
| 311 |
-
total = B * T
|
| 312 |
-
q_f = q.transpose(1, 2).reshape(total, H, D).to(torch.bfloat16)
|
| 313 |
-
k_f = k.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 314 |
-
v_f = v.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 315 |
-
if Hkv != H:
|
| 316 |
-
k_f = k_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 317 |
-
v_f = v_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 318 |
-
q_f, k_f = apply_rope_flat(q_f, k_f, cos, sin)
|
| 319 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 320 |
-
o_f = _flash_varlen(q_f, k_f, v_f, cu_dev, T)
|
| 321 |
-
attn_out = o_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 322 |
-
v_xsa = v_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 323 |
-
if self.xsa_projection:
|
| 324 |
-
attn_out = self._xsa_projection_step(attn_out, v_xsa)
|
| 325 |
-
out = attn_out.reshape(B, T, H * D)
|
| 326 |
-
return self.o_proj(out)
|
| 327 |
-
|
| 328 |
-
q, k = apply_rope(q, k, cos, sin)
|
| 329 |
-
v_cur = v
|
| 330 |
-
if cache is not None and use_cache:
|
| 331 |
-
if slot in cache.kv:
|
| 332 |
-
pk, pv = cache.kv[slot]
|
| 333 |
-
k = torch.cat([pk, k.to(pk.dtype)], dim=2)
|
| 334 |
-
v = torch.cat([pv, v.to(pv.dtype)], dim=2)
|
| 335 |
-
cache.kv[slot] = (k, v)
|
| 336 |
-
S = k.shape[2]
|
| 337 |
-
if Hkv != H:
|
| 338 |
-
k_e = k.repeat_interleave(self.num_kv_groups, dim=1)
|
| 339 |
-
v_e = v.repeat_interleave(self.num_kv_groups, dim=1)
|
| 340 |
-
v_cur_e = v_cur.repeat_interleave(self.num_kv_groups, dim=1)
|
| 341 |
-
else:
|
| 342 |
-
k_e, v_e, v_cur_e = k, v, v_cur
|
| 343 |
-
|
| 344 |
-
is_causal = False
|
| 345 |
-
mask4 = None
|
| 346 |
-
if attention_mask is not None:
|
| 347 |
-
L = attention_mask.shape[-1]
|
| 348 |
-
if L < S:
|
| 349 |
-
attention_mask = F.pad(attention_mask, (S - L, 0), value=1)
|
| 350 |
-
elif L > S:
|
| 351 |
-
attention_mask = attention_mask[:, -S:]
|
| 352 |
-
neg = torch.finfo(q.dtype).min
|
| 353 |
-
m = attention_mask[:, None, None, :].to(q.dtype)
|
| 354 |
-
if T == S:
|
| 355 |
-
if T > 1:
|
| 356 |
-
causal = torch.ones(T, S, device=q.device, dtype=q.dtype).tril()
|
| 357 |
-
allow = causal[None, None] * m
|
| 358 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 359 |
-
torch.full_like(allow, neg))
|
| 360 |
-
else:
|
| 361 |
-
mask4 = torch.where(m > 0, torch.zeros_like(m),
|
| 362 |
-
torch.full_like(m, neg))
|
| 363 |
-
else:
|
| 364 |
-
if cache_position is None:
|
| 365 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 366 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 367 |
-
causal = kv_pos[None, :] <= cache_position[:, None].to(q.device)
|
| 368 |
-
allow = causal[None, None].to(q.dtype) * m
|
| 369 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 370 |
-
torch.full_like(allow, neg))
|
| 371 |
-
elif cu_seqlens is not None and T > 1:
|
| 372 |
-
neg = torch.finfo(q.dtype).min
|
| 373 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32)
|
| 374 |
-
gpos = torch.arange(B * T, device=q.device)
|
| 375 |
-
doc_id = torch.searchsorted(cu_dev, gpos, right=True) - 1
|
| 376 |
-
doc_id = doc_id.clamp(min=0).view(B, T)
|
| 377 |
-
same = doc_id.unsqueeze(2) == doc_id.unsqueeze(1)
|
| 378 |
-
idx = torch.arange(T, device=q.device)
|
| 379 |
-
causal = idx.unsqueeze(0) <= idx.unsqueeze(1)
|
| 380 |
-
allow = (same & causal).unsqueeze(1)
|
| 381 |
-
mask4 = torch.where(
|
| 382 |
-
allow,
|
| 383 |
-
torch.zeros(B, 1, T, T, dtype=q.dtype, device=q.device),
|
| 384 |
-
torch.full((B, 1, T, T), neg, dtype=q.dtype, device=q.device),
|
| 385 |
-
)
|
| 386 |
-
else:
|
| 387 |
-
if T == S and T > 1:
|
| 388 |
-
is_causal = True
|
| 389 |
-
elif T > 1:
|
| 390 |
-
if cache_position is None:
|
| 391 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 392 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 393 |
-
neg = torch.finfo(q.dtype).min
|
| 394 |
-
causal = torch.zeros(T, S, device=q.device, dtype=q.dtype)
|
| 395 |
-
causal = causal.masked_fill(
|
| 396 |
-
kv_pos[None, :] > cache_position[:, None], neg
|
| 397 |
-
)
|
| 398 |
-
mask4 = causal[None, None, :, :]
|
| 399 |
-
|
| 400 |
-
attn = F.scaled_dot_product_attention(
|
| 401 |
-
q, k_e, v_e, attn_mask=mask4, is_causal=is_causal,
|
| 402 |
-
dropout_p=self.dropout if self.training else 0.0,
|
| 403 |
-
)
|
| 404 |
-
|
| 405 |
-
if self.xsa_projection:
|
| 406 |
-
attn = self._xsa_projection_step(attn, v_cur_e)
|
| 407 |
-
|
| 408 |
-
out = attn.transpose(1, 2).reshape(B, T, H * D)
|
| 409 |
-
return self.o_proj(out)
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
class GDN2Attention(nn.Module):
|
| 413 |
-
"""Gated DeltaNet-2 linear attention."""
|
| 414 |
-
|
| 415 |
-
def __init__(self, config, layer_idx: int):
|
| 416 |
-
super().__init__()
|
| 417 |
-
self.layer_idx = layer_idx
|
| 418 |
-
H = config.num_attention_heads
|
| 419 |
-
Hv = config.gdn_num_v_heads
|
| 420 |
-
self.num_heads = H
|
| 421 |
-
self.num_v_heads = Hv
|
| 422 |
-
self.gva = Hv // H
|
| 423 |
-
self.head_k_dim = config.gdn_key_dim
|
| 424 |
-
self.head_v_dim = config.gdn_value_dim
|
| 425 |
-
self.key_dim = H * self.head_k_dim
|
| 426 |
-
self.value_dim = Hv * self.head_v_dim
|
| 427 |
-
self.conv_kernel = config.gdn_conv_kernel_size
|
| 428 |
-
self.allow_neg_eigval = config.gdn_allow_neg_eigval
|
| 429 |
-
hidden = config.hidden_size
|
| 430 |
-
self.q_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 431 |
-
self.k_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 432 |
-
self.v_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 433 |
-
self.q_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 434 |
-
self.k_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 435 |
-
self.v_conv = ShortConvolution(self.value_dim, self.conv_kernel)
|
| 436 |
-
self.f_proj = nn.Sequential(
|
| 437 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 438 |
-
nn.Linear(self.head_v_dim, self.key_dim, bias=False),
|
| 439 |
-
)
|
| 440 |
-
self.b_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 441 |
-
self.w_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 442 |
-
self.A_log = nn.Parameter(
|
| 443 |
-
torch.log(torch.empty(H, dtype=torch.float32).uniform_(1, 16))
|
| 444 |
-
)
|
| 445 |
-
self.A_log._no_weight_decay = True
|
| 446 |
-
dt = torch.exp(
|
| 447 |
-
torch.rand(self.key_dim, dtype=torch.float32)
|
| 448 |
-
* (math.log(0.1) - math.log(0.001))
|
| 449 |
-
+ math.log(0.001)
|
| 450 |
-
).clamp(min=1e-4)
|
| 451 |
-
self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt)))
|
| 452 |
-
self.dt_bias._no_weight_decay = True
|
| 453 |
-
self.g_proj = nn.Sequential(
|
| 454 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 455 |
-
nn.Linear(self.head_v_dim, self.value_dim, bias=True),
|
| 456 |
-
)
|
| 457 |
-
self.o_norm = SurjoRMSNorm(self.head_v_dim, eps=config.rms_norm_eps)
|
| 458 |
-
self.o_proj = nn.Linear(self.value_dim, hidden, bias=False)
|
| 459 |
-
|
| 460 |
-
def forward(self, hidden_states, attention_mask, gdn_state, conv_state,
|
| 461 |
-
output_state, cu_seqlens=None):
|
| 462 |
-
B, T, _ = hidden_states.shape
|
| 463 |
-
if attention_mask is not None:
|
| 464 |
-
if attention_mask.shape[-1] != T:
|
| 465 |
-
attention_mask = (
|
| 466 |
-
attention_mask[:, -T:] if attention_mask.shape[-1] > T else None
|
| 467 |
-
)
|
| 468 |
-
if attention_mask is not None:
|
| 469 |
-
hidden_states = _mask_padding_states(hidden_states, attention_mask)
|
| 470 |
-
cq = conv_state[0] if conv_state is not None else None
|
| 471 |
-
ck = conv_state[1] if conv_state is not None else None
|
| 472 |
-
cvs = conv_state[2] if conv_state is not None else None
|
| 473 |
-
q, nq = self.q_conv(self.q_proj(hidden_states), cq, output_state)
|
| 474 |
-
k, nk = self.k_conv(self.k_proj(hidden_states), ck, output_state)
|
| 475 |
-
v, nv = self.v_conv(self.v_proj(hidden_states), cvs, output_state)
|
| 476 |
-
g = F.softplus(self.f_proj(hidden_states).float() + self.dt_bias)
|
| 477 |
-
b = self.b_proj(hidden_states).sigmoid()
|
| 478 |
-
w = self.w_proj(hidden_states).sigmoid()
|
| 479 |
-
q = q.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 480 |
-
k = k.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 481 |
-
v = v.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 482 |
-
g = g.view(B, T, self.num_heads, self.head_k_dim)
|
| 483 |
-
b = b.view(B, T, self.num_heads, self.head_k_dim)
|
| 484 |
-
w = w.view(B, T, self.num_v_heads, self.head_v_dim)
|
| 485 |
-
g = -self.A_log.float().exp().view(1, 1, self.num_heads, 1) * g
|
| 486 |
-
if self.allow_neg_eigval:
|
| 487 |
-
b = b * 2.0
|
| 488 |
-
if self.gva > 1:
|
| 489 |
-
q = q.repeat_interleave(self.gva, dim=2)
|
| 490 |
-
k = k.repeat_interleave(self.gva, dim=2)
|
| 491 |
-
g = g.repeat_interleave(self.gva, dim=2)
|
| 492 |
-
b = b.repeat_interleave(self.gva, dim=2)
|
| 493 |
-
init = gdn_state.float() if gdn_state is not None else None
|
| 494 |
-
|
| 495 |
-
if FLA_AVAILABLE and hidden_states.is_cuda:
|
| 496 |
-
if T == 1 and init is not None:
|
| 497 |
-
o, fs = _fla_recurrent(q, k, v, g, b, w, init, output_state)
|
| 498 |
-
elif cu_seqlens is not None:
|
| 499 |
-
total = B * T
|
| 500 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 501 |
-
q_f = q.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 502 |
-
k_f = k.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 503 |
-
v_f = v.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 504 |
-
g_f = g.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 505 |
-
b_f = b.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 506 |
-
w_f = w.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 507 |
-
o, fs = _fla_chunk(q_f, k_f, v_f, g_f, b_f, w_f, init,
|
| 508 |
-
output_state, cu_dev)
|
| 509 |
-
o = o.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 510 |
-
else:
|
| 511 |
-
o, fs = _fla_chunk(q, k, v, g, b, w, init, output_state, None)
|
| 512 |
-
else:
|
| 513 |
-
o, fs = naive_gdn2_reference(q.float(), k.float(), v.float(), g,
|
| 514 |
-
b.float(), w.float(), init)
|
| 515 |
-
|
| 516 |
-
# Cast back to activation precision
|
| 517 |
-
o = o.to(hidden_states.dtype)
|
| 518 |
-
|
| 519 |
-
fs = fs if output_state else None
|
| 520 |
-
gate = self.g_proj(hidden_states).view(B, T, self.num_v_heads, self.head_v_dim)
|
| 521 |
-
o = self.o_norm(o)
|
| 522 |
-
o = o * torch.sigmoid(gate)
|
| 523 |
-
o = o.reshape(B, T, self.value_dim)
|
| 524 |
-
conv_out = (nq, nk, nv) if output_state else None
|
| 525 |
-
return self.o_proj(o), fs, conv_out
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
def _is_xsa(config, li: int) -> bool:
|
| 529 |
-
if li < config.prelude_layers:
|
| 530 |
-
return True
|
| 531 |
-
if li >= config.prelude_layers + config.recurrent_layers:
|
| 532 |
-
return True
|
| 533 |
-
return (li - config.prelude_layers) % (config.gdn_per_xsa + 1) == config.gdn_per_xsa
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
class SurjoDecoderLayer(nn.Module):
|
| 537 |
-
def __init__(self, config, layer_idx: int):
|
| 538 |
-
super().__init__()
|
| 539 |
-
self.layer_idx = layer_idx
|
| 540 |
-
self.layer_type = "xsa" if _is_xsa(config, layer_idx) else "gdn"
|
| 541 |
-
if self.layer_type == "xsa":
|
| 542 |
-
self.self_attn = XSAAttention(config, layer_idx)
|
| 543 |
-
else:
|
| 544 |
-
self.linear_attn = GDN2Attention(config, layer_idx)
|
| 545 |
-
self.mlp = ClampedMLP(config)
|
| 546 |
-
self.input_layernorm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 547 |
-
self.post_attention_layernorm = SurjoRMSNorm(config.hidden_size,
|
| 548 |
-
eps=config.rms_norm_eps)
|
| 549 |
-
|
| 550 |
-
def forward(self, hidden_states, attention_mask=None, cos=None, sin=None,
|
| 551 |
-
cu_seqlens=None):
|
| 552 |
-
h = self.input_layernorm(hidden_states)
|
| 553 |
-
if self.layer_type == "xsa":
|
| 554 |
-
out = self.self_attn(h, attention_mask, None, -1, False, None,
|
| 555 |
-
cos, sin, cu_seqlens)
|
| 556 |
-
else:
|
| 557 |
-
out, _, _ = self.linear_attn(h, attention_mask, None, None, False,
|
| 558 |
-
cu_seqlens)
|
| 559 |
-
hidden_states = hidden_states + out
|
| 560 |
-
h2 = self.post_attention_layernorm(hidden_states)
|
| 561 |
-
return hidden_states + self.mlp(h2)
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
class SurjoPreTrainedModel(PreTrainedModel):
|
| 565 |
-
config_class = SurjoConfig
|
| 566 |
-
base_model_prefix = "model"
|
| 567 |
-
_no_split_modules = ["SurjoDecoderLayer"]
|
| 568 |
-
_supports_flash_attn = False
|
| 569 |
-
_supports_flash_attn_2 = False
|
| 570 |
-
_supports_sdpa = True
|
| 571 |
-
_is_stateful = True
|
| 572 |
-
_can_compile_fullgraph = True
|
| 573 |
-
|
| 574 |
-
def _init_weights(self, module):
|
| 575 |
-
std = self.config.initializer_range
|
| 576 |
-
if isinstance(module, nn.Linear):
|
| 577 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 578 |
-
if module.bias is not None:
|
| 579 |
-
module.bias.data.zero_()
|
| 580 |
-
elif isinstance(module, nn.Embedding):
|
| 581 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 582 |
-
if module.padding_idx is not None:
|
| 583 |
-
module.weight.data[module.padding_idx].zero_()
|
| 584 |
-
elif isinstance(module, GDN2Attention):
|
| 585 |
-
module.A_log.data.copy_(
|
| 586 |
-
torch.log(
|
| 587 |
-
torch.empty(module.num_heads, dtype=torch.float32,
|
| 588 |
-
device=module.A_log.device).uniform_(1, 16)
|
| 589 |
-
)
|
| 590 |
-
)
|
| 591 |
-
dt = torch.exp(
|
| 592 |
-
torch.rand(module.key_dim, dtype=torch.float32,
|
| 593 |
-
device=module.dt_bias.device)
|
| 594 |
-
* (math.log(0.1) - math.log(0.001)) + math.log(0.001)
|
| 595 |
-
).clamp(min=1e-4)
|
| 596 |
-
module.dt_bias.data.copy_(dt + torch.log(-torch.expm1(-dt)))
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
class SurjoModel(SurjoPreTrainedModel):
|
| 600 |
-
def __init__(self, config):
|
| 601 |
-
super().__init__(config)
|
| 602 |
-
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 603 |
-
self.layers = nn.ModuleList(
|
| 604 |
-
[SurjoDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 605 |
-
)
|
| 606 |
-
self.norm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 607 |
-
self.rotary = SurjoRotaryEmbedding(config)
|
| 608 |
-
self.grad_checkpointing = False
|
| 609 |
-
|
| 610 |
-
slot = 0
|
| 611 |
-
self.xsa_slot_map = {}
|
| 612 |
-
self.exec_plan = []
|
| 613 |
-
for li in range(config.prelude_layers):
|
| 614 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 615 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 616 |
-
slot += 1
|
| 617 |
-
for p in range(config.recurrent_passes):
|
| 618 |
-
for g in range(config.num_groups):
|
| 619 |
-
base = config.prelude_layers + g * (config.gdn_per_xsa + 1)
|
| 620 |
-
for j in range(config.gdn_per_xsa):
|
| 621 |
-
self.exec_plan.append((self.layers[base + j], base + j, p, -1))
|
| 622 |
-
li = base + config.gdn_per_xsa
|
| 623 |
-
self.xsa_slot_map[(li, p)] = slot
|
| 624 |
-
self.exec_plan.append((self.layers[li], li, p, slot))
|
| 625 |
-
slot += 1
|
| 626 |
-
for li in range(config.prelude_layers + config.recurrent_layers,
|
| 627 |
-
config.num_hidden_layers):
|
| 628 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 629 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 630 |
-
slot += 1
|
| 631 |
-
self.num_xsa_slots = slot
|
| 632 |
-
self.post_init()
|
| 633 |
-
|
| 634 |
-
def get_input_embeddings(self):
|
| 635 |
-
return self.embed_tokens
|
| 636 |
-
|
| 637 |
-
def set_input_embeddings(self, value):
|
| 638 |
-
self.embed_tokens = value
|
| 639 |
-
|
| 640 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 641 |
-
past_key_values=None, inputs_embeds=None, use_cache=None,
|
| 642 |
-
cache_position=None, return_dict=True,
|
| 643 |
-
output_hidden_states=False, output_attentions=False,
|
| 644 |
-
cu_seqlens=None, **kwargs):
|
| 645 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 646 |
-
past_key_values = None
|
| 647 |
-
if use_cache is None:
|
| 648 |
-
use_cache = past_key_values is not None
|
| 649 |
-
if use_cache and past_key_values is None:
|
| 650 |
-
past_key_values = SurjoCache()
|
| 651 |
-
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 652 |
-
|
| 653 |
-
if past_len > 0:
|
| 654 |
-
if input_ids is not None:
|
| 655 |
-
n_ids = input_ids.shape[1]
|
| 656 |
-
if (attention_mask is not None
|
| 657 |
-
and attention_mask.shape[-1] > n_ids
|
| 658 |
-
and attention_mask.shape[-1] > past_len):
|
| 659 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 660 |
-
input_ids = input_ids[:, -n_new:] if n_new <= n_ids else input_ids
|
| 661 |
-
elif n_ids > past_len:
|
| 662 |
-
input_ids = input_ids[:, past_len:]
|
| 663 |
-
else:
|
| 664 |
-
input_ids = input_ids[:, -1:]
|
| 665 |
-
elif inputs_embeds is not None:
|
| 666 |
-
n_emb = inputs_embeds.shape[1]
|
| 667 |
-
if (attention_mask is not None
|
| 668 |
-
and attention_mask.shape[-1] > n_emb
|
| 669 |
-
and attention_mask.shape[-1] > past_len):
|
| 670 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 671 |
-
inputs_embeds = (inputs_embeds[:, -n_new:] if n_new <= n_emb
|
| 672 |
-
else inputs_embeds)
|
| 673 |
-
elif n_emb > past_len:
|
| 674 |
-
inputs_embeds = inputs_embeds[:, past_len:]
|
| 675 |
-
else:
|
| 676 |
-
inputs_embeds = inputs_embeds[:, -1:]
|
| 677 |
-
|
| 678 |
-
if inputs_embeds is None:
|
| 679 |
-
if input_ids is None:
|
| 680 |
-
raise ValueError("Specify input_ids or inputs_embeds")
|
| 681 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
| 682 |
-
B, T = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 683 |
-
|
| 684 |
-
cache_position = torch.arange(past_len, past_len + T,
|
| 685 |
-
device=inputs_embeds.device)
|
| 686 |
-
if position_ids is not None and position_ids.shape[-1] != T:
|
| 687 |
-
position_ids = None
|
| 688 |
-
if position_ids is None:
|
| 689 |
-
position_ids = cache_position.unsqueeze(0).expand(B, -1)
|
| 690 |
-
cos, sin = self.rotary(position_ids)
|
| 691 |
-
|
| 692 |
-
gdn_states = dict(past_key_values.gdn_state) if past_key_values is not None else {}
|
| 693 |
-
conv_states = dict(past_key_values.gdn_conv) if past_key_values is not None else {}
|
| 694 |
-
|
| 695 |
-
noise_std = self.config.loop_noise_std
|
| 696 |
-
hidden = inputs_embeds
|
| 697 |
-
prev_p = 0
|
| 698 |
-
use_ckpt = self.training and self.grad_checkpointing
|
| 699 |
-
all_hidden_states = () if output_hidden_states else None
|
| 700 |
-
|
| 701 |
-
for (layer, li, p, slot) in self.exec_plan:
|
| 702 |
-
if output_hidden_states:
|
| 703 |
-
all_hidden_states += (hidden,)
|
| 704 |
-
if p != prev_p and p > 0 and self.training and noise_std > 0.0:
|
| 705 |
-
hidden = hidden + torch.randn_like(hidden) * noise_std
|
| 706 |
-
prev_p = p
|
| 707 |
-
|
| 708 |
-
if use_ckpt:
|
| 709 |
-
hidden = torch.utils.checkpoint.checkpoint(
|
| 710 |
-
self._train_layer, layer, hidden, attention_mask, cos, sin,
|
| 711 |
-
cu_seqlens, use_reentrant=False,
|
| 712 |
-
)
|
| 713 |
-
elif use_cache:
|
| 714 |
-
h = layer.input_layernorm(hidden)
|
| 715 |
-
if layer.layer_type == "xsa":
|
| 716 |
-
out = layer.self_attn(h, attention_mask, past_key_values,
|
| 717 |
-
slot, use_cache, cache_position,
|
| 718 |
-
cos, sin, cu_seqlens)
|
| 719 |
-
else:
|
| 720 |
-
gs = gdn_states.get((li, p))
|
| 721 |
-
cs = conv_states.get((li, p))
|
| 722 |
-
out, ngs, ncs = layer.linear_attn(h, attention_mask, gs, cs,
|
| 723 |
-
use_cache, cu_seqlens)
|
| 724 |
-
if ngs is not None:
|
| 725 |
-
gdn_states[(li, p)] = ngs
|
| 726 |
-
if ncs is not None:
|
| 727 |
-
conv_states[(li, p)] = ncs
|
| 728 |
-
hidden = hidden + out
|
| 729 |
-
h2 = layer.post_attention_layernorm(hidden)
|
| 730 |
-
hidden = hidden + layer.mlp(h2)
|
| 731 |
-
else:
|
| 732 |
-
hidden = layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 733 |
-
|
| 734 |
-
hidden = self.norm(hidden)
|
| 735 |
-
if output_hidden_states:
|
| 736 |
-
all_hidden_states += (hidden,)
|
| 737 |
-
|
| 738 |
-
if use_cache and past_key_values is not None:
|
| 739 |
-
past_key_values.gdn_state.update(gdn_states)
|
| 740 |
-
past_key_values.gdn_conv.update(conv_states)
|
| 741 |
-
|
| 742 |
-
if not return_dict:
|
| 743 |
-
out = tuple(v for v in [hidden, past_key_values if use_cache else None,
|
| 744 |
-
all_hidden_states] if v is not None)
|
| 745 |
-
return out
|
| 746 |
-
return BaseModelOutputWithPast(
|
| 747 |
-
last_hidden_state=hidden,
|
| 748 |
-
past_key_values=past_key_values if use_cache else None,
|
| 749 |
-
hidden_states=all_hidden_states,
|
| 750 |
-
attentions=None,
|
| 751 |
-
)
|
| 752 |
-
|
| 753 |
-
def _train_layer(self, layer, hidden, attention_mask, cos, sin, cu_seqlens):
|
| 754 |
-
return layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
class SurjoForCausalLM(SurjoPreTrainedModel, GenerationMixin):
|
| 758 |
-
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 759 |
-
|
| 760 |
-
def __init__(self, config):
|
| 761 |
-
super().__init__(config)
|
| 762 |
-
self.model = SurjoModel(config)
|
| 763 |
-
self.vocab_size = config.vocab_size
|
| 764 |
-
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 765 |
-
self.post_init()
|
| 766 |
-
|
| 767 |
-
def tie_weights(self, **kwargs):
|
| 768 |
-
try:
|
| 769 |
-
super().tie_weights(**kwargs)
|
| 770 |
-
except TypeError:
|
| 771 |
-
pass
|
| 772 |
-
except Exception:
|
| 773 |
-
pass
|
| 774 |
-
if (getattr(self.config, "tie_word_embeddings", False)
|
| 775 |
-
and getattr(self, "model", None) is not None
|
| 776 |
-
and getattr(self, "lm_head", None) is not None):
|
| 777 |
-
self.lm_head.weight = self.model.embed_tokens.weight
|
| 778 |
-
|
| 779 |
-
def save_pretrained(self, *args, **kwargs):
|
| 780 |
-
was_tied = (getattr(self, "lm_head", None) is not None
|
| 781 |
-
and getattr(self, "model", None) is not None
|
| 782 |
-
and self.lm_head.weight is self.model.embed_tokens.weight)
|
| 783 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 784 |
-
self.lm_head.weight = nn.Parameter(
|
| 785 |
-
self.model.embed_tokens.weight.detach().clone(),
|
| 786 |
-
requires_grad=self.model.embed_tokens.weight.requires_grad,
|
| 787 |
-
)
|
| 788 |
-
try:
|
| 789 |
-
return super().save_pretrained(*args, **kwargs)
|
| 790 |
-
finally:
|
| 791 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 792 |
-
self.tie_weights()
|
| 793 |
-
|
| 794 |
-
def get_input_embeddings(self):
|
| 795 |
-
return self.model.embed_tokens
|
| 796 |
-
|
| 797 |
-
def set_input_embeddings(self, value):
|
| 798 |
-
self.model.embed_tokens = value
|
| 799 |
-
|
| 800 |
-
def get_output_embeddings(self):
|
| 801 |
-
return self.lm_head
|
| 802 |
-
|
| 803 |
-
def set_output_embeddings(self, value):
|
| 804 |
-
self.lm_head = value
|
| 805 |
-
|
| 806 |
-
def set_decoder(self, decoder):
|
| 807 |
-
self.model = decoder
|
| 808 |
-
|
| 809 |
-
def get_decoder(self):
|
| 810 |
-
return self.model
|
| 811 |
-
|
| 812 |
-
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, **kwargs):
|
| 813 |
-
self.model.grad_checkpointing = True
|
| 814 |
-
|
| 815 |
-
def gradient_checkpointing_disable(self):
|
| 816 |
-
self.model.grad_checkpointing = False
|
| 817 |
-
|
| 818 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 819 |
-
past_key_values=None, inputs_embeds=None, labels=None,
|
| 820 |
-
use_cache=None, output_hidden_states=None, output_attentions=None,
|
| 821 |
-
return_dict=None, logits_to_keep=0, cache_position=None,
|
| 822 |
-
cu_seqlens=None, **kwargs):
|
| 823 |
-
if logits_to_keep in (None, 0) and kwargs.get("num_logits_to_keep"):
|
| 824 |
-
logits_to_keep = kwargs.pop("num_logits_to_keep")
|
| 825 |
-
return_dict = True if return_dict is None else return_dict
|
| 826 |
-
if use_cache is None:
|
| 827 |
-
use_cache = not (self.training or labels is not None)
|
| 828 |
-
|
| 829 |
-
outputs = self.model(
|
| 830 |
-
input_ids=input_ids, attention_mask=attention_mask,
|
| 831 |
-
position_ids=position_ids, past_key_values=past_key_values,
|
| 832 |
-
inputs_embeds=inputs_embeds, use_cache=use_cache,
|
| 833 |
-
cache_position=cache_position,
|
| 834 |
-
output_hidden_states=output_hidden_states,
|
| 835 |
-
output_attentions=output_attentions,
|
| 836 |
-
cu_seqlens=cu_seqlens,
|
| 837 |
-
**kwargs,
|
| 838 |
-
)
|
| 839 |
-
hidden_states = outputs[0]
|
| 840 |
-
|
| 841 |
-
loss, logits = None, None
|
| 842 |
-
if labels is not None:
|
| 843 |
-
sh = hidden_states[..., :-1, :].contiguous()
|
| 844 |
-
sl = labels[..., 1:].contiguous()
|
| 845 |
-
if _USE_FLA_FUSED_CE and _fla_flce is not None:
|
| 846 |
-
loss = _fla_flce(
|
| 847 |
-
sh.view(-1, sh.shape[-1]),
|
| 848 |
-
sl.view(-1),
|
| 849 |
-
self.lm_head.weight,
|
| 850 |
-
num_chunks=8,
|
| 851 |
-
reduction="mean",
|
| 852 |
-
)
|
| 853 |
-
else:
|
| 854 |
-
n_chunks = max(8, sh.shape[0] // 8)
|
| 855 |
-
tot = hidden_states.new_zeros((), dtype=torch.float32)
|
| 856 |
-
n_tok = 0
|
| 857 |
-
for h_c, l_c in zip(sh.chunk(n_chunks, dim=0), sl.chunk(n_chunks, dim=0)):
|
| 858 |
-
if l_c.numel() == 0:
|
| 859 |
-
continue
|
| 860 |
-
lg = self.lm_head(h_c)
|
| 861 |
-
tot = tot + F.cross_entropy(
|
| 862 |
-
lg.float().view(-1, lg.size(-1)), l_c.view(-1), reduction="sum"
|
| 863 |
-
)
|
| 864 |
-
n_tok += l_c.numel()
|
| 865 |
-
loss = tot / max(n_tok, 1)
|
| 866 |
-
else:
|
| 867 |
-
if isinstance(logits_to_keep, int) and logits_to_keep > 0:
|
| 868 |
-
sl_hidden = hidden_states[:, -logits_to_keep:, :]
|
| 869 |
-
elif torch.is_tensor(logits_to_keep):
|
| 870 |
-
sl_hidden = hidden_states[:, logits_to_keep, :]
|
| 871 |
-
else:
|
| 872 |
-
sl_hidden = hidden_states
|
| 873 |
-
logits = self.lm_head(sl_hidden)
|
| 874 |
-
|
| 875 |
-
if not return_dict:
|
| 876 |
-
out = (logits,) + outputs[1:]
|
| 877 |
-
return (loss,) + out if loss is not None else out
|
| 878 |
-
return CausalLMOutputWithPast(
|
| 879 |
-
loss=loss, logits=logits,
|
| 880 |
-
past_key_values=outputs.past_key_values,
|
| 881 |
-
hidden_states=outputs.hidden_states,
|
| 882 |
-
attentions=outputs.attentions,
|
| 883 |
-
)
|
| 884 |
-
|
| 885 |
-
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
|
| 886 |
-
attention_mask=None, inputs_embeds=None,
|
| 887 |
-
cache_position=None, use_cache=True, **kwargs):
|
| 888 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 889 |
-
past_key_values = None
|
| 890 |
-
has_state = past_key_values is not None and len(past_key_values.kv) > 0
|
| 891 |
-
if has_state:
|
| 892 |
-
input_ids = input_ids[:, -1:]
|
| 893 |
-
if kwargs.get("logits_to_keep") is None:
|
| 894 |
-
kwargs["logits_to_keep"] = 1
|
| 895 |
-
past_len = past_key_values.get_seq_length() if has_state else 0
|
| 896 |
-
cache_position = torch.arange(past_len, past_len + input_ids.shape[1],
|
| 897 |
-
device=input_ids.device)
|
| 898 |
-
model_inputs = {
|
| 899 |
-
"input_ids": input_ids.contiguous(),
|
| 900 |
-
"past_key_values": past_key_values,
|
| 901 |
-
"use_cache": use_cache,
|
| 902 |
-
"cache_position": cache_position,
|
| 903 |
-
"attention_mask": attention_mask,
|
| 904 |
-
}
|
| 905 |
-
model_inputs.update(kwargs)
|
| 906 |
-
return model_inputs
|
| 907 |
-
|
| 908 |
-
def _reorder_cache(self, past_key_values: SurjoCache, beam_idx):
|
| 909 |
-
for slot, (k, v) in past_key_values.kv.items():
|
| 910 |
-
past_key_values.kv[slot] = (k.index_select(0, beam_idx),
|
| 911 |
-
v.index_select(0, beam_idx))
|
| 912 |
-
for key in list(past_key_values.gdn_state.keys()):
|
| 913 |
-
s = past_key_values.gdn_state[key]
|
| 914 |
-
if s is not None:
|
| 915 |
-
past_key_values.gdn_state[key] = s.index_select(0, beam_idx)
|
| 916 |
-
for key in list(past_key_values.gdn_conv.keys()):
|
| 917 |
-
cs = past_key_values.gdn_conv[key]
|
| 918 |
-
if cs is not None:
|
| 919 |
-
past_key_values.gdn_conv[key] = tuple(
|
| 920 |
-
c.index_select(0, beam_idx) if c is not None else None for c in cs
|
| 921 |
-
)
|
| 922 |
-
return past_key_values
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
SurjoConfig.register_for_auto_class()
|
| 926 |
-
SurjoForCausalLM.register_for_auto_class()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/optimizer.bin
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:329160acb14ad89d30b66d262c4f163a6a38360ff4be17f0602534fa887e01d0
|
| 3 |
-
size 148034507
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/optimizer_1.bin
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:f4e8fe1c9ad35ca5d4cb90c625ac6e1351e65e92d848090f51eadf7d99f6e4b4
|
| 3 |
-
size 134405851
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/random_states_0.pkl
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:a56e4c6f6a6f8275a982682f65388f684d03e1e8168844e5f2c802364cc8e1f3
|
| 3 |
-
size 14821
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10000/tokenizer.json
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
checkpoint-10000/tokenizer_config.json
DELETED
|
@@ -1,85 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"backend": "tokenizers",
|
| 3 |
-
"bos_token": "<|bos|>",
|
| 4 |
-
"clean_up_tokenization_spaces": false,
|
| 5 |
-
"eos_token": "<|eos|>",
|
| 6 |
-
"extra_special_tokens": [
|
| 7 |
-
"<|unk|>",
|
| 8 |
-
"<|pad|>",
|
| 9 |
-
"<|bos|>",
|
| 10 |
-
"<|eos|>",
|
| 11 |
-
"<|mask|>",
|
| 12 |
-
"<|im_start|>",
|
| 13 |
-
"<|im_end|>",
|
| 14 |
-
"<|system|>",
|
| 15 |
-
"<|user|>",
|
| 16 |
-
"<|assistant|>",
|
| 17 |
-
"<think>",
|
| 18 |
-
"</think>",
|
| 19 |
-
"<|begin_of_thought|>",
|
| 20 |
-
"<|end_of_thought|>",
|
| 21 |
-
"<answer>",
|
| 22 |
-
"</answer>",
|
| 23 |
-
"<|step|>",
|
| 24 |
-
"<|/step|>",
|
| 25 |
-
"<context>",
|
| 26 |
-
"</context>",
|
| 27 |
-
"<|doc_start|>",
|
| 28 |
-
"<|doc_end|>",
|
| 29 |
-
"<|search|>",
|
| 30 |
-
"<|search_results|>",
|
| 31 |
-
"<|tool_list_start|>",
|
| 32 |
-
"<|tool_list_end|>",
|
| 33 |
-
"<tools>",
|
| 34 |
-
"</tools>",
|
| 35 |
-
"<|tool_call_start|>",
|
| 36 |
-
"<|tool_call_end|>",
|
| 37 |
-
"<|tool_call|>",
|
| 38 |
-
"<|/tool_call|>",
|
| 39 |
-
"<|tool_response_start|>",
|
| 40 |
-
"<|tool_response_end|>",
|
| 41 |
-
"<|tool_response|>",
|
| 42 |
-
"<|/tool_response|>",
|
| 43 |
-
"<|image|>",
|
| 44 |
-
"<|image_pad|>",
|
| 45 |
-
"<|image_placeholder|>",
|
| 46 |
-
"<|audio|>",
|
| 47 |
-
"<|audio_pad|>",
|
| 48 |
-
"<|audio_placeholder|>",
|
| 49 |
-
"<|video|>",
|
| 50 |
-
"<|video_pad|>",
|
| 51 |
-
"<|fim_prefix|>",
|
| 52 |
-
"<|fim_suffix|>",
|
| 53 |
-
"<|fim_middle|>",
|
| 54 |
-
"<|repo_name|>",
|
| 55 |
-
"<|file_separator|>",
|
| 56 |
-
"<|reward|>",
|
| 57 |
-
"<|reserved_0|>",
|
| 58 |
-
"<|reserved_1|>",
|
| 59 |
-
"<|reserved_2|>",
|
| 60 |
-
"<|reserved_3|>",
|
| 61 |
-
"<|reserved_4|>",
|
| 62 |
-
"<|reserved_5|>",
|
| 63 |
-
"<|reserved_6|>",
|
| 64 |
-
"<|reserved_7|>",
|
| 65 |
-
"<|reserved_8|>",
|
| 66 |
-
"<|reserved_9|>",
|
| 67 |
-
"<|reserved_10|>",
|
| 68 |
-
"<|reserved_11|>",
|
| 69 |
-
"<|reserved_12|>",
|
| 70 |
-
"<|reserved_13|>",
|
| 71 |
-
"<|reserved_14|>",
|
| 72 |
-
"<|reserved_15|>",
|
| 73 |
-
"<|reserved_16|>",
|
| 74 |
-
"<|reserved_17|>",
|
| 75 |
-
"<|reserved_18|>",
|
| 76 |
-
"<|reserved_19|>"
|
| 77 |
-
],
|
| 78 |
-
"is_local": false,
|
| 79 |
-
"local_files_only": false,
|
| 80 |
-
"mask_token": "<|mask|>",
|
| 81 |
-
"model_max_length": 10000000,
|
| 82 |
-
"pad_token": "<|pad|>",
|
| 83 |
-
"tokenizer_class": "TokenizersBackend",
|
| 84 |
-
"unk_token": "<|unk|>"
|
| 85 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/chat_template.jinja
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
-
' + message['content'] + '<|im_end|>
|
| 3 |
-
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
-
' }}{% endif %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/config.json
DELETED
|
@@ -1,62 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_use_flash_xsa": true,
|
| 3 |
-
"architectures": [
|
| 4 |
-
"SurjoForCausalLM"
|
| 5 |
-
],
|
| 6 |
-
"attention_bias": false,
|
| 7 |
-
"attention_dropout": 0.0,
|
| 8 |
-
"auto_map": {
|
| 9 |
-
"AutoConfig": "configuration_surjo.SurjoConfig",
|
| 10 |
-
"AutoModel": "modeling_surjo.SurjoForCausalLM",
|
| 11 |
-
"AutoModelForCausalLM": "modeling_surjo.SurjoForCausalLM"
|
| 12 |
-
},
|
| 13 |
-
"coda_layers": 1,
|
| 14 |
-
"dtype": "float32",
|
| 15 |
-
"gdn_allow_neg_eigval": false,
|
| 16 |
-
"gdn_conv_kernel_size": 4,
|
| 17 |
-
"gdn_key_dim": 64,
|
| 18 |
-
"gdn_num_v_heads": 8,
|
| 19 |
-
"gdn_per_xsa": 3,
|
| 20 |
-
"gdn_value_dim": 64,
|
| 21 |
-
"gradient_checkpointing": false,
|
| 22 |
-
"head_dim": 64,
|
| 23 |
-
"hidden_act": "silu",
|
| 24 |
-
"hidden_size": 512,
|
| 25 |
-
"initializer_range": 0.02,
|
| 26 |
-
"intermediate_size": 1536,
|
| 27 |
-
"layer_types": [
|
| 28 |
-
"full_attention",
|
| 29 |
-
"linear_attention",
|
| 30 |
-
"linear_attention",
|
| 31 |
-
"linear_attention",
|
| 32 |
-
"full_attention",
|
| 33 |
-
"linear_attention",
|
| 34 |
-
"linear_attention",
|
| 35 |
-
"linear_attention",
|
| 36 |
-
"full_attention",
|
| 37 |
-
"full_attention"
|
| 38 |
-
],
|
| 39 |
-
"loop_noise_std": 0.02,
|
| 40 |
-
"max_position_embeddings": 2048,
|
| 41 |
-
"model_type": "surjo",
|
| 42 |
-
"num_attention_heads": 8,
|
| 43 |
-
"num_groups": 2,
|
| 44 |
-
"num_hidden_layers": 10,
|
| 45 |
-
"num_key_value_heads": 4,
|
| 46 |
-
"partial_rotary_factor": 1.0,
|
| 47 |
-
"prelude_layers": 1,
|
| 48 |
-
"recurrent_layers": 8,
|
| 49 |
-
"recurrent_passes": 2,
|
| 50 |
-
"rms_norm_eps": 1e-05,
|
| 51 |
-
"rope_parameters": {
|
| 52 |
-
"partial_rotary_factor": 1.0,
|
| 53 |
-
"rope_theta": 10000.0,
|
| 54 |
-
"rope_type": "default"
|
| 55 |
-
},
|
| 56 |
-
"rope_theta": 10000.0,
|
| 57 |
-
"tie_word_embeddings": true,
|
| 58 |
-
"transformers_version": "5.16.1",
|
| 59 |
-
"use_cache": false,
|
| 60 |
-
"vocab_size": 32768,
|
| 61 |
-
"xsa_projection": true
|
| 62 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/configuration_surjo.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""Surjo gen-3 model configuration."""
|
| 5 |
-
|
| 6 |
-
from typing import List, Optional
|
| 7 |
-
from transformers import PretrainedConfig
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
class SurjoConfig(PretrainedConfig):
|
| 11 |
-
r"""Configuration for the Surjo gen-3 hybrid architecture."""
|
| 12 |
-
|
| 13 |
-
model_type = "surjo"
|
| 14 |
-
keys_to_ignore_at_inference = ["past_key_values"]
|
| 15 |
-
|
| 16 |
-
def __init__(
|
| 17 |
-
self,
|
| 18 |
-
vocab_size: int = 50257,
|
| 19 |
-
hidden_size: int = 384,
|
| 20 |
-
intermediate_size: int = 1024,
|
| 21 |
-
num_attention_heads: int = 6,
|
| 22 |
-
num_key_value_heads: int = 2,
|
| 23 |
-
head_dim: int = 64,
|
| 24 |
-
hidden_act: str = "silu",
|
| 25 |
-
max_position_embeddings: int = 2048,
|
| 26 |
-
initializer_range: float = 0.02,
|
| 27 |
-
rms_norm_eps: float = 1e-6,
|
| 28 |
-
tie_word_embeddings: bool = True,
|
| 29 |
-
rope_theta: float = 10000.0,
|
| 30 |
-
attention_dropout: float = 0.0,
|
| 31 |
-
attention_bias: bool = False,
|
| 32 |
-
prelude_layers: int = 1,
|
| 33 |
-
recurrent_layers: int = 8,
|
| 34 |
-
coda_layers: int = 1,
|
| 35 |
-
recurrent_passes: int = 2,
|
| 36 |
-
loop_noise_std: float = 0.02,
|
| 37 |
-
gdn_per_xsa: int = 3,
|
| 38 |
-
gdn_key_dim: Optional[int] = None,
|
| 39 |
-
gdn_value_dim: Optional[int] = None,
|
| 40 |
-
gdn_num_v_heads: Optional[int] = None,
|
| 41 |
-
gdn_conv_kernel_size: int = 4,
|
| 42 |
-
gdn_allow_neg_eigval: bool = False,
|
| 43 |
-
xsa_projection: bool = True,
|
| 44 |
-
rope_parameters: Optional[dict] = None,
|
| 45 |
-
rope_scaling: Optional[dict] = None,
|
| 46 |
-
partial_rotary_factor: float = 1.0,
|
| 47 |
-
gradient_checkpointing: bool = False,
|
| 48 |
-
use_cache: bool = True,
|
| 49 |
-
**kwargs,
|
| 50 |
-
):
|
| 51 |
-
self.vocab_size = vocab_size
|
| 52 |
-
self.hidden_size = hidden_size
|
| 53 |
-
self.intermediate_size = intermediate_size
|
| 54 |
-
self.num_attention_heads = num_attention_heads
|
| 55 |
-
self.num_key_value_heads = num_key_value_heads
|
| 56 |
-
self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads
|
| 57 |
-
self.hidden_act = hidden_act
|
| 58 |
-
self.max_position_embeddings = max_position_embeddings
|
| 59 |
-
self.initializer_range = initializer_range
|
| 60 |
-
self.rms_norm_eps = rms_norm_eps
|
| 61 |
-
self.tie_word_embeddings = tie_word_embeddings
|
| 62 |
-
self.rope_theta = rope_theta
|
| 63 |
-
self.attention_dropout = attention_dropout
|
| 64 |
-
self.attention_bias = attention_bias
|
| 65 |
-
|
| 66 |
-
self.prelude_layers = prelude_layers
|
| 67 |
-
self.recurrent_layers = recurrent_layers
|
| 68 |
-
self.coda_layers = coda_layers
|
| 69 |
-
self.recurrent_passes = recurrent_passes
|
| 70 |
-
self.loop_noise_std = loop_noise_std
|
| 71 |
-
self.gdn_per_xsa = gdn_per_xsa
|
| 72 |
-
|
| 73 |
-
self.gdn_key_dim = gdn_key_dim if gdn_key_dim is not None else self.head_dim
|
| 74 |
-
self.gdn_value_dim = gdn_value_dim if gdn_value_dim is not None else self.head_dim
|
| 75 |
-
self.gdn_num_v_heads = (
|
| 76 |
-
gdn_num_v_heads if gdn_num_v_heads is not None else num_attention_heads
|
| 77 |
-
)
|
| 78 |
-
self.gdn_conv_kernel_size = gdn_conv_kernel_size
|
| 79 |
-
self.gdn_allow_neg_eigval = gdn_allow_neg_eigval
|
| 80 |
-
|
| 81 |
-
self.xsa_projection = xsa_projection
|
| 82 |
-
|
| 83 |
-
if rope_parameters is not None:
|
| 84 |
-
self.rope_parameters = dict(rope_parameters)
|
| 85 |
-
elif rope_scaling is not None:
|
| 86 |
-
self.rope_parameters = dict(rope_scaling)
|
| 87 |
-
else:
|
| 88 |
-
self.rope_parameters = {"rope_type": "default"}
|
| 89 |
-
self.rope_parameters.setdefault("rope_type", "default")
|
| 90 |
-
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
| 91 |
-
if self.rope_parameters.get("rope_type") != "default":
|
| 92 |
-
self.rope_parameters.setdefault("factor", 1.0)
|
| 93 |
-
self.rope_scaling = dict(self.rope_parameters)
|
| 94 |
-
self.partial_rotary_factor = partial_rotary_factor
|
| 95 |
-
|
| 96 |
-
self.gradient_checkpointing = gradient_checkpointing
|
| 97 |
-
self.use_cache = use_cache
|
| 98 |
-
|
| 99 |
-
group = gdn_per_xsa + 1
|
| 100 |
-
if recurrent_layers % group != 0:
|
| 101 |
-
raise ValueError(
|
| 102 |
-
f"recurrent_layers ({recurrent_layers}) must be divisible by "
|
| 103 |
-
f"gdn_per_xsa + 1 = {group}"
|
| 104 |
-
)
|
| 105 |
-
if num_attention_heads % num_key_value_heads != 0:
|
| 106 |
-
raise ValueError(
|
| 107 |
-
f"num_attention_heads ({num_attention_heads}) must be divisible by "
|
| 108 |
-
f"num_key_value_heads ({num_key_value_heads})"
|
| 109 |
-
)
|
| 110 |
-
if (
|
| 111 |
-
self.gdn_num_v_heads < num_attention_heads
|
| 112 |
-
or self.gdn_num_v_heads % num_attention_heads != 0
|
| 113 |
-
):
|
| 114 |
-
raise ValueError(
|
| 115 |
-
f"gdn_num_v_heads ({self.gdn_num_v_heads}) must be >= "
|
| 116 |
-
f"num_attention_heads ({num_attention_heads}) and divisible by it"
|
| 117 |
-
)
|
| 118 |
-
valid_rope_types = {"default", "linear", "dynamic", "yarn", "longrope", "llama3"}
|
| 119 |
-
rt = self.rope_parameters.get("rope_type", "default")
|
| 120 |
-
if rt not in valid_rope_types:
|
| 121 |
-
raise ValueError(f"rope_type must be one of {valid_rope_types}, got {rt}")
|
| 122 |
-
|
| 123 |
-
self.num_groups = recurrent_layers // group
|
| 124 |
-
self.num_hidden_layers = prelude_layers + recurrent_layers + coda_layers
|
| 125 |
-
self.layer_types = self._build_layer_types()
|
| 126 |
-
|
| 127 |
-
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 128 |
-
|
| 129 |
-
def _build_layer_types(self) -> List[str]:
|
| 130 |
-
types = ["full_attention"] * self.prelude_layers
|
| 131 |
-
for _ in range(self.num_groups):
|
| 132 |
-
types.extend(["linear_attention"] * self.gdn_per_xsa)
|
| 133 |
-
types.append("full_attention")
|
| 134 |
-
types.extend(["full_attention"] * self.coda_layers)
|
| 135 |
-
assert len(types) == self.num_hidden_layers
|
| 136 |
-
return types
|
| 137 |
-
|
| 138 |
-
@property
|
| 139 |
-
def surjo_layer_types(self) -> List[str]:
|
| 140 |
-
return ["xsa" if t == "full_attention" else "gdn" for t in self.layer_types]
|
| 141 |
-
|
| 142 |
-
@property
|
| 143 |
-
def effective_num_layers(self) -> int:
|
| 144 |
-
return (
|
| 145 |
-
self.prelude_layers
|
| 146 |
-
+ self.recurrent_layers * self.recurrent_passes
|
| 147 |
-
+ self.coda_layers
|
| 148 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/generation_config.json
DELETED
|
@@ -1,7 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_from_model_config": true,
|
| 3 |
-
"output_attentions": false,
|
| 4 |
-
"output_hidden_states": false,
|
| 5 |
-
"transformers_version": "5.16.1",
|
| 6 |
-
"use_cache": false
|
| 7 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/model.safetensors
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:f9aee4cb4e131c9a6a77f9a56b3db728622e4450c2b318043c9804031008949d
|
| 3 |
-
size 215196728
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/modeling_surjo.py
DELETED
|
@@ -1,926 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""SurjoLabs Surjo Architecture"""
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
from typing import Dict, List, Optional, Tuple
|
| 8 |
-
|
| 9 |
-
import torch
|
| 10 |
-
import torch.nn as nn
|
| 11 |
-
import torch.nn.functional as F
|
| 12 |
-
import torch.utils.checkpoint
|
| 13 |
-
|
| 14 |
-
from transformers import PreTrainedModel
|
| 15 |
-
from transformers.activations import ACT2FN
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
from transformers import GenerationMixin
|
| 19 |
-
except ImportError:
|
| 20 |
-
from transformers.generation import GenerationMixin
|
| 21 |
-
from transformers.modeling_outputs import (
|
| 22 |
-
BaseModelOutputWithPast,
|
| 23 |
-
CausalLMOutputWithPast,
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
from .configuration_surjo import SurjoConfig
|
| 28 |
-
except (ImportError, ValueError):
|
| 29 |
-
from configuration_surjo import SurjoConfig
|
| 30 |
-
|
| 31 |
-
try:
|
| 32 |
-
from fla.modules.fused_linear_cross_entropy import (
|
| 33 |
-
fused_linear_cross_entropy_loss as _fla_flce,
|
| 34 |
-
)
|
| 35 |
-
except ImportError:
|
| 36 |
-
try:
|
| 37 |
-
from fla.modules import fused_linear_cross_entropy_loss as _fla_flce
|
| 38 |
-
except ImportError:
|
| 39 |
-
_fla_flce = None
|
| 40 |
-
|
| 41 |
-
try:
|
| 42 |
-
from fla.modules.norm import rms_norm as _fla_rms_norm
|
| 43 |
-
except ImportError:
|
| 44 |
-
try:
|
| 45 |
-
from fla.modules import rms_norm as _fla_rms_norm
|
| 46 |
-
except ImportError:
|
| 47 |
-
_fla_rms_norm = None
|
| 48 |
-
|
| 49 |
-
try:
|
| 50 |
-
from fla.ops.gdn2 import chunk_gdn2, fused_recurrent_gdn2
|
| 51 |
-
FLA_AVAILABLE = True
|
| 52 |
-
except ImportError:
|
| 53 |
-
chunk_gdn2 = None
|
| 54 |
-
fused_recurrent_gdn2 = None
|
| 55 |
-
FLA_AVAILABLE = False
|
| 56 |
-
|
| 57 |
-
_USE_FLA_FUSED_CE = True
|
| 58 |
-
_USE_FLA_RMS_NORM = False
|
| 59 |
-
|
| 60 |
-
if FLA_AVAILABLE:
|
| 61 |
-
|
| 62 |
-
@torch.compiler.disable
|
| 63 |
-
def _fla_chunk(q, k, v, g, b, w, initial_state=None, output_final_state=False,
|
| 64 |
-
cu_seqlens=None):
|
| 65 |
-
return chunk_gdn2(
|
| 66 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 67 |
-
initial_state=initial_state,
|
| 68 |
-
output_final_state=output_final_state,
|
| 69 |
-
use_qk_l2norm_in_kernel=True,
|
| 70 |
-
cu_seqlens=cu_seqlens,
|
| 71 |
-
)
|
| 72 |
-
|
| 73 |
-
@torch.compiler.disable
|
| 74 |
-
def _fla_recurrent(q, k, v, g, b, w, initial_state=None, output_final_state=False):
|
| 75 |
-
return fused_recurrent_gdn2(
|
| 76 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 77 |
-
initial_state=initial_state,
|
| 78 |
-
output_final_state=output_final_state,
|
| 79 |
-
use_qk_l2norm_in_kernel=True,
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
try:
|
| 83 |
-
from flash_attn import flash_attn_varlen_func
|
| 84 |
-
FLASH_ATTN_AVAILABLE = True
|
| 85 |
-
except ImportError:
|
| 86 |
-
flash_attn_varlen_func = None
|
| 87 |
-
FLASH_ATTN_AVAILABLE = False
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def _mask_padding_states(hidden_states, padding_mask):
|
| 91 |
-
if padding_mask is not None:
|
| 92 |
-
return hidden_states * padding_mask.unsqueeze(-1).to(hidden_states.dtype)
|
| 93 |
-
return hidden_states
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def naive_gdn2_reference(q, k, v, g, b, w, initial_state=None):
|
| 97 |
-
"""fp32 reference for GDN-2."""
|
| 98 |
-
B, T, H, K = q.shape
|
| 99 |
-
V = v.shape[-1]
|
| 100 |
-
S = (
|
| 101 |
-
torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)
|
| 102 |
-
if initial_state is None
|
| 103 |
-
else initial_state.float()
|
| 104 |
-
)
|
| 105 |
-
scale = K ** -0.5
|
| 106 |
-
outs = []
|
| 107 |
-
for t in range(T):
|
| 108 |
-
q_t = F.normalize(q[:, t], dim=-1)
|
| 109 |
-
k_t = F.normalize(k[:, t], dim=-1)
|
| 110 |
-
v_t, g_t, b_t, w_t = v[:, t], g[:, t], b[:, t], w[:, t]
|
| 111 |
-
S = S * torch.exp(g_t).unsqueeze(-1)
|
| 112 |
-
e = b_t * k_t
|
| 113 |
-
r = torch.einsum("bhkv,bhk->bhv", S, e)
|
| 114 |
-
z = w_t * v_t
|
| 115 |
-
S = S + torch.einsum("bhk,bhv->bhkv", k_t, z - r)
|
| 116 |
-
outs.append(scale * torch.einsum("bhkv,bhk->bhv", S, q_t))
|
| 117 |
-
return torch.stack(outs, dim=1), S
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
class SurjoRMSNorm(nn.Module):
|
| 121 |
-
"""FLA Triton RMSNorm when available; else fused ATen F.rms_norm."""
|
| 122 |
-
|
| 123 |
-
def __init__(self, dim: int, eps: float = 1e-6):
|
| 124 |
-
super().__init__()
|
| 125 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 126 |
-
self.eps = eps
|
| 127 |
-
|
| 128 |
-
def forward(self, x):
|
| 129 |
-
if x.dtype != self.weight.dtype:
|
| 130 |
-
x = x.to(self.weight.dtype)
|
| 131 |
-
if _USE_FLA_RMS_NORM and _fla_rms_norm is not None and x.is_cuda:
|
| 132 |
-
return _fla_rms_norm(x, self.weight, None, eps=self.eps)
|
| 133 |
-
return F.rms_norm(x, (x.shape[-1],), self.weight, self.eps)
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class ClampedMLP(nn.Module):
|
| 137 |
-
def __init__(self, config):
|
| 138 |
-
hidden_size = config.hidden_size
|
| 139 |
-
intermediate_size = config.intermediate_size
|
| 140 |
-
super().__init__()
|
| 141 |
-
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 142 |
-
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 143 |
-
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
| 144 |
-
self.act_fn = ACT2FN[config.hidden_act]
|
| 145 |
-
|
| 146 |
-
def forward(self, x):
|
| 147 |
-
return self.down_proj(
|
| 148 |
-
self.act_fn(self.gate_proj(x).clamp(-15.0, 15.0)) * self.up_proj(x)
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
class SurjoRotaryEmbedding(nn.Module):
|
| 153 |
-
"""RoPE with frequencies computed in forward() (no stored buffer)."""
|
| 154 |
-
|
| 155 |
-
def __init__(self, config, device=None):
|
| 156 |
-
super().__init__()
|
| 157 |
-
self.config = config
|
| 158 |
-
self.rope_type = config.rope_parameters.get("rope_type", "default")
|
| 159 |
-
self.max_position_embeddings = config.max_position_embeddings
|
| 160 |
-
self.base = config.rope_parameters.get("rope_theta", config.rope_theta)
|
| 161 |
-
self.factor = config.rope_parameters.get("factor", 1.0)
|
| 162 |
-
self.dim = int(config.head_dim * config.partial_rotary_factor)
|
| 163 |
-
|
| 164 |
-
def _inv_freq(self, device):
|
| 165 |
-
inv = 1.0 / (
|
| 166 |
-
self.base
|
| 167 |
-
** (torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim)
|
| 168 |
-
)
|
| 169 |
-
if self.rope_type == "linear":
|
| 170 |
-
inv = inv / self.factor
|
| 171 |
-
return inv
|
| 172 |
-
|
| 173 |
-
@torch.no_grad()
|
| 174 |
-
def forward(self, position_ids):
|
| 175 |
-
inv = self._inv_freq(position_ids.device)
|
| 176 |
-
freqs = torch.einsum("bt,f->btf", position_ids.float(), inv)
|
| 177 |
-
emb = torch.cat([freqs, freqs], dim=-1)
|
| 178 |
-
return emb.cos(), emb.sin()
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def rotate_half(x):
|
| 182 |
-
x1, x2 = x.chunk(2, dim=-1)
|
| 183 |
-
return torch.cat((-x2, x1), dim=-1)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def apply_rope(q, k, cos, sin):
|
| 187 |
-
cos = cos[:, None, :, :].to(q.dtype)
|
| 188 |
-
sin = sin[:, None, :, :].to(q.dtype)
|
| 189 |
-
q = q * cos + rotate_half(q) * sin
|
| 190 |
-
k = k * cos + rotate_half(k) * sin
|
| 191 |
-
return q, k
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
def apply_rope_flat(q, k, cos, sin):
|
| 195 |
-
"""RoPE on flat varlen tensors. q, k: [total, H, D]; cos, sin: [B, T, D]."""
|
| 196 |
-
total = q.shape[0]
|
| 197 |
-
cos_f = cos.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 198 |
-
sin_f = sin.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 199 |
-
q = q * cos_f + rotate_half(q) * sin_f
|
| 200 |
-
k = k * cos_f + rotate_half(k) * sin_f
|
| 201 |
-
return q, k
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
@torch.compiler.disable
|
| 205 |
-
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen):
|
| 206 |
-
"""FA2 varlen. cu_seqlens device int32; max_seqlen a constant (no sync)."""
|
| 207 |
-
return flash_attn_varlen_func(
|
| 208 |
-
q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen,
|
| 209 |
-
dropout_p=0.0, causal=True,
|
| 210 |
-
)
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
class ShortConvolution(nn.Module):
|
| 214 |
-
def __init__(self, dim: int, kernel_size: int = 4):
|
| 215 |
-
super().__init__()
|
| 216 |
-
self.kernel_size = kernel_size
|
| 217 |
-
self.conv = nn.Conv1d(dim, dim, kernel_size, groups=dim, bias=False)
|
| 218 |
-
|
| 219 |
-
def forward(self, x, cache=None, output_state=False):
|
| 220 |
-
B, T, C = x.shape
|
| 221 |
-
xt = x.transpose(1, 2)
|
| 222 |
-
if T == 1 and cache is not None:
|
| 223 |
-
comb = torch.cat([cache, xt], dim=2)
|
| 224 |
-
w = self.conv.weight.squeeze(1)
|
| 225 |
-
out = F.silu(torch.einsum("bck,ck->bc", comb, w).unsqueeze(-1))
|
| 226 |
-
new = comb[:, :, 1:] if output_state else None
|
| 227 |
-
return out.transpose(1, 2), new
|
| 228 |
-
if cache is not None:
|
| 229 |
-
xt_in = torch.cat([cache, xt], dim=2)
|
| 230 |
-
else:
|
| 231 |
-
xt_in = F.pad(xt, (self.kernel_size - 1, 0))
|
| 232 |
-
out = F.silu(self.conv(xt_in))
|
| 233 |
-
new = xt_in[:, :, -(self.kernel_size - 1):] if output_state else None
|
| 234 |
-
return out.transpose(1, 2), new
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
class SurjoCache:
|
| 238 |
-
def __init__(self):
|
| 239 |
-
self.kv = {}
|
| 240 |
-
self.gdn_state = {}
|
| 241 |
-
self.gdn_conv = {}
|
| 242 |
-
|
| 243 |
-
def get_seq_length(self):
|
| 244 |
-
if not self.kv:
|
| 245 |
-
return 0
|
| 246 |
-
return next(iter(self.kv.values()))[0].shape[2]
|
| 247 |
-
|
| 248 |
-
@staticmethod
|
| 249 |
-
def num_xsa_slots(config):
|
| 250 |
-
return (
|
| 251 |
-
config.prelude_layers
|
| 252 |
-
+ config.num_groups * config.recurrent_passes
|
| 253 |
-
+ config.coda_layers
|
| 254 |
-
)
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
class XSAAttention(nn.Module):
|
| 258 |
-
"""Full attention with XSA value-projection subtraction."""
|
| 259 |
-
|
| 260 |
-
def __init__(self, config, layer_idx: int):
|
| 261 |
-
super().__init__()
|
| 262 |
-
self.layer_idx = layer_idx
|
| 263 |
-
self.num_heads = config.num_attention_heads
|
| 264 |
-
self.num_kv_heads = config.num_key_value_heads
|
| 265 |
-
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 266 |
-
self.head_dim = config.head_dim
|
| 267 |
-
self.xsa_projection = config.xsa_projection
|
| 268 |
-
self.dropout = config.attention_dropout
|
| 269 |
-
self.hidden_size = config.hidden_size
|
| 270 |
-
self.use_flash = getattr(config, "_use_flash_xsa", False)
|
| 271 |
-
self.q_proj = nn.Linear(
|
| 272 |
-
self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
|
| 273 |
-
)
|
| 274 |
-
self.k_proj = nn.Linear(
|
| 275 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 276 |
-
)
|
| 277 |
-
self.v_proj = nn.Linear(
|
| 278 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 279 |
-
)
|
| 280 |
-
self.o_proj = nn.Linear(
|
| 281 |
-
self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias
|
| 282 |
-
)
|
| 283 |
-
self.q_norm = SurjoRMSNorm(self.head_dim)
|
| 284 |
-
self.k_norm = SurjoRMSNorm(self.head_dim)
|
| 285 |
-
|
| 286 |
-
def _xsa_projection_step(self, attn, v):
|
| 287 |
-
dv = (attn.float() * v.float()).sum(dim=-1, keepdim=True)
|
| 288 |
-
vv = (v.float() * v.float()).sum(dim=-1, keepdim=True).clamp_min(1e-4)
|
| 289 |
-
scale = (dv / vv).to(attn.dtype)
|
| 290 |
-
return attn - scale * v
|
| 291 |
-
|
| 292 |
-
def forward(self, hidden_states, attention_mask, cache, slot, use_cache,
|
| 293 |
-
cache_position, cos, sin, cu_seqlens=None):
|
| 294 |
-
B, T, _ = hidden_states.shape
|
| 295 |
-
H, Hkv, D = self.num_heads, self.num_kv_heads, self.head_dim
|
| 296 |
-
|
| 297 |
-
q = self.q_proj(hidden_states).view(B, T, H, D).transpose(1, 2)
|
| 298 |
-
k = self.k_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 299 |
-
v = self.v_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 300 |
-
q = self.q_norm(q)
|
| 301 |
-
k = self.k_norm(k)
|
| 302 |
-
|
| 303 |
-
use_varlen = (
|
| 304 |
-
cu_seqlens is not None
|
| 305 |
-
and cache is None
|
| 306 |
-
and self.use_flash
|
| 307 |
-
and FLASH_ATTN_AVAILABLE
|
| 308 |
-
and hidden_states.is_cuda
|
| 309 |
-
)
|
| 310 |
-
if use_varlen:
|
| 311 |
-
total = B * T
|
| 312 |
-
q_f = q.transpose(1, 2).reshape(total, H, D).to(torch.bfloat16)
|
| 313 |
-
k_f = k.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 314 |
-
v_f = v.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 315 |
-
if Hkv != H:
|
| 316 |
-
k_f = k_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 317 |
-
v_f = v_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 318 |
-
q_f, k_f = apply_rope_flat(q_f, k_f, cos, sin)
|
| 319 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 320 |
-
o_f = _flash_varlen(q_f, k_f, v_f, cu_dev, T)
|
| 321 |
-
attn_out = o_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 322 |
-
v_xsa = v_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 323 |
-
if self.xsa_projection:
|
| 324 |
-
attn_out = self._xsa_projection_step(attn_out, v_xsa)
|
| 325 |
-
out = attn_out.reshape(B, T, H * D)
|
| 326 |
-
return self.o_proj(out)
|
| 327 |
-
|
| 328 |
-
q, k = apply_rope(q, k, cos, sin)
|
| 329 |
-
v_cur = v
|
| 330 |
-
if cache is not None and use_cache:
|
| 331 |
-
if slot in cache.kv:
|
| 332 |
-
pk, pv = cache.kv[slot]
|
| 333 |
-
k = torch.cat([pk, k.to(pk.dtype)], dim=2)
|
| 334 |
-
v = torch.cat([pv, v.to(pv.dtype)], dim=2)
|
| 335 |
-
cache.kv[slot] = (k, v)
|
| 336 |
-
S = k.shape[2]
|
| 337 |
-
if Hkv != H:
|
| 338 |
-
k_e = k.repeat_interleave(self.num_kv_groups, dim=1)
|
| 339 |
-
v_e = v.repeat_interleave(self.num_kv_groups, dim=1)
|
| 340 |
-
v_cur_e = v_cur.repeat_interleave(self.num_kv_groups, dim=1)
|
| 341 |
-
else:
|
| 342 |
-
k_e, v_e, v_cur_e = k, v, v_cur
|
| 343 |
-
|
| 344 |
-
is_causal = False
|
| 345 |
-
mask4 = None
|
| 346 |
-
if attention_mask is not None:
|
| 347 |
-
L = attention_mask.shape[-1]
|
| 348 |
-
if L < S:
|
| 349 |
-
attention_mask = F.pad(attention_mask, (S - L, 0), value=1)
|
| 350 |
-
elif L > S:
|
| 351 |
-
attention_mask = attention_mask[:, -S:]
|
| 352 |
-
neg = torch.finfo(q.dtype).min
|
| 353 |
-
m = attention_mask[:, None, None, :].to(q.dtype)
|
| 354 |
-
if T == S:
|
| 355 |
-
if T > 1:
|
| 356 |
-
causal = torch.ones(T, S, device=q.device, dtype=q.dtype).tril()
|
| 357 |
-
allow = causal[None, None] * m
|
| 358 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 359 |
-
torch.full_like(allow, neg))
|
| 360 |
-
else:
|
| 361 |
-
mask4 = torch.where(m > 0, torch.zeros_like(m),
|
| 362 |
-
torch.full_like(m, neg))
|
| 363 |
-
else:
|
| 364 |
-
if cache_position is None:
|
| 365 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 366 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 367 |
-
causal = kv_pos[None, :] <= cache_position[:, None].to(q.device)
|
| 368 |
-
allow = causal[None, None].to(q.dtype) * m
|
| 369 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 370 |
-
torch.full_like(allow, neg))
|
| 371 |
-
elif cu_seqlens is not None and T > 1:
|
| 372 |
-
neg = torch.finfo(q.dtype).min
|
| 373 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32)
|
| 374 |
-
gpos = torch.arange(B * T, device=q.device)
|
| 375 |
-
doc_id = torch.searchsorted(cu_dev, gpos, right=True) - 1
|
| 376 |
-
doc_id = doc_id.clamp(min=0).view(B, T)
|
| 377 |
-
same = doc_id.unsqueeze(2) == doc_id.unsqueeze(1)
|
| 378 |
-
idx = torch.arange(T, device=q.device)
|
| 379 |
-
causal = idx.unsqueeze(0) <= idx.unsqueeze(1)
|
| 380 |
-
allow = (same & causal).unsqueeze(1)
|
| 381 |
-
mask4 = torch.where(
|
| 382 |
-
allow,
|
| 383 |
-
torch.zeros(B, 1, T, T, dtype=q.dtype, device=q.device),
|
| 384 |
-
torch.full((B, 1, T, T), neg, dtype=q.dtype, device=q.device),
|
| 385 |
-
)
|
| 386 |
-
else:
|
| 387 |
-
if T == S and T > 1:
|
| 388 |
-
is_causal = True
|
| 389 |
-
elif T > 1:
|
| 390 |
-
if cache_position is None:
|
| 391 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 392 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 393 |
-
neg = torch.finfo(q.dtype).min
|
| 394 |
-
causal = torch.zeros(T, S, device=q.device, dtype=q.dtype)
|
| 395 |
-
causal = causal.masked_fill(
|
| 396 |
-
kv_pos[None, :] > cache_position[:, None], neg
|
| 397 |
-
)
|
| 398 |
-
mask4 = causal[None, None, :, :]
|
| 399 |
-
|
| 400 |
-
attn = F.scaled_dot_product_attention(
|
| 401 |
-
q, k_e, v_e, attn_mask=mask4, is_causal=is_causal,
|
| 402 |
-
dropout_p=self.dropout if self.training else 0.0,
|
| 403 |
-
)
|
| 404 |
-
|
| 405 |
-
if self.xsa_projection:
|
| 406 |
-
attn = self._xsa_projection_step(attn, v_cur_e)
|
| 407 |
-
|
| 408 |
-
out = attn.transpose(1, 2).reshape(B, T, H * D)
|
| 409 |
-
return self.o_proj(out)
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
class GDN2Attention(nn.Module):
|
| 413 |
-
"""Gated DeltaNet-2 linear attention."""
|
| 414 |
-
|
| 415 |
-
def __init__(self, config, layer_idx: int):
|
| 416 |
-
super().__init__()
|
| 417 |
-
self.layer_idx = layer_idx
|
| 418 |
-
H = config.num_attention_heads
|
| 419 |
-
Hv = config.gdn_num_v_heads
|
| 420 |
-
self.num_heads = H
|
| 421 |
-
self.num_v_heads = Hv
|
| 422 |
-
self.gva = Hv // H
|
| 423 |
-
self.head_k_dim = config.gdn_key_dim
|
| 424 |
-
self.head_v_dim = config.gdn_value_dim
|
| 425 |
-
self.key_dim = H * self.head_k_dim
|
| 426 |
-
self.value_dim = Hv * self.head_v_dim
|
| 427 |
-
self.conv_kernel = config.gdn_conv_kernel_size
|
| 428 |
-
self.allow_neg_eigval = config.gdn_allow_neg_eigval
|
| 429 |
-
hidden = config.hidden_size
|
| 430 |
-
self.q_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 431 |
-
self.k_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 432 |
-
self.v_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 433 |
-
self.q_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 434 |
-
self.k_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 435 |
-
self.v_conv = ShortConvolution(self.value_dim, self.conv_kernel)
|
| 436 |
-
self.f_proj = nn.Sequential(
|
| 437 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 438 |
-
nn.Linear(self.head_v_dim, self.key_dim, bias=False),
|
| 439 |
-
)
|
| 440 |
-
self.b_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 441 |
-
self.w_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 442 |
-
self.A_log = nn.Parameter(
|
| 443 |
-
torch.log(torch.empty(H, dtype=torch.float32).uniform_(1, 16))
|
| 444 |
-
)
|
| 445 |
-
self.A_log._no_weight_decay = True
|
| 446 |
-
dt = torch.exp(
|
| 447 |
-
torch.rand(self.key_dim, dtype=torch.float32)
|
| 448 |
-
* (math.log(0.1) - math.log(0.001))
|
| 449 |
-
+ math.log(0.001)
|
| 450 |
-
).clamp(min=1e-4)
|
| 451 |
-
self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt)))
|
| 452 |
-
self.dt_bias._no_weight_decay = True
|
| 453 |
-
self.g_proj = nn.Sequential(
|
| 454 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 455 |
-
nn.Linear(self.head_v_dim, self.value_dim, bias=True),
|
| 456 |
-
)
|
| 457 |
-
self.o_norm = SurjoRMSNorm(self.head_v_dim, eps=config.rms_norm_eps)
|
| 458 |
-
self.o_proj = nn.Linear(self.value_dim, hidden, bias=False)
|
| 459 |
-
|
| 460 |
-
def forward(self, hidden_states, attention_mask, gdn_state, conv_state,
|
| 461 |
-
output_state, cu_seqlens=None):
|
| 462 |
-
B, T, _ = hidden_states.shape
|
| 463 |
-
if attention_mask is not None:
|
| 464 |
-
if attention_mask.shape[-1] != T:
|
| 465 |
-
attention_mask = (
|
| 466 |
-
attention_mask[:, -T:] if attention_mask.shape[-1] > T else None
|
| 467 |
-
)
|
| 468 |
-
if attention_mask is not None:
|
| 469 |
-
hidden_states = _mask_padding_states(hidden_states, attention_mask)
|
| 470 |
-
cq = conv_state[0] if conv_state is not None else None
|
| 471 |
-
ck = conv_state[1] if conv_state is not None else None
|
| 472 |
-
cvs = conv_state[2] if conv_state is not None else None
|
| 473 |
-
q, nq = self.q_conv(self.q_proj(hidden_states), cq, output_state)
|
| 474 |
-
k, nk = self.k_conv(self.k_proj(hidden_states), ck, output_state)
|
| 475 |
-
v, nv = self.v_conv(self.v_proj(hidden_states), cvs, output_state)
|
| 476 |
-
g = F.softplus(self.f_proj(hidden_states).float() + self.dt_bias)
|
| 477 |
-
b = self.b_proj(hidden_states).sigmoid()
|
| 478 |
-
w = self.w_proj(hidden_states).sigmoid()
|
| 479 |
-
q = q.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 480 |
-
k = k.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 481 |
-
v = v.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 482 |
-
g = g.view(B, T, self.num_heads, self.head_k_dim)
|
| 483 |
-
b = b.view(B, T, self.num_heads, self.head_k_dim)
|
| 484 |
-
w = w.view(B, T, self.num_v_heads, self.head_v_dim)
|
| 485 |
-
g = -self.A_log.float().exp().view(1, 1, self.num_heads, 1) * g
|
| 486 |
-
if self.allow_neg_eigval:
|
| 487 |
-
b = b * 2.0
|
| 488 |
-
if self.gva > 1:
|
| 489 |
-
q = q.repeat_interleave(self.gva, dim=2)
|
| 490 |
-
k = k.repeat_interleave(self.gva, dim=2)
|
| 491 |
-
g = g.repeat_interleave(self.gva, dim=2)
|
| 492 |
-
b = b.repeat_interleave(self.gva, dim=2)
|
| 493 |
-
init = gdn_state.float() if gdn_state is not None else None
|
| 494 |
-
|
| 495 |
-
if FLA_AVAILABLE and hidden_states.is_cuda:
|
| 496 |
-
if T == 1 and init is not None:
|
| 497 |
-
o, fs = _fla_recurrent(q, k, v, g, b, w, init, output_state)
|
| 498 |
-
elif cu_seqlens is not None:
|
| 499 |
-
total = B * T
|
| 500 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 501 |
-
q_f = q.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 502 |
-
k_f = k.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 503 |
-
v_f = v.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 504 |
-
g_f = g.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 505 |
-
b_f = b.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 506 |
-
w_f = w.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 507 |
-
o, fs = _fla_chunk(q_f, k_f, v_f, g_f, b_f, w_f, init,
|
| 508 |
-
output_state, cu_dev)
|
| 509 |
-
o = o.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 510 |
-
else:
|
| 511 |
-
o, fs = _fla_chunk(q, k, v, g, b, w, init, output_state, None)
|
| 512 |
-
else:
|
| 513 |
-
o, fs = naive_gdn2_reference(q.float(), k.float(), v.float(), g,
|
| 514 |
-
b.float(), w.float(), init)
|
| 515 |
-
|
| 516 |
-
# Cast back to activation precision
|
| 517 |
-
o = o.to(hidden_states.dtype)
|
| 518 |
-
|
| 519 |
-
fs = fs if output_state else None
|
| 520 |
-
gate = self.g_proj(hidden_states).view(B, T, self.num_v_heads, self.head_v_dim)
|
| 521 |
-
o = self.o_norm(o)
|
| 522 |
-
o = o * torch.sigmoid(gate)
|
| 523 |
-
o = o.reshape(B, T, self.value_dim)
|
| 524 |
-
conv_out = (nq, nk, nv) if output_state else None
|
| 525 |
-
return self.o_proj(o), fs, conv_out
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
def _is_xsa(config, li: int) -> bool:
|
| 529 |
-
if li < config.prelude_layers:
|
| 530 |
-
return True
|
| 531 |
-
if li >= config.prelude_layers + config.recurrent_layers:
|
| 532 |
-
return True
|
| 533 |
-
return (li - config.prelude_layers) % (config.gdn_per_xsa + 1) == config.gdn_per_xsa
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
class SurjoDecoderLayer(nn.Module):
|
| 537 |
-
def __init__(self, config, layer_idx: int):
|
| 538 |
-
super().__init__()
|
| 539 |
-
self.layer_idx = layer_idx
|
| 540 |
-
self.layer_type = "xsa" if _is_xsa(config, layer_idx) else "gdn"
|
| 541 |
-
if self.layer_type == "xsa":
|
| 542 |
-
self.self_attn = XSAAttention(config, layer_idx)
|
| 543 |
-
else:
|
| 544 |
-
self.linear_attn = GDN2Attention(config, layer_idx)
|
| 545 |
-
self.mlp = ClampedMLP(config)
|
| 546 |
-
self.input_layernorm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 547 |
-
self.post_attention_layernorm = SurjoRMSNorm(config.hidden_size,
|
| 548 |
-
eps=config.rms_norm_eps)
|
| 549 |
-
|
| 550 |
-
def forward(self, hidden_states, attention_mask=None, cos=None, sin=None,
|
| 551 |
-
cu_seqlens=None):
|
| 552 |
-
h = self.input_layernorm(hidden_states)
|
| 553 |
-
if self.layer_type == "xsa":
|
| 554 |
-
out = self.self_attn(h, attention_mask, None, -1, False, None,
|
| 555 |
-
cos, sin, cu_seqlens)
|
| 556 |
-
else:
|
| 557 |
-
out, _, _ = self.linear_attn(h, attention_mask, None, None, False,
|
| 558 |
-
cu_seqlens)
|
| 559 |
-
hidden_states = hidden_states + out
|
| 560 |
-
h2 = self.post_attention_layernorm(hidden_states)
|
| 561 |
-
return hidden_states + self.mlp(h2)
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
class SurjoPreTrainedModel(PreTrainedModel):
|
| 565 |
-
config_class = SurjoConfig
|
| 566 |
-
base_model_prefix = "model"
|
| 567 |
-
_no_split_modules = ["SurjoDecoderLayer"]
|
| 568 |
-
_supports_flash_attn = False
|
| 569 |
-
_supports_flash_attn_2 = False
|
| 570 |
-
_supports_sdpa = True
|
| 571 |
-
_is_stateful = True
|
| 572 |
-
_can_compile_fullgraph = True
|
| 573 |
-
|
| 574 |
-
def _init_weights(self, module):
|
| 575 |
-
std = self.config.initializer_range
|
| 576 |
-
if isinstance(module, nn.Linear):
|
| 577 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 578 |
-
if module.bias is not None:
|
| 579 |
-
module.bias.data.zero_()
|
| 580 |
-
elif isinstance(module, nn.Embedding):
|
| 581 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 582 |
-
if module.padding_idx is not None:
|
| 583 |
-
module.weight.data[module.padding_idx].zero_()
|
| 584 |
-
elif isinstance(module, GDN2Attention):
|
| 585 |
-
module.A_log.data.copy_(
|
| 586 |
-
torch.log(
|
| 587 |
-
torch.empty(module.num_heads, dtype=torch.float32,
|
| 588 |
-
device=module.A_log.device).uniform_(1, 16)
|
| 589 |
-
)
|
| 590 |
-
)
|
| 591 |
-
dt = torch.exp(
|
| 592 |
-
torch.rand(module.key_dim, dtype=torch.float32,
|
| 593 |
-
device=module.dt_bias.device)
|
| 594 |
-
* (math.log(0.1) - math.log(0.001)) + math.log(0.001)
|
| 595 |
-
).clamp(min=1e-4)
|
| 596 |
-
module.dt_bias.data.copy_(dt + torch.log(-torch.expm1(-dt)))
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
class SurjoModel(SurjoPreTrainedModel):
|
| 600 |
-
def __init__(self, config):
|
| 601 |
-
super().__init__(config)
|
| 602 |
-
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 603 |
-
self.layers = nn.ModuleList(
|
| 604 |
-
[SurjoDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 605 |
-
)
|
| 606 |
-
self.norm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 607 |
-
self.rotary = SurjoRotaryEmbedding(config)
|
| 608 |
-
self.grad_checkpointing = False
|
| 609 |
-
|
| 610 |
-
slot = 0
|
| 611 |
-
self.xsa_slot_map = {}
|
| 612 |
-
self.exec_plan = []
|
| 613 |
-
for li in range(config.prelude_layers):
|
| 614 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 615 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 616 |
-
slot += 1
|
| 617 |
-
for p in range(config.recurrent_passes):
|
| 618 |
-
for g in range(config.num_groups):
|
| 619 |
-
base = config.prelude_layers + g * (config.gdn_per_xsa + 1)
|
| 620 |
-
for j in range(config.gdn_per_xsa):
|
| 621 |
-
self.exec_plan.append((self.layers[base + j], base + j, p, -1))
|
| 622 |
-
li = base + config.gdn_per_xsa
|
| 623 |
-
self.xsa_slot_map[(li, p)] = slot
|
| 624 |
-
self.exec_plan.append((self.layers[li], li, p, slot))
|
| 625 |
-
slot += 1
|
| 626 |
-
for li in range(config.prelude_layers + config.recurrent_layers,
|
| 627 |
-
config.num_hidden_layers):
|
| 628 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 629 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 630 |
-
slot += 1
|
| 631 |
-
self.num_xsa_slots = slot
|
| 632 |
-
self.post_init()
|
| 633 |
-
|
| 634 |
-
def get_input_embeddings(self):
|
| 635 |
-
return self.embed_tokens
|
| 636 |
-
|
| 637 |
-
def set_input_embeddings(self, value):
|
| 638 |
-
self.embed_tokens = value
|
| 639 |
-
|
| 640 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 641 |
-
past_key_values=None, inputs_embeds=None, use_cache=None,
|
| 642 |
-
cache_position=None, return_dict=True,
|
| 643 |
-
output_hidden_states=False, output_attentions=False,
|
| 644 |
-
cu_seqlens=None, **kwargs):
|
| 645 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 646 |
-
past_key_values = None
|
| 647 |
-
if use_cache is None:
|
| 648 |
-
use_cache = past_key_values is not None
|
| 649 |
-
if use_cache and past_key_values is None:
|
| 650 |
-
past_key_values = SurjoCache()
|
| 651 |
-
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 652 |
-
|
| 653 |
-
if past_len > 0:
|
| 654 |
-
if input_ids is not None:
|
| 655 |
-
n_ids = input_ids.shape[1]
|
| 656 |
-
if (attention_mask is not None
|
| 657 |
-
and attention_mask.shape[-1] > n_ids
|
| 658 |
-
and attention_mask.shape[-1] > past_len):
|
| 659 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 660 |
-
input_ids = input_ids[:, -n_new:] if n_new <= n_ids else input_ids
|
| 661 |
-
elif n_ids > past_len:
|
| 662 |
-
input_ids = input_ids[:, past_len:]
|
| 663 |
-
else:
|
| 664 |
-
input_ids = input_ids[:, -1:]
|
| 665 |
-
elif inputs_embeds is not None:
|
| 666 |
-
n_emb = inputs_embeds.shape[1]
|
| 667 |
-
if (attention_mask is not None
|
| 668 |
-
and attention_mask.shape[-1] > n_emb
|
| 669 |
-
and attention_mask.shape[-1] > past_len):
|
| 670 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 671 |
-
inputs_embeds = (inputs_embeds[:, -n_new:] if n_new <= n_emb
|
| 672 |
-
else inputs_embeds)
|
| 673 |
-
elif n_emb > past_len:
|
| 674 |
-
inputs_embeds = inputs_embeds[:, past_len:]
|
| 675 |
-
else:
|
| 676 |
-
inputs_embeds = inputs_embeds[:, -1:]
|
| 677 |
-
|
| 678 |
-
if inputs_embeds is None:
|
| 679 |
-
if input_ids is None:
|
| 680 |
-
raise ValueError("Specify input_ids or inputs_embeds")
|
| 681 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
| 682 |
-
B, T = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 683 |
-
|
| 684 |
-
cache_position = torch.arange(past_len, past_len + T,
|
| 685 |
-
device=inputs_embeds.device)
|
| 686 |
-
if position_ids is not None and position_ids.shape[-1] != T:
|
| 687 |
-
position_ids = None
|
| 688 |
-
if position_ids is None:
|
| 689 |
-
position_ids = cache_position.unsqueeze(0).expand(B, -1)
|
| 690 |
-
cos, sin = self.rotary(position_ids)
|
| 691 |
-
|
| 692 |
-
gdn_states = dict(past_key_values.gdn_state) if past_key_values is not None else {}
|
| 693 |
-
conv_states = dict(past_key_values.gdn_conv) if past_key_values is not None else {}
|
| 694 |
-
|
| 695 |
-
noise_std = self.config.loop_noise_std
|
| 696 |
-
hidden = inputs_embeds
|
| 697 |
-
prev_p = 0
|
| 698 |
-
use_ckpt = self.training and self.grad_checkpointing
|
| 699 |
-
all_hidden_states = () if output_hidden_states else None
|
| 700 |
-
|
| 701 |
-
for (layer, li, p, slot) in self.exec_plan:
|
| 702 |
-
if output_hidden_states:
|
| 703 |
-
all_hidden_states += (hidden,)
|
| 704 |
-
if p != prev_p and p > 0 and self.training and noise_std > 0.0:
|
| 705 |
-
hidden = hidden + torch.randn_like(hidden) * noise_std
|
| 706 |
-
prev_p = p
|
| 707 |
-
|
| 708 |
-
if use_ckpt:
|
| 709 |
-
hidden = torch.utils.checkpoint.checkpoint(
|
| 710 |
-
self._train_layer, layer, hidden, attention_mask, cos, sin,
|
| 711 |
-
cu_seqlens, use_reentrant=False,
|
| 712 |
-
)
|
| 713 |
-
elif use_cache:
|
| 714 |
-
h = layer.input_layernorm(hidden)
|
| 715 |
-
if layer.layer_type == "xsa":
|
| 716 |
-
out = layer.self_attn(h, attention_mask, past_key_values,
|
| 717 |
-
slot, use_cache, cache_position,
|
| 718 |
-
cos, sin, cu_seqlens)
|
| 719 |
-
else:
|
| 720 |
-
gs = gdn_states.get((li, p))
|
| 721 |
-
cs = conv_states.get((li, p))
|
| 722 |
-
out, ngs, ncs = layer.linear_attn(h, attention_mask, gs, cs,
|
| 723 |
-
use_cache, cu_seqlens)
|
| 724 |
-
if ngs is not None:
|
| 725 |
-
gdn_states[(li, p)] = ngs
|
| 726 |
-
if ncs is not None:
|
| 727 |
-
conv_states[(li, p)] = ncs
|
| 728 |
-
hidden = hidden + out
|
| 729 |
-
h2 = layer.post_attention_layernorm(hidden)
|
| 730 |
-
hidden = hidden + layer.mlp(h2)
|
| 731 |
-
else:
|
| 732 |
-
hidden = layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 733 |
-
|
| 734 |
-
hidden = self.norm(hidden)
|
| 735 |
-
if output_hidden_states:
|
| 736 |
-
all_hidden_states += (hidden,)
|
| 737 |
-
|
| 738 |
-
if use_cache and past_key_values is not None:
|
| 739 |
-
past_key_values.gdn_state.update(gdn_states)
|
| 740 |
-
past_key_values.gdn_conv.update(conv_states)
|
| 741 |
-
|
| 742 |
-
if not return_dict:
|
| 743 |
-
out = tuple(v for v in [hidden, past_key_values if use_cache else None,
|
| 744 |
-
all_hidden_states] if v is not None)
|
| 745 |
-
return out
|
| 746 |
-
return BaseModelOutputWithPast(
|
| 747 |
-
last_hidden_state=hidden,
|
| 748 |
-
past_key_values=past_key_values if use_cache else None,
|
| 749 |
-
hidden_states=all_hidden_states,
|
| 750 |
-
attentions=None,
|
| 751 |
-
)
|
| 752 |
-
|
| 753 |
-
def _train_layer(self, layer, hidden, attention_mask, cos, sin, cu_seqlens):
|
| 754 |
-
return layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
class SurjoForCausalLM(SurjoPreTrainedModel, GenerationMixin):
|
| 758 |
-
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 759 |
-
|
| 760 |
-
def __init__(self, config):
|
| 761 |
-
super().__init__(config)
|
| 762 |
-
self.model = SurjoModel(config)
|
| 763 |
-
self.vocab_size = config.vocab_size
|
| 764 |
-
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 765 |
-
self.post_init()
|
| 766 |
-
|
| 767 |
-
def tie_weights(self, **kwargs):
|
| 768 |
-
try:
|
| 769 |
-
super().tie_weights(**kwargs)
|
| 770 |
-
except TypeError:
|
| 771 |
-
pass
|
| 772 |
-
except Exception:
|
| 773 |
-
pass
|
| 774 |
-
if (getattr(self.config, "tie_word_embeddings", False)
|
| 775 |
-
and getattr(self, "model", None) is not None
|
| 776 |
-
and getattr(self, "lm_head", None) is not None):
|
| 777 |
-
self.lm_head.weight = self.model.embed_tokens.weight
|
| 778 |
-
|
| 779 |
-
def save_pretrained(self, *args, **kwargs):
|
| 780 |
-
was_tied = (getattr(self, "lm_head", None) is not None
|
| 781 |
-
and getattr(self, "model", None) is not None
|
| 782 |
-
and self.lm_head.weight is self.model.embed_tokens.weight)
|
| 783 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 784 |
-
self.lm_head.weight = nn.Parameter(
|
| 785 |
-
self.model.embed_tokens.weight.detach().clone(),
|
| 786 |
-
requires_grad=self.model.embed_tokens.weight.requires_grad,
|
| 787 |
-
)
|
| 788 |
-
try:
|
| 789 |
-
return super().save_pretrained(*args, **kwargs)
|
| 790 |
-
finally:
|
| 791 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 792 |
-
self.tie_weights()
|
| 793 |
-
|
| 794 |
-
def get_input_embeddings(self):
|
| 795 |
-
return self.model.embed_tokens
|
| 796 |
-
|
| 797 |
-
def set_input_embeddings(self, value):
|
| 798 |
-
self.model.embed_tokens = value
|
| 799 |
-
|
| 800 |
-
def get_output_embeddings(self):
|
| 801 |
-
return self.lm_head
|
| 802 |
-
|
| 803 |
-
def set_output_embeddings(self, value):
|
| 804 |
-
self.lm_head = value
|
| 805 |
-
|
| 806 |
-
def set_decoder(self, decoder):
|
| 807 |
-
self.model = decoder
|
| 808 |
-
|
| 809 |
-
def get_decoder(self):
|
| 810 |
-
return self.model
|
| 811 |
-
|
| 812 |
-
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, **kwargs):
|
| 813 |
-
self.model.grad_checkpointing = True
|
| 814 |
-
|
| 815 |
-
def gradient_checkpointing_disable(self):
|
| 816 |
-
self.model.grad_checkpointing = False
|
| 817 |
-
|
| 818 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 819 |
-
past_key_values=None, inputs_embeds=None, labels=None,
|
| 820 |
-
use_cache=None, output_hidden_states=None, output_attentions=None,
|
| 821 |
-
return_dict=None, logits_to_keep=0, cache_position=None,
|
| 822 |
-
cu_seqlens=None, **kwargs):
|
| 823 |
-
if logits_to_keep in (None, 0) and kwargs.get("num_logits_to_keep"):
|
| 824 |
-
logits_to_keep = kwargs.pop("num_logits_to_keep")
|
| 825 |
-
return_dict = True if return_dict is None else return_dict
|
| 826 |
-
if use_cache is None:
|
| 827 |
-
use_cache = not (self.training or labels is not None)
|
| 828 |
-
|
| 829 |
-
outputs = self.model(
|
| 830 |
-
input_ids=input_ids, attention_mask=attention_mask,
|
| 831 |
-
position_ids=position_ids, past_key_values=past_key_values,
|
| 832 |
-
inputs_embeds=inputs_embeds, use_cache=use_cache,
|
| 833 |
-
cache_position=cache_position,
|
| 834 |
-
output_hidden_states=output_hidden_states,
|
| 835 |
-
output_attentions=output_attentions,
|
| 836 |
-
cu_seqlens=cu_seqlens,
|
| 837 |
-
**kwargs,
|
| 838 |
-
)
|
| 839 |
-
hidden_states = outputs[0]
|
| 840 |
-
|
| 841 |
-
loss, logits = None, None
|
| 842 |
-
if labels is not None:
|
| 843 |
-
sh = hidden_states[..., :-1, :].contiguous()
|
| 844 |
-
sl = labels[..., 1:].contiguous()
|
| 845 |
-
if _USE_FLA_FUSED_CE and _fla_flce is not None:
|
| 846 |
-
loss = _fla_flce(
|
| 847 |
-
sh.view(-1, sh.shape[-1]),
|
| 848 |
-
sl.view(-1),
|
| 849 |
-
self.lm_head.weight,
|
| 850 |
-
num_chunks=8,
|
| 851 |
-
reduction="mean",
|
| 852 |
-
)
|
| 853 |
-
else:
|
| 854 |
-
n_chunks = max(8, sh.shape[0] // 8)
|
| 855 |
-
tot = hidden_states.new_zeros((), dtype=torch.float32)
|
| 856 |
-
n_tok = 0
|
| 857 |
-
for h_c, l_c in zip(sh.chunk(n_chunks, dim=0), sl.chunk(n_chunks, dim=0)):
|
| 858 |
-
if l_c.numel() == 0:
|
| 859 |
-
continue
|
| 860 |
-
lg = self.lm_head(h_c)
|
| 861 |
-
tot = tot + F.cross_entropy(
|
| 862 |
-
lg.float().view(-1, lg.size(-1)), l_c.view(-1), reduction="sum"
|
| 863 |
-
)
|
| 864 |
-
n_tok += l_c.numel()
|
| 865 |
-
loss = tot / max(n_tok, 1)
|
| 866 |
-
else:
|
| 867 |
-
if isinstance(logits_to_keep, int) and logits_to_keep > 0:
|
| 868 |
-
sl_hidden = hidden_states[:, -logits_to_keep:, :]
|
| 869 |
-
elif torch.is_tensor(logits_to_keep):
|
| 870 |
-
sl_hidden = hidden_states[:, logits_to_keep, :]
|
| 871 |
-
else:
|
| 872 |
-
sl_hidden = hidden_states
|
| 873 |
-
logits = self.lm_head(sl_hidden)
|
| 874 |
-
|
| 875 |
-
if not return_dict:
|
| 876 |
-
out = (logits,) + outputs[1:]
|
| 877 |
-
return (loss,) + out if loss is not None else out
|
| 878 |
-
return CausalLMOutputWithPast(
|
| 879 |
-
loss=loss, logits=logits,
|
| 880 |
-
past_key_values=outputs.past_key_values,
|
| 881 |
-
hidden_states=outputs.hidden_states,
|
| 882 |
-
attentions=outputs.attentions,
|
| 883 |
-
)
|
| 884 |
-
|
| 885 |
-
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
|
| 886 |
-
attention_mask=None, inputs_embeds=None,
|
| 887 |
-
cache_position=None, use_cache=True, **kwargs):
|
| 888 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 889 |
-
past_key_values = None
|
| 890 |
-
has_state = past_key_values is not None and len(past_key_values.kv) > 0
|
| 891 |
-
if has_state:
|
| 892 |
-
input_ids = input_ids[:, -1:]
|
| 893 |
-
if kwargs.get("logits_to_keep") is None:
|
| 894 |
-
kwargs["logits_to_keep"] = 1
|
| 895 |
-
past_len = past_key_values.get_seq_length() if has_state else 0
|
| 896 |
-
cache_position = torch.arange(past_len, past_len + input_ids.shape[1],
|
| 897 |
-
device=input_ids.device)
|
| 898 |
-
model_inputs = {
|
| 899 |
-
"input_ids": input_ids.contiguous(),
|
| 900 |
-
"past_key_values": past_key_values,
|
| 901 |
-
"use_cache": use_cache,
|
| 902 |
-
"cache_position": cache_position,
|
| 903 |
-
"attention_mask": attention_mask,
|
| 904 |
-
}
|
| 905 |
-
model_inputs.update(kwargs)
|
| 906 |
-
return model_inputs
|
| 907 |
-
|
| 908 |
-
def _reorder_cache(self, past_key_values: SurjoCache, beam_idx):
|
| 909 |
-
for slot, (k, v) in past_key_values.kv.items():
|
| 910 |
-
past_key_values.kv[slot] = (k.index_select(0, beam_idx),
|
| 911 |
-
v.index_select(0, beam_idx))
|
| 912 |
-
for key in list(past_key_values.gdn_state.keys()):
|
| 913 |
-
s = past_key_values.gdn_state[key]
|
| 914 |
-
if s is not None:
|
| 915 |
-
past_key_values.gdn_state[key] = s.index_select(0, beam_idx)
|
| 916 |
-
for key in list(past_key_values.gdn_conv.keys()):
|
| 917 |
-
cs = past_key_values.gdn_conv[key]
|
| 918 |
-
if cs is not None:
|
| 919 |
-
past_key_values.gdn_conv[key] = tuple(
|
| 920 |
-
c.index_select(0, beam_idx) if c is not None else None for c in cs
|
| 921 |
-
)
|
| 922 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/optimizer.bin
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:b48fb49509808c6074512892098a39c2be225b1f7964d138e8c71afa64d320e8
|
| 3 |
-
size 148034507
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/optimizer_1.bin
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:a26307eb5c035abcfac3afab28155763576f921db5eb919a341f98dcfaa13958
|
| 3 |
-
size 134405851
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/random_states_0.pkl
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:5dfe2537b8f7e81a5971d1e93fe3fb2f280ed043ff3409bca61cdc2e66aa6cd6
|
| 3 |
-
size 14821
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-10500/tokenizer.json
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
checkpoint-10500/tokenizer_config.json
DELETED
|
@@ -1,85 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"backend": "tokenizers",
|
| 3 |
-
"bos_token": "<|bos|>",
|
| 4 |
-
"clean_up_tokenization_spaces": false,
|
| 5 |
-
"eos_token": "<|eos|>",
|
| 6 |
-
"extra_special_tokens": [
|
| 7 |
-
"<|unk|>",
|
| 8 |
-
"<|pad|>",
|
| 9 |
-
"<|bos|>",
|
| 10 |
-
"<|eos|>",
|
| 11 |
-
"<|mask|>",
|
| 12 |
-
"<|im_start|>",
|
| 13 |
-
"<|im_end|>",
|
| 14 |
-
"<|system|>",
|
| 15 |
-
"<|user|>",
|
| 16 |
-
"<|assistant|>",
|
| 17 |
-
"<think>",
|
| 18 |
-
"</think>",
|
| 19 |
-
"<|begin_of_thought|>",
|
| 20 |
-
"<|end_of_thought|>",
|
| 21 |
-
"<answer>",
|
| 22 |
-
"</answer>",
|
| 23 |
-
"<|step|>",
|
| 24 |
-
"<|/step|>",
|
| 25 |
-
"<context>",
|
| 26 |
-
"</context>",
|
| 27 |
-
"<|doc_start|>",
|
| 28 |
-
"<|doc_end|>",
|
| 29 |
-
"<|search|>",
|
| 30 |
-
"<|search_results|>",
|
| 31 |
-
"<|tool_list_start|>",
|
| 32 |
-
"<|tool_list_end|>",
|
| 33 |
-
"<tools>",
|
| 34 |
-
"</tools>",
|
| 35 |
-
"<|tool_call_start|>",
|
| 36 |
-
"<|tool_call_end|>",
|
| 37 |
-
"<|tool_call|>",
|
| 38 |
-
"<|/tool_call|>",
|
| 39 |
-
"<|tool_response_start|>",
|
| 40 |
-
"<|tool_response_end|>",
|
| 41 |
-
"<|tool_response|>",
|
| 42 |
-
"<|/tool_response|>",
|
| 43 |
-
"<|image|>",
|
| 44 |
-
"<|image_pad|>",
|
| 45 |
-
"<|image_placeholder|>",
|
| 46 |
-
"<|audio|>",
|
| 47 |
-
"<|audio_pad|>",
|
| 48 |
-
"<|audio_placeholder|>",
|
| 49 |
-
"<|video|>",
|
| 50 |
-
"<|video_pad|>",
|
| 51 |
-
"<|fim_prefix|>",
|
| 52 |
-
"<|fim_suffix|>",
|
| 53 |
-
"<|fim_middle|>",
|
| 54 |
-
"<|repo_name|>",
|
| 55 |
-
"<|file_separator|>",
|
| 56 |
-
"<|reward|>",
|
| 57 |
-
"<|reserved_0|>",
|
| 58 |
-
"<|reserved_1|>",
|
| 59 |
-
"<|reserved_2|>",
|
| 60 |
-
"<|reserved_3|>",
|
| 61 |
-
"<|reserved_4|>",
|
| 62 |
-
"<|reserved_5|>",
|
| 63 |
-
"<|reserved_6|>",
|
| 64 |
-
"<|reserved_7|>",
|
| 65 |
-
"<|reserved_8|>",
|
| 66 |
-
"<|reserved_9|>",
|
| 67 |
-
"<|reserved_10|>",
|
| 68 |
-
"<|reserved_11|>",
|
| 69 |
-
"<|reserved_12|>",
|
| 70 |
-
"<|reserved_13|>",
|
| 71 |
-
"<|reserved_14|>",
|
| 72 |
-
"<|reserved_15|>",
|
| 73 |
-
"<|reserved_16|>",
|
| 74 |
-
"<|reserved_17|>",
|
| 75 |
-
"<|reserved_18|>",
|
| 76 |
-
"<|reserved_19|>"
|
| 77 |
-
],
|
| 78 |
-
"is_local": false,
|
| 79 |
-
"local_files_only": false,
|
| 80 |
-
"mask_token": "<|mask|>",
|
| 81 |
-
"model_max_length": 10000000,
|
| 82 |
-
"pad_token": "<|pad|>",
|
| 83 |
-
"tokenizer_class": "TokenizersBackend",
|
| 84 |
-
"unk_token": "<|unk|>"
|
| 85 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/chat_template.jinja
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
-
' + message['content'] + '<|im_end|>
|
| 3 |
-
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
-
' }}{% endif %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/config.json
DELETED
|
@@ -1,62 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_use_flash_xsa": true,
|
| 3 |
-
"architectures": [
|
| 4 |
-
"SurjoForCausalLM"
|
| 5 |
-
],
|
| 6 |
-
"attention_bias": false,
|
| 7 |
-
"attention_dropout": 0.0,
|
| 8 |
-
"auto_map": {
|
| 9 |
-
"AutoConfig": "configuration_surjo.SurjoConfig",
|
| 10 |
-
"AutoModel": "modeling_surjo.SurjoForCausalLM",
|
| 11 |
-
"AutoModelForCausalLM": "modeling_surjo.SurjoForCausalLM"
|
| 12 |
-
},
|
| 13 |
-
"coda_layers": 1,
|
| 14 |
-
"dtype": "float32",
|
| 15 |
-
"gdn_allow_neg_eigval": false,
|
| 16 |
-
"gdn_conv_kernel_size": 4,
|
| 17 |
-
"gdn_key_dim": 64,
|
| 18 |
-
"gdn_num_v_heads": 8,
|
| 19 |
-
"gdn_per_xsa": 3,
|
| 20 |
-
"gdn_value_dim": 64,
|
| 21 |
-
"gradient_checkpointing": false,
|
| 22 |
-
"head_dim": 64,
|
| 23 |
-
"hidden_act": "silu",
|
| 24 |
-
"hidden_size": 512,
|
| 25 |
-
"initializer_range": 0.02,
|
| 26 |
-
"intermediate_size": 1536,
|
| 27 |
-
"layer_types": [
|
| 28 |
-
"full_attention",
|
| 29 |
-
"linear_attention",
|
| 30 |
-
"linear_attention",
|
| 31 |
-
"linear_attention",
|
| 32 |
-
"full_attention",
|
| 33 |
-
"linear_attention",
|
| 34 |
-
"linear_attention",
|
| 35 |
-
"linear_attention",
|
| 36 |
-
"full_attention",
|
| 37 |
-
"full_attention"
|
| 38 |
-
],
|
| 39 |
-
"loop_noise_std": 0.02,
|
| 40 |
-
"max_position_embeddings": 2048,
|
| 41 |
-
"model_type": "surjo",
|
| 42 |
-
"num_attention_heads": 8,
|
| 43 |
-
"num_groups": 2,
|
| 44 |
-
"num_hidden_layers": 10,
|
| 45 |
-
"num_key_value_heads": 4,
|
| 46 |
-
"partial_rotary_factor": 1.0,
|
| 47 |
-
"prelude_layers": 1,
|
| 48 |
-
"recurrent_layers": 8,
|
| 49 |
-
"recurrent_passes": 2,
|
| 50 |
-
"rms_norm_eps": 1e-05,
|
| 51 |
-
"rope_parameters": {
|
| 52 |
-
"partial_rotary_factor": 1.0,
|
| 53 |
-
"rope_theta": 10000.0,
|
| 54 |
-
"rope_type": "default"
|
| 55 |
-
},
|
| 56 |
-
"rope_theta": 10000.0,
|
| 57 |
-
"tie_word_embeddings": true,
|
| 58 |
-
"transformers_version": "5.16.1",
|
| 59 |
-
"use_cache": false,
|
| 60 |
-
"vocab_size": 32768,
|
| 61 |
-
"xsa_projection": true
|
| 62 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/configuration_surjo.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""Surjo gen-3 model configuration."""
|
| 5 |
-
|
| 6 |
-
from typing import List, Optional
|
| 7 |
-
from transformers import PretrainedConfig
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
class SurjoConfig(PretrainedConfig):
|
| 11 |
-
r"""Configuration for the Surjo gen-3 hybrid architecture."""
|
| 12 |
-
|
| 13 |
-
model_type = "surjo"
|
| 14 |
-
keys_to_ignore_at_inference = ["past_key_values"]
|
| 15 |
-
|
| 16 |
-
def __init__(
|
| 17 |
-
self,
|
| 18 |
-
vocab_size: int = 50257,
|
| 19 |
-
hidden_size: int = 384,
|
| 20 |
-
intermediate_size: int = 1024,
|
| 21 |
-
num_attention_heads: int = 6,
|
| 22 |
-
num_key_value_heads: int = 2,
|
| 23 |
-
head_dim: int = 64,
|
| 24 |
-
hidden_act: str = "silu",
|
| 25 |
-
max_position_embeddings: int = 2048,
|
| 26 |
-
initializer_range: float = 0.02,
|
| 27 |
-
rms_norm_eps: float = 1e-6,
|
| 28 |
-
tie_word_embeddings: bool = True,
|
| 29 |
-
rope_theta: float = 10000.0,
|
| 30 |
-
attention_dropout: float = 0.0,
|
| 31 |
-
attention_bias: bool = False,
|
| 32 |
-
prelude_layers: int = 1,
|
| 33 |
-
recurrent_layers: int = 8,
|
| 34 |
-
coda_layers: int = 1,
|
| 35 |
-
recurrent_passes: int = 2,
|
| 36 |
-
loop_noise_std: float = 0.02,
|
| 37 |
-
gdn_per_xsa: int = 3,
|
| 38 |
-
gdn_key_dim: Optional[int] = None,
|
| 39 |
-
gdn_value_dim: Optional[int] = None,
|
| 40 |
-
gdn_num_v_heads: Optional[int] = None,
|
| 41 |
-
gdn_conv_kernel_size: int = 4,
|
| 42 |
-
gdn_allow_neg_eigval: bool = False,
|
| 43 |
-
xsa_projection: bool = True,
|
| 44 |
-
rope_parameters: Optional[dict] = None,
|
| 45 |
-
rope_scaling: Optional[dict] = None,
|
| 46 |
-
partial_rotary_factor: float = 1.0,
|
| 47 |
-
gradient_checkpointing: bool = False,
|
| 48 |
-
use_cache: bool = True,
|
| 49 |
-
**kwargs,
|
| 50 |
-
):
|
| 51 |
-
self.vocab_size = vocab_size
|
| 52 |
-
self.hidden_size = hidden_size
|
| 53 |
-
self.intermediate_size = intermediate_size
|
| 54 |
-
self.num_attention_heads = num_attention_heads
|
| 55 |
-
self.num_key_value_heads = num_key_value_heads
|
| 56 |
-
self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads
|
| 57 |
-
self.hidden_act = hidden_act
|
| 58 |
-
self.max_position_embeddings = max_position_embeddings
|
| 59 |
-
self.initializer_range = initializer_range
|
| 60 |
-
self.rms_norm_eps = rms_norm_eps
|
| 61 |
-
self.tie_word_embeddings = tie_word_embeddings
|
| 62 |
-
self.rope_theta = rope_theta
|
| 63 |
-
self.attention_dropout = attention_dropout
|
| 64 |
-
self.attention_bias = attention_bias
|
| 65 |
-
|
| 66 |
-
self.prelude_layers = prelude_layers
|
| 67 |
-
self.recurrent_layers = recurrent_layers
|
| 68 |
-
self.coda_layers = coda_layers
|
| 69 |
-
self.recurrent_passes = recurrent_passes
|
| 70 |
-
self.loop_noise_std = loop_noise_std
|
| 71 |
-
self.gdn_per_xsa = gdn_per_xsa
|
| 72 |
-
|
| 73 |
-
self.gdn_key_dim = gdn_key_dim if gdn_key_dim is not None else self.head_dim
|
| 74 |
-
self.gdn_value_dim = gdn_value_dim if gdn_value_dim is not None else self.head_dim
|
| 75 |
-
self.gdn_num_v_heads = (
|
| 76 |
-
gdn_num_v_heads if gdn_num_v_heads is not None else num_attention_heads
|
| 77 |
-
)
|
| 78 |
-
self.gdn_conv_kernel_size = gdn_conv_kernel_size
|
| 79 |
-
self.gdn_allow_neg_eigval = gdn_allow_neg_eigval
|
| 80 |
-
|
| 81 |
-
self.xsa_projection = xsa_projection
|
| 82 |
-
|
| 83 |
-
if rope_parameters is not None:
|
| 84 |
-
self.rope_parameters = dict(rope_parameters)
|
| 85 |
-
elif rope_scaling is not None:
|
| 86 |
-
self.rope_parameters = dict(rope_scaling)
|
| 87 |
-
else:
|
| 88 |
-
self.rope_parameters = {"rope_type": "default"}
|
| 89 |
-
self.rope_parameters.setdefault("rope_type", "default")
|
| 90 |
-
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
| 91 |
-
if self.rope_parameters.get("rope_type") != "default":
|
| 92 |
-
self.rope_parameters.setdefault("factor", 1.0)
|
| 93 |
-
self.rope_scaling = dict(self.rope_parameters)
|
| 94 |
-
self.partial_rotary_factor = partial_rotary_factor
|
| 95 |
-
|
| 96 |
-
self.gradient_checkpointing = gradient_checkpointing
|
| 97 |
-
self.use_cache = use_cache
|
| 98 |
-
|
| 99 |
-
group = gdn_per_xsa + 1
|
| 100 |
-
if recurrent_layers % group != 0:
|
| 101 |
-
raise ValueError(
|
| 102 |
-
f"recurrent_layers ({recurrent_layers}) must be divisible by "
|
| 103 |
-
f"gdn_per_xsa + 1 = {group}"
|
| 104 |
-
)
|
| 105 |
-
if num_attention_heads % num_key_value_heads != 0:
|
| 106 |
-
raise ValueError(
|
| 107 |
-
f"num_attention_heads ({num_attention_heads}) must be divisible by "
|
| 108 |
-
f"num_key_value_heads ({num_key_value_heads})"
|
| 109 |
-
)
|
| 110 |
-
if (
|
| 111 |
-
self.gdn_num_v_heads < num_attention_heads
|
| 112 |
-
or self.gdn_num_v_heads % num_attention_heads != 0
|
| 113 |
-
):
|
| 114 |
-
raise ValueError(
|
| 115 |
-
f"gdn_num_v_heads ({self.gdn_num_v_heads}) must be >= "
|
| 116 |
-
f"num_attention_heads ({num_attention_heads}) and divisible by it"
|
| 117 |
-
)
|
| 118 |
-
valid_rope_types = {"default", "linear", "dynamic", "yarn", "longrope", "llama3"}
|
| 119 |
-
rt = self.rope_parameters.get("rope_type", "default")
|
| 120 |
-
if rt not in valid_rope_types:
|
| 121 |
-
raise ValueError(f"rope_type must be one of {valid_rope_types}, got {rt}")
|
| 122 |
-
|
| 123 |
-
self.num_groups = recurrent_layers // group
|
| 124 |
-
self.num_hidden_layers = prelude_layers + recurrent_layers + coda_layers
|
| 125 |
-
self.layer_types = self._build_layer_types()
|
| 126 |
-
|
| 127 |
-
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 128 |
-
|
| 129 |
-
def _build_layer_types(self) -> List[str]:
|
| 130 |
-
types = ["full_attention"] * self.prelude_layers
|
| 131 |
-
for _ in range(self.num_groups):
|
| 132 |
-
types.extend(["linear_attention"] * self.gdn_per_xsa)
|
| 133 |
-
types.append("full_attention")
|
| 134 |
-
types.extend(["full_attention"] * self.coda_layers)
|
| 135 |
-
assert len(types) == self.num_hidden_layers
|
| 136 |
-
return types
|
| 137 |
-
|
| 138 |
-
@property
|
| 139 |
-
def surjo_layer_types(self) -> List[str]:
|
| 140 |
-
return ["xsa" if t == "full_attention" else "gdn" for t in self.layer_types]
|
| 141 |
-
|
| 142 |
-
@property
|
| 143 |
-
def effective_num_layers(self) -> int:
|
| 144 |
-
return (
|
| 145 |
-
self.prelude_layers
|
| 146 |
-
+ self.recurrent_layers * self.recurrent_passes
|
| 147 |
-
+ self.coda_layers
|
| 148 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/generation_config.json
DELETED
|
@@ -1,7 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_from_model_config": true,
|
| 3 |
-
"output_attentions": false,
|
| 4 |
-
"output_hidden_states": false,
|
| 5 |
-
"transformers_version": "5.16.1",
|
| 6 |
-
"use_cache": false
|
| 7 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/model.safetensors
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:4947b5f518852154f008f7311c50e54b07859b5ede121424ec7fd2ed5e9aefcb
|
| 3 |
-
size 215196728
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/modeling_surjo.py
DELETED
|
@@ -1,926 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""SurjoLabs Surjo Architecture"""
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
from typing import Dict, List, Optional, Tuple
|
| 8 |
-
|
| 9 |
-
import torch
|
| 10 |
-
import torch.nn as nn
|
| 11 |
-
import torch.nn.functional as F
|
| 12 |
-
import torch.utils.checkpoint
|
| 13 |
-
|
| 14 |
-
from transformers import PreTrainedModel
|
| 15 |
-
from transformers.activations import ACT2FN
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
from transformers import GenerationMixin
|
| 19 |
-
except ImportError:
|
| 20 |
-
from transformers.generation import GenerationMixin
|
| 21 |
-
from transformers.modeling_outputs import (
|
| 22 |
-
BaseModelOutputWithPast,
|
| 23 |
-
CausalLMOutputWithPast,
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
from .configuration_surjo import SurjoConfig
|
| 28 |
-
except (ImportError, ValueError):
|
| 29 |
-
from configuration_surjo import SurjoConfig
|
| 30 |
-
|
| 31 |
-
try:
|
| 32 |
-
from fla.modules.fused_linear_cross_entropy import (
|
| 33 |
-
fused_linear_cross_entropy_loss as _fla_flce,
|
| 34 |
-
)
|
| 35 |
-
except ImportError:
|
| 36 |
-
try:
|
| 37 |
-
from fla.modules import fused_linear_cross_entropy_loss as _fla_flce
|
| 38 |
-
except ImportError:
|
| 39 |
-
_fla_flce = None
|
| 40 |
-
|
| 41 |
-
try:
|
| 42 |
-
from fla.modules.norm import rms_norm as _fla_rms_norm
|
| 43 |
-
except ImportError:
|
| 44 |
-
try:
|
| 45 |
-
from fla.modules import rms_norm as _fla_rms_norm
|
| 46 |
-
except ImportError:
|
| 47 |
-
_fla_rms_norm = None
|
| 48 |
-
|
| 49 |
-
try:
|
| 50 |
-
from fla.ops.gdn2 import chunk_gdn2, fused_recurrent_gdn2
|
| 51 |
-
FLA_AVAILABLE = True
|
| 52 |
-
except ImportError:
|
| 53 |
-
chunk_gdn2 = None
|
| 54 |
-
fused_recurrent_gdn2 = None
|
| 55 |
-
FLA_AVAILABLE = False
|
| 56 |
-
|
| 57 |
-
_USE_FLA_FUSED_CE = True
|
| 58 |
-
_USE_FLA_RMS_NORM = False
|
| 59 |
-
|
| 60 |
-
if FLA_AVAILABLE:
|
| 61 |
-
|
| 62 |
-
@torch.compiler.disable
|
| 63 |
-
def _fla_chunk(q, k, v, g, b, w, initial_state=None, output_final_state=False,
|
| 64 |
-
cu_seqlens=None):
|
| 65 |
-
return chunk_gdn2(
|
| 66 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 67 |
-
initial_state=initial_state,
|
| 68 |
-
output_final_state=output_final_state,
|
| 69 |
-
use_qk_l2norm_in_kernel=True,
|
| 70 |
-
cu_seqlens=cu_seqlens,
|
| 71 |
-
)
|
| 72 |
-
|
| 73 |
-
@torch.compiler.disable
|
| 74 |
-
def _fla_recurrent(q, k, v, g, b, w, initial_state=None, output_final_state=False):
|
| 75 |
-
return fused_recurrent_gdn2(
|
| 76 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 77 |
-
initial_state=initial_state,
|
| 78 |
-
output_final_state=output_final_state,
|
| 79 |
-
use_qk_l2norm_in_kernel=True,
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
try:
|
| 83 |
-
from flash_attn import flash_attn_varlen_func
|
| 84 |
-
FLASH_ATTN_AVAILABLE = True
|
| 85 |
-
except ImportError:
|
| 86 |
-
flash_attn_varlen_func = None
|
| 87 |
-
FLASH_ATTN_AVAILABLE = False
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def _mask_padding_states(hidden_states, padding_mask):
|
| 91 |
-
if padding_mask is not None:
|
| 92 |
-
return hidden_states * padding_mask.unsqueeze(-1).to(hidden_states.dtype)
|
| 93 |
-
return hidden_states
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def naive_gdn2_reference(q, k, v, g, b, w, initial_state=None):
|
| 97 |
-
"""fp32 reference for GDN-2."""
|
| 98 |
-
B, T, H, K = q.shape
|
| 99 |
-
V = v.shape[-1]
|
| 100 |
-
S = (
|
| 101 |
-
torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)
|
| 102 |
-
if initial_state is None
|
| 103 |
-
else initial_state.float()
|
| 104 |
-
)
|
| 105 |
-
scale = K ** -0.5
|
| 106 |
-
outs = []
|
| 107 |
-
for t in range(T):
|
| 108 |
-
q_t = F.normalize(q[:, t], dim=-1)
|
| 109 |
-
k_t = F.normalize(k[:, t], dim=-1)
|
| 110 |
-
v_t, g_t, b_t, w_t = v[:, t], g[:, t], b[:, t], w[:, t]
|
| 111 |
-
S = S * torch.exp(g_t).unsqueeze(-1)
|
| 112 |
-
e = b_t * k_t
|
| 113 |
-
r = torch.einsum("bhkv,bhk->bhv", S, e)
|
| 114 |
-
z = w_t * v_t
|
| 115 |
-
S = S + torch.einsum("bhk,bhv->bhkv", k_t, z - r)
|
| 116 |
-
outs.append(scale * torch.einsum("bhkv,bhk->bhv", S, q_t))
|
| 117 |
-
return torch.stack(outs, dim=1), S
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
class SurjoRMSNorm(nn.Module):
|
| 121 |
-
"""FLA Triton RMSNorm when available; else fused ATen F.rms_norm."""
|
| 122 |
-
|
| 123 |
-
def __init__(self, dim: int, eps: float = 1e-6):
|
| 124 |
-
super().__init__()
|
| 125 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 126 |
-
self.eps = eps
|
| 127 |
-
|
| 128 |
-
def forward(self, x):
|
| 129 |
-
if x.dtype != self.weight.dtype:
|
| 130 |
-
x = x.to(self.weight.dtype)
|
| 131 |
-
if _USE_FLA_RMS_NORM and _fla_rms_norm is not None and x.is_cuda:
|
| 132 |
-
return _fla_rms_norm(x, self.weight, None, eps=self.eps)
|
| 133 |
-
return F.rms_norm(x, (x.shape[-1],), self.weight, self.eps)
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class ClampedMLP(nn.Module):
|
| 137 |
-
def __init__(self, config):
|
| 138 |
-
hidden_size = config.hidden_size
|
| 139 |
-
intermediate_size = config.intermediate_size
|
| 140 |
-
super().__init__()
|
| 141 |
-
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 142 |
-
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 143 |
-
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
| 144 |
-
self.act_fn = ACT2FN[config.hidden_act]
|
| 145 |
-
|
| 146 |
-
def forward(self, x):
|
| 147 |
-
return self.down_proj(
|
| 148 |
-
self.act_fn(self.gate_proj(x).clamp(-15.0, 15.0)) * self.up_proj(x)
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
class SurjoRotaryEmbedding(nn.Module):
|
| 153 |
-
"""RoPE with frequencies computed in forward() (no stored buffer)."""
|
| 154 |
-
|
| 155 |
-
def __init__(self, config, device=None):
|
| 156 |
-
super().__init__()
|
| 157 |
-
self.config = config
|
| 158 |
-
self.rope_type = config.rope_parameters.get("rope_type", "default")
|
| 159 |
-
self.max_position_embeddings = config.max_position_embeddings
|
| 160 |
-
self.base = config.rope_parameters.get("rope_theta", config.rope_theta)
|
| 161 |
-
self.factor = config.rope_parameters.get("factor", 1.0)
|
| 162 |
-
self.dim = int(config.head_dim * config.partial_rotary_factor)
|
| 163 |
-
|
| 164 |
-
def _inv_freq(self, device):
|
| 165 |
-
inv = 1.0 / (
|
| 166 |
-
self.base
|
| 167 |
-
** (torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim)
|
| 168 |
-
)
|
| 169 |
-
if self.rope_type == "linear":
|
| 170 |
-
inv = inv / self.factor
|
| 171 |
-
return inv
|
| 172 |
-
|
| 173 |
-
@torch.no_grad()
|
| 174 |
-
def forward(self, position_ids):
|
| 175 |
-
inv = self._inv_freq(position_ids.device)
|
| 176 |
-
freqs = torch.einsum("bt,f->btf", position_ids.float(), inv)
|
| 177 |
-
emb = torch.cat([freqs, freqs], dim=-1)
|
| 178 |
-
return emb.cos(), emb.sin()
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def rotate_half(x):
|
| 182 |
-
x1, x2 = x.chunk(2, dim=-1)
|
| 183 |
-
return torch.cat((-x2, x1), dim=-1)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def apply_rope(q, k, cos, sin):
|
| 187 |
-
cos = cos[:, None, :, :].to(q.dtype)
|
| 188 |
-
sin = sin[:, None, :, :].to(q.dtype)
|
| 189 |
-
q = q * cos + rotate_half(q) * sin
|
| 190 |
-
k = k * cos + rotate_half(k) * sin
|
| 191 |
-
return q, k
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
def apply_rope_flat(q, k, cos, sin):
|
| 195 |
-
"""RoPE on flat varlen tensors. q, k: [total, H, D]; cos, sin: [B, T, D]."""
|
| 196 |
-
total = q.shape[0]
|
| 197 |
-
cos_f = cos.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 198 |
-
sin_f = sin.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 199 |
-
q = q * cos_f + rotate_half(q) * sin_f
|
| 200 |
-
k = k * cos_f + rotate_half(k) * sin_f
|
| 201 |
-
return q, k
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
@torch.compiler.disable
|
| 205 |
-
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen):
|
| 206 |
-
"""FA2 varlen. cu_seqlens device int32; max_seqlen a constant (no sync)."""
|
| 207 |
-
return flash_attn_varlen_func(
|
| 208 |
-
q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen,
|
| 209 |
-
dropout_p=0.0, causal=True,
|
| 210 |
-
)
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
class ShortConvolution(nn.Module):
|
| 214 |
-
def __init__(self, dim: int, kernel_size: int = 4):
|
| 215 |
-
super().__init__()
|
| 216 |
-
self.kernel_size = kernel_size
|
| 217 |
-
self.conv = nn.Conv1d(dim, dim, kernel_size, groups=dim, bias=False)
|
| 218 |
-
|
| 219 |
-
def forward(self, x, cache=None, output_state=False):
|
| 220 |
-
B, T, C = x.shape
|
| 221 |
-
xt = x.transpose(1, 2)
|
| 222 |
-
if T == 1 and cache is not None:
|
| 223 |
-
comb = torch.cat([cache, xt], dim=2)
|
| 224 |
-
w = self.conv.weight.squeeze(1)
|
| 225 |
-
out = F.silu(torch.einsum("bck,ck->bc", comb, w).unsqueeze(-1))
|
| 226 |
-
new = comb[:, :, 1:] if output_state else None
|
| 227 |
-
return out.transpose(1, 2), new
|
| 228 |
-
if cache is not None:
|
| 229 |
-
xt_in = torch.cat([cache, xt], dim=2)
|
| 230 |
-
else:
|
| 231 |
-
xt_in = F.pad(xt, (self.kernel_size - 1, 0))
|
| 232 |
-
out = F.silu(self.conv(xt_in))
|
| 233 |
-
new = xt_in[:, :, -(self.kernel_size - 1):] if output_state else None
|
| 234 |
-
return out.transpose(1, 2), new
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
class SurjoCache:
|
| 238 |
-
def __init__(self):
|
| 239 |
-
self.kv = {}
|
| 240 |
-
self.gdn_state = {}
|
| 241 |
-
self.gdn_conv = {}
|
| 242 |
-
|
| 243 |
-
def get_seq_length(self):
|
| 244 |
-
if not self.kv:
|
| 245 |
-
return 0
|
| 246 |
-
return next(iter(self.kv.values()))[0].shape[2]
|
| 247 |
-
|
| 248 |
-
@staticmethod
|
| 249 |
-
def num_xsa_slots(config):
|
| 250 |
-
return (
|
| 251 |
-
config.prelude_layers
|
| 252 |
-
+ config.num_groups * config.recurrent_passes
|
| 253 |
-
+ config.coda_layers
|
| 254 |
-
)
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
class XSAAttention(nn.Module):
|
| 258 |
-
"""Full attention with XSA value-projection subtraction."""
|
| 259 |
-
|
| 260 |
-
def __init__(self, config, layer_idx: int):
|
| 261 |
-
super().__init__()
|
| 262 |
-
self.layer_idx = layer_idx
|
| 263 |
-
self.num_heads = config.num_attention_heads
|
| 264 |
-
self.num_kv_heads = config.num_key_value_heads
|
| 265 |
-
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 266 |
-
self.head_dim = config.head_dim
|
| 267 |
-
self.xsa_projection = config.xsa_projection
|
| 268 |
-
self.dropout = config.attention_dropout
|
| 269 |
-
self.hidden_size = config.hidden_size
|
| 270 |
-
self.use_flash = getattr(config, "_use_flash_xsa", False)
|
| 271 |
-
self.q_proj = nn.Linear(
|
| 272 |
-
self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
|
| 273 |
-
)
|
| 274 |
-
self.k_proj = nn.Linear(
|
| 275 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 276 |
-
)
|
| 277 |
-
self.v_proj = nn.Linear(
|
| 278 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 279 |
-
)
|
| 280 |
-
self.o_proj = nn.Linear(
|
| 281 |
-
self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias
|
| 282 |
-
)
|
| 283 |
-
self.q_norm = SurjoRMSNorm(self.head_dim)
|
| 284 |
-
self.k_norm = SurjoRMSNorm(self.head_dim)
|
| 285 |
-
|
| 286 |
-
def _xsa_projection_step(self, attn, v):
|
| 287 |
-
dv = (attn.float() * v.float()).sum(dim=-1, keepdim=True)
|
| 288 |
-
vv = (v.float() * v.float()).sum(dim=-1, keepdim=True).clamp_min(1e-4)
|
| 289 |
-
scale = (dv / vv).to(attn.dtype)
|
| 290 |
-
return attn - scale * v
|
| 291 |
-
|
| 292 |
-
def forward(self, hidden_states, attention_mask, cache, slot, use_cache,
|
| 293 |
-
cache_position, cos, sin, cu_seqlens=None):
|
| 294 |
-
B, T, _ = hidden_states.shape
|
| 295 |
-
H, Hkv, D = self.num_heads, self.num_kv_heads, self.head_dim
|
| 296 |
-
|
| 297 |
-
q = self.q_proj(hidden_states).view(B, T, H, D).transpose(1, 2)
|
| 298 |
-
k = self.k_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 299 |
-
v = self.v_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 300 |
-
q = self.q_norm(q)
|
| 301 |
-
k = self.k_norm(k)
|
| 302 |
-
|
| 303 |
-
use_varlen = (
|
| 304 |
-
cu_seqlens is not None
|
| 305 |
-
and cache is None
|
| 306 |
-
and self.use_flash
|
| 307 |
-
and FLASH_ATTN_AVAILABLE
|
| 308 |
-
and hidden_states.is_cuda
|
| 309 |
-
)
|
| 310 |
-
if use_varlen:
|
| 311 |
-
total = B * T
|
| 312 |
-
q_f = q.transpose(1, 2).reshape(total, H, D).to(torch.bfloat16)
|
| 313 |
-
k_f = k.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 314 |
-
v_f = v.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 315 |
-
if Hkv != H:
|
| 316 |
-
k_f = k_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 317 |
-
v_f = v_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 318 |
-
q_f, k_f = apply_rope_flat(q_f, k_f, cos, sin)
|
| 319 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 320 |
-
o_f = _flash_varlen(q_f, k_f, v_f, cu_dev, T)
|
| 321 |
-
attn_out = o_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 322 |
-
v_xsa = v_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 323 |
-
if self.xsa_projection:
|
| 324 |
-
attn_out = self._xsa_projection_step(attn_out, v_xsa)
|
| 325 |
-
out = attn_out.reshape(B, T, H * D)
|
| 326 |
-
return self.o_proj(out)
|
| 327 |
-
|
| 328 |
-
q, k = apply_rope(q, k, cos, sin)
|
| 329 |
-
v_cur = v
|
| 330 |
-
if cache is not None and use_cache:
|
| 331 |
-
if slot in cache.kv:
|
| 332 |
-
pk, pv = cache.kv[slot]
|
| 333 |
-
k = torch.cat([pk, k.to(pk.dtype)], dim=2)
|
| 334 |
-
v = torch.cat([pv, v.to(pv.dtype)], dim=2)
|
| 335 |
-
cache.kv[slot] = (k, v)
|
| 336 |
-
S = k.shape[2]
|
| 337 |
-
if Hkv != H:
|
| 338 |
-
k_e = k.repeat_interleave(self.num_kv_groups, dim=1)
|
| 339 |
-
v_e = v.repeat_interleave(self.num_kv_groups, dim=1)
|
| 340 |
-
v_cur_e = v_cur.repeat_interleave(self.num_kv_groups, dim=1)
|
| 341 |
-
else:
|
| 342 |
-
k_e, v_e, v_cur_e = k, v, v_cur
|
| 343 |
-
|
| 344 |
-
is_causal = False
|
| 345 |
-
mask4 = None
|
| 346 |
-
if attention_mask is not None:
|
| 347 |
-
L = attention_mask.shape[-1]
|
| 348 |
-
if L < S:
|
| 349 |
-
attention_mask = F.pad(attention_mask, (S - L, 0), value=1)
|
| 350 |
-
elif L > S:
|
| 351 |
-
attention_mask = attention_mask[:, -S:]
|
| 352 |
-
neg = torch.finfo(q.dtype).min
|
| 353 |
-
m = attention_mask[:, None, None, :].to(q.dtype)
|
| 354 |
-
if T == S:
|
| 355 |
-
if T > 1:
|
| 356 |
-
causal = torch.ones(T, S, device=q.device, dtype=q.dtype).tril()
|
| 357 |
-
allow = causal[None, None] * m
|
| 358 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 359 |
-
torch.full_like(allow, neg))
|
| 360 |
-
else:
|
| 361 |
-
mask4 = torch.where(m > 0, torch.zeros_like(m),
|
| 362 |
-
torch.full_like(m, neg))
|
| 363 |
-
else:
|
| 364 |
-
if cache_position is None:
|
| 365 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 366 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 367 |
-
causal = kv_pos[None, :] <= cache_position[:, None].to(q.device)
|
| 368 |
-
allow = causal[None, None].to(q.dtype) * m
|
| 369 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 370 |
-
torch.full_like(allow, neg))
|
| 371 |
-
elif cu_seqlens is not None and T > 1:
|
| 372 |
-
neg = torch.finfo(q.dtype).min
|
| 373 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32)
|
| 374 |
-
gpos = torch.arange(B * T, device=q.device)
|
| 375 |
-
doc_id = torch.searchsorted(cu_dev, gpos, right=True) - 1
|
| 376 |
-
doc_id = doc_id.clamp(min=0).view(B, T)
|
| 377 |
-
same = doc_id.unsqueeze(2) == doc_id.unsqueeze(1)
|
| 378 |
-
idx = torch.arange(T, device=q.device)
|
| 379 |
-
causal = idx.unsqueeze(0) <= idx.unsqueeze(1)
|
| 380 |
-
allow = (same & causal).unsqueeze(1)
|
| 381 |
-
mask4 = torch.where(
|
| 382 |
-
allow,
|
| 383 |
-
torch.zeros(B, 1, T, T, dtype=q.dtype, device=q.device),
|
| 384 |
-
torch.full((B, 1, T, T), neg, dtype=q.dtype, device=q.device),
|
| 385 |
-
)
|
| 386 |
-
else:
|
| 387 |
-
if T == S and T > 1:
|
| 388 |
-
is_causal = True
|
| 389 |
-
elif T > 1:
|
| 390 |
-
if cache_position is None:
|
| 391 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 392 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 393 |
-
neg = torch.finfo(q.dtype).min
|
| 394 |
-
causal = torch.zeros(T, S, device=q.device, dtype=q.dtype)
|
| 395 |
-
causal = causal.masked_fill(
|
| 396 |
-
kv_pos[None, :] > cache_position[:, None], neg
|
| 397 |
-
)
|
| 398 |
-
mask4 = causal[None, None, :, :]
|
| 399 |
-
|
| 400 |
-
attn = F.scaled_dot_product_attention(
|
| 401 |
-
q, k_e, v_e, attn_mask=mask4, is_causal=is_causal,
|
| 402 |
-
dropout_p=self.dropout if self.training else 0.0,
|
| 403 |
-
)
|
| 404 |
-
|
| 405 |
-
if self.xsa_projection:
|
| 406 |
-
attn = self._xsa_projection_step(attn, v_cur_e)
|
| 407 |
-
|
| 408 |
-
out = attn.transpose(1, 2).reshape(B, T, H * D)
|
| 409 |
-
return self.o_proj(out)
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
class GDN2Attention(nn.Module):
|
| 413 |
-
"""Gated DeltaNet-2 linear attention."""
|
| 414 |
-
|
| 415 |
-
def __init__(self, config, layer_idx: int):
|
| 416 |
-
super().__init__()
|
| 417 |
-
self.layer_idx = layer_idx
|
| 418 |
-
H = config.num_attention_heads
|
| 419 |
-
Hv = config.gdn_num_v_heads
|
| 420 |
-
self.num_heads = H
|
| 421 |
-
self.num_v_heads = Hv
|
| 422 |
-
self.gva = Hv // H
|
| 423 |
-
self.head_k_dim = config.gdn_key_dim
|
| 424 |
-
self.head_v_dim = config.gdn_value_dim
|
| 425 |
-
self.key_dim = H * self.head_k_dim
|
| 426 |
-
self.value_dim = Hv * self.head_v_dim
|
| 427 |
-
self.conv_kernel = config.gdn_conv_kernel_size
|
| 428 |
-
self.allow_neg_eigval = config.gdn_allow_neg_eigval
|
| 429 |
-
hidden = config.hidden_size
|
| 430 |
-
self.q_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 431 |
-
self.k_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 432 |
-
self.v_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 433 |
-
self.q_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 434 |
-
self.k_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 435 |
-
self.v_conv = ShortConvolution(self.value_dim, self.conv_kernel)
|
| 436 |
-
self.f_proj = nn.Sequential(
|
| 437 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 438 |
-
nn.Linear(self.head_v_dim, self.key_dim, bias=False),
|
| 439 |
-
)
|
| 440 |
-
self.b_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 441 |
-
self.w_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 442 |
-
self.A_log = nn.Parameter(
|
| 443 |
-
torch.log(torch.empty(H, dtype=torch.float32).uniform_(1, 16))
|
| 444 |
-
)
|
| 445 |
-
self.A_log._no_weight_decay = True
|
| 446 |
-
dt = torch.exp(
|
| 447 |
-
torch.rand(self.key_dim, dtype=torch.float32)
|
| 448 |
-
* (math.log(0.1) - math.log(0.001))
|
| 449 |
-
+ math.log(0.001)
|
| 450 |
-
).clamp(min=1e-4)
|
| 451 |
-
self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt)))
|
| 452 |
-
self.dt_bias._no_weight_decay = True
|
| 453 |
-
self.g_proj = nn.Sequential(
|
| 454 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 455 |
-
nn.Linear(self.head_v_dim, self.value_dim, bias=True),
|
| 456 |
-
)
|
| 457 |
-
self.o_norm = SurjoRMSNorm(self.head_v_dim, eps=config.rms_norm_eps)
|
| 458 |
-
self.o_proj = nn.Linear(self.value_dim, hidden, bias=False)
|
| 459 |
-
|
| 460 |
-
def forward(self, hidden_states, attention_mask, gdn_state, conv_state,
|
| 461 |
-
output_state, cu_seqlens=None):
|
| 462 |
-
B, T, _ = hidden_states.shape
|
| 463 |
-
if attention_mask is not None:
|
| 464 |
-
if attention_mask.shape[-1] != T:
|
| 465 |
-
attention_mask = (
|
| 466 |
-
attention_mask[:, -T:] if attention_mask.shape[-1] > T else None
|
| 467 |
-
)
|
| 468 |
-
if attention_mask is not None:
|
| 469 |
-
hidden_states = _mask_padding_states(hidden_states, attention_mask)
|
| 470 |
-
cq = conv_state[0] if conv_state is not None else None
|
| 471 |
-
ck = conv_state[1] if conv_state is not None else None
|
| 472 |
-
cvs = conv_state[2] if conv_state is not None else None
|
| 473 |
-
q, nq = self.q_conv(self.q_proj(hidden_states), cq, output_state)
|
| 474 |
-
k, nk = self.k_conv(self.k_proj(hidden_states), ck, output_state)
|
| 475 |
-
v, nv = self.v_conv(self.v_proj(hidden_states), cvs, output_state)
|
| 476 |
-
g = F.softplus(self.f_proj(hidden_states).float() + self.dt_bias)
|
| 477 |
-
b = self.b_proj(hidden_states).sigmoid()
|
| 478 |
-
w = self.w_proj(hidden_states).sigmoid()
|
| 479 |
-
q = q.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 480 |
-
k = k.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 481 |
-
v = v.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 482 |
-
g = g.view(B, T, self.num_heads, self.head_k_dim)
|
| 483 |
-
b = b.view(B, T, self.num_heads, self.head_k_dim)
|
| 484 |
-
w = w.view(B, T, self.num_v_heads, self.head_v_dim)
|
| 485 |
-
g = -self.A_log.float().exp().view(1, 1, self.num_heads, 1) * g
|
| 486 |
-
if self.allow_neg_eigval:
|
| 487 |
-
b = b * 2.0
|
| 488 |
-
if self.gva > 1:
|
| 489 |
-
q = q.repeat_interleave(self.gva, dim=2)
|
| 490 |
-
k = k.repeat_interleave(self.gva, dim=2)
|
| 491 |
-
g = g.repeat_interleave(self.gva, dim=2)
|
| 492 |
-
b = b.repeat_interleave(self.gva, dim=2)
|
| 493 |
-
init = gdn_state.float() if gdn_state is not None else None
|
| 494 |
-
|
| 495 |
-
if FLA_AVAILABLE and hidden_states.is_cuda:
|
| 496 |
-
if T == 1 and init is not None:
|
| 497 |
-
o, fs = _fla_recurrent(q, k, v, g, b, w, init, output_state)
|
| 498 |
-
elif cu_seqlens is not None:
|
| 499 |
-
total = B * T
|
| 500 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 501 |
-
q_f = q.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 502 |
-
k_f = k.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 503 |
-
v_f = v.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 504 |
-
g_f = g.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 505 |
-
b_f = b.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 506 |
-
w_f = w.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 507 |
-
o, fs = _fla_chunk(q_f, k_f, v_f, g_f, b_f, w_f, init,
|
| 508 |
-
output_state, cu_dev)
|
| 509 |
-
o = o.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 510 |
-
else:
|
| 511 |
-
o, fs = _fla_chunk(q, k, v, g, b, w, init, output_state, None)
|
| 512 |
-
else:
|
| 513 |
-
o, fs = naive_gdn2_reference(q.float(), k.float(), v.float(), g,
|
| 514 |
-
b.float(), w.float(), init)
|
| 515 |
-
|
| 516 |
-
# Cast back to activation precision
|
| 517 |
-
o = o.to(hidden_states.dtype)
|
| 518 |
-
|
| 519 |
-
fs = fs if output_state else None
|
| 520 |
-
gate = self.g_proj(hidden_states).view(B, T, self.num_v_heads, self.head_v_dim)
|
| 521 |
-
o = self.o_norm(o)
|
| 522 |
-
o = o * torch.sigmoid(gate)
|
| 523 |
-
o = o.reshape(B, T, self.value_dim)
|
| 524 |
-
conv_out = (nq, nk, nv) if output_state else None
|
| 525 |
-
return self.o_proj(o), fs, conv_out
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
def _is_xsa(config, li: int) -> bool:
|
| 529 |
-
if li < config.prelude_layers:
|
| 530 |
-
return True
|
| 531 |
-
if li >= config.prelude_layers + config.recurrent_layers:
|
| 532 |
-
return True
|
| 533 |
-
return (li - config.prelude_layers) % (config.gdn_per_xsa + 1) == config.gdn_per_xsa
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
class SurjoDecoderLayer(nn.Module):
|
| 537 |
-
def __init__(self, config, layer_idx: int):
|
| 538 |
-
super().__init__()
|
| 539 |
-
self.layer_idx = layer_idx
|
| 540 |
-
self.layer_type = "xsa" if _is_xsa(config, layer_idx) else "gdn"
|
| 541 |
-
if self.layer_type == "xsa":
|
| 542 |
-
self.self_attn = XSAAttention(config, layer_idx)
|
| 543 |
-
else:
|
| 544 |
-
self.linear_attn = GDN2Attention(config, layer_idx)
|
| 545 |
-
self.mlp = ClampedMLP(config)
|
| 546 |
-
self.input_layernorm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 547 |
-
self.post_attention_layernorm = SurjoRMSNorm(config.hidden_size,
|
| 548 |
-
eps=config.rms_norm_eps)
|
| 549 |
-
|
| 550 |
-
def forward(self, hidden_states, attention_mask=None, cos=None, sin=None,
|
| 551 |
-
cu_seqlens=None):
|
| 552 |
-
h = self.input_layernorm(hidden_states)
|
| 553 |
-
if self.layer_type == "xsa":
|
| 554 |
-
out = self.self_attn(h, attention_mask, None, -1, False, None,
|
| 555 |
-
cos, sin, cu_seqlens)
|
| 556 |
-
else:
|
| 557 |
-
out, _, _ = self.linear_attn(h, attention_mask, None, None, False,
|
| 558 |
-
cu_seqlens)
|
| 559 |
-
hidden_states = hidden_states + out
|
| 560 |
-
h2 = self.post_attention_layernorm(hidden_states)
|
| 561 |
-
return hidden_states + self.mlp(h2)
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
class SurjoPreTrainedModel(PreTrainedModel):
|
| 565 |
-
config_class = SurjoConfig
|
| 566 |
-
base_model_prefix = "model"
|
| 567 |
-
_no_split_modules = ["SurjoDecoderLayer"]
|
| 568 |
-
_supports_flash_attn = False
|
| 569 |
-
_supports_flash_attn_2 = False
|
| 570 |
-
_supports_sdpa = True
|
| 571 |
-
_is_stateful = True
|
| 572 |
-
_can_compile_fullgraph = True
|
| 573 |
-
|
| 574 |
-
def _init_weights(self, module):
|
| 575 |
-
std = self.config.initializer_range
|
| 576 |
-
if isinstance(module, nn.Linear):
|
| 577 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 578 |
-
if module.bias is not None:
|
| 579 |
-
module.bias.data.zero_()
|
| 580 |
-
elif isinstance(module, nn.Embedding):
|
| 581 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 582 |
-
if module.padding_idx is not None:
|
| 583 |
-
module.weight.data[module.padding_idx].zero_()
|
| 584 |
-
elif isinstance(module, GDN2Attention):
|
| 585 |
-
module.A_log.data.copy_(
|
| 586 |
-
torch.log(
|
| 587 |
-
torch.empty(module.num_heads, dtype=torch.float32,
|
| 588 |
-
device=module.A_log.device).uniform_(1, 16)
|
| 589 |
-
)
|
| 590 |
-
)
|
| 591 |
-
dt = torch.exp(
|
| 592 |
-
torch.rand(module.key_dim, dtype=torch.float32,
|
| 593 |
-
device=module.dt_bias.device)
|
| 594 |
-
* (math.log(0.1) - math.log(0.001)) + math.log(0.001)
|
| 595 |
-
).clamp(min=1e-4)
|
| 596 |
-
module.dt_bias.data.copy_(dt + torch.log(-torch.expm1(-dt)))
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
class SurjoModel(SurjoPreTrainedModel):
|
| 600 |
-
def __init__(self, config):
|
| 601 |
-
super().__init__(config)
|
| 602 |
-
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 603 |
-
self.layers = nn.ModuleList(
|
| 604 |
-
[SurjoDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 605 |
-
)
|
| 606 |
-
self.norm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 607 |
-
self.rotary = SurjoRotaryEmbedding(config)
|
| 608 |
-
self.grad_checkpointing = False
|
| 609 |
-
|
| 610 |
-
slot = 0
|
| 611 |
-
self.xsa_slot_map = {}
|
| 612 |
-
self.exec_plan = []
|
| 613 |
-
for li in range(config.prelude_layers):
|
| 614 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 615 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 616 |
-
slot += 1
|
| 617 |
-
for p in range(config.recurrent_passes):
|
| 618 |
-
for g in range(config.num_groups):
|
| 619 |
-
base = config.prelude_layers + g * (config.gdn_per_xsa + 1)
|
| 620 |
-
for j in range(config.gdn_per_xsa):
|
| 621 |
-
self.exec_plan.append((self.layers[base + j], base + j, p, -1))
|
| 622 |
-
li = base + config.gdn_per_xsa
|
| 623 |
-
self.xsa_slot_map[(li, p)] = slot
|
| 624 |
-
self.exec_plan.append((self.layers[li], li, p, slot))
|
| 625 |
-
slot += 1
|
| 626 |
-
for li in range(config.prelude_layers + config.recurrent_layers,
|
| 627 |
-
config.num_hidden_layers):
|
| 628 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 629 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 630 |
-
slot += 1
|
| 631 |
-
self.num_xsa_slots = slot
|
| 632 |
-
self.post_init()
|
| 633 |
-
|
| 634 |
-
def get_input_embeddings(self):
|
| 635 |
-
return self.embed_tokens
|
| 636 |
-
|
| 637 |
-
def set_input_embeddings(self, value):
|
| 638 |
-
self.embed_tokens = value
|
| 639 |
-
|
| 640 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 641 |
-
past_key_values=None, inputs_embeds=None, use_cache=None,
|
| 642 |
-
cache_position=None, return_dict=True,
|
| 643 |
-
output_hidden_states=False, output_attentions=False,
|
| 644 |
-
cu_seqlens=None, **kwargs):
|
| 645 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 646 |
-
past_key_values = None
|
| 647 |
-
if use_cache is None:
|
| 648 |
-
use_cache = past_key_values is not None
|
| 649 |
-
if use_cache and past_key_values is None:
|
| 650 |
-
past_key_values = SurjoCache()
|
| 651 |
-
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 652 |
-
|
| 653 |
-
if past_len > 0:
|
| 654 |
-
if input_ids is not None:
|
| 655 |
-
n_ids = input_ids.shape[1]
|
| 656 |
-
if (attention_mask is not None
|
| 657 |
-
and attention_mask.shape[-1] > n_ids
|
| 658 |
-
and attention_mask.shape[-1] > past_len):
|
| 659 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 660 |
-
input_ids = input_ids[:, -n_new:] if n_new <= n_ids else input_ids
|
| 661 |
-
elif n_ids > past_len:
|
| 662 |
-
input_ids = input_ids[:, past_len:]
|
| 663 |
-
else:
|
| 664 |
-
input_ids = input_ids[:, -1:]
|
| 665 |
-
elif inputs_embeds is not None:
|
| 666 |
-
n_emb = inputs_embeds.shape[1]
|
| 667 |
-
if (attention_mask is not None
|
| 668 |
-
and attention_mask.shape[-1] > n_emb
|
| 669 |
-
and attention_mask.shape[-1] > past_len):
|
| 670 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 671 |
-
inputs_embeds = (inputs_embeds[:, -n_new:] if n_new <= n_emb
|
| 672 |
-
else inputs_embeds)
|
| 673 |
-
elif n_emb > past_len:
|
| 674 |
-
inputs_embeds = inputs_embeds[:, past_len:]
|
| 675 |
-
else:
|
| 676 |
-
inputs_embeds = inputs_embeds[:, -1:]
|
| 677 |
-
|
| 678 |
-
if inputs_embeds is None:
|
| 679 |
-
if input_ids is None:
|
| 680 |
-
raise ValueError("Specify input_ids or inputs_embeds")
|
| 681 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
| 682 |
-
B, T = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 683 |
-
|
| 684 |
-
cache_position = torch.arange(past_len, past_len + T,
|
| 685 |
-
device=inputs_embeds.device)
|
| 686 |
-
if position_ids is not None and position_ids.shape[-1] != T:
|
| 687 |
-
position_ids = None
|
| 688 |
-
if position_ids is None:
|
| 689 |
-
position_ids = cache_position.unsqueeze(0).expand(B, -1)
|
| 690 |
-
cos, sin = self.rotary(position_ids)
|
| 691 |
-
|
| 692 |
-
gdn_states = dict(past_key_values.gdn_state) if past_key_values is not None else {}
|
| 693 |
-
conv_states = dict(past_key_values.gdn_conv) if past_key_values is not None else {}
|
| 694 |
-
|
| 695 |
-
noise_std = self.config.loop_noise_std
|
| 696 |
-
hidden = inputs_embeds
|
| 697 |
-
prev_p = 0
|
| 698 |
-
use_ckpt = self.training and self.grad_checkpointing
|
| 699 |
-
all_hidden_states = () if output_hidden_states else None
|
| 700 |
-
|
| 701 |
-
for (layer, li, p, slot) in self.exec_plan:
|
| 702 |
-
if output_hidden_states:
|
| 703 |
-
all_hidden_states += (hidden,)
|
| 704 |
-
if p != prev_p and p > 0 and self.training and noise_std > 0.0:
|
| 705 |
-
hidden = hidden + torch.randn_like(hidden) * noise_std
|
| 706 |
-
prev_p = p
|
| 707 |
-
|
| 708 |
-
if use_ckpt:
|
| 709 |
-
hidden = torch.utils.checkpoint.checkpoint(
|
| 710 |
-
self._train_layer, layer, hidden, attention_mask, cos, sin,
|
| 711 |
-
cu_seqlens, use_reentrant=False,
|
| 712 |
-
)
|
| 713 |
-
elif use_cache:
|
| 714 |
-
h = layer.input_layernorm(hidden)
|
| 715 |
-
if layer.layer_type == "xsa":
|
| 716 |
-
out = layer.self_attn(h, attention_mask, past_key_values,
|
| 717 |
-
slot, use_cache, cache_position,
|
| 718 |
-
cos, sin, cu_seqlens)
|
| 719 |
-
else:
|
| 720 |
-
gs = gdn_states.get((li, p))
|
| 721 |
-
cs = conv_states.get((li, p))
|
| 722 |
-
out, ngs, ncs = layer.linear_attn(h, attention_mask, gs, cs,
|
| 723 |
-
use_cache, cu_seqlens)
|
| 724 |
-
if ngs is not None:
|
| 725 |
-
gdn_states[(li, p)] = ngs
|
| 726 |
-
if ncs is not None:
|
| 727 |
-
conv_states[(li, p)] = ncs
|
| 728 |
-
hidden = hidden + out
|
| 729 |
-
h2 = layer.post_attention_layernorm(hidden)
|
| 730 |
-
hidden = hidden + layer.mlp(h2)
|
| 731 |
-
else:
|
| 732 |
-
hidden = layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 733 |
-
|
| 734 |
-
hidden = self.norm(hidden)
|
| 735 |
-
if output_hidden_states:
|
| 736 |
-
all_hidden_states += (hidden,)
|
| 737 |
-
|
| 738 |
-
if use_cache and past_key_values is not None:
|
| 739 |
-
past_key_values.gdn_state.update(gdn_states)
|
| 740 |
-
past_key_values.gdn_conv.update(conv_states)
|
| 741 |
-
|
| 742 |
-
if not return_dict:
|
| 743 |
-
out = tuple(v for v in [hidden, past_key_values if use_cache else None,
|
| 744 |
-
all_hidden_states] if v is not None)
|
| 745 |
-
return out
|
| 746 |
-
return BaseModelOutputWithPast(
|
| 747 |
-
last_hidden_state=hidden,
|
| 748 |
-
past_key_values=past_key_values if use_cache else None,
|
| 749 |
-
hidden_states=all_hidden_states,
|
| 750 |
-
attentions=None,
|
| 751 |
-
)
|
| 752 |
-
|
| 753 |
-
def _train_layer(self, layer, hidden, attention_mask, cos, sin, cu_seqlens):
|
| 754 |
-
return layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
class SurjoForCausalLM(SurjoPreTrainedModel, GenerationMixin):
|
| 758 |
-
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 759 |
-
|
| 760 |
-
def __init__(self, config):
|
| 761 |
-
super().__init__(config)
|
| 762 |
-
self.model = SurjoModel(config)
|
| 763 |
-
self.vocab_size = config.vocab_size
|
| 764 |
-
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 765 |
-
self.post_init()
|
| 766 |
-
|
| 767 |
-
def tie_weights(self, **kwargs):
|
| 768 |
-
try:
|
| 769 |
-
super().tie_weights(**kwargs)
|
| 770 |
-
except TypeError:
|
| 771 |
-
pass
|
| 772 |
-
except Exception:
|
| 773 |
-
pass
|
| 774 |
-
if (getattr(self.config, "tie_word_embeddings", False)
|
| 775 |
-
and getattr(self, "model", None) is not None
|
| 776 |
-
and getattr(self, "lm_head", None) is not None):
|
| 777 |
-
self.lm_head.weight = self.model.embed_tokens.weight
|
| 778 |
-
|
| 779 |
-
def save_pretrained(self, *args, **kwargs):
|
| 780 |
-
was_tied = (getattr(self, "lm_head", None) is not None
|
| 781 |
-
and getattr(self, "model", None) is not None
|
| 782 |
-
and self.lm_head.weight is self.model.embed_tokens.weight)
|
| 783 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 784 |
-
self.lm_head.weight = nn.Parameter(
|
| 785 |
-
self.model.embed_tokens.weight.detach().clone(),
|
| 786 |
-
requires_grad=self.model.embed_tokens.weight.requires_grad,
|
| 787 |
-
)
|
| 788 |
-
try:
|
| 789 |
-
return super().save_pretrained(*args, **kwargs)
|
| 790 |
-
finally:
|
| 791 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 792 |
-
self.tie_weights()
|
| 793 |
-
|
| 794 |
-
def get_input_embeddings(self):
|
| 795 |
-
return self.model.embed_tokens
|
| 796 |
-
|
| 797 |
-
def set_input_embeddings(self, value):
|
| 798 |
-
self.model.embed_tokens = value
|
| 799 |
-
|
| 800 |
-
def get_output_embeddings(self):
|
| 801 |
-
return self.lm_head
|
| 802 |
-
|
| 803 |
-
def set_output_embeddings(self, value):
|
| 804 |
-
self.lm_head = value
|
| 805 |
-
|
| 806 |
-
def set_decoder(self, decoder):
|
| 807 |
-
self.model = decoder
|
| 808 |
-
|
| 809 |
-
def get_decoder(self):
|
| 810 |
-
return self.model
|
| 811 |
-
|
| 812 |
-
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, **kwargs):
|
| 813 |
-
self.model.grad_checkpointing = True
|
| 814 |
-
|
| 815 |
-
def gradient_checkpointing_disable(self):
|
| 816 |
-
self.model.grad_checkpointing = False
|
| 817 |
-
|
| 818 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 819 |
-
past_key_values=None, inputs_embeds=None, labels=None,
|
| 820 |
-
use_cache=None, output_hidden_states=None, output_attentions=None,
|
| 821 |
-
return_dict=None, logits_to_keep=0, cache_position=None,
|
| 822 |
-
cu_seqlens=None, **kwargs):
|
| 823 |
-
if logits_to_keep in (None, 0) and kwargs.get("num_logits_to_keep"):
|
| 824 |
-
logits_to_keep = kwargs.pop("num_logits_to_keep")
|
| 825 |
-
return_dict = True if return_dict is None else return_dict
|
| 826 |
-
if use_cache is None:
|
| 827 |
-
use_cache = not (self.training or labels is not None)
|
| 828 |
-
|
| 829 |
-
outputs = self.model(
|
| 830 |
-
input_ids=input_ids, attention_mask=attention_mask,
|
| 831 |
-
position_ids=position_ids, past_key_values=past_key_values,
|
| 832 |
-
inputs_embeds=inputs_embeds, use_cache=use_cache,
|
| 833 |
-
cache_position=cache_position,
|
| 834 |
-
output_hidden_states=output_hidden_states,
|
| 835 |
-
output_attentions=output_attentions,
|
| 836 |
-
cu_seqlens=cu_seqlens,
|
| 837 |
-
**kwargs,
|
| 838 |
-
)
|
| 839 |
-
hidden_states = outputs[0]
|
| 840 |
-
|
| 841 |
-
loss, logits = None, None
|
| 842 |
-
if labels is not None:
|
| 843 |
-
sh = hidden_states[..., :-1, :].contiguous()
|
| 844 |
-
sl = labels[..., 1:].contiguous()
|
| 845 |
-
if _USE_FLA_FUSED_CE and _fla_flce is not None:
|
| 846 |
-
loss = _fla_flce(
|
| 847 |
-
sh.view(-1, sh.shape[-1]),
|
| 848 |
-
sl.view(-1),
|
| 849 |
-
self.lm_head.weight,
|
| 850 |
-
num_chunks=8,
|
| 851 |
-
reduction="mean",
|
| 852 |
-
)
|
| 853 |
-
else:
|
| 854 |
-
n_chunks = max(8, sh.shape[0] // 8)
|
| 855 |
-
tot = hidden_states.new_zeros((), dtype=torch.float32)
|
| 856 |
-
n_tok = 0
|
| 857 |
-
for h_c, l_c in zip(sh.chunk(n_chunks, dim=0), sl.chunk(n_chunks, dim=0)):
|
| 858 |
-
if l_c.numel() == 0:
|
| 859 |
-
continue
|
| 860 |
-
lg = self.lm_head(h_c)
|
| 861 |
-
tot = tot + F.cross_entropy(
|
| 862 |
-
lg.float().view(-1, lg.size(-1)), l_c.view(-1), reduction="sum"
|
| 863 |
-
)
|
| 864 |
-
n_tok += l_c.numel()
|
| 865 |
-
loss = tot / max(n_tok, 1)
|
| 866 |
-
else:
|
| 867 |
-
if isinstance(logits_to_keep, int) and logits_to_keep > 0:
|
| 868 |
-
sl_hidden = hidden_states[:, -logits_to_keep:, :]
|
| 869 |
-
elif torch.is_tensor(logits_to_keep):
|
| 870 |
-
sl_hidden = hidden_states[:, logits_to_keep, :]
|
| 871 |
-
else:
|
| 872 |
-
sl_hidden = hidden_states
|
| 873 |
-
logits = self.lm_head(sl_hidden)
|
| 874 |
-
|
| 875 |
-
if not return_dict:
|
| 876 |
-
out = (logits,) + outputs[1:]
|
| 877 |
-
return (loss,) + out if loss is not None else out
|
| 878 |
-
return CausalLMOutputWithPast(
|
| 879 |
-
loss=loss, logits=logits,
|
| 880 |
-
past_key_values=outputs.past_key_values,
|
| 881 |
-
hidden_states=outputs.hidden_states,
|
| 882 |
-
attentions=outputs.attentions,
|
| 883 |
-
)
|
| 884 |
-
|
| 885 |
-
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
|
| 886 |
-
attention_mask=None, inputs_embeds=None,
|
| 887 |
-
cache_position=None, use_cache=True, **kwargs):
|
| 888 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 889 |
-
past_key_values = None
|
| 890 |
-
has_state = past_key_values is not None and len(past_key_values.kv) > 0
|
| 891 |
-
if has_state:
|
| 892 |
-
input_ids = input_ids[:, -1:]
|
| 893 |
-
if kwargs.get("logits_to_keep") is None:
|
| 894 |
-
kwargs["logits_to_keep"] = 1
|
| 895 |
-
past_len = past_key_values.get_seq_length() if has_state else 0
|
| 896 |
-
cache_position = torch.arange(past_len, past_len + input_ids.shape[1],
|
| 897 |
-
device=input_ids.device)
|
| 898 |
-
model_inputs = {
|
| 899 |
-
"input_ids": input_ids.contiguous(),
|
| 900 |
-
"past_key_values": past_key_values,
|
| 901 |
-
"use_cache": use_cache,
|
| 902 |
-
"cache_position": cache_position,
|
| 903 |
-
"attention_mask": attention_mask,
|
| 904 |
-
}
|
| 905 |
-
model_inputs.update(kwargs)
|
| 906 |
-
return model_inputs
|
| 907 |
-
|
| 908 |
-
def _reorder_cache(self, past_key_values: SurjoCache, beam_idx):
|
| 909 |
-
for slot, (k, v) in past_key_values.kv.items():
|
| 910 |
-
past_key_values.kv[slot] = (k.index_select(0, beam_idx),
|
| 911 |
-
v.index_select(0, beam_idx))
|
| 912 |
-
for key in list(past_key_values.gdn_state.keys()):
|
| 913 |
-
s = past_key_values.gdn_state[key]
|
| 914 |
-
if s is not None:
|
| 915 |
-
past_key_values.gdn_state[key] = s.index_select(0, beam_idx)
|
| 916 |
-
for key in list(past_key_values.gdn_conv.keys()):
|
| 917 |
-
cs = past_key_values.gdn_conv[key]
|
| 918 |
-
if cs is not None:
|
| 919 |
-
past_key_values.gdn_conv[key] = tuple(
|
| 920 |
-
c.index_select(0, beam_idx) if c is not None else None for c in cs
|
| 921 |
-
)
|
| 922 |
-
return past_key_values
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
SurjoConfig.register_for_auto_class()
|
| 926 |
-
SurjoForCausalLM.register_for_auto_class()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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b6a9070389bf8004fc2664292455b891c2b66ebebef9a1d22
|
| 3 |
-
size 148034507
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/optimizer_1.bin
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:30d8b290568d14613f48a45c46ea1e1b1951e7d4f229533ef02526f2c35647ee
|
| 3 |
-
size 134405851
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/random_states_0.pkl
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:4d0af987318d035cbf3b8ebc860997b833d6d9ae9456c5fc8fd84590e13d5040
|
| 3 |
-
size 14821
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11000/tokenizer.json
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
checkpoint-11000/tokenizer_config.json
DELETED
|
@@ -1,85 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"backend": "tokenizers",
|
| 3 |
-
"bos_token": "<|bos|>",
|
| 4 |
-
"clean_up_tokenization_spaces": false,
|
| 5 |
-
"eos_token": "<|eos|>",
|
| 6 |
-
"extra_special_tokens": [
|
| 7 |
-
"<|unk|>",
|
| 8 |
-
"<|pad|>",
|
| 9 |
-
"<|bos|>",
|
| 10 |
-
"<|eos|>",
|
| 11 |
-
"<|mask|>",
|
| 12 |
-
"<|im_start|>",
|
| 13 |
-
"<|im_end|>",
|
| 14 |
-
"<|system|>",
|
| 15 |
-
"<|user|>",
|
| 16 |
-
"<|assistant|>",
|
| 17 |
-
"<think>",
|
| 18 |
-
"</think>",
|
| 19 |
-
"<|begin_of_thought|>",
|
| 20 |
-
"<|end_of_thought|>",
|
| 21 |
-
"<answer>",
|
| 22 |
-
"</answer>",
|
| 23 |
-
"<|step|>",
|
| 24 |
-
"<|/step|>",
|
| 25 |
-
"<context>",
|
| 26 |
-
"</context>",
|
| 27 |
-
"<|doc_start|>",
|
| 28 |
-
"<|doc_end|>",
|
| 29 |
-
"<|search|>",
|
| 30 |
-
"<|search_results|>",
|
| 31 |
-
"<|tool_list_start|>",
|
| 32 |
-
"<|tool_list_end|>",
|
| 33 |
-
"<tools>",
|
| 34 |
-
"</tools>",
|
| 35 |
-
"<|tool_call_start|>",
|
| 36 |
-
"<|tool_call_end|>",
|
| 37 |
-
"<|tool_call|>",
|
| 38 |
-
"<|/tool_call|>",
|
| 39 |
-
"<|tool_response_start|>",
|
| 40 |
-
"<|tool_response_end|>",
|
| 41 |
-
"<|tool_response|>",
|
| 42 |
-
"<|/tool_response|>",
|
| 43 |
-
"<|image|>",
|
| 44 |
-
"<|image_pad|>",
|
| 45 |
-
"<|image_placeholder|>",
|
| 46 |
-
"<|audio|>",
|
| 47 |
-
"<|audio_pad|>",
|
| 48 |
-
"<|audio_placeholder|>",
|
| 49 |
-
"<|video|>",
|
| 50 |
-
"<|video_pad|>",
|
| 51 |
-
"<|fim_prefix|>",
|
| 52 |
-
"<|fim_suffix|>",
|
| 53 |
-
"<|fim_middle|>",
|
| 54 |
-
"<|repo_name|>",
|
| 55 |
-
"<|file_separator|>",
|
| 56 |
-
"<|reward|>",
|
| 57 |
-
"<|reserved_0|>",
|
| 58 |
-
"<|reserved_1|>",
|
| 59 |
-
"<|reserved_2|>",
|
| 60 |
-
"<|reserved_3|>",
|
| 61 |
-
"<|reserved_4|>",
|
| 62 |
-
"<|reserved_5|>",
|
| 63 |
-
"<|reserved_6|>",
|
| 64 |
-
"<|reserved_7|>",
|
| 65 |
-
"<|reserved_8|>",
|
| 66 |
-
"<|reserved_9|>",
|
| 67 |
-
"<|reserved_10|>",
|
| 68 |
-
"<|reserved_11|>",
|
| 69 |
-
"<|reserved_12|>",
|
| 70 |
-
"<|reserved_13|>",
|
| 71 |
-
"<|reserved_14|>",
|
| 72 |
-
"<|reserved_15|>",
|
| 73 |
-
"<|reserved_16|>",
|
| 74 |
-
"<|reserved_17|>",
|
| 75 |
-
"<|reserved_18|>",
|
| 76 |
-
"<|reserved_19|>"
|
| 77 |
-
],
|
| 78 |
-
"is_local": false,
|
| 79 |
-
"local_files_only": false,
|
| 80 |
-
"mask_token": "<|mask|>",
|
| 81 |
-
"model_max_length": 10000000,
|
| 82 |
-
"pad_token": "<|pad|>",
|
| 83 |
-
"tokenizer_class": "TokenizersBackend",
|
| 84 |
-
"unk_token": "<|unk|>"
|
| 85 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11500/chat_template.jinja
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
{{ bos_token }}{% for message in messages %}{{ '<|im_start|>' + message['role'] + '
|
| 2 |
-
' + message['content'] + '<|im_end|>
|
| 3 |
-
' }}{% endfor %}{% if add_generation_prompt %}{{ '<|im_start|>assistant
|
| 4 |
-
' }}{% endif %}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11500/config.json
DELETED
|
@@ -1,62 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_use_flash_xsa": true,
|
| 3 |
-
"architectures": [
|
| 4 |
-
"SurjoForCausalLM"
|
| 5 |
-
],
|
| 6 |
-
"attention_bias": false,
|
| 7 |
-
"attention_dropout": 0.0,
|
| 8 |
-
"auto_map": {
|
| 9 |
-
"AutoConfig": "configuration_surjo.SurjoConfig",
|
| 10 |
-
"AutoModel": "modeling_surjo.SurjoForCausalLM",
|
| 11 |
-
"AutoModelForCausalLM": "modeling_surjo.SurjoForCausalLM"
|
| 12 |
-
},
|
| 13 |
-
"coda_layers": 1,
|
| 14 |
-
"dtype": "float32",
|
| 15 |
-
"gdn_allow_neg_eigval": false,
|
| 16 |
-
"gdn_conv_kernel_size": 4,
|
| 17 |
-
"gdn_key_dim": 64,
|
| 18 |
-
"gdn_num_v_heads": 8,
|
| 19 |
-
"gdn_per_xsa": 3,
|
| 20 |
-
"gdn_value_dim": 64,
|
| 21 |
-
"gradient_checkpointing": false,
|
| 22 |
-
"head_dim": 64,
|
| 23 |
-
"hidden_act": "silu",
|
| 24 |
-
"hidden_size": 512,
|
| 25 |
-
"initializer_range": 0.02,
|
| 26 |
-
"intermediate_size": 1536,
|
| 27 |
-
"layer_types": [
|
| 28 |
-
"full_attention",
|
| 29 |
-
"linear_attention",
|
| 30 |
-
"linear_attention",
|
| 31 |
-
"linear_attention",
|
| 32 |
-
"full_attention",
|
| 33 |
-
"linear_attention",
|
| 34 |
-
"linear_attention",
|
| 35 |
-
"linear_attention",
|
| 36 |
-
"full_attention",
|
| 37 |
-
"full_attention"
|
| 38 |
-
],
|
| 39 |
-
"loop_noise_std": 0.02,
|
| 40 |
-
"max_position_embeddings": 2048,
|
| 41 |
-
"model_type": "surjo",
|
| 42 |
-
"num_attention_heads": 8,
|
| 43 |
-
"num_groups": 2,
|
| 44 |
-
"num_hidden_layers": 10,
|
| 45 |
-
"num_key_value_heads": 4,
|
| 46 |
-
"partial_rotary_factor": 1.0,
|
| 47 |
-
"prelude_layers": 1,
|
| 48 |
-
"recurrent_layers": 8,
|
| 49 |
-
"recurrent_passes": 2,
|
| 50 |
-
"rms_norm_eps": 1e-05,
|
| 51 |
-
"rope_parameters": {
|
| 52 |
-
"partial_rotary_factor": 1.0,
|
| 53 |
-
"rope_theta": 10000.0,
|
| 54 |
-
"rope_type": "default"
|
| 55 |
-
},
|
| 56 |
-
"rope_theta": 10000.0,
|
| 57 |
-
"tie_word_embeddings": true,
|
| 58 |
-
"transformers_version": "5.16.1",
|
| 59 |
-
"use_cache": false,
|
| 60 |
-
"vocab_size": 32768,
|
| 61 |
-
"xsa_projection": true
|
| 62 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11500/configuration_surjo.py
DELETED
|
@@ -1,148 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""Surjo gen-3 model configuration."""
|
| 5 |
-
|
| 6 |
-
from typing import List, Optional
|
| 7 |
-
from transformers import PretrainedConfig
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
class SurjoConfig(PretrainedConfig):
|
| 11 |
-
r"""Configuration for the Surjo gen-3 hybrid architecture."""
|
| 12 |
-
|
| 13 |
-
model_type = "surjo"
|
| 14 |
-
keys_to_ignore_at_inference = ["past_key_values"]
|
| 15 |
-
|
| 16 |
-
def __init__(
|
| 17 |
-
self,
|
| 18 |
-
vocab_size: int = 50257,
|
| 19 |
-
hidden_size: int = 384,
|
| 20 |
-
intermediate_size: int = 1024,
|
| 21 |
-
num_attention_heads: int = 6,
|
| 22 |
-
num_key_value_heads: int = 2,
|
| 23 |
-
head_dim: int = 64,
|
| 24 |
-
hidden_act: str = "silu",
|
| 25 |
-
max_position_embeddings: int = 2048,
|
| 26 |
-
initializer_range: float = 0.02,
|
| 27 |
-
rms_norm_eps: float = 1e-6,
|
| 28 |
-
tie_word_embeddings: bool = True,
|
| 29 |
-
rope_theta: float = 10000.0,
|
| 30 |
-
attention_dropout: float = 0.0,
|
| 31 |
-
attention_bias: bool = False,
|
| 32 |
-
prelude_layers: int = 1,
|
| 33 |
-
recurrent_layers: int = 8,
|
| 34 |
-
coda_layers: int = 1,
|
| 35 |
-
recurrent_passes: int = 2,
|
| 36 |
-
loop_noise_std: float = 0.02,
|
| 37 |
-
gdn_per_xsa: int = 3,
|
| 38 |
-
gdn_key_dim: Optional[int] = None,
|
| 39 |
-
gdn_value_dim: Optional[int] = None,
|
| 40 |
-
gdn_num_v_heads: Optional[int] = None,
|
| 41 |
-
gdn_conv_kernel_size: int = 4,
|
| 42 |
-
gdn_allow_neg_eigval: bool = False,
|
| 43 |
-
xsa_projection: bool = True,
|
| 44 |
-
rope_parameters: Optional[dict] = None,
|
| 45 |
-
rope_scaling: Optional[dict] = None,
|
| 46 |
-
partial_rotary_factor: float = 1.0,
|
| 47 |
-
gradient_checkpointing: bool = False,
|
| 48 |
-
use_cache: bool = True,
|
| 49 |
-
**kwargs,
|
| 50 |
-
):
|
| 51 |
-
self.vocab_size = vocab_size
|
| 52 |
-
self.hidden_size = hidden_size
|
| 53 |
-
self.intermediate_size = intermediate_size
|
| 54 |
-
self.num_attention_heads = num_attention_heads
|
| 55 |
-
self.num_key_value_heads = num_key_value_heads
|
| 56 |
-
self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads
|
| 57 |
-
self.hidden_act = hidden_act
|
| 58 |
-
self.max_position_embeddings = max_position_embeddings
|
| 59 |
-
self.initializer_range = initializer_range
|
| 60 |
-
self.rms_norm_eps = rms_norm_eps
|
| 61 |
-
self.tie_word_embeddings = tie_word_embeddings
|
| 62 |
-
self.rope_theta = rope_theta
|
| 63 |
-
self.attention_dropout = attention_dropout
|
| 64 |
-
self.attention_bias = attention_bias
|
| 65 |
-
|
| 66 |
-
self.prelude_layers = prelude_layers
|
| 67 |
-
self.recurrent_layers = recurrent_layers
|
| 68 |
-
self.coda_layers = coda_layers
|
| 69 |
-
self.recurrent_passes = recurrent_passes
|
| 70 |
-
self.loop_noise_std = loop_noise_std
|
| 71 |
-
self.gdn_per_xsa = gdn_per_xsa
|
| 72 |
-
|
| 73 |
-
self.gdn_key_dim = gdn_key_dim if gdn_key_dim is not None else self.head_dim
|
| 74 |
-
self.gdn_value_dim = gdn_value_dim if gdn_value_dim is not None else self.head_dim
|
| 75 |
-
self.gdn_num_v_heads = (
|
| 76 |
-
gdn_num_v_heads if gdn_num_v_heads is not None else num_attention_heads
|
| 77 |
-
)
|
| 78 |
-
self.gdn_conv_kernel_size = gdn_conv_kernel_size
|
| 79 |
-
self.gdn_allow_neg_eigval = gdn_allow_neg_eigval
|
| 80 |
-
|
| 81 |
-
self.xsa_projection = xsa_projection
|
| 82 |
-
|
| 83 |
-
if rope_parameters is not None:
|
| 84 |
-
self.rope_parameters = dict(rope_parameters)
|
| 85 |
-
elif rope_scaling is not None:
|
| 86 |
-
self.rope_parameters = dict(rope_scaling)
|
| 87 |
-
else:
|
| 88 |
-
self.rope_parameters = {"rope_type": "default"}
|
| 89 |
-
self.rope_parameters.setdefault("rope_type", "default")
|
| 90 |
-
self.rope_parameters.setdefault("rope_theta", rope_theta)
|
| 91 |
-
if self.rope_parameters.get("rope_type") != "default":
|
| 92 |
-
self.rope_parameters.setdefault("factor", 1.0)
|
| 93 |
-
self.rope_scaling = dict(self.rope_parameters)
|
| 94 |
-
self.partial_rotary_factor = partial_rotary_factor
|
| 95 |
-
|
| 96 |
-
self.gradient_checkpointing = gradient_checkpointing
|
| 97 |
-
self.use_cache = use_cache
|
| 98 |
-
|
| 99 |
-
group = gdn_per_xsa + 1
|
| 100 |
-
if recurrent_layers % group != 0:
|
| 101 |
-
raise ValueError(
|
| 102 |
-
f"recurrent_layers ({recurrent_layers}) must be divisible by "
|
| 103 |
-
f"gdn_per_xsa + 1 = {group}"
|
| 104 |
-
)
|
| 105 |
-
if num_attention_heads % num_key_value_heads != 0:
|
| 106 |
-
raise ValueError(
|
| 107 |
-
f"num_attention_heads ({num_attention_heads}) must be divisible by "
|
| 108 |
-
f"num_key_value_heads ({num_key_value_heads})"
|
| 109 |
-
)
|
| 110 |
-
if (
|
| 111 |
-
self.gdn_num_v_heads < num_attention_heads
|
| 112 |
-
or self.gdn_num_v_heads % num_attention_heads != 0
|
| 113 |
-
):
|
| 114 |
-
raise ValueError(
|
| 115 |
-
f"gdn_num_v_heads ({self.gdn_num_v_heads}) must be >= "
|
| 116 |
-
f"num_attention_heads ({num_attention_heads}) and divisible by it"
|
| 117 |
-
)
|
| 118 |
-
valid_rope_types = {"default", "linear", "dynamic", "yarn", "longrope", "llama3"}
|
| 119 |
-
rt = self.rope_parameters.get("rope_type", "default")
|
| 120 |
-
if rt not in valid_rope_types:
|
| 121 |
-
raise ValueError(f"rope_type must be one of {valid_rope_types}, got {rt}")
|
| 122 |
-
|
| 123 |
-
self.num_groups = recurrent_layers // group
|
| 124 |
-
self.num_hidden_layers = prelude_layers + recurrent_layers + coda_layers
|
| 125 |
-
self.layer_types = self._build_layer_types()
|
| 126 |
-
|
| 127 |
-
super().__init__(tie_word_embeddings=tie_word_embeddings, **kwargs)
|
| 128 |
-
|
| 129 |
-
def _build_layer_types(self) -> List[str]:
|
| 130 |
-
types = ["full_attention"] * self.prelude_layers
|
| 131 |
-
for _ in range(self.num_groups):
|
| 132 |
-
types.extend(["linear_attention"] * self.gdn_per_xsa)
|
| 133 |
-
types.append("full_attention")
|
| 134 |
-
types.extend(["full_attention"] * self.coda_layers)
|
| 135 |
-
assert len(types) == self.num_hidden_layers
|
| 136 |
-
return types
|
| 137 |
-
|
| 138 |
-
@property
|
| 139 |
-
def surjo_layer_types(self) -> List[str]:
|
| 140 |
-
return ["xsa" if t == "full_attention" else "gdn" for t in self.layer_types]
|
| 141 |
-
|
| 142 |
-
@property
|
| 143 |
-
def effective_num_layers(self) -> int:
|
| 144 |
-
return (
|
| 145 |
-
self.prelude_layers
|
| 146 |
-
+ self.recurrent_layers * self.recurrent_passes
|
| 147 |
-
+ self.coda_layers
|
| 148 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11500/generation_config.json
DELETED
|
@@ -1,7 +0,0 @@
|
|
| 1 |
-
{
|
| 2 |
-
"_from_model_config": true,
|
| 3 |
-
"output_attentions": false,
|
| 4 |
-
"output_hidden_states": false,
|
| 5 |
-
"transformers_version": "5.16.1",
|
| 6 |
-
"use_cache": false
|
| 7 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11500/model.safetensors
DELETED
|
@@ -1,3 +0,0 @@
|
|
| 1 |
-
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:117dcbdaf78bdc4fe621f314821ef375e693f6b47f31cce978eebd2f1d64abd0
|
| 3 |
-
size 215196728
|
|
|
|
|
|
|
|
|
|
|
|
checkpoint-11500/modeling_surjo.py
DELETED
|
@@ -1,926 +0,0 @@
|
|
| 1 |
-
# Copyright 2026 SurjoLabs. All rights reserved.
|
| 2 |
-
# Licensed under the Apache License, Version 2.0
|
| 3 |
-
|
| 4 |
-
"""SurjoLabs Surjo Architecture"""
|
| 5 |
-
|
| 6 |
-
import math
|
| 7 |
-
from typing import Dict, List, Optional, Tuple
|
| 8 |
-
|
| 9 |
-
import torch
|
| 10 |
-
import torch.nn as nn
|
| 11 |
-
import torch.nn.functional as F
|
| 12 |
-
import torch.utils.checkpoint
|
| 13 |
-
|
| 14 |
-
from transformers import PreTrainedModel
|
| 15 |
-
from transformers.activations import ACT2FN
|
| 16 |
-
|
| 17 |
-
try:
|
| 18 |
-
from transformers import GenerationMixin
|
| 19 |
-
except ImportError:
|
| 20 |
-
from transformers.generation import GenerationMixin
|
| 21 |
-
from transformers.modeling_outputs import (
|
| 22 |
-
BaseModelOutputWithPast,
|
| 23 |
-
CausalLMOutputWithPast,
|
| 24 |
-
)
|
| 25 |
-
|
| 26 |
-
try:
|
| 27 |
-
from .configuration_surjo import SurjoConfig
|
| 28 |
-
except (ImportError, ValueError):
|
| 29 |
-
from configuration_surjo import SurjoConfig
|
| 30 |
-
|
| 31 |
-
try:
|
| 32 |
-
from fla.modules.fused_linear_cross_entropy import (
|
| 33 |
-
fused_linear_cross_entropy_loss as _fla_flce,
|
| 34 |
-
)
|
| 35 |
-
except ImportError:
|
| 36 |
-
try:
|
| 37 |
-
from fla.modules import fused_linear_cross_entropy_loss as _fla_flce
|
| 38 |
-
except ImportError:
|
| 39 |
-
_fla_flce = None
|
| 40 |
-
|
| 41 |
-
try:
|
| 42 |
-
from fla.modules.norm import rms_norm as _fla_rms_norm
|
| 43 |
-
except ImportError:
|
| 44 |
-
try:
|
| 45 |
-
from fla.modules import rms_norm as _fla_rms_norm
|
| 46 |
-
except ImportError:
|
| 47 |
-
_fla_rms_norm = None
|
| 48 |
-
|
| 49 |
-
try:
|
| 50 |
-
from fla.ops.gdn2 import chunk_gdn2, fused_recurrent_gdn2
|
| 51 |
-
FLA_AVAILABLE = True
|
| 52 |
-
except ImportError:
|
| 53 |
-
chunk_gdn2 = None
|
| 54 |
-
fused_recurrent_gdn2 = None
|
| 55 |
-
FLA_AVAILABLE = False
|
| 56 |
-
|
| 57 |
-
_USE_FLA_FUSED_CE = True
|
| 58 |
-
_USE_FLA_RMS_NORM = False
|
| 59 |
-
|
| 60 |
-
if FLA_AVAILABLE:
|
| 61 |
-
|
| 62 |
-
@torch.compiler.disable
|
| 63 |
-
def _fla_chunk(q, k, v, g, b, w, initial_state=None, output_final_state=False,
|
| 64 |
-
cu_seqlens=None):
|
| 65 |
-
return chunk_gdn2(
|
| 66 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 67 |
-
initial_state=initial_state,
|
| 68 |
-
output_final_state=output_final_state,
|
| 69 |
-
use_qk_l2norm_in_kernel=True,
|
| 70 |
-
cu_seqlens=cu_seqlens,
|
| 71 |
-
)
|
| 72 |
-
|
| 73 |
-
@torch.compiler.disable
|
| 74 |
-
def _fla_recurrent(q, k, v, g, b, w, initial_state=None, output_final_state=False):
|
| 75 |
-
return fused_recurrent_gdn2(
|
| 76 |
-
q=q, k=k, v=v, g=g, b=b, w=w,
|
| 77 |
-
initial_state=initial_state,
|
| 78 |
-
output_final_state=output_final_state,
|
| 79 |
-
use_qk_l2norm_in_kernel=True,
|
| 80 |
-
)
|
| 81 |
-
|
| 82 |
-
try:
|
| 83 |
-
from flash_attn import flash_attn_varlen_func
|
| 84 |
-
FLASH_ATTN_AVAILABLE = True
|
| 85 |
-
except ImportError:
|
| 86 |
-
flash_attn_varlen_func = None
|
| 87 |
-
FLASH_ATTN_AVAILABLE = False
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
def _mask_padding_states(hidden_states, padding_mask):
|
| 91 |
-
if padding_mask is not None:
|
| 92 |
-
return hidden_states * padding_mask.unsqueeze(-1).to(hidden_states.dtype)
|
| 93 |
-
return hidden_states
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
def naive_gdn2_reference(q, k, v, g, b, w, initial_state=None):
|
| 97 |
-
"""fp32 reference for GDN-2."""
|
| 98 |
-
B, T, H, K = q.shape
|
| 99 |
-
V = v.shape[-1]
|
| 100 |
-
S = (
|
| 101 |
-
torch.zeros(B, H, K, V, dtype=torch.float32, device=q.device)
|
| 102 |
-
if initial_state is None
|
| 103 |
-
else initial_state.float()
|
| 104 |
-
)
|
| 105 |
-
scale = K ** -0.5
|
| 106 |
-
outs = []
|
| 107 |
-
for t in range(T):
|
| 108 |
-
q_t = F.normalize(q[:, t], dim=-1)
|
| 109 |
-
k_t = F.normalize(k[:, t], dim=-1)
|
| 110 |
-
v_t, g_t, b_t, w_t = v[:, t], g[:, t], b[:, t], w[:, t]
|
| 111 |
-
S = S * torch.exp(g_t).unsqueeze(-1)
|
| 112 |
-
e = b_t * k_t
|
| 113 |
-
r = torch.einsum("bhkv,bhk->bhv", S, e)
|
| 114 |
-
z = w_t * v_t
|
| 115 |
-
S = S + torch.einsum("bhk,bhv->bhkv", k_t, z - r)
|
| 116 |
-
outs.append(scale * torch.einsum("bhkv,bhk->bhv", S, q_t))
|
| 117 |
-
return torch.stack(outs, dim=1), S
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
class SurjoRMSNorm(nn.Module):
|
| 121 |
-
"""FLA Triton RMSNorm when available; else fused ATen F.rms_norm."""
|
| 122 |
-
|
| 123 |
-
def __init__(self, dim: int, eps: float = 1e-6):
|
| 124 |
-
super().__init__()
|
| 125 |
-
self.weight = nn.Parameter(torch.ones(dim))
|
| 126 |
-
self.eps = eps
|
| 127 |
-
|
| 128 |
-
def forward(self, x):
|
| 129 |
-
if x.dtype != self.weight.dtype:
|
| 130 |
-
x = x.to(self.weight.dtype)
|
| 131 |
-
if _USE_FLA_RMS_NORM and _fla_rms_norm is not None and x.is_cuda:
|
| 132 |
-
return _fla_rms_norm(x, self.weight, None, eps=self.eps)
|
| 133 |
-
return F.rms_norm(x, (x.shape[-1],), self.weight, self.eps)
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
class ClampedMLP(nn.Module):
|
| 137 |
-
def __init__(self, config):
|
| 138 |
-
hidden_size = config.hidden_size
|
| 139 |
-
intermediate_size = config.intermediate_size
|
| 140 |
-
super().__init__()
|
| 141 |
-
self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 142 |
-
self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
|
| 143 |
-
self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
|
| 144 |
-
self.act_fn = ACT2FN[config.hidden_act]
|
| 145 |
-
|
| 146 |
-
def forward(self, x):
|
| 147 |
-
return self.down_proj(
|
| 148 |
-
self.act_fn(self.gate_proj(x).clamp(-15.0, 15.0)) * self.up_proj(x)
|
| 149 |
-
)
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
class SurjoRotaryEmbedding(nn.Module):
|
| 153 |
-
"""RoPE with frequencies computed in forward() (no stored buffer)."""
|
| 154 |
-
|
| 155 |
-
def __init__(self, config, device=None):
|
| 156 |
-
super().__init__()
|
| 157 |
-
self.config = config
|
| 158 |
-
self.rope_type = config.rope_parameters.get("rope_type", "default")
|
| 159 |
-
self.max_position_embeddings = config.max_position_embeddings
|
| 160 |
-
self.base = config.rope_parameters.get("rope_theta", config.rope_theta)
|
| 161 |
-
self.factor = config.rope_parameters.get("factor", 1.0)
|
| 162 |
-
self.dim = int(config.head_dim * config.partial_rotary_factor)
|
| 163 |
-
|
| 164 |
-
def _inv_freq(self, device):
|
| 165 |
-
inv = 1.0 / (
|
| 166 |
-
self.base
|
| 167 |
-
** (torch.arange(0, self.dim, 2, dtype=torch.float32, device=device) / self.dim)
|
| 168 |
-
)
|
| 169 |
-
if self.rope_type == "linear":
|
| 170 |
-
inv = inv / self.factor
|
| 171 |
-
return inv
|
| 172 |
-
|
| 173 |
-
@torch.no_grad()
|
| 174 |
-
def forward(self, position_ids):
|
| 175 |
-
inv = self._inv_freq(position_ids.device)
|
| 176 |
-
freqs = torch.einsum("bt,f->btf", position_ids.float(), inv)
|
| 177 |
-
emb = torch.cat([freqs, freqs], dim=-1)
|
| 178 |
-
return emb.cos(), emb.sin()
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
def rotate_half(x):
|
| 182 |
-
x1, x2 = x.chunk(2, dim=-1)
|
| 183 |
-
return torch.cat((-x2, x1), dim=-1)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
def apply_rope(q, k, cos, sin):
|
| 187 |
-
cos = cos[:, None, :, :].to(q.dtype)
|
| 188 |
-
sin = sin[:, None, :, :].to(q.dtype)
|
| 189 |
-
q = q * cos + rotate_half(q) * sin
|
| 190 |
-
k = k * cos + rotate_half(k) * sin
|
| 191 |
-
return q, k
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
def apply_rope_flat(q, k, cos, sin):
|
| 195 |
-
"""RoPE on flat varlen tensors. q, k: [total, H, D]; cos, sin: [B, T, D]."""
|
| 196 |
-
total = q.shape[0]
|
| 197 |
-
cos_f = cos.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 198 |
-
sin_f = sin.reshape(total, -1)[:, None, :].to(q.dtype)
|
| 199 |
-
q = q * cos_f + rotate_half(q) * sin_f
|
| 200 |
-
k = k * cos_f + rotate_half(k) * sin_f
|
| 201 |
-
return q, k
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
@torch.compiler.disable
|
| 205 |
-
def _flash_varlen(q, k, v, cu_seqlens, max_seqlen):
|
| 206 |
-
"""FA2 varlen. cu_seqlens device int32; max_seqlen a constant (no sync)."""
|
| 207 |
-
return flash_attn_varlen_func(
|
| 208 |
-
q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen,
|
| 209 |
-
dropout_p=0.0, causal=True,
|
| 210 |
-
)
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
class ShortConvolution(nn.Module):
|
| 214 |
-
def __init__(self, dim: int, kernel_size: int = 4):
|
| 215 |
-
super().__init__()
|
| 216 |
-
self.kernel_size = kernel_size
|
| 217 |
-
self.conv = nn.Conv1d(dim, dim, kernel_size, groups=dim, bias=False)
|
| 218 |
-
|
| 219 |
-
def forward(self, x, cache=None, output_state=False):
|
| 220 |
-
B, T, C = x.shape
|
| 221 |
-
xt = x.transpose(1, 2)
|
| 222 |
-
if T == 1 and cache is not None:
|
| 223 |
-
comb = torch.cat([cache, xt], dim=2)
|
| 224 |
-
w = self.conv.weight.squeeze(1)
|
| 225 |
-
out = F.silu(torch.einsum("bck,ck->bc", comb, w).unsqueeze(-1))
|
| 226 |
-
new = comb[:, :, 1:] if output_state else None
|
| 227 |
-
return out.transpose(1, 2), new
|
| 228 |
-
if cache is not None:
|
| 229 |
-
xt_in = torch.cat([cache, xt], dim=2)
|
| 230 |
-
else:
|
| 231 |
-
xt_in = F.pad(xt, (self.kernel_size - 1, 0))
|
| 232 |
-
out = F.silu(self.conv(xt_in))
|
| 233 |
-
new = xt_in[:, :, -(self.kernel_size - 1):] if output_state else None
|
| 234 |
-
return out.transpose(1, 2), new
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
class SurjoCache:
|
| 238 |
-
def __init__(self):
|
| 239 |
-
self.kv = {}
|
| 240 |
-
self.gdn_state = {}
|
| 241 |
-
self.gdn_conv = {}
|
| 242 |
-
|
| 243 |
-
def get_seq_length(self):
|
| 244 |
-
if not self.kv:
|
| 245 |
-
return 0
|
| 246 |
-
return next(iter(self.kv.values()))[0].shape[2]
|
| 247 |
-
|
| 248 |
-
@staticmethod
|
| 249 |
-
def num_xsa_slots(config):
|
| 250 |
-
return (
|
| 251 |
-
config.prelude_layers
|
| 252 |
-
+ config.num_groups * config.recurrent_passes
|
| 253 |
-
+ config.coda_layers
|
| 254 |
-
)
|
| 255 |
-
|
| 256 |
-
|
| 257 |
-
class XSAAttention(nn.Module):
|
| 258 |
-
"""Full attention with XSA value-projection subtraction."""
|
| 259 |
-
|
| 260 |
-
def __init__(self, config, layer_idx: int):
|
| 261 |
-
super().__init__()
|
| 262 |
-
self.layer_idx = layer_idx
|
| 263 |
-
self.num_heads = config.num_attention_heads
|
| 264 |
-
self.num_kv_heads = config.num_key_value_heads
|
| 265 |
-
self.num_kv_groups = self.num_heads // self.num_kv_heads
|
| 266 |
-
self.head_dim = config.head_dim
|
| 267 |
-
self.xsa_projection = config.xsa_projection
|
| 268 |
-
self.dropout = config.attention_dropout
|
| 269 |
-
self.hidden_size = config.hidden_size
|
| 270 |
-
self.use_flash = getattr(config, "_use_flash_xsa", False)
|
| 271 |
-
self.q_proj = nn.Linear(
|
| 272 |
-
self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias
|
| 273 |
-
)
|
| 274 |
-
self.k_proj = nn.Linear(
|
| 275 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 276 |
-
)
|
| 277 |
-
self.v_proj = nn.Linear(
|
| 278 |
-
self.hidden_size, self.num_kv_heads * self.head_dim, bias=config.attention_bias
|
| 279 |
-
)
|
| 280 |
-
self.o_proj = nn.Linear(
|
| 281 |
-
self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias
|
| 282 |
-
)
|
| 283 |
-
self.q_norm = SurjoRMSNorm(self.head_dim)
|
| 284 |
-
self.k_norm = SurjoRMSNorm(self.head_dim)
|
| 285 |
-
|
| 286 |
-
def _xsa_projection_step(self, attn, v):
|
| 287 |
-
dv = (attn.float() * v.float()).sum(dim=-1, keepdim=True)
|
| 288 |
-
vv = (v.float() * v.float()).sum(dim=-1, keepdim=True).clamp_min(1e-4)
|
| 289 |
-
scale = (dv / vv).to(attn.dtype)
|
| 290 |
-
return attn - scale * v
|
| 291 |
-
|
| 292 |
-
def forward(self, hidden_states, attention_mask, cache, slot, use_cache,
|
| 293 |
-
cache_position, cos, sin, cu_seqlens=None):
|
| 294 |
-
B, T, _ = hidden_states.shape
|
| 295 |
-
H, Hkv, D = self.num_heads, self.num_kv_heads, self.head_dim
|
| 296 |
-
|
| 297 |
-
q = self.q_proj(hidden_states).view(B, T, H, D).transpose(1, 2)
|
| 298 |
-
k = self.k_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 299 |
-
v = self.v_proj(hidden_states).view(B, T, Hkv, D).transpose(1, 2)
|
| 300 |
-
q = self.q_norm(q)
|
| 301 |
-
k = self.k_norm(k)
|
| 302 |
-
|
| 303 |
-
use_varlen = (
|
| 304 |
-
cu_seqlens is not None
|
| 305 |
-
and cache is None
|
| 306 |
-
and self.use_flash
|
| 307 |
-
and FLASH_ATTN_AVAILABLE
|
| 308 |
-
and hidden_states.is_cuda
|
| 309 |
-
)
|
| 310 |
-
if use_varlen:
|
| 311 |
-
total = B * T
|
| 312 |
-
q_f = q.transpose(1, 2).reshape(total, H, D).to(torch.bfloat16)
|
| 313 |
-
k_f = k.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 314 |
-
v_f = v.transpose(1, 2).reshape(total, Hkv, D).to(torch.bfloat16)
|
| 315 |
-
if Hkv != H:
|
| 316 |
-
k_f = k_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 317 |
-
v_f = v_f.repeat_interleave(self.num_kv_groups, dim=1)
|
| 318 |
-
q_f, k_f = apply_rope_flat(q_f, k_f, cos, sin)
|
| 319 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 320 |
-
o_f = _flash_varlen(q_f, k_f, v_f, cu_dev, T)
|
| 321 |
-
attn_out = o_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 322 |
-
v_xsa = v_f.view(B, T, H, D).to(hidden_states.dtype)
|
| 323 |
-
if self.xsa_projection:
|
| 324 |
-
attn_out = self._xsa_projection_step(attn_out, v_xsa)
|
| 325 |
-
out = attn_out.reshape(B, T, H * D)
|
| 326 |
-
return self.o_proj(out)
|
| 327 |
-
|
| 328 |
-
q, k = apply_rope(q, k, cos, sin)
|
| 329 |
-
v_cur = v
|
| 330 |
-
if cache is not None and use_cache:
|
| 331 |
-
if slot in cache.kv:
|
| 332 |
-
pk, pv = cache.kv[slot]
|
| 333 |
-
k = torch.cat([pk, k.to(pk.dtype)], dim=2)
|
| 334 |
-
v = torch.cat([pv, v.to(pv.dtype)], dim=2)
|
| 335 |
-
cache.kv[slot] = (k, v)
|
| 336 |
-
S = k.shape[2]
|
| 337 |
-
if Hkv != H:
|
| 338 |
-
k_e = k.repeat_interleave(self.num_kv_groups, dim=1)
|
| 339 |
-
v_e = v.repeat_interleave(self.num_kv_groups, dim=1)
|
| 340 |
-
v_cur_e = v_cur.repeat_interleave(self.num_kv_groups, dim=1)
|
| 341 |
-
else:
|
| 342 |
-
k_e, v_e, v_cur_e = k, v, v_cur
|
| 343 |
-
|
| 344 |
-
is_causal = False
|
| 345 |
-
mask4 = None
|
| 346 |
-
if attention_mask is not None:
|
| 347 |
-
L = attention_mask.shape[-1]
|
| 348 |
-
if L < S:
|
| 349 |
-
attention_mask = F.pad(attention_mask, (S - L, 0), value=1)
|
| 350 |
-
elif L > S:
|
| 351 |
-
attention_mask = attention_mask[:, -S:]
|
| 352 |
-
neg = torch.finfo(q.dtype).min
|
| 353 |
-
m = attention_mask[:, None, None, :].to(q.dtype)
|
| 354 |
-
if T == S:
|
| 355 |
-
if T > 1:
|
| 356 |
-
causal = torch.ones(T, S, device=q.device, dtype=q.dtype).tril()
|
| 357 |
-
allow = causal[None, None] * m
|
| 358 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 359 |
-
torch.full_like(allow, neg))
|
| 360 |
-
else:
|
| 361 |
-
mask4 = torch.where(m > 0, torch.zeros_like(m),
|
| 362 |
-
torch.full_like(m, neg))
|
| 363 |
-
else:
|
| 364 |
-
if cache_position is None:
|
| 365 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 366 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 367 |
-
causal = kv_pos[None, :] <= cache_position[:, None].to(q.device)
|
| 368 |
-
allow = causal[None, None].to(q.dtype) * m
|
| 369 |
-
mask4 = torch.where(allow > 0, torch.zeros_like(allow),
|
| 370 |
-
torch.full_like(allow, neg))
|
| 371 |
-
elif cu_seqlens is not None and T > 1:
|
| 372 |
-
neg = torch.finfo(q.dtype).min
|
| 373 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32)
|
| 374 |
-
gpos = torch.arange(B * T, device=q.device)
|
| 375 |
-
doc_id = torch.searchsorted(cu_dev, gpos, right=True) - 1
|
| 376 |
-
doc_id = doc_id.clamp(min=0).view(B, T)
|
| 377 |
-
same = doc_id.unsqueeze(2) == doc_id.unsqueeze(1)
|
| 378 |
-
idx = torch.arange(T, device=q.device)
|
| 379 |
-
causal = idx.unsqueeze(0) <= idx.unsqueeze(1)
|
| 380 |
-
allow = (same & causal).unsqueeze(1)
|
| 381 |
-
mask4 = torch.where(
|
| 382 |
-
allow,
|
| 383 |
-
torch.zeros(B, 1, T, T, dtype=q.dtype, device=q.device),
|
| 384 |
-
torch.full((B, 1, T, T), neg, dtype=q.dtype, device=q.device),
|
| 385 |
-
)
|
| 386 |
-
else:
|
| 387 |
-
if T == S and T > 1:
|
| 388 |
-
is_causal = True
|
| 389 |
-
elif T > 1:
|
| 390 |
-
if cache_position is None:
|
| 391 |
-
cache_position = torch.arange(S - T, S, device=q.device)
|
| 392 |
-
kv_pos = torch.arange(S, device=q.device)
|
| 393 |
-
neg = torch.finfo(q.dtype).min
|
| 394 |
-
causal = torch.zeros(T, S, device=q.device, dtype=q.dtype)
|
| 395 |
-
causal = causal.masked_fill(
|
| 396 |
-
kv_pos[None, :] > cache_position[:, None], neg
|
| 397 |
-
)
|
| 398 |
-
mask4 = causal[None, None, :, :]
|
| 399 |
-
|
| 400 |
-
attn = F.scaled_dot_product_attention(
|
| 401 |
-
q, k_e, v_e, attn_mask=mask4, is_causal=is_causal,
|
| 402 |
-
dropout_p=self.dropout if self.training else 0.0,
|
| 403 |
-
)
|
| 404 |
-
|
| 405 |
-
if self.xsa_projection:
|
| 406 |
-
attn = self._xsa_projection_step(attn, v_cur_e)
|
| 407 |
-
|
| 408 |
-
out = attn.transpose(1, 2).reshape(B, T, H * D)
|
| 409 |
-
return self.o_proj(out)
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
class GDN2Attention(nn.Module):
|
| 413 |
-
"""Gated DeltaNet-2 linear attention."""
|
| 414 |
-
|
| 415 |
-
def __init__(self, config, layer_idx: int):
|
| 416 |
-
super().__init__()
|
| 417 |
-
self.layer_idx = layer_idx
|
| 418 |
-
H = config.num_attention_heads
|
| 419 |
-
Hv = config.gdn_num_v_heads
|
| 420 |
-
self.num_heads = H
|
| 421 |
-
self.num_v_heads = Hv
|
| 422 |
-
self.gva = Hv // H
|
| 423 |
-
self.head_k_dim = config.gdn_key_dim
|
| 424 |
-
self.head_v_dim = config.gdn_value_dim
|
| 425 |
-
self.key_dim = H * self.head_k_dim
|
| 426 |
-
self.value_dim = Hv * self.head_v_dim
|
| 427 |
-
self.conv_kernel = config.gdn_conv_kernel_size
|
| 428 |
-
self.allow_neg_eigval = config.gdn_allow_neg_eigval
|
| 429 |
-
hidden = config.hidden_size
|
| 430 |
-
self.q_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 431 |
-
self.k_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 432 |
-
self.v_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 433 |
-
self.q_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 434 |
-
self.k_conv = ShortConvolution(self.key_dim, self.conv_kernel)
|
| 435 |
-
self.v_conv = ShortConvolution(self.value_dim, self.conv_kernel)
|
| 436 |
-
self.f_proj = nn.Sequential(
|
| 437 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 438 |
-
nn.Linear(self.head_v_dim, self.key_dim, bias=False),
|
| 439 |
-
)
|
| 440 |
-
self.b_proj = nn.Linear(hidden, self.key_dim, bias=False)
|
| 441 |
-
self.w_proj = nn.Linear(hidden, self.value_dim, bias=False)
|
| 442 |
-
self.A_log = nn.Parameter(
|
| 443 |
-
torch.log(torch.empty(H, dtype=torch.float32).uniform_(1, 16))
|
| 444 |
-
)
|
| 445 |
-
self.A_log._no_weight_decay = True
|
| 446 |
-
dt = torch.exp(
|
| 447 |
-
torch.rand(self.key_dim, dtype=torch.float32)
|
| 448 |
-
* (math.log(0.1) - math.log(0.001))
|
| 449 |
-
+ math.log(0.001)
|
| 450 |
-
).clamp(min=1e-4)
|
| 451 |
-
self.dt_bias = nn.Parameter(dt + torch.log(-torch.expm1(-dt)))
|
| 452 |
-
self.dt_bias._no_weight_decay = True
|
| 453 |
-
self.g_proj = nn.Sequential(
|
| 454 |
-
nn.Linear(hidden, self.head_v_dim, bias=False),
|
| 455 |
-
nn.Linear(self.head_v_dim, self.value_dim, bias=True),
|
| 456 |
-
)
|
| 457 |
-
self.o_norm = SurjoRMSNorm(self.head_v_dim, eps=config.rms_norm_eps)
|
| 458 |
-
self.o_proj = nn.Linear(self.value_dim, hidden, bias=False)
|
| 459 |
-
|
| 460 |
-
def forward(self, hidden_states, attention_mask, gdn_state, conv_state,
|
| 461 |
-
output_state, cu_seqlens=None):
|
| 462 |
-
B, T, _ = hidden_states.shape
|
| 463 |
-
if attention_mask is not None:
|
| 464 |
-
if attention_mask.shape[-1] != T:
|
| 465 |
-
attention_mask = (
|
| 466 |
-
attention_mask[:, -T:] if attention_mask.shape[-1] > T else None
|
| 467 |
-
)
|
| 468 |
-
if attention_mask is not None:
|
| 469 |
-
hidden_states = _mask_padding_states(hidden_states, attention_mask)
|
| 470 |
-
cq = conv_state[0] if conv_state is not None else None
|
| 471 |
-
ck = conv_state[1] if conv_state is not None else None
|
| 472 |
-
cvs = conv_state[2] if conv_state is not None else None
|
| 473 |
-
q, nq = self.q_conv(self.q_proj(hidden_states), cq, output_state)
|
| 474 |
-
k, nk = self.k_conv(self.k_proj(hidden_states), ck, output_state)
|
| 475 |
-
v, nv = self.v_conv(self.v_proj(hidden_states), cvs, output_state)
|
| 476 |
-
g = F.softplus(self.f_proj(hidden_states).float() + self.dt_bias)
|
| 477 |
-
b = self.b_proj(hidden_states).sigmoid()
|
| 478 |
-
w = self.w_proj(hidden_states).sigmoid()
|
| 479 |
-
q = q.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 480 |
-
k = k.reshape(B, T, self.num_heads, self.head_k_dim)
|
| 481 |
-
v = v.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 482 |
-
g = g.view(B, T, self.num_heads, self.head_k_dim)
|
| 483 |
-
b = b.view(B, T, self.num_heads, self.head_k_dim)
|
| 484 |
-
w = w.view(B, T, self.num_v_heads, self.head_v_dim)
|
| 485 |
-
g = -self.A_log.float().exp().view(1, 1, self.num_heads, 1) * g
|
| 486 |
-
if self.allow_neg_eigval:
|
| 487 |
-
b = b * 2.0
|
| 488 |
-
if self.gva > 1:
|
| 489 |
-
q = q.repeat_interleave(self.gva, dim=2)
|
| 490 |
-
k = k.repeat_interleave(self.gva, dim=2)
|
| 491 |
-
g = g.repeat_interleave(self.gva, dim=2)
|
| 492 |
-
b = b.repeat_interleave(self.gva, dim=2)
|
| 493 |
-
init = gdn_state.float() if gdn_state is not None else None
|
| 494 |
-
|
| 495 |
-
if FLA_AVAILABLE and hidden_states.is_cuda:
|
| 496 |
-
if T == 1 and init is not None:
|
| 497 |
-
o, fs = _fla_recurrent(q, k, v, g, b, w, init, output_state)
|
| 498 |
-
elif cu_seqlens is not None:
|
| 499 |
-
total = B * T
|
| 500 |
-
cu_dev = cu_seqlens.to(q.device, torch.int32).contiguous()
|
| 501 |
-
q_f = q.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 502 |
-
k_f = k.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 503 |
-
v_f = v.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 504 |
-
g_f = g.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 505 |
-
b_f = b.reshape(1, total, self.num_heads, self.head_k_dim)
|
| 506 |
-
w_f = w.reshape(1, total, self.num_v_heads, self.head_v_dim)
|
| 507 |
-
o, fs = _fla_chunk(q_f, k_f, v_f, g_f, b_f, w_f, init,
|
| 508 |
-
output_state, cu_dev)
|
| 509 |
-
o = o.reshape(B, T, self.num_v_heads, self.head_v_dim)
|
| 510 |
-
else:
|
| 511 |
-
o, fs = _fla_chunk(q, k, v, g, b, w, init, output_state, None)
|
| 512 |
-
else:
|
| 513 |
-
o, fs = naive_gdn2_reference(q.float(), k.float(), v.float(), g,
|
| 514 |
-
b.float(), w.float(), init)
|
| 515 |
-
|
| 516 |
-
# Cast back to activation precision
|
| 517 |
-
o = o.to(hidden_states.dtype)
|
| 518 |
-
|
| 519 |
-
fs = fs if output_state else None
|
| 520 |
-
gate = self.g_proj(hidden_states).view(B, T, self.num_v_heads, self.head_v_dim)
|
| 521 |
-
o = self.o_norm(o)
|
| 522 |
-
o = o * torch.sigmoid(gate)
|
| 523 |
-
o = o.reshape(B, T, self.value_dim)
|
| 524 |
-
conv_out = (nq, nk, nv) if output_state else None
|
| 525 |
-
return self.o_proj(o), fs, conv_out
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
def _is_xsa(config, li: int) -> bool:
|
| 529 |
-
if li < config.prelude_layers:
|
| 530 |
-
return True
|
| 531 |
-
if li >= config.prelude_layers + config.recurrent_layers:
|
| 532 |
-
return True
|
| 533 |
-
return (li - config.prelude_layers) % (config.gdn_per_xsa + 1) == config.gdn_per_xsa
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
class SurjoDecoderLayer(nn.Module):
|
| 537 |
-
def __init__(self, config, layer_idx: int):
|
| 538 |
-
super().__init__()
|
| 539 |
-
self.layer_idx = layer_idx
|
| 540 |
-
self.layer_type = "xsa" if _is_xsa(config, layer_idx) else "gdn"
|
| 541 |
-
if self.layer_type == "xsa":
|
| 542 |
-
self.self_attn = XSAAttention(config, layer_idx)
|
| 543 |
-
else:
|
| 544 |
-
self.linear_attn = GDN2Attention(config, layer_idx)
|
| 545 |
-
self.mlp = ClampedMLP(config)
|
| 546 |
-
self.input_layernorm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 547 |
-
self.post_attention_layernorm = SurjoRMSNorm(config.hidden_size,
|
| 548 |
-
eps=config.rms_norm_eps)
|
| 549 |
-
|
| 550 |
-
def forward(self, hidden_states, attention_mask=None, cos=None, sin=None,
|
| 551 |
-
cu_seqlens=None):
|
| 552 |
-
h = self.input_layernorm(hidden_states)
|
| 553 |
-
if self.layer_type == "xsa":
|
| 554 |
-
out = self.self_attn(h, attention_mask, None, -1, False, None,
|
| 555 |
-
cos, sin, cu_seqlens)
|
| 556 |
-
else:
|
| 557 |
-
out, _, _ = self.linear_attn(h, attention_mask, None, None, False,
|
| 558 |
-
cu_seqlens)
|
| 559 |
-
hidden_states = hidden_states + out
|
| 560 |
-
h2 = self.post_attention_layernorm(hidden_states)
|
| 561 |
-
return hidden_states + self.mlp(h2)
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
class SurjoPreTrainedModel(PreTrainedModel):
|
| 565 |
-
config_class = SurjoConfig
|
| 566 |
-
base_model_prefix = "model"
|
| 567 |
-
_no_split_modules = ["SurjoDecoderLayer"]
|
| 568 |
-
_supports_flash_attn = False
|
| 569 |
-
_supports_flash_attn_2 = False
|
| 570 |
-
_supports_sdpa = True
|
| 571 |
-
_is_stateful = True
|
| 572 |
-
_can_compile_fullgraph = True
|
| 573 |
-
|
| 574 |
-
def _init_weights(self, module):
|
| 575 |
-
std = self.config.initializer_range
|
| 576 |
-
if isinstance(module, nn.Linear):
|
| 577 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 578 |
-
if module.bias is not None:
|
| 579 |
-
module.bias.data.zero_()
|
| 580 |
-
elif isinstance(module, nn.Embedding):
|
| 581 |
-
module.weight.data.normal_(mean=0.0, std=std)
|
| 582 |
-
if module.padding_idx is not None:
|
| 583 |
-
module.weight.data[module.padding_idx].zero_()
|
| 584 |
-
elif isinstance(module, GDN2Attention):
|
| 585 |
-
module.A_log.data.copy_(
|
| 586 |
-
torch.log(
|
| 587 |
-
torch.empty(module.num_heads, dtype=torch.float32,
|
| 588 |
-
device=module.A_log.device).uniform_(1, 16)
|
| 589 |
-
)
|
| 590 |
-
)
|
| 591 |
-
dt = torch.exp(
|
| 592 |
-
torch.rand(module.key_dim, dtype=torch.float32,
|
| 593 |
-
device=module.dt_bias.device)
|
| 594 |
-
* (math.log(0.1) - math.log(0.001)) + math.log(0.001)
|
| 595 |
-
).clamp(min=1e-4)
|
| 596 |
-
module.dt_bias.data.copy_(dt + torch.log(-torch.expm1(-dt)))
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
class SurjoModel(SurjoPreTrainedModel):
|
| 600 |
-
def __init__(self, config):
|
| 601 |
-
super().__init__(config)
|
| 602 |
-
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 603 |
-
self.layers = nn.ModuleList(
|
| 604 |
-
[SurjoDecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
| 605 |
-
)
|
| 606 |
-
self.norm = SurjoRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
|
| 607 |
-
self.rotary = SurjoRotaryEmbedding(config)
|
| 608 |
-
self.grad_checkpointing = False
|
| 609 |
-
|
| 610 |
-
slot = 0
|
| 611 |
-
self.xsa_slot_map = {}
|
| 612 |
-
self.exec_plan = []
|
| 613 |
-
for li in range(config.prelude_layers):
|
| 614 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 615 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 616 |
-
slot += 1
|
| 617 |
-
for p in range(config.recurrent_passes):
|
| 618 |
-
for g in range(config.num_groups):
|
| 619 |
-
base = config.prelude_layers + g * (config.gdn_per_xsa + 1)
|
| 620 |
-
for j in range(config.gdn_per_xsa):
|
| 621 |
-
self.exec_plan.append((self.layers[base + j], base + j, p, -1))
|
| 622 |
-
li = base + config.gdn_per_xsa
|
| 623 |
-
self.xsa_slot_map[(li, p)] = slot
|
| 624 |
-
self.exec_plan.append((self.layers[li], li, p, slot))
|
| 625 |
-
slot += 1
|
| 626 |
-
for li in range(config.prelude_layers + config.recurrent_layers,
|
| 627 |
-
config.num_hidden_layers):
|
| 628 |
-
self.xsa_slot_map[(li, 0)] = slot
|
| 629 |
-
self.exec_plan.append((self.layers[li], li, 0, slot))
|
| 630 |
-
slot += 1
|
| 631 |
-
self.num_xsa_slots = slot
|
| 632 |
-
self.post_init()
|
| 633 |
-
|
| 634 |
-
def get_input_embeddings(self):
|
| 635 |
-
return self.embed_tokens
|
| 636 |
-
|
| 637 |
-
def set_input_embeddings(self, value):
|
| 638 |
-
self.embed_tokens = value
|
| 639 |
-
|
| 640 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 641 |
-
past_key_values=None, inputs_embeds=None, use_cache=None,
|
| 642 |
-
cache_position=None, return_dict=True,
|
| 643 |
-
output_hidden_states=False, output_attentions=False,
|
| 644 |
-
cu_seqlens=None, **kwargs):
|
| 645 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 646 |
-
past_key_values = None
|
| 647 |
-
if use_cache is None:
|
| 648 |
-
use_cache = past_key_values is not None
|
| 649 |
-
if use_cache and past_key_values is None:
|
| 650 |
-
past_key_values = SurjoCache()
|
| 651 |
-
past_len = past_key_values.get_seq_length() if past_key_values is not None else 0
|
| 652 |
-
|
| 653 |
-
if past_len > 0:
|
| 654 |
-
if input_ids is not None:
|
| 655 |
-
n_ids = input_ids.shape[1]
|
| 656 |
-
if (attention_mask is not None
|
| 657 |
-
and attention_mask.shape[-1] > n_ids
|
| 658 |
-
and attention_mask.shape[-1] > past_len):
|
| 659 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 660 |
-
input_ids = input_ids[:, -n_new:] if n_new <= n_ids else input_ids
|
| 661 |
-
elif n_ids > past_len:
|
| 662 |
-
input_ids = input_ids[:, past_len:]
|
| 663 |
-
else:
|
| 664 |
-
input_ids = input_ids[:, -1:]
|
| 665 |
-
elif inputs_embeds is not None:
|
| 666 |
-
n_emb = inputs_embeds.shape[1]
|
| 667 |
-
if (attention_mask is not None
|
| 668 |
-
and attention_mask.shape[-1] > n_emb
|
| 669 |
-
and attention_mask.shape[-1] > past_len):
|
| 670 |
-
n_new = attention_mask.shape[-1] - past_len
|
| 671 |
-
inputs_embeds = (inputs_embeds[:, -n_new:] if n_new <= n_emb
|
| 672 |
-
else inputs_embeds)
|
| 673 |
-
elif n_emb > past_len:
|
| 674 |
-
inputs_embeds = inputs_embeds[:, past_len:]
|
| 675 |
-
else:
|
| 676 |
-
inputs_embeds = inputs_embeds[:, -1:]
|
| 677 |
-
|
| 678 |
-
if inputs_embeds is None:
|
| 679 |
-
if input_ids is None:
|
| 680 |
-
raise ValueError("Specify input_ids or inputs_embeds")
|
| 681 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
| 682 |
-
B, T = inputs_embeds.shape[0], inputs_embeds.shape[1]
|
| 683 |
-
|
| 684 |
-
cache_position = torch.arange(past_len, past_len + T,
|
| 685 |
-
device=inputs_embeds.device)
|
| 686 |
-
if position_ids is not None and position_ids.shape[-1] != T:
|
| 687 |
-
position_ids = None
|
| 688 |
-
if position_ids is None:
|
| 689 |
-
position_ids = cache_position.unsqueeze(0).expand(B, -1)
|
| 690 |
-
cos, sin = self.rotary(position_ids)
|
| 691 |
-
|
| 692 |
-
gdn_states = dict(past_key_values.gdn_state) if past_key_values is not None else {}
|
| 693 |
-
conv_states = dict(past_key_values.gdn_conv) if past_key_values is not None else {}
|
| 694 |
-
|
| 695 |
-
noise_std = self.config.loop_noise_std
|
| 696 |
-
hidden = inputs_embeds
|
| 697 |
-
prev_p = 0
|
| 698 |
-
use_ckpt = self.training and self.grad_checkpointing
|
| 699 |
-
all_hidden_states = () if output_hidden_states else None
|
| 700 |
-
|
| 701 |
-
for (layer, li, p, slot) in self.exec_plan:
|
| 702 |
-
if output_hidden_states:
|
| 703 |
-
all_hidden_states += (hidden,)
|
| 704 |
-
if p != prev_p and p > 0 and self.training and noise_std > 0.0:
|
| 705 |
-
hidden = hidden + torch.randn_like(hidden) * noise_std
|
| 706 |
-
prev_p = p
|
| 707 |
-
|
| 708 |
-
if use_ckpt:
|
| 709 |
-
hidden = torch.utils.checkpoint.checkpoint(
|
| 710 |
-
self._train_layer, layer, hidden, attention_mask, cos, sin,
|
| 711 |
-
cu_seqlens, use_reentrant=False,
|
| 712 |
-
)
|
| 713 |
-
elif use_cache:
|
| 714 |
-
h = layer.input_layernorm(hidden)
|
| 715 |
-
if layer.layer_type == "xsa":
|
| 716 |
-
out = layer.self_attn(h, attention_mask, past_key_values,
|
| 717 |
-
slot, use_cache, cache_position,
|
| 718 |
-
cos, sin, cu_seqlens)
|
| 719 |
-
else:
|
| 720 |
-
gs = gdn_states.get((li, p))
|
| 721 |
-
cs = conv_states.get((li, p))
|
| 722 |
-
out, ngs, ncs = layer.linear_attn(h, attention_mask, gs, cs,
|
| 723 |
-
use_cache, cu_seqlens)
|
| 724 |
-
if ngs is not None:
|
| 725 |
-
gdn_states[(li, p)] = ngs
|
| 726 |
-
if ncs is not None:
|
| 727 |
-
conv_states[(li, p)] = ncs
|
| 728 |
-
hidden = hidden + out
|
| 729 |
-
h2 = layer.post_attention_layernorm(hidden)
|
| 730 |
-
hidden = hidden + layer.mlp(h2)
|
| 731 |
-
else:
|
| 732 |
-
hidden = layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 733 |
-
|
| 734 |
-
hidden = self.norm(hidden)
|
| 735 |
-
if output_hidden_states:
|
| 736 |
-
all_hidden_states += (hidden,)
|
| 737 |
-
|
| 738 |
-
if use_cache and past_key_values is not None:
|
| 739 |
-
past_key_values.gdn_state.update(gdn_states)
|
| 740 |
-
past_key_values.gdn_conv.update(conv_states)
|
| 741 |
-
|
| 742 |
-
if not return_dict:
|
| 743 |
-
out = tuple(v for v in [hidden, past_key_values if use_cache else None,
|
| 744 |
-
all_hidden_states] if v is not None)
|
| 745 |
-
return out
|
| 746 |
-
return BaseModelOutputWithPast(
|
| 747 |
-
last_hidden_state=hidden,
|
| 748 |
-
past_key_values=past_key_values if use_cache else None,
|
| 749 |
-
hidden_states=all_hidden_states,
|
| 750 |
-
attentions=None,
|
| 751 |
-
)
|
| 752 |
-
|
| 753 |
-
def _train_layer(self, layer, hidden, attention_mask, cos, sin, cu_seqlens):
|
| 754 |
-
return layer(hidden, attention_mask, cos, sin, cu_seqlens)
|
| 755 |
-
|
| 756 |
-
|
| 757 |
-
class SurjoForCausalLM(SurjoPreTrainedModel, GenerationMixin):
|
| 758 |
-
_tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
|
| 759 |
-
|
| 760 |
-
def __init__(self, config):
|
| 761 |
-
super().__init__(config)
|
| 762 |
-
self.model = SurjoModel(config)
|
| 763 |
-
self.vocab_size = config.vocab_size
|
| 764 |
-
self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
|
| 765 |
-
self.post_init()
|
| 766 |
-
|
| 767 |
-
def tie_weights(self, **kwargs):
|
| 768 |
-
try:
|
| 769 |
-
super().tie_weights(**kwargs)
|
| 770 |
-
except TypeError:
|
| 771 |
-
pass
|
| 772 |
-
except Exception:
|
| 773 |
-
pass
|
| 774 |
-
if (getattr(self.config, "tie_word_embeddings", False)
|
| 775 |
-
and getattr(self, "model", None) is not None
|
| 776 |
-
and getattr(self, "lm_head", None) is not None):
|
| 777 |
-
self.lm_head.weight = self.model.embed_tokens.weight
|
| 778 |
-
|
| 779 |
-
def save_pretrained(self, *args, **kwargs):
|
| 780 |
-
was_tied = (getattr(self, "lm_head", None) is not None
|
| 781 |
-
and getattr(self, "model", None) is not None
|
| 782 |
-
and self.lm_head.weight is self.model.embed_tokens.weight)
|
| 783 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 784 |
-
self.lm_head.weight = nn.Parameter(
|
| 785 |
-
self.model.embed_tokens.weight.detach().clone(),
|
| 786 |
-
requires_grad=self.model.embed_tokens.weight.requires_grad,
|
| 787 |
-
)
|
| 788 |
-
try:
|
| 789 |
-
return super().save_pretrained(*args, **kwargs)
|
| 790 |
-
finally:
|
| 791 |
-
if was_tied and self.config.tie_word_embeddings:
|
| 792 |
-
self.tie_weights()
|
| 793 |
-
|
| 794 |
-
def get_input_embeddings(self):
|
| 795 |
-
return self.model.embed_tokens
|
| 796 |
-
|
| 797 |
-
def set_input_embeddings(self, value):
|
| 798 |
-
self.model.embed_tokens = value
|
| 799 |
-
|
| 800 |
-
def get_output_embeddings(self):
|
| 801 |
-
return self.lm_head
|
| 802 |
-
|
| 803 |
-
def set_output_embeddings(self, value):
|
| 804 |
-
self.lm_head = value
|
| 805 |
-
|
| 806 |
-
def set_decoder(self, decoder):
|
| 807 |
-
self.model = decoder
|
| 808 |
-
|
| 809 |
-
def get_decoder(self):
|
| 810 |
-
return self.model
|
| 811 |
-
|
| 812 |
-
def gradient_checkpointing_enable(self, gradient_checkpointing_kwargs=None, **kwargs):
|
| 813 |
-
self.model.grad_checkpointing = True
|
| 814 |
-
|
| 815 |
-
def gradient_checkpointing_disable(self):
|
| 816 |
-
self.model.grad_checkpointing = False
|
| 817 |
-
|
| 818 |
-
def forward(self, input_ids=None, attention_mask=None, position_ids=None,
|
| 819 |
-
past_key_values=None, inputs_embeds=None, labels=None,
|
| 820 |
-
use_cache=None, output_hidden_states=None, output_attentions=None,
|
| 821 |
-
return_dict=None, logits_to_keep=0, cache_position=None,
|
| 822 |
-
cu_seqlens=None, **kwargs):
|
| 823 |
-
if logits_to_keep in (None, 0) and kwargs.get("num_logits_to_keep"):
|
| 824 |
-
logits_to_keep = kwargs.pop("num_logits_to_keep")
|
| 825 |
-
return_dict = True if return_dict is None else return_dict
|
| 826 |
-
if use_cache is None:
|
| 827 |
-
use_cache = not (self.training or labels is not None)
|
| 828 |
-
|
| 829 |
-
outputs = self.model(
|
| 830 |
-
input_ids=input_ids, attention_mask=attention_mask,
|
| 831 |
-
position_ids=position_ids, past_key_values=past_key_values,
|
| 832 |
-
inputs_embeds=inputs_embeds, use_cache=use_cache,
|
| 833 |
-
cache_position=cache_position,
|
| 834 |
-
output_hidden_states=output_hidden_states,
|
| 835 |
-
output_attentions=output_attentions,
|
| 836 |
-
cu_seqlens=cu_seqlens,
|
| 837 |
-
**kwargs,
|
| 838 |
-
)
|
| 839 |
-
hidden_states = outputs[0]
|
| 840 |
-
|
| 841 |
-
loss, logits = None, None
|
| 842 |
-
if labels is not None:
|
| 843 |
-
sh = hidden_states[..., :-1, :].contiguous()
|
| 844 |
-
sl = labels[..., 1:].contiguous()
|
| 845 |
-
if _USE_FLA_FUSED_CE and _fla_flce is not None:
|
| 846 |
-
loss = _fla_flce(
|
| 847 |
-
sh.view(-1, sh.shape[-1]),
|
| 848 |
-
sl.view(-1),
|
| 849 |
-
self.lm_head.weight,
|
| 850 |
-
num_chunks=8,
|
| 851 |
-
reduction="mean",
|
| 852 |
-
)
|
| 853 |
-
else:
|
| 854 |
-
n_chunks = max(8, sh.shape[0] // 8)
|
| 855 |
-
tot = hidden_states.new_zeros((), dtype=torch.float32)
|
| 856 |
-
n_tok = 0
|
| 857 |
-
for h_c, l_c in zip(sh.chunk(n_chunks, dim=0), sl.chunk(n_chunks, dim=0)):
|
| 858 |
-
if l_c.numel() == 0:
|
| 859 |
-
continue
|
| 860 |
-
lg = self.lm_head(h_c)
|
| 861 |
-
tot = tot + F.cross_entropy(
|
| 862 |
-
lg.float().view(-1, lg.size(-1)), l_c.view(-1), reduction="sum"
|
| 863 |
-
)
|
| 864 |
-
n_tok += l_c.numel()
|
| 865 |
-
loss = tot / max(n_tok, 1)
|
| 866 |
-
else:
|
| 867 |
-
if isinstance(logits_to_keep, int) and logits_to_keep > 0:
|
| 868 |
-
sl_hidden = hidden_states[:, -logits_to_keep:, :]
|
| 869 |
-
elif torch.is_tensor(logits_to_keep):
|
| 870 |
-
sl_hidden = hidden_states[:, logits_to_keep, :]
|
| 871 |
-
else:
|
| 872 |
-
sl_hidden = hidden_states
|
| 873 |
-
logits = self.lm_head(sl_hidden)
|
| 874 |
-
|
| 875 |
-
if not return_dict:
|
| 876 |
-
out = (logits,) + outputs[1:]
|
| 877 |
-
return (loss,) + out if loss is not None else out
|
| 878 |
-
return CausalLMOutputWithPast(
|
| 879 |
-
loss=loss, logits=logits,
|
| 880 |
-
past_key_values=outputs.past_key_values,
|
| 881 |
-
hidden_states=outputs.hidden_states,
|
| 882 |
-
attentions=outputs.attentions,
|
| 883 |
-
)
|
| 884 |
-
|
| 885 |
-
def prepare_inputs_for_generation(self, input_ids, past_key_values=None,
|
| 886 |
-
attention_mask=None, inputs_embeds=None,
|
| 887 |
-
cache_position=None, use_cache=True, **kwargs):
|
| 888 |
-
if past_key_values is not None and not isinstance(past_key_values, SurjoCache):
|
| 889 |
-
past_key_values = None
|
| 890 |
-
has_state = past_key_values is not None and len(past_key_values.kv) > 0
|
| 891 |
-
if has_state:
|
| 892 |
-
input_ids = input_ids[:, -1:]
|
| 893 |
-
if kwargs.get("logits_to_keep") is None:
|
| 894 |
-
kwargs["logits_to_keep"] = 1
|
| 895 |
-
past_len = past_key_values.get_seq_length() if has_state else 0
|
| 896 |
-
cache_position = torch.arange(past_len, past_len + input_ids.shape[1],
|
| 897 |
-
device=input_ids.device)
|
| 898 |
-
model_inputs = {
|
| 899 |
-
"input_ids": input_ids.contiguous(),
|
| 900 |
-
"past_key_values": past_key_values,
|
| 901 |
-
"use_cache": use_cache,
|
| 902 |
-
"cache_position": cache_position,
|
| 903 |
-
"attention_mask": attention_mask,
|
| 904 |
-
}
|
| 905 |
-
model_inputs.update(kwargs)
|
| 906 |
-
return model_inputs
|
| 907 |
-
|
| 908 |
-
def _reorder_cache(self, past_key_values: SurjoCache, beam_idx):
|
| 909 |
-
for slot, (k, v) in past_key_values.kv.items():
|
| 910 |
-
past_key_values.kv[slot] = (k.index_select(0, beam_idx),
|
| 911 |
-
v.index_select(0, beam_idx))
|
| 912 |
-
for key in list(past_key_values.gdn_state.keys()):
|
| 913 |
-
s = past_key_values.gdn_state[key]
|
| 914 |
-
if s is not None:
|
| 915 |
-
past_key_values.gdn_state[key] = s.index_select(0, beam_idx)
|
| 916 |
-
for key in list(past_key_values.gdn_conv.keys()):
|
| 917 |
-
cs = past_key_values.gdn_conv[key]
|
| 918 |
-
if cs is not None:
|
| 919 |
-
past_key_values.gdn_conv[key] = tuple(
|
| 920 |
-
c.index_select(0, beam_idx) if c is not None else None for c in cs
|
| 921 |
-
)
|
| 922 |
-
return past_key_values
|
| 923 |
-
|
| 924 |
-
|
| 925 |
-
SurjoConfig.register_for_auto_class()
|
| 926 |
-
SurjoForCausalLM.register_for_auto_class()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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