File size: 1,913 Bytes
63e99b4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | """
GLADIUS v2.0 — Shared Embeddings
Token embeddings and output projection head.
Optionally weight-tied (saves ~8M params at full scale).
Tool embeddings live in the same space — see tools.py.
"""
import torch
import torch.nn as nn
import math
from .config import KernelConfig
class SharedEmbeddings(nn.Module):
"""
Shared vocabulary embedding layer.
Tokens, tools, and specialist routing all project into the same
hidden_dim space. This is what makes tool activation = generation:
they live in the same manifold.
"""
def __init__(self, config: KernelConfig):
super().__init__()
self.config = config
# Token embeddings
self.token_embed = nn.Embedding(
config.vocab_size, config.hidden_dim,
padding_idx=config.pad_token_id
)
# Output projection (vocab logits)
self.output_head = nn.Linear(config.hidden_dim, config.vocab_size, bias=False)
# Weight tying: output_head shares weights with token_embed
self.output_head.weight = self.token_embed.weight
# Scaling factor (Vaswani et al.)
self.scale = math.sqrt(config.hidden_dim)
self._init_weights()
def _init_weights(self):
nn.init.normal_(self.token_embed.weight, mean=0.0, std=0.02)
# Pad token should be zero
with torch.no_grad():
self.token_embed.weight[self.config.pad_token_id].zero_()
def embed(self, input_ids: torch.Tensor) -> torch.Tensor:
"""Token IDs → hidden representations."""
return self.token_embed(input_ids) * self.scale
def project(self, hidden: torch.Tensor) -> torch.Tensor:
"""Hidden representations → vocabulary logits."""
return self.output_head(hidden)
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
"""Convenience: embed."""
return self.embed(input_ids)
|