CortexAether commited on
Commit
c6552d8
·
verified ·
1 Parent(s): b65f5ea

Upload 11 files

Browse files
README.md CHANGED
@@ -1,3 +1,29 @@
1
  ---
2
  license: apache-2.0
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: apache-2.0
3
+ language:
4
+ - fa
5
+ - en
6
+ - multilingual
7
+ tags:
8
+ - aethermind
9
+ - decoder-only
10
+ - rope
11
+ - gqa
12
+ - swiglu
13
+ - moe
14
+ - safetensors
15
+ library_name: transformers
16
  ---
17
+
18
+ # AetherMind-Tiny (pipeline-validation prototype)
19
+
20
+ A real, trainable 5.83M-parameter decoder-only model produced by the AetherMind
21
+ training pipeline (`training/train_proto.py`, 900 steps on CPU). Loads via
22
+ `AutoModelForCausalLM.from_pretrained(..., trust_remote_code=True)` with
23
+ safetensors weights, config.json, tokenizer JSONs and a ChatML tool-aware
24
+ chat template.
25
+
26
+ Real metrics: train loss 0.49 · val loss 9.05 (memorization regime —
27
+ prototype scale) · task checks 4/4 multilingual FAQ, 3/3 chat format.
28
+ This is NOT a production chat model; it validates the full pipeline that
29
+ scales to the 1B–70B presets.
chat_template.jinja ADDED
@@ -0,0 +1 @@
 
 
1
+ {%- if tools %}{{- '<|im_start|>system\nYou are AetherMind, a helpful, honest and safe multilingual assistant.\nYou have access to the following tools (JSON schema):\n' + tools | tojson + '\nWhen you decide to call a tool, output one JSON object between <|tool_start|> and <|tool_end|>. After receiving tool results, answer the user.<|im_end|>\n' }}{%- endif %}{%- for message in messages %}{%- if message.role == 'assistant' and message.tool_calls %}{{- '<|im_start|>assistant\n' + (message.content or '') }}{%- for tc in message.tool_calls %}{{- '<|tool_start|>' + {'name': tc['function']['name'], 'arguments': tc['function']['arguments']} | tojson + '<|tool_end|>' }}{%- endfor %}{{- '<|im_end|>\n' }}{%- else %}{{- '<|im_start|>' + message['role'] + '\n' + (message['content'] or '') + '<|im_end|>\n' }}{%- endif %}{%- endfor %}{%- if add_generation_prompt %}{{- '<|im_start|>assistant\n' }}{%- endif %}
chat_template.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ {
2
+ "chat_template": "{%- if tools %}{{- '<|im_start|>system\\nYou are AetherMind, a helpful, honest and safe multilingual assistant.\\nYou have access to the following tools (JSON schema):\\n' + tools | tojson + '\\nWhen you decide to call a tool, output one JSON object between <|tool_start|> and <|tool_end|>. After receiving tool results, answer the user.<|im_end|>\\n' }}{%- endif %}{%- for message in messages %}{%- if message.role == 'assistant' and message.tool_calls %}{{- '<|im_start|>assistant\\n' + (message.content or '') }}{%- for tc in message.tool_calls %}{{- '<|tool_start|>' + {'name': tc['function']['name'], 'arguments': tc['function']['arguments']} | tojson + '<|tool_end|>' }}{%- endfor %}{{- '<|im_end|>\\n' }}{%- else %}{{- '<|im_start|>' + message['role'] + '\\n' + (message['content'] or '') + '<|im_end|>\\n' }}{%- endif %}{%- endfor %}{%- if add_generation_prompt %}{{- '<|im_start|>assistant\\n' }}{%- endif %}"
3
+ }
config.json ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "architectures": [
3
+ "AetherMindForCausalLM"
4
+ ],
5
+ "attention_bias": false,
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 2,
8
+ "dtype": "float32",
9
+ "eos_token_id": 3,
10
+ "head_dim": 32,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 256,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 768,
15
+ "max_position_embeddings": 1024,
16
+ "model_type": "aethermind",
17
+ "moe_aux_loss_coeff": 0.01,
18
+ "moe_intermediate_size": 768,
19
+ "moe_layers_freq": 1,
20
+ "num_attention_heads": 8,
21
+ "num_experts": 8,
22
+ "num_experts_per_tok": 2,
23
+ "num_hidden_layers": 6,
24
+ "num_key_value_heads": 4,
25
+ "pad_token_id": 0,
26
+ "rms_norm_eps": 1e-06,
27
+ "rope_parameters": {
28
+ "rope_theta": 10000.0,
29
+ "rope_type": "default"
30
+ },
31
+ "rope_theta": 10000.0,
32
+ "tie_word_embeddings": true,
33
+ "transformers_version": "5.17.0",
34
+ "use_cache": true,
35
+ "use_moe": false,
36
+ "vocab_size": 4326,
37
+ "auto_map": {
38
+ "AutoConfig": "configuration_aethermind.AetherMindConfig",
39
+ "AutoModel": "modeling_aethermind.AetherMindModel",
40
+ "AutoModelForCausalLM": "modeling_aethermind.AetherMindForCausalLM"
41
+ }
42
+ }
configuration_aethermind.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AetherMind — configuration_aethermind.py
2
+ # Copyright 2026 AetherMind Project. Apache License 2.0.
3
+ """AetherMind model configuration.
4
+
5
+ AetherMind is a fully open, trainable family of decoder-only Transformer
6
+ language models with a modern architecture:
7
+
8
+ * RMSNorm pre-normalization
9
+ * Rotary Position Embeddings (RoPE, with optional linear scaling)
10
+ * SwiGLU feed-forward blocks
11
+ * Grouped-Query Attention (GQA)
12
+ * Scaled-dot-product / Flash attention (via torch sdpa on CUDA)
13
+ * Dynamic KV cache for fast generation
14
+ * Optional Mixture-of-Experts (MoE) feed-forward for very large configs
15
+ * Optional gradient checkpointing (enable via ``model.gradient_checkpointing_enable()``)
16
+
17
+ The same code path scales from the CPU-trainable ``tiny`` prototype up to
18
+ 70B-class configs; every hyper-parameter lives here.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ from typing import Any, Dict, Optional
24
+
25
+ from transformers import PretrainedConfig
26
+
27
+
28
+ # ----------------------------------------------------------------------
29
+ # Named size presets (scaling path: tiny -> 70B)
30
+ # ----------------------------------------------------------------------
31
+ SIZE_PRESETS: Dict[str, Dict[str, Any]] = {
32
+ # CPU-trainable prototype used to validate the full pipeline.
33
+ "tiny": dict(
34
+ hidden_size=256, intermediate_size=768, num_hidden_layers=6,
35
+ num_attention_heads=8, num_key_value_heads=4, head_dim=32,
36
+ max_position_embeddings=1024, tie_word_embeddings=True,
37
+ ),
38
+ "1B": dict(
39
+ hidden_size=2048, intermediate_size=5632, num_hidden_layers=24,
40
+ num_attention_heads=16, num_key_value_heads=4, head_dim=128,
41
+ max_position_embeddings=32768, vocab_size=65536,
42
+ ),
43
+ "3B": dict(
44
+ hidden_size=3200, intermediate_size=8704, num_hidden_layers=32,
45
+ num_attention_heads=25, num_key_value_heads=5, head_dim=128,
46
+ max_position_embeddings=32768, vocab_size=65536,
47
+ ),
48
+ "7B": dict(
49
+ hidden_size=4096, intermediate_size=11008, num_hidden_layers=32,
50
+ num_attention_heads=32, num_key_value_heads=8, head_dim=128,
51
+ max_position_embeddings=32768, vocab_size=65536,
52
+ ),
53
+ "14B": dict(
54
+ hidden_size=5120, intermediate_size=13824, num_hidden_layers=40,
55
+ num_attention_heads=40, num_key_value_heads=8, head_dim=128,
56
+ max_position_embeddings=32768, vocab_size=65536,
57
+ ),
58
+ # From here up, sparse MoE feed-forward keeps FLOPs per token bounded.
59
+ "32B": dict(
60
+ hidden_size=5120, intermediate_size=13824, num_hidden_layers=48,
61
+ num_attention_heads=40, num_key_value_heads=8, head_dim=128,
62
+ max_position_embeddings=32768, vocab_size=65536,
63
+ use_moe=True, num_experts=64, num_experts_per_tok=6,
64
+ moe_intermediate_size=1408, moe_layers_freq=1,
65
+ ),
66
+ "70B": dict(
67
+ hidden_size=8192, intermediate_size=28672, num_hidden_layers=80,
68
+ num_attention_heads=64, num_key_value_heads=8, head_dim=128,
69
+ max_position_embeddings=32768, vocab_size=65536,
70
+ use_moe=True, num_experts=128, num_experts_per_tok=8,
71
+ moe_intermediate_size=2048, moe_layers_freq=1,
72
+ rope_scaling={"type": "linear", "factor": 4.0}, # 32K -> 128K effective
73
+ ),
74
+ }
75
+
76
+
77
+ class AetherMindConfig(PretrainedConfig):
78
+ r"""Configuration class for :class:`~model.modeling_aethermind.AetherMindModel`."""
79
+
80
+ model_type = "aethermind"
81
+ keys_to_ignore_at_inference = ["past_key_values"]
82
+
83
+ def __init__(
84
+ self,
85
+ vocab_size: int = 32768,
86
+ hidden_size: int = 512,
87
+ intermediate_size: int = 1376,
88
+ num_hidden_layers: int = 8,
89
+ num_attention_heads: int = 8,
90
+ num_key_value_heads: int = 4,
91
+ head_dim: Optional[int] = None,
92
+ hidden_act: str = "silu",
93
+ max_position_embeddings: int = 4096,
94
+ initializer_range: float = 0.02,
95
+ rms_norm_eps: float = 1e-6,
96
+ use_cache: bool = True,
97
+ pad_token_id: Optional[int] = None,
98
+ bos_token_id: Optional[int] = None,
99
+ eos_token_id: Optional[int] = None,
100
+ tie_word_embeddings: bool = False,
101
+ rope_theta: float = 10000.0,
102
+ rope_scaling: Optional[Dict[str, Any]] = None,
103
+ attention_bias: bool = False,
104
+ attention_dropout: float = 0.0,
105
+ # ---- Mixture of Experts (for large-scale configs) ----
106
+ use_moe: bool = False,
107
+ num_experts: int = 8,
108
+ num_experts_per_tok: int = 2,
109
+ moe_intermediate_size: Optional[int] = None,
110
+ moe_layers_freq: int = 1,
111
+ moe_aux_loss_coeff: float = 0.01,
112
+ **kwargs,
113
+ ) -> None:
114
+ self.vocab_size = vocab_size
115
+ self.hidden_size = hidden_size
116
+ self.intermediate_size = intermediate_size
117
+ self.num_hidden_layers = num_hidden_layers
118
+ self.num_attention_heads = num_attention_heads
119
+ if num_key_value_heads is None:
120
+ num_key_value_heads = num_attention_heads
121
+ self.num_key_value_heads = num_key_value_heads
122
+ self.head_dim = head_dim if head_dim is not None else hidden_size // num_attention_heads
123
+ self.hidden_act = hidden_act
124
+ self.max_position_embeddings = max_position_embeddings
125
+ self.initializer_range = initializer_range
126
+ self.rms_norm_eps = rms_norm_eps
127
+ self.use_cache = use_cache
128
+ self.rope_theta = rope_theta
129
+ self.rope_scaling = rope_scaling
130
+ if rope_scaling is not None and rope_scaling.get("type", rope_scaling.get("rope_type")) not in (None, "linear"):
131
+ raise ValueError("AetherMind currently supports rope_scaling type='linear' (or None).")
132
+ self.attention_bias = attention_bias
133
+ self.attention_dropout = attention_dropout
134
+
135
+ self.use_moe = use_moe
136
+ self.num_experts = num_experts
137
+ self.num_experts_per_tok = num_experts_per_tok
138
+ self.moe_intermediate_size = moe_intermediate_size or intermediate_size
139
+ self.moe_layers_freq = moe_layers_freq
140
+ self.moe_aux_loss_coeff = moe_aux_loss_coeff
141
+
142
+ super().__init__(
143
+ pad_token_id=pad_token_id,
144
+ bos_token_id=bos_token_id,
145
+ eos_token_id=eos_token_id,
146
+ tie_word_embeddings=tie_word_embeddings,
147
+ **kwargs,
148
+ )
149
+
150
+ @classmethod
151
+ def from_preset(
152
+ cls,
153
+ name: str = "tiny",
154
+ vocab_size: Optional[int] = None,
155
+ **overrides: Any,
156
+ ) -> "AetherMindConfig":
157
+ """Build a config from a named preset (tiny, 1B, 3B, 7B, 14B, 32B, 70B)."""
158
+ if name not in SIZE_PRESETS:
159
+ raise KeyError(f"Unknown preset '{name}'. Available: {sorted(SIZE_PRESETS)}")
160
+ params: Dict[str, Any] = dict(SIZE_PRESETS[name])
161
+ if vocab_size is not None:
162
+ params["vocab_size"] = vocab_size
163
+ params.update(overrides)
164
+ return cls(**params)
165
+
166
+
167
+ __all__ = ["AetherMindConfig", "SIZE_PRESETS"]
generation_config.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token_id": 2,
3
+ "do_sample": false,
4
+ "eos_token_id": 3,
5
+ "max_new_tokens": 64,
6
+ "pad_token_id": 0,
7
+ "transformers_version": "5.17.0"
8
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c08e260e255960a1a1ea2ee8b37c46c106168b73a600f2ba73b1b0038ed8a03b
3
+ size 23323560
modeling_aethermind.py ADDED
@@ -0,0 +1,684 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # AetherMind — modeling_aethermind.py
2
+ # Copyright 2026 AetherMind Project. Apache License 2.0.
3
+ """PyTorch AetherMind model: a modern decoder-only Transformer.
4
+
5
+ Components implemented from scratch (no third-party LLM code):
6
+
7
+ * ``AetherMindRMSNorm`` — RMSNorm with fp32 statistics
8
+ * ``AetherMindRotaryEmbedding`` — RoPE with optional linear scaling
9
+ * ``AetherMindAttention`` — Grouped-Query Attention + KV cache
10
+ * ``AetherMindMLP`` — SwiGLU feed-forward
11
+ * ``AetherMindSparseMoE`` — top-k Mixture-of-Experts + aux loss
12
+ * ``AetherMindDecoderLayer`` — pre-norm Transformer block
13
+ * ``AetherMindModel`` — embedding + blocks + final norm
14
+ * ``AetherMindForCausalLM`` — LM head + loss + generation
15
+
16
+ Attention runs through ``torch.nn.functional.scaled_dot_product_attention``:
17
+ on CUDA this dispatches to FlashAttention kernels when no explicit mask is
18
+ needed (no padding), and to the memory-efficient backend otherwise.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ import warnings
25
+ from typing import List, Optional, Tuple, Union
26
+
27
+ import torch
28
+ import torch.nn as nn
29
+ import torch.nn.functional as F
30
+ from transformers import GenerationMixin
31
+ from transformers.cache_utils import DynamicCache
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ )
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.utils import logging
38
+
39
+ from .configuration_aethermind import AetherMindConfig
40
+
41
+ logger = logging.get_logger(__name__)
42
+
43
+ _CONFIG_FOR_DOC = "AetherMindConfig"
44
+
45
+
46
+ # ======================================================================
47
+ # Building blocks
48
+ # ======================================================================
49
+ class AetherMindRMSNorm(nn.Module):
50
+ """Root-mean-square layer normalization (as in the Llama/RWKV family)."""
51
+
52
+ def __init__(self, hidden_size: int, eps: float = 1e-6) -> None:
53
+ super().__init__()
54
+ self.weight = nn.Parameter(torch.ones(hidden_size))
55
+ self.variance_epsilon = eps
56
+
57
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
58
+ input_dtype = hidden_states.dtype
59
+ hidden_states = hidden_states.to(torch.float32)
60
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
61
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
62
+ return self.weight * hidden_states.to(input_dtype)
63
+
64
+
65
+ class AetherMindRotaryEmbedding(nn.Module):
66
+ """Rotary position embeddings with optional linear interpolation scaling."""
67
+
68
+ def __init__(
69
+ self,
70
+ head_dim: int,
71
+ max_position_embeddings: int = 4096,
72
+ base: float = 10000.0,
73
+ rope_scaling: Optional[dict] = None,
74
+ ) -> None:
75
+ super().__init__()
76
+ self.head_dim = head_dim
77
+ self.max_position_embeddings = max_position_embeddings
78
+ self.base = base
79
+ factor = 1.0
80
+ if rope_scaling is not None:
81
+ rtype = rope_scaling.get("rope_type", rope_scaling.get("type", "linear"))
82
+ if rtype == "linear":
83
+ factor = float(rope_scaling.get("factor", 1.0))
84
+ self.scaling_factor = factor
85
+ # inv_freq is kept as a plain attribute (NOT a registered buffer):
86
+ # it is deterministic from (head_dim, base, scaling_factor), so saving it
87
+ # is redundant; keeping it out of the state dict avoids meta-device
88
+ # materialization bugs and accidental dtype casts (e.g. model.to(bf16)).
89
+ self._inv_freq: Optional[torch.Tensor] = None
90
+
91
+ def _get_inv_freq(self, device: torch.device) -> torch.Tensor:
92
+ if (
93
+ self._inv_freq is None
94
+ or self._inv_freq.device != device
95
+ or self._inv_freq.dtype != torch.float32
96
+ ):
97
+ inv_freq = 1.0 / (
98
+ self.base ** (torch.arange(0, self.head_dim, 2, dtype=torch.float32, device=device) / self.head_dim)
99
+ )
100
+ self._inv_freq = inv_freq / self.scaling_factor
101
+ return self._inv_freq
102
+
103
+ @torch.no_grad()
104
+ def forward(self, x: torch.Tensor, position_ids: torch.Tensor):
105
+ """Return cos/sin of shape ``(batch, seq_len, head_dim)`` in float32."""
106
+ inv_freq = self._get_inv_freq(x.device)[None, None, :] # (1, 1, hd/2)
107
+ pos = position_ids[:, :, None].to(torch.float32) # (b, s, 1)
108
+ freqs = pos * inv_freq # (b, s, hd/2)
109
+ emb = torch.cat((freqs, freqs), dim=-1) # (b, s, hd)
110
+ if position_ids.max() >= self.max_position_embeddings:
111
+ warnings.warn(
112
+ "Sequence length exceeds max_position_embeddings; RoPE positions "
113
+ "beyond the trained window degrade quality. Consider context extension."
114
+ )
115
+ return emb.cos().to(torch.float32), emb.sin().to(torch.float32)
116
+
117
+
118
+ def rotate_half(x: torch.Tensor) -> torch.Tensor:
119
+ x1, x2 = x.chunk(2, dim=-1)
120
+ return torch.cat((-x2, x1), dim=-1)
121
+
122
+
123
+ def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim: int = 1):
124
+ cos = cos.unsqueeze(unsqueeze_dim) # (b, 1, s, d)
125
+ sin = sin.unsqueeze(unsqueeze_dim)
126
+ q_embed = (q * cos) + (rotate_half(q) * sin)
127
+ k_embed = (k * cos) + (rotate_half(k) * sin)
128
+ return q_embed, k_embed
129
+
130
+
131
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
132
+ """Expand KV heads to match the number of query heads (GQA)."""
133
+ if n_rep == 1:
134
+ return hidden_states
135
+ batch, num_kv_heads, slen, head_dim = hidden_states.shape
136
+ hidden_states = hidden_states[:, :, None, :, :].expand(
137
+ batch, num_kv_heads, n_rep, slen, head_dim
138
+ )
139
+ return hidden_states.reshape(batch, num_kv_heads * n_rep, slen, head_dim)
140
+
141
+
142
+ # ======================================================================
143
+ # Attention
144
+ # ======================================================================
145
+ class AetherMindAttention(nn.Module):
146
+ """Grouped-Query Attention with RoPE and a dynamic KV cache."""
147
+
148
+ def __init__(self, config: AetherMindConfig, layer_idx: int) -> None:
149
+ super().__init__()
150
+ self.config = config
151
+ self.layer_idx = layer_idx
152
+ self.hidden_size = config.hidden_size
153
+ self.num_heads = config.num_attention_heads
154
+ self.head_dim = config.head_dim or config.hidden_size // config.num_attention_heads
155
+ self.num_key_value_heads = config.num_key_value_heads
156
+ if self.num_heads % self.num_key_value_heads != 0:
157
+ raise ValueError(
158
+ f"num_attention_heads ({self.num_heads}) must be divisible by "
159
+ f"num_key_value_heads ({self.num_key_value_heads})"
160
+ )
161
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
162
+ self.scaling = self.head_dim ** -0.5
163
+ self.attention_dropout = config.attention_dropout
164
+ self.is_causal = True
165
+
166
+ op_size = self.num_heads * self.head_dim
167
+ self.q_proj = nn.Linear(self.hidden_size, op_size, bias=config.attention_bias)
168
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
169
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
170
+ self.o_proj = nn.Linear(op_size, self.hidden_size, bias=config.attention_bias)
171
+
172
+ self.rotary_emb = AetherMindRotaryEmbedding(
173
+ self.head_dim,
174
+ config.max_position_embeddings,
175
+ config.rope_theta,
176
+ config.rope_scaling,
177
+ )
178
+
179
+ def forward(
180
+ self,
181
+ hidden_states: torch.Tensor,
182
+ attention_mask: Optional[torch.Tensor] = None,
183
+ position_ids: Optional[torch.Tensor] = None,
184
+ past_key_values: Optional[DynamicCache] = None,
185
+ use_cache: bool = False,
186
+ cache_position: Optional[torch.Tensor] = None,
187
+ output_attentions: bool = False,
188
+ **kwargs,
189
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor]]:
190
+ bsz, q_len, _ = hidden_states.shape
191
+
192
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
193
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
194
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
195
+
196
+ cos, sin = self.rotary_emb(value_states, position_ids)
197
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
198
+
199
+ if past_key_values is not None:
200
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
201
+ key_states, value_states = past_key_values.update(
202
+ key_states, value_states, self.layer_idx, cache_kwargs
203
+ )
204
+
205
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
206
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
207
+
208
+ if output_attentions:
209
+ # Explicit path (returns attention probabilities, CPU-friendly)
210
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
211
+ if attention_mask is not None:
212
+ attn_weights = attn_weights + attention_mask
213
+ attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
214
+ attn_output = torch.matmul(attn_weights, value_states)
215
+ attn_weights_out = attn_weights
216
+ else:
217
+ full_prefill = attention_mask is None and q_len == key_states.shape[-2] and q_len > 1
218
+ attn_output = F.scaled_dot_product_attention(
219
+ query_states,
220
+ key_states,
221
+ value_states,
222
+ attn_mask=None if full_prefill else attention_mask,
223
+ dropout_p=self.attention_dropout if self.training else 0.0,
224
+ is_causal=full_prefill,
225
+ scale=self.scaling,
226
+ )
227
+ attn_weights_out = None
228
+
229
+ attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, q_len, -1)
230
+ attn_output = self.o_proj(attn_output)
231
+ return attn_output, attn_weights_out
232
+
233
+
234
+ # ======================================================================
235
+ # Feed-forward blocks
236
+ # ======================================================================
237
+ ACT2FN = {"silu": F.silu, "gelu": F.gelu, "relu": F.relu}
238
+
239
+
240
+ class AetherMindMLP(nn.Module):
241
+ """SwiGLU feed-forward: down( act(gate(x)) * up(x) )."""
242
+
243
+ def __init__(self, config: AetherMindConfig, intermediate_size: Optional[int] = None) -> None:
244
+ super().__init__()
245
+ inter = intermediate_size or config.intermediate_size
246
+ self.gate_proj = nn.Linear(config.hidden_size, inter, bias=False)
247
+ self.up_proj = nn.Linear(config.hidden_size, inter, bias=False)
248
+ self.down_proj = nn.Linear(inter, config.hidden_size, bias=False)
249
+ self.act_fn = ACT2FN[config.hidden_act]
250
+
251
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
252
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
253
+
254
+
255
+ class AetherMindSparseMoE(nn.Module):
256
+ """Top-k Mixture-of-Experts feed-forward with a load-balancing aux loss.
257
+
258
+ The router picks ``num_experts_per_tok`` experts per token; outputs are
259
+ the probability-weighted sum of the selected experts. A switch-transformer
260
+ style auxiliary loss (importance x load) encourages balanced routing and
261
+ is accumulated in ``AetherMindModel.moe_aux_loss`` during training.
262
+ """
263
+
264
+ def __init__(self, config: AetherMindConfig) -> None:
265
+ super().__init__()
266
+ self.num_experts = config.num_experts
267
+ self.top_k = config.num_experts_per_tok
268
+ self.gate = nn.Linear(config.hidden_size, self.num_experts, bias=False)
269
+ self.experts = nn.ModuleList(
270
+ [AetherMindMLP(config, intermediate_size=config.moe_intermediate_size) for _ in range(self.num_experts)]
271
+ )
272
+
273
+ def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
274
+ bsz, seq_len, hidden = x.shape
275
+ flat = x.reshape(-1, hidden)
276
+ router_logits = self.gate(flat) # (N, E)
277
+ routing_probs = F.softmax(router_logits, dim=-1, dtype=torch.float32)
278
+ topk_weights, topk_ids = torch.topk(routing_probs, self.top_k, dim=-1)
279
+ topk_weights = topk_weights / topk_weights.sum(dim=-1, keepdim=True)
280
+
281
+ out = torch.zeros_like(flat)
282
+ for e_idx, expert in enumerate(self.experts):
283
+ mask = topk_ids == e_idx # (N, k)
284
+ token_mask = mask.any(dim=-1)
285
+ if token_mask.any():
286
+ weights = (topk_weights * mask).sum(dim=-1)[token_mask].to(flat.dtype)
287
+ out[token_mask] += expert(flat[token_mask]) * weights.unsqueeze(-1)
288
+
289
+ # Auxiliary load-balancing loss (importance x load), switch-transformer style
290
+ importance = routing_probs.mean(dim=0) # (E,)
291
+ load = topk_ids.new_zeros(self.num_experts, dtype=torch.float32)
292
+ for k in range(self.top_k):
293
+ load += torch.bincount(topk_ids[:, k], minlength=self.num_experts).to(torch.float32)
294
+ load = load / (flat.shape[0] * self.top_k)
295
+ aux_loss = self.num_experts * torch.sum(importance * load)
296
+
297
+ return out.reshape(bsz, seq_len, hidden), aux_loss
298
+
299
+
300
+ # ======================================================================
301
+ # Decoder layer
302
+ # ======================================================================
303
+ class AetherMindDecoderLayer(nn.Module):
304
+ """Pre-norm block: x + Attn(RMSNorm(x)); x + FFN(RMSNorm(x))."""
305
+
306
+ def __init__(self, config: AetherMindConfig, layer_idx: int) -> None:
307
+ super().__init__()
308
+ self.layer_idx = layer_idx
309
+ self.self_attn = AetherMindAttention(config, layer_idx=layer_idx)
310
+ use_moe = config.use_moe and (layer_idx % max(1, config.moe_layers_freq) == 0)
311
+ self.mlp = AetherMindSparseMoE(config) if use_moe else AetherMindMLP(config)
312
+ self.input_layernorm = AetherMindRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
313
+ self.post_attention_layernorm = AetherMindRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
314
+
315
+ def forward(
316
+ self,
317
+ hidden_states: torch.Tensor,
318
+ attention_mask: Optional[torch.Tensor] = None,
319
+ position_ids: Optional[torch.Tensor] = None,
320
+ past_key_values: Optional[DynamicCache] = None,
321
+ use_cache: bool = False,
322
+ cache_position: Optional[torch.Tensor] = None,
323
+ output_attentions: bool = False,
324
+ **kwargs,
325
+ ):
326
+ residual = hidden_states
327
+ hidden_states = self.input_layernorm(hidden_states)
328
+
329
+ attn_out, attn_weights = self.self_attn(
330
+ hidden_states=hidden_states,
331
+ attention_mask=attention_mask,
332
+ position_ids=position_ids,
333
+ past_key_values=past_key_values,
334
+ use_cache=use_cache,
335
+ cache_position=cache_position,
336
+ output_attentions=output_attentions,
337
+ )
338
+ hidden_states = residual + attn_out
339
+
340
+ residual = hidden_states
341
+ hidden_states = self.post_attention_layernorm(hidden_states)
342
+ aux_loss = None
343
+ if isinstance(self.mlp, AetherMindSparseMoE):
344
+ hidden_states, aux_loss = self.mlp(hidden_states)
345
+ else:
346
+ hidden_states = self.mlp(hidden_states)
347
+ hidden_states = residual + hidden_states
348
+
349
+ outputs = (hidden_states, attn_weights, aux_loss)
350
+ return outputs
351
+
352
+
353
+ # ======================================================================
354
+ # Base model
355
+ # ======================================================================
356
+ class AetherMindPreTrainedModel(PreTrainedModel):
357
+ config_class = AetherMindConfig
358
+ base_model_prefix = "model"
359
+ supports_gradient_checkpointing = True
360
+ _no_split_modules = ["AetherMindDecoderLayer"]
361
+ _supports_flash_attn_2 = False
362
+ _supports_sdpa = True
363
+ _supports_cache_class = True
364
+
365
+ def _init_weights(self, module: nn.Module) -> None:
366
+ std = self.config.initializer_range
367
+ if isinstance(module, nn.Linear):
368
+ module.weight.data.normal_(mean=0.0, std=std)
369
+ if module.bias is not None:
370
+ module.bias.data.zero_()
371
+ elif isinstance(module, nn.Embedding):
372
+ module.weight.data.normal_(mean=0.0, std=std)
373
+ if module.padding_idx is not None:
374
+ module.weight.data[module.padding_idx].zero_()
375
+
376
+
377
+ class AetherMindModel(AetherMindPreTrainedModel):
378
+ """Transformer backbone without the LM head."""
379
+
380
+ def __init__(self, config: AetherMindConfig) -> None:
381
+ super().__init__(config)
382
+ self.padding_idx = config.pad_token_id
383
+ self.vocab_size = config.vocab_size
384
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
385
+ self.layers = nn.ModuleList(
386
+ [AetherMindDecoderLayer(config, layer_idx=i) for i in range(config.num_hidden_layers)]
387
+ )
388
+ self.norm = AetherMindRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
389
+ self.gradient_checkpointing = False
390
+ self.moe_aux_loss: Optional[torch.Tensor] = None
391
+ self.post_init()
392
+
393
+ def get_input_embeddings(self) -> nn.Embedding:
394
+ return self.embed_tokens
395
+
396
+ def set_input_embeddings(self, value: nn.Embedding) -> None:
397
+ self.embed_tokens = value
398
+
399
+ # ------------------------------------------------------------------
400
+ def _create_causal_mask(
401
+ self,
402
+ bsz: int,
403
+ q_len: int,
404
+ kv_len: int,
405
+ device: torch.device,
406
+ dtype: torch.dtype,
407
+ attention_mask: Optional[torch.Tensor],
408
+ ) -> torch.Tensor:
409
+ """Additive (min-val) mask combining causality and padding."""
410
+ min_val = torch.finfo(dtype).min
411
+ q_pos = torch.arange(kv_len - q_len, kv_len, device=device).unsqueeze(-1) # (q, 1)
412
+ k_pos = torch.arange(0, kv_len, device=device).unsqueeze(0) # (1, kv)
413
+ causal = (k_pos > q_pos).unsqueeze(0).unsqueeze(0) # (1, 1, q, kv)
414
+ mask = torch.zeros((bsz, 1, q_len, kv_len), dtype=dtype, device=device)
415
+ mask = mask.masked_fill(causal, min_val)
416
+ if attention_mask is not None:
417
+ pad = (attention_mask[:, None, None, :kv_len] == 0)
418
+ mask = mask.masked_fill(pad, min_val)
419
+ return mask
420
+
421
+ # ------------------------------------------------------------------
422
+ def forward(
423
+ self,
424
+ input_ids: Optional[torch.LongTensor] = None,
425
+ attention_mask: Optional[torch.Tensor] = None,
426
+ position_ids: Optional[torch.LongTensor] = None,
427
+ past_key_values: Optional[Union[DynamicCache, List[Tuple[torch.Tensor, torch.Tensor]]]] = None,
428
+ inputs_embeds: Optional[torch.FloatTensor] = None,
429
+ use_cache: Optional[bool] = None,
430
+ output_attentions: Optional[bool] = None,
431
+ output_hidden_states: Optional[bool] = None,
432
+ return_dict: Optional[bool] = None,
433
+ cache_position: Optional[torch.LongTensor] = None,
434
+ **kwargs,
435
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
436
+ output_attentions = output_attentions if output_attentions is not None else False
437
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else False
438
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
439
+ return_dict = return_dict if return_dict is not None else True
440
+ if self.gradient_checkpointing and self.training:
441
+ use_cache = False # the cache is mutated in-place and breaks recomputation
442
+
443
+ if (input_ids is None) == (inputs_embeds is None):
444
+ raise ValueError("Pass exactly one of input_ids or inputs_embeds.")
445
+
446
+ if inputs_embeds is None:
447
+ inputs_embeds = self.embed_tokens(input_ids)
448
+ bsz, seq_len, _ = inputs_embeds.shape
449
+ device = inputs_embeds.device
450
+
451
+ # ---- cache handling (accepts DynamicCache or legacy tuple list) ----
452
+ if past_key_values is not None and not hasattr(past_key_values, "update"):
453
+ legacy = past_key_values
454
+ past_key_values = DynamicCache()
455
+ for layer_idx, (k, v) in enumerate(legacy):
456
+ past_key_values.update(k.to(device), v.to(device), layer_idx)
457
+ if use_cache and past_key_values is None:
458
+ past_key_values = DynamicCache()
459
+
460
+ past_seen = past_key_values.get_seq_length() if past_key_values is not None else 0
461
+ if cache_position is None:
462
+ cache_position = torch.arange(past_seen, past_seen + seq_len, device=device)
463
+ if position_ids is None:
464
+ position_ids = cache_position.unsqueeze(0)
465
+
466
+ # Explicit mask is required for padding, or for chunked prefill where the
467
+ # fast is_causal=True kernel cannot express the offset (kv_len > q_len > 1).
468
+ kv_len = past_seen + seq_len
469
+ need_explicit_mask = attention_mask is not None or (seq_len > 1 and kv_len > seq_len)
470
+ causal_mask = (
471
+ self._create_causal_mask(bsz, seq_len, kv_len, device, inputs_embeds.dtype, attention_mask)
472
+ if need_explicit_mask
473
+ else None
474
+ )
475
+
476
+ hidden_states = inputs_embeds
477
+ all_hidden_states: Tuple = ()
478
+ all_self_attns: Tuple = ()
479
+ aux_total: Optional[torch.Tensor] = None
480
+
481
+ for decoder_layer in self.layers:
482
+ if output_hidden_states:
483
+ all_hidden_states += (hidden_states,)
484
+
485
+ if self.gradient_checkpointing and self.training:
486
+ layer_outputs = self._gradient_checkpointing_func(
487
+ decoder_layer.__call__,
488
+ hidden_states,
489
+ causal_mask,
490
+ position_ids,
491
+ past_key_values if use_cache else None,
492
+ use_cache,
493
+ cache_position,
494
+ output_attentions,
495
+ )
496
+ else:
497
+ layer_outputs = decoder_layer(
498
+ hidden_states,
499
+ attention_mask=causal_mask,
500
+ position_ids=position_ids,
501
+ past_key_values=past_key_values if use_cache else None,
502
+ use_cache=use_cache,
503
+ cache_position=cache_position,
504
+ output_attentions=output_attentions,
505
+ )
506
+
507
+ hidden_states = layer_outputs[0]
508
+ if output_attentions:
509
+ all_self_attns += (layer_outputs[1],)
510
+ if layer_outputs[2] is not None:
511
+ aux_total = layer_outputs[2] if aux_total is None else aux_total + layer_outputs[2]
512
+
513
+ hidden_states = self.norm(hidden_states)
514
+ if output_hidden_states:
515
+ all_hidden_states += (hidden_states,)
516
+ self.moe_aux_loss = aux_total
517
+
518
+ if not return_dict:
519
+ return tuple(
520
+ v for v in (hidden_states, past_key_values, all_hidden_states, all_self_attns) if v is not None
521
+ )
522
+ return BaseModelOutputWithPast(
523
+ last_hidden_state=hidden_states,
524
+ past_key_values=past_key_values if use_cache else None,
525
+ hidden_states=all_hidden_states if output_hidden_states else None,
526
+ attentions=all_self_attns if output_attentions else None,
527
+ )
528
+
529
+
530
+ # ======================================================================
531
+ # Causal LM
532
+ # ======================================================================
533
+ class AetherMindForCausalLM(AetherMindPreTrainedModel, GenerationMixin):
534
+ """AetherMind with a tied/untied LM head for causal language modeling."""
535
+
536
+ _tied_weights_keys = {"lm_head.weight": "model.embed_tokens.weight"}
537
+
538
+ def __init__(self, config: AetherMindConfig) -> None:
539
+ super().__init__(config)
540
+ self.model = AetherMindModel(config)
541
+ self.vocab_size = config.vocab_size
542
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
543
+ self.post_init()
544
+
545
+ def get_input_embeddings(self) -> nn.Embedding:
546
+ return self.model.embed_tokens
547
+
548
+ def set_input_embeddings(self, value: nn.Embedding) -> None:
549
+ self.model.embed_tokens = value
550
+
551
+ def get_output_embeddings(self) -> nn.Linear:
552
+ return self.lm_head
553
+
554
+ def set_output_embeddings(self, value: nn.Linear) -> None:
555
+ self.lm_head = value
556
+
557
+ # ------------------------------------------------------------------
558
+ def forward(
559
+ self,
560
+ input_ids: Optional[torch.LongTensor] = None,
561
+ attention_mask: Optional[torch.Tensor] = None,
562
+ position_ids: Optional[torch.LongTensor] = None,
563
+ past_key_values: Optional[Union[DynamicCache, List[Tuple[torch.Tensor, torch.Tensor]]]] = None,
564
+ inputs_embeds: Optional[torch.FloatTensor] = None,
565
+ labels: Optional[torch.LongTensor] = None,
566
+ use_cache: Optional[bool] = None,
567
+ output_attentions: Optional[bool] = None,
568
+ output_hidden_states: Optional[bool] = None,
569
+ return_dict: Optional[bool] = None,
570
+ cache_position: Optional[torch.LongTensor] = None,
571
+ logits_to_keep: Union[int, torch.Tensor] = 0,
572
+ **kwargs,
573
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
574
+ output_attentions = output_attentions if output_attentions is not None else False
575
+ output_hidden_states = output_hidden_states if output_hidden_states is not None else False
576
+ return_dict = return_dict if return_dict is not None else True
577
+
578
+ outputs = self.model(
579
+ input_ids=input_ids,
580
+ attention_mask=attention_mask,
581
+ position_ids=position_ids,
582
+ past_key_values=past_key_values,
583
+ inputs_embeds=inputs_embeds,
584
+ use_cache=use_cache,
585
+ output_attentions=output_attentions,
586
+ output_hidden_states=output_hidden_states,
587
+ return_dict=True,
588
+ cache_position=cache_position,
589
+ )
590
+ hidden_states = outputs.last_hidden_state
591
+
592
+ if isinstance(logits_to_keep, int):
593
+ slice_indices = slice(None, -logits_to_keep if logits_to_keep > 0 else None)
594
+ else:
595
+ slice_indices = logits_to_keep
596
+ logits = self.lm_head(hidden_states[:, slice_indices, :]).float()
597
+
598
+ loss = None
599
+ if labels is not None:
600
+ shift_logits = logits[..., :-1, :].contiguous()
601
+ shift_labels = labels[..., 1:].contiguous()
602
+ loss = F.cross_entropy(
603
+ shift_logits.view(-1, self.vocab_size),
604
+ shift_labels.view(-1),
605
+ ignore_index=-100,
606
+ )
607
+ if self.config.use_moe and self.model.moe_aux_loss is not None:
608
+ loss = loss + self.config.moe_aux_loss_coeff * self.model.moe_aux_loss
609
+
610
+ if not return_dict:
611
+ output = (logits, outputs.past_key_values)
612
+ if output_hidden_states:
613
+ output += (outputs.hidden_states,)
614
+ if output_attentions:
615
+ output += (outputs.attentions,)
616
+ return ((loss,) + output) if loss is not None else output
617
+
618
+ return CausalLMOutputWithPast(
619
+ loss=loss,
620
+ logits=logits,
621
+ past_key_values=outputs.past_key_values,
622
+ hidden_states=outputs.hidden_states,
623
+ attentions=outputs.attentions,
624
+ )
625
+
626
+ # ------------------------------------------------------------------
627
+ def prepare_inputs_for_generation(
628
+ self,
629
+ input_ids: torch.LongTensor,
630
+ past_key_values: Optional[DynamicCache] = None,
631
+ attention_mask: Optional[torch.Tensor] = None,
632
+ inputs_embeds: Optional[torch.FloatTensor] = None,
633
+ cache_position: Optional[torch.LongTensor] = None,
634
+ use_cache: bool = True,
635
+ **kwargs,
636
+ ):
637
+ past_length = 0
638
+ if past_key_values is not None and hasattr(past_key_values, "get_seq_length"):
639
+ past_length = past_key_values.get_seq_length()
640
+
641
+ model_inputs = {}
642
+ if inputs_embeds is not None and past_length == 0:
643
+ model_inputs["inputs_embeds"] = inputs_embeds
644
+ elif cache_position is not None:
645
+ model_inputs["input_ids"] = input_ids[:, cache_position].contiguous()
646
+ else:
647
+ model_inputs["input_ids"] = input_ids[:, past_length:].contiguous()
648
+ cache_position = torch.arange(
649
+ past_length, past_length + model_inputs["input_ids"].shape[1], device=input_ids.device
650
+ )
651
+
652
+ input_length = model_inputs["inputs_embeds"].shape[1] if "inputs_embeds" in model_inputs \
653
+ else model_inputs["input_ids"].shape[1]
654
+
655
+ position_ids = None
656
+ if attention_mask is not None:
657
+ position_ids = attention_mask.long().cumsum(-1) - 1
658
+ position_ids.masked_fill_(attention_mask == 0, 1)
659
+ position_ids = position_ids[:, -input_length:]
660
+
661
+ model_inputs.update(
662
+ {
663
+ "past_key_values": past_key_values,
664
+ "use_cache": use_cache,
665
+ "attention_mask": attention_mask,
666
+ "position_ids": position_ids,
667
+ "cache_position": cache_position,
668
+ }
669
+ )
670
+ return model_inputs
671
+
672
+
673
+ __all__ = [
674
+ "AetherMindConfig",
675
+ "AetherMindModel",
676
+ "AetherMindForCausalLM",
677
+ "AetherMindPreTrainedModel",
678
+ "AetherMindRMSNorm",
679
+ "AetherMindRotaryEmbedding",
680
+ "AetherMindAttention",
681
+ "AetherMindMLP",
682
+ "AetherMindSparseMoE",
683
+ "AetherMindDecoderLayer",
684
+ ]
special_tokens_map.json ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": "<|im_start|>",
3
+ "eos_token": "<|im_end|>",
4
+ "pad_token": "<|pad|>",
5
+ "unk_token": "<|unk|>",
6
+ "additional_special_tokens": [
7
+ "<|tool_start|>",
8
+ "<|tool_end|>",
9
+ "<|reasoning_start|>",
10
+ "<|reasoning_end|>"
11
+ ]
12
+ }
tokenizer.json ADDED
The diff for this file is too large to render. See raw diff
 
tokenizer_config.json ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "backend": "tokenizers",
3
+ "bos_token": "<|im_start|>",
4
+ "eos_token": "<|im_end|>",
5
+ "is_local": true,
6
+ "local_files_only": false,
7
+ "model_max_length": 1024,
8
+ "pad_token": "<|pad|>",
9
+ "tokenizer_class": "TokenizersBackend",
10
+ "unk_token": "<|unk|>"
11
+ }