File size: 11,494 Bytes
6ac124b | 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 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 | """HuggingFace compatible Namer model."""
from __future__ import annotations
import math
from typing import Optional, Union
import torch
import torch.nn as nn
from transformers import PreTrainedModel, PretrainedConfig
from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions
from transformers.generation import GenerationMixin
class NamerConfig(PretrainedConfig):
"""Configuration class for NamerModel."""
model_type = "custom"
def __init__(
self,
vocab_size: int = 41,
max_output_len: int = 20,
d_model: int = 128,
nhead: int = 4,
num_encoder_layers: int = 4,
dim_feedforward: int = 512,
dropout: float = 0.1,
pad_token_id: int = 10,
eos_token_id: int = 40, # <EOS> token index
**kwargs,
):
self.vocab_size = vocab_size
self.max_output_len = max_output_len
self.d_model = d_model
self.nhead = nhead
self.num_encoder_layers = num_encoder_layers
self.dim_feedforward = dim_feedforward
self.dropout = dropout
super().__init__(
pad_token_id=pad_token_id,
eos_token_id=eos_token_id,
**kwargs,
)
class PositionalEncoding(nn.Module):
"""Sinusoidal positional encoding for transformer."""
def __init__(self, d_model: int, max_len: int = 5000) -> None:
super().__init__()
pe = torch.zeros(max_len, d_model)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(
torch.arange(0, d_model, 2).float()
* (-math.log(10000.0) / d_model)
)
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
self.register_buffer("pe", pe)
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""Add positional encoding to input."""
return x + self.pe[: x.size(1)]
class NamerModel(PreTrainedModel, GenerationMixin):
"""HuggingFace compatible Namer transformer model.
Converts integer digit sequences to English number names.
"""
config_class = NamerConfig
base_model_prefix = "namer"
def __init__(self, config: NamerConfig):
super().__init__(config)
self.vocab_size = config.vocab_size
self.max_output_len = config.max_output_len
self.d_model = config.d_model
# Digit embedding (10 digits + 1 padding token = 11)
self.digit_embedding = nn.Embedding(11, config.d_model, padding_idx=config.pad_token_id)
# Positional encoding
self.pos_encoder = PositionalEncoding(config.d_model, max_len=100)
# Transformer encoder
encoder_layer = nn.TransformerEncoderLayer(
d_model=config.d_model,
nhead=config.nhead,
dim_feedforward=config.dim_feedforward,
dropout=config.dropout,
batch_first=True,
)
self.transformer_encoder = nn.TransformerEncoder(
encoder_layer, num_layers=config.num_encoder_layers
)
# Output projection
self.output_projection = nn.Linear(config.d_model, config.vocab_size)
# Learned queries for each output position
self.output_queries = nn.Parameter(torch.randn(config.max_output_len, config.d_model))
# Cross-attention from output positions to encoded input
self.cross_attention = nn.MultiheadAttention(
config.d_model, config.nhead, dropout=config.dropout, batch_first=True
)
# Final output layers
self.output_norm = nn.LayerNorm(config.d_model)
self.post_init()
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
labels: Optional[torch.Tensor] = None,
**kwargs,
) -> CausalLMOutputWithCrossAttentions:
"""Forward pass for HF compatibility.
Args:
input_ids: (batch_size, seq_len) tensor of digit indices (0-9), padding=10
attention_mask: Optional mask for padding
labels: Optional target labels for training
Returns:
CausalLMOutputWithCrossAttentions with logits
"""
if input_ids is None:
raise ValueError("input_ids must be provided")
batch_size, seq_len = input_ids.shape
# Handle padding: convert -1 padding to 10 (our padding index)
digits = input_ids.clone()
digits[digits == -1] = self.config.pad_token_id
# Create padding mask for transformer (True = padding)
if attention_mask is None:
src_key_padding_mask = digits == self.config.pad_token_id
else:
src_key_padding_mask = ~attention_mask.bool()
# Embed digits: (batch, seq_len, d_model)
embedded = self.digit_embedding(digits)
# Add positional encoding
embedded = self.pos_encoder(embedded)
# Transformer encoder: (batch, seq_len, d_model)
memory = self.transformer_encoder(
embedded, src_key_padding_mask=src_key_padding_mask
)
# Expand queries for batch: (batch, max_output_len, d_model)
queries = self.output_queries.unsqueeze(0).expand(batch_size, -1, -1)
# Cross-attention from queries to encoded input
attn_output, _ = self.cross_attention(
queries, memory, memory, key_padding_mask=src_key_padding_mask
)
# Normalize and project to vocab
output = self.output_norm(attn_output)
logits = self.output_projection(output)
loss = None
if labels is not None:
loss_fct = nn.CrossEntropyLoss(ignore_index=-100)
loss = loss_fct(logits.view(-1, self.vocab_size), labels.view(-1))
return CausalLMOutputWithCrossAttentions(
loss=loss,
logits=logits,
hidden_states=None,
attentions=None,
cross_attentions=None,
)
def prepare_inputs_for_generation(self, input_ids, **kwargs):
"""Prepare inputs for text generation."""
return {"input_ids": input_ids}
def _reorder_cache(self, past_key_values, beam_idx):
"""Reorder cache for beam search."""
return past_key_values
class NamerPipeline:
"""Simple pipeline for Namer model inference.
Usage:
from transformers import AutoModel
# Load model
model = AutoModel.from_pretrained(
"edwinhere/namer",
trust_remote_code=True
)
# Create pipeline
pipe = NamerPipeline(model)
# Generate
result = pipe.generate(42) # "forty two"
result = pipe(42) # {"generated_text": "forty two"}
"""
def __init__(self, model: NamerModel, tokenizer=None, device: str = None):
if device is None:
device = "cuda" if torch.cuda.is_available() else "cpu"
self.model = model.to(device)
self.model.eval()
self.device = device
self.tokenizer = tokenizer # Placeholder if we add a tokenizer later
# Vocabulary mapping (index -> word)
# Must match utils.py vocabulary exactly
self.id2word = {
0: "zero", 1: "one", 2: "two", 3: "three", 4: "four",
5: "five", 6: "six", 7: "seven", 8: "eight", 9: "nine",
10: "ten", 11: "eleven", 12: "twelve", 13: "thirteen", 14: "fourteen",
15: "fifteen", 16: "sixteen", 17: "seventeen", 18: "eighteen", 19: "nineteen",
20: "twenty", 21: "thirty", 22: "forty", 23: "fifty",
24: "sixty", 25: "seventy", 26: "eighty", 27: "ninety",
28: "hundred",
29: "thousand", 30: "million", 31: "billion", 32: "trillion",
33: "quadrillion", 34: "quintillion", 35: "sextillion",
36: "septillion", 37: "octillion", 38: "nonillion", 39: "decillion",
40: "<EOS>"
}
# Reverse mapping
self.word2id = {v: k for k, v in self.id2word.items()}
def _int_to_digits(self, n: int) -> list[int]:
"""Convert integer to list of digit indices."""
if n == 0:
return [0]
digits = []
while n > 0:
digits.append(n % 10)
n //= 10
return digits[::-1] # Reverse to get most significant digit first
def _decode(self, token_ids: list[int]) -> str:
"""Decode token IDs to text, stopping at first EOS."""
words = []
eos_idx = self.model.config.eos_token_id # Should be 40
for idx in token_ids:
if idx == eos_idx: # Stop at EOS
break
if idx in self.id2word:
word = self.id2word[idx]
if word != "<EOS>": # Skip EOS token itself
words.append(word)
return " ".join(words) if words else "zero"
def generate(self, text: Union[str, int], **kwargs) -> str:
"""Generate English name for a number.
Args:
text: Integer or string representation of integer
Returns:
English name of the number
"""
# Parse input
if isinstance(text, str):
n = int(text.strip())
else:
n = int(text)
# Convert to digits
digits = self._int_to_digits(n)
# Pad to max length (20)
while len(digits) < 20:
digits.append(10) # padding token
# Create tensor
input_ids = torch.tensor([digits], dtype=torch.long).to(self.device)
# Forward pass
with torch.no_grad():
outputs = self.model(input_ids)
logits = outputs.logits
predictions = logits.argmax(dim=-1)[0].cpu().tolist()
# Decode
return self._decode(predictions)
def __call__(self, text: Union[str, int], **kwargs) -> dict:
"""Callable interface for pipeline.
Returns dict with 'generated_text' key for HF pipeline compatibility.
"""
result = self.generate(text, **kwargs)
return {"generated_text": result}
def load_namer_pipeline(model_name_or_path: str = "edwinhere/namer", device: str = None, **kwargs):
"""Load a Namer pipeline with model.
This is a convenience function that loads both the model and creates
a pipeline for easy inference.
Args:
model_name_or_path: HuggingFace model ID or local path
device: Device to run on ('cuda', 'cpu', or None for auto)
**kwargs: Additional args passed to from_pretrained
Returns:
NamerPipeline instance ready for inference
Example:
>>> pipe = load_namer_pipeline("edwinhere/namer")
>>> pipe.generate(42)
'forty two'
>>> pipe(123)
{'generated_text': 'one hundred twenty three'}
"""
from transformers import AutoModel
model = AutoModel.from_pretrained(
model_name_or_path,
trust_remote_code=True,
**kwargs
)
return NamerPipeline(model, device=device)
|