wincode commited on
Commit
ccf4695
·
verified ·
1 Parent(s): 2c46db6

Upload modeling_aetherstory.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_aetherstory.py +133 -0
modeling_aetherstory.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Minimal load+generate helper for the AetherStory model on Hugging Face.
2
+
3
+ Users can copy this file next to ``model.safetensors`` / ``config.json`` /
4
+ ``tokenizer.json`` and run::
5
+
6
+ from modeling_aetherstory import StoryTeller
7
+ t = StoryTeller.from_dir(".")
8
+ print(t("Once upon a time"))
9
+ """
10
+
11
+ import json
12
+ from pathlib import Path
13
+ import torch
14
+ import torch.nn as nn
15
+ import torch.nn.functional as F
16
+ from safetensors.torch import load_file
17
+
18
+
19
+ # --- model definition (mirrors src/model.py) -------------------------------
20
+ class _Attn(nn.Module):
21
+ def __init__(s, d, h, drop):
22
+ super().__init__()
23
+ s.h, s.hd, s.scale = h, d // h, (d // h) ** -0.5
24
+ s.qkv = nn.Linear(d, 3 * d, bias=False)
25
+ s.proj = nn.Linear(d, d, bias=False)
26
+ s.drop = nn.Dropout(drop)
27
+ def forward(s, x):
28
+ B, T, C = x.shape
29
+ qkv = s.qkv(x).reshape(B, T, 3, s.h, s.hd).permute(2, 0, 3, 1, 4)
30
+ q, k, v = qkv[0], qkv[1], qkv[2]
31
+ att = (q @ k.transpose(-2, -1)) * s.scale
32
+ att = att.masked_fill(~torch.tril(torch.ones(T, T, device=x.device, dtype=torch.bool)), float("-inf"))
33
+ att = s.drop(F.softmax(att, dim=-1))
34
+ y = (att @ v).transpose(1, 2).contiguous().reshape(B, T, C)
35
+ return s.drop(s.proj(y))
36
+
37
+
38
+ class _FFN(nn.Module):
39
+ def __init__(s, d, f, drop):
40
+ super().__init__()
41
+ s.fc1, s.fc2, s.drop = nn.Linear(d, f, bias=False), nn.Linear(f, d, bias=False), nn.Dropout(drop)
42
+ def forward(s, x):
43
+ return s.drop(s.fc2(F.gelu(s.fc1(x))))
44
+
45
+
46
+ class _Block(nn.Module):
47
+ def __init__(s, d, h, f, drop):
48
+ super().__init__()
49
+ s.ln1, s.attn = nn.LayerNorm(d), _Attn(d, h, drop)
50
+ s.ln2, s.ffn = nn.LayerNorm(d), _FFN(d, f, drop)
51
+ def forward(s, x):
52
+ x = x + s.attn(s.ln1(x)); x = x + s.ffn(s.ln2(x)); return x
53
+
54
+
55
+ class AetherStoryModel(nn.Module):
56
+ def __init__(s, cfg):
57
+ super().__init__()
58
+ s.cfg = cfg
59
+ s.tok_emb = nn.Embedding(cfg["vocab_size"], cfg["d_model"])
60
+ s.pos_emb = nn.Parameter(torch.zeros(1, cfg["max_seq_len"], cfg["d_model"]))
61
+ s.blocks = nn.ModuleList([_Block(cfg["d_model"], cfg["n_heads"], cfg["ffn_dim"], cfg["dropout"]) for _ in range(cfg["n_layers"])])
62
+ s.ln_f = nn.LayerNorm(cfg["d_model"])
63
+ if cfg.get("tie_embeddings", True):
64
+ s.head_bias = nn.Parameter(torch.zeros(cfg["vocab_size"])); s.lm_head = None
65
+ else:
66
+ s.head_bias = None; s.lm_head = nn.Linear(cfg["d_model"], cfg["vocab_size"], bias=False)
67
+ def forward(s, idx, targets=None):
68
+ B, T = idx.shape
69
+ x = s.tok_emb(idx) + s.pos_emb[:, :T, :]
70
+ for b in s.blocks: x = b(x)
71
+ x = s.ln_f(x)
72
+ logits = s.lm_head(x) if s.lm_head is not None else (x @ s.tok_emb.weight.t() + s.head_bias)
73
+ loss = None
74
+ if targets is not None:
75
+ loss = F.cross_entropy(logits.reshape(-1, s.cfg["vocab_size"]), targets.reshape(-1), ignore_index=s.cfg.get("pad_token_id", 0))
76
+ return logits, loss
77
+ @torch.no_grad()
78
+ def generate(s, idx, max_new, temperature=0.9, top_k=40, eos_token_id=None):
79
+ s.eval()
80
+ for _ in range(max_new):
81
+ ic = idx if idx.size(1) <= s.cfg["max_seq_len"] else idx[:, -s.cfg["max_seq_len"]:]
82
+ logits, _ = s(ic)
83
+ logits = logits[:, -1, :] / max(temperature, 1e-5)
84
+ if top_k and top_k > 0:
85
+ v, _ = torch.topk(logits, min(top_k, logits.size(-1)))
86
+ logits[logits < v[:, [-1]]] = float("-inf")
87
+ nxt = torch.multinomial(F.softmax(logits, dim=-1), num_samples=1)
88
+ idx = torch.cat([idx, nxt], dim=1)
89
+ if eos_token_id is not None and (nxt == eos_token_id).all(): break
90
+ return idx
91
+
92
+
93
+ class StoryTeller:
94
+ @classmethod
95
+ def from_dir(cls, d="."):
96
+ d = Path(d)
97
+ cfg = json.loads((d / "config.json").read_text(encoding="utf-8"))
98
+ tok_payload = json.loads((d / "tokenizer.json").read_text(encoding="utf-8"))
99
+ model = AetherStoryModel(cfg)
100
+ state = load_file(str(d / "model.safetensors"))
101
+ model.load_state_dict({k: v for k, v in state.items()})
102
+ model.eval()
103
+ w2i = {}
104
+ for word, idx in tok_payload["special_tokens"].items(): w2i[word] = idx
105
+ for idx, word in enumerate(tok_payload["vocab"]):
106
+ if idx not in w2i: w2i[word] = idx
107
+ i2w = {v: k for k, v in w2i.items()}
108
+ inst = cls(); inst.model = model; inst.w2i = w2i; inst.i2w = i2w
109
+ inst.bos = tok_payload["special_tokens"]["<bos>"]; inst.eos = tok_payload["special_tokens"]["<eos>"]
110
+ return inst
111
+ def _encode(self, text):
112
+ import re
113
+ ids = [self.bos]
114
+ for t in re.findall(r"\w+|[^\w\s]|\s+", text.lower()):
115
+ if t.strip() and t in self.w2i: ids.append(self.w2i[t])
116
+ return ids
117
+ def _decode(self, ids):
118
+ out = []
119
+ for i in ids:
120
+ if i == self.bos or i == 0: continue
121
+ if i == self.eos: break
122
+ w = self.i2w.get(i, "")
123
+ if w.startswith("<") and w.endswith(">"): continue
124
+ out.append(w)
125
+ t = " ".join(out)
126
+ import re
127
+ return re.sub(r"\s+([,.;:!?\'\"()])", r"\1", t).strip()
128
+ def __call__(self, prompt, max_tokens=80, temperature=0.9, top_k=40, seed=None):
129
+ if seed is not None: torch.manual_seed(seed)
130
+ ids = self._encode(prompt)
131
+ idx = torch.tensor([ids], dtype=torch.long)
132
+ out = self.model.generate(idx, max_tokens, temperature, top_k, self.eos)
133
+ return self._decode(out[0].tolist())