lowerkey commited on
Commit
02afb58
·
verified ·
1 Parent(s): d669858

Upload folder using huggingface_hub

Browse files
Files changed (11) hide show
  1. .gitattributes +1 -0
  2. README.md +173 -0
  3. bard_core.py +516 -0
  4. bard_game.py +442 -0
  5. bard_tokenizer.py +106 -0
  6. config.json +22 -0
  7. configuration_bard.py +35 -0
  8. fictionet-16k.vocab +3 -0
  9. format.txt +5 -0
  10. model.safetensors +3 -0
  11. modeling_bard.py +115 -0
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ fictionet-16k.vocab filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language: en
3
+ license: apache-2.0
4
+ library_name: transformers
5
+ pipeline_tag: text-generation
6
+ tags:
7
+ - interactive-fiction
8
+ - text-adventure
9
+ - storytelling
10
+ - custom_code
11
+ ---
12
+
13
+ # bard-small
14
+
15
+ A 137M parameter model that runs text adventures. You give it a first line, it writes the next bit of the story, says
16
+ what changed (money, health, whatever) and offers a few choices. Pick one, or type your own thing, and it carries on.
17
+
18
+ I trained it from scratch for a game I made, [Stochastic Lands of Prophecy](https://slop.szymon.space), where it runs
19
+ completely in your browser (no server, nothing you write leaves your device). You can play with it right there, or in
20
+ the [Space](https://huggingface.co/spaces/lowerkey/stochastic-lands-of-prophecy). This repo has the weights and all
21
+ the code around them (tokenizer, number handling, the game rules), so it also works with plain `transformers`.
22
+
23
+ ## What it writes
24
+
25
+ This is the start of a tale, with the opening `You arrive at the gates of the old castle.` and the first choice picked
26
+ (it's from a handful of runs, one of the better ones):
27
+
28
+ ```
29
+ You arrive at the gates of the old castle. “You’ve come a long way, little Prince. The guards say that you are only
30
+ here for a few days. If you wish for it, I can take you back home and live somewhere else. Just tell me where your
31
+ home is and the guards will let you pass.”
32
+
33
+ This request really brings a smile to your face. The king asks you to accompany him to his manor and there you will
34
+ learn more.
35
+
36
+ The gate opens and you follow him inside. He takes a deep breath before leading you into a room. You see a man sitting
37
+ on a chair.
38
+
39
+ “I have a question for you son,” he says with a smile.
40
+
41
+ 1. “What do you want to ask me?”
42
+ 2. “What will you be doing now?”
43
+ 3. “What is your name?”
44
+
45
+ > “What do you want to ask me?”
46
+
47
+ “Well, Prince, I have been summoned to King Arthur’s castle and I have come to ask for your help. Do you know where
48
+ your home is located?”
49
+
50
+ You think about this for a moment. The king is waiting for you to speak but he already knows.
51
+ ...
52
+ ```
53
+
54
+ It doesn't stay on track for long (see the bit about limits at the end), but each turn reads like a scene and the
55
+ choices are usually things you can actually do.
56
+
57
+ ## Quick start
58
+
59
+ ```python
60
+ # pip install torch transformers tokenmonster
61
+ from transformers import AutoModelForCausalLM
62
+
63
+ bard = AutoModelForCausalLM.from_pretrained("lowerkey/bard-small", trust_remote_code=True)
64
+
65
+ tale = bard.begin("You wake up in a dungeon.")
66
+ print(tale.text) # what the model wrote
67
+ print(tale.choices) # what you can do next
68
+
69
+ tale = bard.act(tale, tale.choices[0]) # take one of the choices
70
+ tale = bard.act(tale, "I ask the guard about the key") # or type your own
71
+ ```
72
+
73
+ `bard.play()` runs the same loop in the terminal if you just want to try it.
74
+
75
+ `begin` takes a few options: `length` ("short", "medium" or "long", how much it writes per turn), `state` (the things
76
+ the player carries, default `{"money": 100}`), `seed`, and `on_text`, a function that gets the text piece by piece
77
+ while it's being written.
78
+
79
+ A tale is just a little dataclass. The whole story lives in `tale.history` (a string), so saving it is
80
+ `tale.to_dict()` and loading it is `Tale.from_dict(d)`.
81
+
82
+ On a GPU load it in bf16, `from_pretrained(..., dtype=torch.bfloat16).to("cuda")` (it's `torch_dtype=` on older
83
+ transformers versions). A turn takes about a second there and a few seconds on a CPU. I tried it on transformers 4.46
84
+ and 5.19.
85
+
86
+ `trust_remote_code=True` is needed because the architecture isn't in transformers. The code it runs is the `.py` files
87
+ in this repo, you can read them.
88
+
89
+ ## Why not `generate()`
90
+
91
+ Numbers are handled separately. Every run of digits in the text becomes a single `<|num|>` token, and the actual value
92
+ goes in a second stream next to the token ids. A small encoder turns it into a vector that's added to the embedding, and
93
+ when the model wants to write a number a small decoder predicts the digits. So the input is two tensors (`input_ids`
94
+ and `number_values`) and the normal `generate()` doesn't know about the second one. `bard.begin` and `bard.act` do all
95
+ of this for you. If you want the raw logits, `bard(input_ids, number_values).logits` works.
96
+
97
+ ## The format
98
+
99
+ A tale is a list of blocks, and each block looks like this:
100
+
101
+ ```
102
+ <|start|>ROLE<|content|>text<|end|>
103
+ ```
104
+
105
+ There are three roles.
106
+
107
+ **state** is written by the game, not the model. It lists what the player has. Each thing is its name, a newline and
108
+ its value, and the things are separated by `<|sep|>`. After every turn the game puts a fresh state block in.
109
+
110
+ **player** is what the player did: the text of the choice they took, or whatever they typed.
111
+
112
+ **story** is written by the model, and it has up to three parts in a fixed order. First the narration. Then, if
113
+ anything changed, `<|vars|>` followed by the changes, separated by `<|sep|>`. A change is a name, then `<|add|>` or
114
+ `<|set|>`, then a number. Last, `<|choices|>` followed by the choices, again separated by `<|sep|>`. If the model
115
+ writes a story block with no choices at all, the tale is over.
116
+
117
+ Here's a short one:
118
+
119
+ ```
120
+ <|start|>state<|content|>money
121
+ 100<|end|>
122
+ <|start|>story<|content|>The guard looks at your coin purse and smiles.<|vars|>money<|add|>-20<|choices|>Pay him<|sep|>Run<|end|>
123
+ <|start|>state<|content|>money
124
+ 80<|end|>
125
+ <|start|>player<|content|>Pay him<|end|>
126
+ <|start|>story<|content|>He steps aside and the door swings open. ...
127
+ ```
128
+
129
+ (That's the rough shape. The first story block would really be a longer passage, and the model could add a second
130
+ variable like `rusty key<|set|>1`.)
131
+
132
+ The role headers (`<|start|>story` and so on) are single tokens, and so are all the markers. The model only ever
133
+ writes inside story blocks. The game is the only thing that writes state and player blocks.
134
+
135
+ The changes the model proposes are only proposals. A 137M model will happily write `money -400` when you have 100, or
136
+ take your money after a fight with no coins in it, so `bard_game.py` checks them. A change to money only goes through
137
+ if the passage actually talks about money, amounts can't go below zero or jump by more than ten times, and so on.
138
+ The same file keeps passages from running on forever and makes sure the model offers at least two different choices.
139
+
140
+ ## About the model
141
+
142
+ | | |
143
+ |---|---|
144
+ | Parameters | 136.7M |
145
+ | Layers, width, heads | 36, 512, 8 |
146
+ | Attention | sliding window of 256 with a global layer every 4th, RoPE on the windowed layers only, QK-norm, gated |
147
+ | Blocks | attention and SwiGLU in parallel, one fused matmul in, one out |
148
+ | Context | 4096 tokens (older text falls off the back as the tale goes on) |
149
+ | Vocabulary | 16,128 ids, tokenmonster `fiction-16000-strict-v1` plus the special tokens above |
150
+ | Weights | bf16, `model.safetensors`, 273 MB |
151
+
152
+ ## Training
153
+
154
+ Three stages, all from scratch. First plain English (FineWeb-Edu, about 11B tokens). Then fiction: Royal Road
155
+ stories, Project Gutenberg fiction, WritingPrompts and BookCorpus, with some FineWeb mixed back in. Last, the
156
+ interactive part: choose-your-own-adventure stories, turned into the block format above, so it learns to write
157
+ narration, changes and choices in that shape.
158
+
159
+ ## What it's bad at
160
+
161
+ A lot of things. It's small. Names and details change from one turn to the next, the plot wanders, and sometimes a turn
162
+ makes no sense at all. It feels more like a dream than a story. If it goes off the rails, pick a different choice or
163
+ write your own, that usually fixes it.
164
+
165
+ It was trained on web text and fiction, some of it for adults, and I didn't do any safety tuning. It can write violent,
166
+ sexual or biased stuff. Don't use it for anything that matters.
167
+
168
+ ## License and data
169
+
170
+ The weights and the code here are Apache 2.0. The training data is publicly available text from the sources listed
171
+ above. Some of it (Royal Road, BookCorpus) belongs to its authors and has its own terms, so if you want to build
172
+ something on top of the weights, check that they work for what you're doing. The tokenizer vocabulary comes from
173
+ tokenmonster's `fiction-16000-strict-v1` (MIT).
bard_core.py ADDED
@@ -0,0 +1,516 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The network of bard-small, taken whole from the training code (fictionet/model.py, numhead.py, train/pretrain.py): windowed attention with a key/value cache, the number encoder/decoder, the LM."""
2
+ import re
3
+ import math
4
+ import time
5
+ from functools import lru_cache
6
+
7
+ import torch
8
+ from torch import nn
9
+ from torch.nn import functional as F
10
+ try: # only the training path (and a full forward without a cache) uses it
11
+ from torch.nn.attention.flex_attention import create_block_mask, flex_attention
12
+ except ImportError: # pragma: no cover
13
+ create_block_mask = flex_attention = None
14
+ from torch.utils.checkpoint import checkpoint
15
+
16
+
17
+ @lru_cache(maxsize=32)
18
+ def sliding_window_block_mask(T: int, window: int, device: str):
19
+ def mask_mod(b, h, q_idx, kv_idx):
20
+ causal = q_idx >= kv_idx
21
+ in_window = (q_idx - kv_idx) < window
22
+ return causal & in_window
23
+
24
+ return create_block_mask(mask_mod, B=None, H=None, Q_LEN=T, KV_LEN=T, device=device)
25
+
26
+
27
+ def apply_rope(x, base=10000.0, offset=0):
28
+ """Rotary embedding on (B, H, T, D) for absolute positions offset .. offset+T-1.
29
+ Frequencies are built in fp32 inside forward, so a .bfloat16() model cast can't
30
+ quantise them (a registered buffer would get cast)."""
31
+ T, D = x.shape[-2], x.shape[-1]
32
+ inv_freq = base ** (-torch.arange(0, D, 2, device=x.device, dtype=torch.float32) / D)
33
+ ang = torch.arange(offset, offset + T, device=x.device, dtype=torch.float32)[:, None] * inv_freq
34
+ cos, sin = ang.cos().to(x.dtype), ang.sin().to(x.dtype)
35
+ x1, x2 = x[..., : D // 2], x[..., D // 2:]
36
+ return torch.cat([x1 * cos - x2 * sin, x1 * sin + x2 * cos], dim=-1)
37
+
38
+
39
+ class LayerKV:
40
+ """One layer's cached keys and values, (B, H, S, D), in a buffer that grows by doubling.
41
+
42
+ Keys are stored after RoPE, at their absolute positions, so they never need
43
+ re-rotating. A sliding-window layer keeps only the last `window - 1` keys - all
44
+ any later query can still see - so its memory stays bounded however long the
45
+ sequence runs; the kept span is moved to the front only when the buffer fills.
46
+ """
47
+
48
+ def __init__(self, window):
49
+ self.window = window
50
+ self.k = self.v = None # buffers
51
+ self.lo = self.hi = 0 # live span [lo, hi) of the buffers
52
+ self.start = 0 # absolute position of the key at `lo`
53
+
54
+ def append(self, k, v):
55
+ """Add T new keys/values; return all visible keys, values and the absolute
56
+ position of the first of them."""
57
+ T = k.shape[2]
58
+ if self.k is None:
59
+ cap = max(64, 2 * T)
60
+ self.k = k.new_empty(k.shape[:2] + (cap,) + k.shape[3:])
61
+ self.v = v.new_empty(self.k.shape)
62
+ elif self.hi + T > self.k.shape[2]:
63
+ live = self.hi - self.lo
64
+ cap = self.k.shape[2]
65
+ if live + T > cap // 2: # still mostly full after compacting: grow
66
+ cap = 2 * (live + T)
67
+ k_buf = self.k.new_empty(self.k.shape[:2] + (cap,) + self.k.shape[3:])
68
+ v_buf = self.v.new_empty(k_buf.shape)
69
+ k_buf[:, :, :live] = self.k[:, :, self.lo:self.hi]
70
+ v_buf[:, :, :live] = self.v[:, :, self.lo:self.hi]
71
+ self.k, self.v, self.lo, self.hi = k_buf, v_buf, 0, live
72
+ self.k[:, :, self.hi:self.hi + T] = k
73
+ self.v[:, :, self.hi:self.hi + T] = v
74
+ self.hi += T
75
+ return self.k[:, :, self.lo:self.hi], self.v[:, :, self.lo:self.hi], self.start
76
+
77
+ def trim(self):
78
+ """After this step's attention: forget keys no future query can reach."""
79
+ if self.window is not None and self.hi - self.lo > self.window - 1:
80
+ drop = self.hi - self.lo - (self.window - 1)
81
+ self.lo += drop
82
+ self.start += drop
83
+
84
+
85
+ class KVCache:
86
+ """Keys/values for every block of a CausalTransformer, plus how many tokens it has
87
+ seen. Pass it to CausalTransformer.forward (or LM.hidden) to process only the new
88
+ tokens: any number of them, on top of any amount already cached."""
89
+
90
+ def __init__(self, transformer):
91
+ self.windows = [block.window for block in transformer.blocks]
92
+ self.reset()
93
+
94
+ def reset(self):
95
+ self.layers = [LayerKV(w) for w in self.windows]
96
+ self.pos = 0
97
+
98
+ def __len__(self):
99
+ return self.pos
100
+
101
+
102
+ def attend(q, k, v, rope, window, block_mask, cache=None, pos=0):
103
+ """Causal (optionally sliding-window) attention for (B, H, T, D) q/k/v.
104
+
105
+ Without a cache this is exactly the training path. With one, q/k/v hold only the
106
+ T new tokens at absolute positions pos .. pos+T-1: keys are rotated at those
107
+ positions, appended to the cache, and the queries attend over cached + new keys
108
+ under the true mask - key <= query, and query - key < window on sliding-window
109
+ layers - so a chunk of any length (including one crossing the window edge) sees
110
+ exactly what it would in a full forward pass.
111
+ """
112
+ if cache is None:
113
+ if rope:
114
+ q, k = apply_rope(q), apply_rope(k)
115
+ if block_mask is None:
116
+ return F.scaled_dot_product_attention(q, k, v, is_causal=True)
117
+ return flex_attention(q, k, v, block_mask=block_mask)
118
+
119
+ T = q.shape[2]
120
+ if rope:
121
+ q, k = apply_rope(q, offset=pos), apply_rope(k, offset=pos)
122
+ k_all, v_all, k_start = cache.append(k, v)
123
+ S = k_all.shape[2]
124
+ if T == 1 and (window is None or S <= window):
125
+ out = F.scaled_dot_product_attention(q, k_all, v_all) # decode: all visible
126
+ elif S == T and (window is None or T <= window):
127
+ out = F.scaled_dot_product_attention(q, k_all, v_all, is_causal=True) # fresh prefill
128
+ else:
129
+ q_pos = torch.arange(pos, pos + T, device=q.device)[:, None]
130
+ k_pos = torch.arange(k_start, k_start + S, device=q.device)[None, :]
131
+ mask = k_pos <= q_pos
132
+ if window is not None:
133
+ mask = mask & (q_pos - k_pos < window)
134
+ out = F.scaled_dot_product_attention(q, k_all, v_all, attn_mask=mask)
135
+ cache.trim()
136
+ return out
137
+
138
+
139
+ class Attention(nn.Module):
140
+ def __init__(self, d_model, heads, window=None, rope=False):
141
+ super().__init__()
142
+ assert d_model % heads == 0
143
+ self.d_model = d_model
144
+ self.heads = heads
145
+ self.head_dim = d_model // heads
146
+ self.window = window # None -> global causal attention
147
+ self.rope = rope
148
+
149
+ self.qkvg = nn.Linear(d_model, 4 * d_model, bias=False)
150
+ self.out = nn.Linear(d_model, d_model, bias=False)
151
+
152
+ self.qnorm = nn.RMSNorm(self.head_dim)
153
+ self.knorm = nn.RMSNorm(self.head_dim)
154
+
155
+ def forward(self, x, block_mask=None, cache=None, pos=0):
156
+ B, T, E = x.shape
157
+ H, D = self.heads, self.head_dim
158
+
159
+ q, k, v, g = self.qkvg(x).split(self.d_model, dim=-1)
160
+
161
+ q = self.qnorm(q.view(B, T, H, D)).transpose(1, 2)
162
+ k = self.knorm(k.view(B, T, H, D)).transpose(1, 2)
163
+ v = v.view(B, T, H, D).transpose(1, 2)
164
+ out = attend(q, k, v, self.rope, self.window, block_mask, cache, pos)
165
+
166
+ out = out.transpose(1, 2).reshape(B, T, E)
167
+
168
+ out = out * torch.sigmoid(g)
169
+ return self.out(out)
170
+
171
+
172
+ class FFN(nn.Module):
173
+ def __init__(self, d_model, expansion=4, match_naive_params=True):
174
+ super().__init__()
175
+ hidden = d_model * expansion
176
+ if match_naive_params:
177
+ hidden = int(hidden * 2 / 3)
178
+ hidden = max(128, (hidden // 128) * 128)
179
+ self.hidden = hidden
180
+
181
+ self.W_gate_up = nn.Linear(d_model, 2 * hidden, bias=False)
182
+ self.W_down = nn.Linear(hidden, d_model, bias=False)
183
+
184
+ def forward(self, x):
185
+ gate, value = self.W_gate_up(x).chunk(2, dim=-1)
186
+ return self.W_down(F.silu(gate) * value)
187
+
188
+
189
+ class Block(nn.Module):
190
+ def __init__(self, d_model, heads, ffn_expansion=4, window=None, rope=False):
191
+ super().__init__()
192
+ self.attn = Attention(d_model, heads, window, rope)
193
+ self.ffn = FFN(d_model, ffn_expansion)
194
+ self.norm1 = nn.RMSNorm(d_model)
195
+ self.norm2 = nn.RMSNorm(d_model)
196
+
197
+ @property
198
+ def window(self):
199
+ return self.attn.window
200
+
201
+ def forward(self, x, block_mask=None, cache=None, pos=0):
202
+ x = x + self.attn(self.norm1(x), block_mask, cache, pos)
203
+ x = x + self.ffn(self.norm2(x))
204
+ return x
205
+
206
+
207
+ class ParallelBlock(nn.Module):
208
+ """PaLM-style parallel block: x + Attn(norm(x)) + FFN(norm(x)), actually fused.
209
+
210
+ One norm; ONE input matmul producing q|k|v|g|gate|up; ONE output matmul over
211
+ [gated attn | swiglu] (= attn.out and W_down stacked along the input dim, which is
212
+ exactly out(a) + W_down(f)). 2 matmuls per block instead of 4, each wider, which is
213
+ what a narrow model on a small GPU needs to keep the tensor cores fed.
214
+ """
215
+
216
+ def __init__(self, d_model, heads, ffn_expansion=4, window=None, rope=False):
217
+ super().__init__()
218
+ assert d_model % heads == 0
219
+ self.d_model, self.heads, self.head_dim = d_model, heads, d_model // heads
220
+ self.window = window
221
+ self.rope = rope
222
+ hidden = int(d_model * ffn_expansion * 2 / 3)
223
+ self.hidden = max(128, (hidden // 128) * 128)
224
+
225
+ self.norm = nn.RMSNorm(d_model)
226
+ self.W_in = nn.Linear(d_model, 4 * d_model + 2 * self.hidden, bias=False)
227
+ self.W_out = nn.Linear(d_model + self.hidden, d_model, bias=False)
228
+ self.qnorm = nn.RMSNorm(self.head_dim)
229
+ self.knorm = nn.RMSNorm(self.head_dim)
230
+
231
+ def forward(self, x, block_mask=None, cache=None, pos=0):
232
+ B, T, E = x.shape
233
+ H, D = self.heads, self.head_dim
234
+ q, k, v, g, gate, up = self.W_in(self.norm(x)).split(
235
+ [E, E, E, E, self.hidden, self.hidden], dim=-1)
236
+
237
+ q = self.qnorm(q.view(B, T, H, D)).transpose(1, 2)
238
+ k = self.knorm(k.view(B, T, H, D)).transpose(1, 2)
239
+ v = v.view(B, T, H, D).transpose(1, 2)
240
+ a = attend(q, k, v, self.rope, self.window, block_mask, cache, pos)
241
+ a = a.transpose(1, 2).reshape(B, T, E) * torch.sigmoid(g)
242
+
243
+ f = F.silu(gate) * up
244
+ return x + self.W_out(torch.cat([a, f], dim=-1))
245
+
246
+
247
+ def _init_weights(module):
248
+ if isinstance(module, nn.Linear):
249
+ nn.init.normal_(module.weight, mean=0.0, std=0.02)
250
+ if module.bias is not None:
251
+ nn.init.zeros_(module.bias)
252
+
253
+
254
+ class CausalTransformer(nn.Module):
255
+ def __init__(
256
+ self,
257
+ d_model: int,
258
+ heads: int,
259
+ n_blocks: int,
260
+ ffn_expansion: int = 4,
261
+ window: int = 1024,
262
+ global_every: int = 4,
263
+ grad_checkpoint: bool = True,
264
+ compile_blocks: bool = True,
265
+ parallel: bool = False,
266
+ rope: str = "local",
267
+ ):
268
+ """rope: "local" = RoPE on sliding-window layers, NoPE on global ones (RNoPE-SWA,
269
+ Yang et al. 2025; SmolLM3 ablation at 3B: better long context, no short-context
270
+ cost; NoPE LMs stay competitive down to ~250M, Haviv et al. 2022), "all", or "none"."""
271
+ super().__init__()
272
+ self.grad_checkpoint = grad_checkpoint
273
+
274
+ windows = []
275
+ for i in range(n_blocks):
276
+ is_global = ((i + 1) % global_every == 0) or (i == n_blocks - 1)
277
+ windows.append(None if is_global else window)
278
+ self.windows = windows
279
+
280
+ block_cls = ParallelBlock if parallel else Block
281
+ self.blocks = nn.ModuleList(
282
+ [block_cls(d_model, heads, ffn_expansion, w,
283
+ rope=(rope == "all" or (rope == "local" and w is not None)))
284
+ for w in windows]
285
+ )
286
+ self.norm = nn.RMSNorm(d_model)
287
+
288
+ self.apply(_init_weights)
289
+ residual_std = 0.02 / math.sqrt(2 * n_blocks)
290
+ for block in self.blocks:
291
+ if parallel:
292
+ nn.init.normal_(block.W_out.weight, mean=0.0, std=residual_std)
293
+ else:
294
+ nn.init.normal_(block.attn.out.weight, mean=0.0, std=residual_std)
295
+ nn.init.normal_(block.ffn.W_down.weight, mean=0.0, std=residual_std)
296
+
297
+ if compile_blocks:
298
+ for block in self.blocks:
299
+ block.compile()
300
+
301
+ def block_masks(self, T, device):
302
+ return {
303
+ w: sliding_window_block_mask(T, w, str(device))
304
+ for w in set(self.windows)
305
+ if w is not None and w < T
306
+ }
307
+
308
+ cache_offset = 0
309
+ """While a cached forward runs: the absolute position of x[:, 0] (hooks that index
310
+ positions, like steering, need it). 0 otherwise."""
311
+
312
+ def forward(self, x, masks=None, cache=None):
313
+ """masks: precomputed block_masks(T, device); pass them when this runs inside an outer
314
+ torch.compile, so mask construction stays out of the compiled graph.
315
+
316
+ cache: a KVCache. x then holds only the tokens not yet in it (any number), the
317
+ cache is extended with them, and the result is identical to running the whole
318
+ sequence - at the cost of the new tokens only."""
319
+ if cache is not None:
320
+ pos = cache.pos
321
+ self.cache_offset = pos
322
+ try:
323
+ for block, layer_cache in zip(self.blocks, cache.layers):
324
+ x = block(x, None, layer_cache, pos)
325
+ finally:
326
+ self.cache_offset = 0
327
+ cache.pos += x.shape[1]
328
+ return self.norm(x)
329
+
330
+ if masks is None:
331
+ masks = self.block_masks(x.shape[1], x.device)
332
+
333
+ for block in self.blocks:
334
+ m = masks.get(block.window)
335
+ if self.grad_checkpoint and self.training:
336
+ x = checkpoint(block, x, m, use_reentrant=False)
337
+ else:
338
+ x = block(x, m)
339
+
340
+ return self.norm(x)
341
+
342
+
343
+ # ----------------------------------------------------------------------------- numbers
344
+
345
+ import re # noqa: E402
346
+
347
+ MAX_DIGITS = 8 # 10**8 - 1 < 2**27
348
+ LEN_SHIFT = 27
349
+ VALUE_MASK = (1 << LEN_SHIFT) - 1
350
+
351
+ NUMBER_RE = re.compile(r"( ?)([0-9]+)")
352
+
353
+
354
+ # ----------------------------------------------------------------------------- packing
355
+
356
+ def pack(digits: str) -> int:
357
+ assert 0 < len(digits) <= MAX_DIGITS
358
+ return int(digits) | (len(digits) << LEN_SHIFT)
359
+
360
+
361
+ def unpack(packed: int) -> str:
362
+ return str(packed & VALUE_MASK).zfill(packed >> LEN_SHIFT)
363
+
364
+
365
+ def split_numbers(text):
366
+ """-> list of str (text segment) and (spaced: bool, packed: int) items, in order."""
367
+ out, pos = [], 0
368
+ for m in NUMBER_RE.finditer(text):
369
+ if m.start() > pos:
370
+ out.append(text[pos:m.start()])
371
+ spaced, digits = bool(m.group(1)), m.group(2)
372
+ for i in range(0, len(digits), MAX_DIGITS):
373
+ out.append((spaced and i == 0, pack(digits[i:i + MAX_DIGITS])))
374
+ pos = m.end()
375
+ if pos < len(text):
376
+ out.append(text[pos:])
377
+ return out
378
+
379
+
380
+ def _lengths_values(packed):
381
+ packed = packed.long()
382
+ return packed >> LEN_SHIFT, packed & VALUE_MASK
383
+
384
+
385
+ def _pow10(n, device):
386
+ return 10 ** torch.arange(n, device=device, dtype=torch.long)
387
+
388
+
389
+ # ----------------------------------------------------------------------------- encoder
390
+
391
+ class NumberEncoder(nn.Module):
392
+ def __init__(self, d_model, n_freq=4):
393
+ super().__init__()
394
+ self.n_freq = n_freq
395
+ n_feat = MAX_DIGITS * (2 * n_freq + 1) + MAX_DIGITS + 1
396
+ self.mlp = nn.Sequential(nn.Linear(n_feat, d_model), nn.SiLU(), nn.Linear(d_model, d_model))
397
+ for m in self.mlp:
398
+ if isinstance(m, nn.Linear):
399
+ nn.init.normal_(m.weight, std=0.02)
400
+ nn.init.zeros_(m.bias)
401
+
402
+ def forward(self, packed):
403
+ """packed: (...) int, 0 where the token is not a number -> (..., d_model), zero there."""
404
+ L, value = _lengths_values(packed)
405
+ digits = value.unsqueeze(-1) // _pow10(MAX_DIGITS, packed.device) % 10 # LSB first
406
+ present = (torch.arange(MAX_DIGITS, device=packed.device) < L.unsqueeze(-1)).float()
407
+ freqs = torch.arange(1, self.n_freq + 1, dtype=torch.float32, device=packed.device)
408
+ angle = 2 * math.pi * digits.float().unsqueeze(-1) / 10 * freqs
409
+ places = torch.cat([angle.sin(), angle.cos()], -1) * present.unsqueeze(-1)
410
+ feats = torch.cat([
411
+ places.flatten(-2),
412
+ present,
413
+ F.one_hot((L - 1).clamp(min=0), MAX_DIGITS).float() * (L > 0).unsqueeze(-1),
414
+ (torch.log10(value.float() + 1) / MAX_DIGITS).unsqueeze(-1),
415
+ ], -1)
416
+ out = self.mlp(feats.to(self.mlp[0].weight.dtype))
417
+ return out * (packed != 0).unsqueeze(-1).to(out.dtype)
418
+
419
+
420
+ # ----------------------------------------------------------------------------- decoder
421
+
422
+ class NumberDecoder(nn.Module):
423
+ def __init__(self, d_model, width=256, heads=4, layers=2):
424
+ super().__init__()
425
+ self.len_head = nn.Sequential(nn.Linear(d_model, width, bias=False), nn.SiLU(),
426
+ nn.Linear(width, MAX_DIGITS, bias=False))
427
+ self.ctx = nn.Linear(d_model, width, bias=False)
428
+ self.len_emb = nn.Embedding(MAX_DIGITS, width)
429
+ self.place_emb = nn.Embedding(MAX_DIGITS, width) # power of ten of the slot
430
+ self.prev_emb = nn.Embedding(11, width) # previous digit, 10 = start
431
+ self.blocks = nn.ModuleList([Block(width, heads) for _ in range(layers)])
432
+ self.norm = nn.RMSNorm(width)
433
+ self.out = nn.Linear(width, 10, bias=False)
434
+ for m in self.modules():
435
+ if isinstance(m, (nn.Linear, nn.Embedding)):
436
+ nn.init.normal_(m.weight, std=0.02)
437
+ for b in self.blocks:
438
+ nn.init.normal_(b.attn.out.weight, std=0.02 / math.sqrt(2 * layers))
439
+ nn.init.normal_(b.ffn.W_down.weight, std=0.02 / math.sqrt(2 * layers))
440
+
441
+ def _digit_logits(self, h, L, prev):
442
+ """h (N, d), L (N,) in 1..MAX, prev (N, MAX) previous-digit ids -> (N, MAX, 10)."""
443
+ j = torch.arange(MAX_DIGITS, device=h.device)
444
+ power = (L.unsqueeze(-1) - 1 - j).clamp(min=0) # slots past L are masked anyway
445
+ x = (self.ctx(h) + self.len_emb(L - 1)).unsqueeze(1) + self.place_emb(power) + self.prev_emb(prev)
446
+ for b in self.blocks:
447
+ x = b(x) # no mask -> causal SDPA
448
+ return self.out(self.norm(x))
449
+
450
+ @staticmethod
451
+ def _msb_digits(packed):
452
+ L, value = _lengths_values(packed)
453
+ power = (L.unsqueeze(-1) - 1 - torch.arange(MAX_DIGITS, device=packed.device)).clamp(min=0)
454
+ digits = value.unsqueeze(-1) // (10 ** power) % 10
455
+ valid = torch.arange(MAX_DIGITS, device=packed.device) < L.unsqueeze(-1)
456
+ return L, digits, valid
457
+
458
+ def nll(self, h, packed, weight=None):
459
+ """Summed NLL (length + every digit) of the target numbers. h (N, d), packed (N,).
460
+ weight (N,) masks padding rows, so N can be a fixed capacity (static shapes -> compile);
461
+ padded rows must still hold a valid packed number (e.g. pack("0"))."""
462
+ L, digits, valid = self._msb_digits(packed)
463
+ prev = torch.cat([torch.full_like(digits[:, :1], 10), digits[:, :-1]], 1)
464
+ len_nll = F.cross_entropy(self.len_head(h).float(), L - 1, reduction="none")
465
+ logits = self._digit_logits(h, L, prev).float()
466
+ dig_nll = F.cross_entropy(logits.view(-1, 10), digits.view(-1), reduction="none")
467
+ per_num = len_nll + (dig_nll.view_as(digits) * valid).sum(-1)
468
+ return per_num.sum() if weight is None else (per_num * weight).sum()
469
+
470
+ @torch.no_grad()
471
+ def generate(self, h, temperature=0.0):
472
+ """h (N, d) -> packed numbers (N,). temperature 0 = greedy."""
473
+ def pick(logits):
474
+ if temperature <= 0:
475
+ return logits.argmax(-1)
476
+ return torch.multinomial(F.softmax(logits.float() / temperature, -1), 1).squeeze(-1)
477
+
478
+ L = pick(self.len_head(h)) + 1
479
+ prev = torch.full((h.shape[0], MAX_DIGITS), 10, dtype=torch.long, device=h.device)
480
+ digits = torch.zeros_like(prev)
481
+ for j in range(MAX_DIGITS):
482
+ digits[:, j] = pick(self._digit_logits(h, L, prev)[:, j])
483
+ if j + 1 < MAX_DIGITS:
484
+ prev[:, j + 1] = digits[:, j]
485
+ power = (L.unsqueeze(-1) - 1 - torch.arange(MAX_DIGITS, device=h.device)).clamp(min=0)
486
+ valid = torch.arange(MAX_DIGITS, device=h.device) < L.unsqueeze(-1)
487
+ value = (digits * 10 ** power * valid).sum(-1)
488
+ return value | (L << LEN_SHIFT)
489
+
490
+
491
+ # ----------------------------------------------------------------------------- the language model
492
+
493
+ LOGIT_SOFTCAP = 30.0
494
+
495
+
496
+ def softcap(logits):
497
+ # Gemma 2 / modded-nanogpt: bounds the logits smoothly
498
+ return LOGIT_SOFTCAP * torch.tanh(logits.float() / LOGIT_SOFTCAP)
499
+
500
+
501
+ class LM(nn.Module):
502
+ """Token LM + dedicated number path: <|num|>/<|snum|> inputs get NumberEncoder(value) added to their embedding;
503
+ where the next token is a number, NumberDecoder predicts its digits."""
504
+
505
+ def __init__(self, vocab, d_model, heads, n_blocks, window, global_every, parallel=True, rope="local"):
506
+ super().__init__()
507
+ self.emb = nn.Embedding(vocab, d_model)
508
+ self.num_enc = NumberEncoder(d_model)
509
+ self.body = CausalTransformer(d_model, heads, n_blocks, window=window, global_every=global_every,
510
+ grad_checkpoint=False, parallel=parallel, rope=rope, compile_blocks=False)
511
+ self.head = nn.Linear(d_model, vocab, bias=False)
512
+ self.num_dec = NumberDecoder(d_model)
513
+
514
+ def hidden(self, idx, vals, masks=None, cache=None):
515
+ """cache: a KVCache - then idx/vals hold only the tokens not yet in it."""
516
+ return self.body(self.emb(idx) + self.num_enc(vals), masks, cache)
bard_game.py ADDED
@@ -0,0 +1,442 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The story engine of bard-small. The model narrates and proposes state changes and choices; this code applies the
2
+ changes it believes, keeps the state, steers the length of a passage and the shape of the choices, and keeps the
3
+ tale as one string in the model's own format (see format.txt).
4
+
5
+ <|start|>state<|content|>money\\n100<|end|><|start|>story<|content|>...narration...<|vars|>money<|add|>-20
6
+ <|choices|>Pay<|sep|>Run<|end|><|start|>state<|content|>money\\n80<|end|><|start|>player<|content|>Pay<|end|>...
7
+ """
8
+ import math
9
+ import re
10
+ import time
11
+ import unicodedata
12
+ from dataclasses import dataclass, field
13
+
14
+ import numpy as np
15
+ import torch
16
+ from torch.nn import functional as F
17
+
18
+ from .bard_core import KVCache, softcap
19
+
20
+ TITLE = "Stochastic Lands of Prophecy"
21
+ DEFAULT_OPENING = "You wake up in a dungeon."
22
+ MAX_INPUT = 300
23
+ ANNOUNCE = {"money", "gold", "health"}
24
+ LENGTHS = {"short": 60, "medium": 150, "long": None} # narration tokens a passage aims at
25
+ SAMPLING = dict(temperature=0.8, top_k=50, top_p=0.95, rep_penalty=1.1, rep_window=128)
26
+
27
+ OP_RE = re.compile(r"^\s*(.+?)\s*<\|(add|set)\|>\s*(-?\s*\d+)\s*$")
28
+ SENTENCE_END = re.compile(r"[.!?…][\"”’')\]]*\s*$|\n\s*$")
29
+ SENTENCE_DONE = re.compile(r"[.!?…][\"”’')\]]*(\s|$)")
30
+ SPELLED_MARKER = re.compile(r"<?\|\s*(vars|choices|sep|end|add|set)\s*\|\s*>?", re.I)
31
+ TURN = re.compile(r"<\|start\|>(state|story|player)<\|content\|>(.*?)<\|end\|>", re.S)
32
+
33
+ # the story site's own interface links, not story choices ("End Game and Leave Comments", "Start over", ...)
34
+ META_CHOICE = re.compile(
35
+ r"leave (a )?comments?|rate (this|the) (story|game)|end (the )?game|give (me )?(a )?rating|"
36
+ r"back to (the )?(menu|site|story list|main menu)|return to (the )?main menu|main menu|"
37
+ r"play again|^\W*(restart|start over|start again|comments?)\W*$|(reset|refresh) (the )?game|"
38
+ r"previous page|^\W*go back to the (beginning|start)\W*$|"
39
+ r"^\W*(the )?end\W*(\[[^\]]*\]|\([^)]*\))?\W*$|^\W*the end of (the|this|your) "
40
+ r"(tale|story|game|adventure|line)\W*$|this is the end of (your|the) (adventure|story|game)",
41
+ re.I)
42
+
43
+ # changes the engine only believes when the narration is about them: a 137M model writes "money -10" after being
44
+ # eaten alive; the passage has to mention money for that
45
+ EVIDENCE = {
46
+ "money": r"\b(money|coins?|gold|silver|copper|cash|dollars?|bucks|credits?|price|pay|paid|"
47
+ r"buy|bought|sell|sold|cost|steal|stole|stolen|rob|robbed|reward|bribe|purse|wallet|"
48
+ r"payment|fee|tip|earn|earned|spend|spent|wage|loot|treasure)\b|\$",
49
+ "health": r"\b(health|hurt|wound|wounded|injur\w*|bleed\w*|blood|pain|heal\w*|damage\w*|hit|"
50
+ r"stab\w*|cut|bite|bitten|burn\w*|poison\w*|potion|bandage\w*|recover\w*|weak\w*)\b",
51
+ }
52
+ EVIDENCE["gold"] = EVIDENCE["money"]
53
+ EVIDENCE = {k: re.compile(v, re.I) for k, v in EVIDENCE.items()}
54
+ AMOUNTS = {"money", "gold", "coins", "health"} # owned as an amount: spent and earned, never below 0
55
+
56
+
57
+ def story_choices(choices):
58
+ return [c for c in choices if not META_CHOICE.search(c)]
59
+
60
+
61
+ def believable(name, narration):
62
+ rule = EVIDENCE.get(name)
63
+ return rule is None or bool(rule.search(narration))
64
+
65
+
66
+ def sane(name, old, new):
67
+ """Spending more than you have is refused, and so is a more than tenfold gain."""
68
+ if name not in AMOUNTS or old is None:
69
+ return True
70
+ return 0 <= new <= max(1000, 10 * old)
71
+
72
+
73
+ def canonical(name):
74
+ return re.sub(r"\s+", " ", name).strip().lower()
75
+
76
+
77
+ def state_text(state):
78
+ return "<|sep|>".join(f"{n}\n{v}" for n, v in state.items())
79
+
80
+
81
+ def parse_state(content):
82
+ state = {}
83
+ for item in filter(None, content.split("<|sep|>")):
84
+ name, _, value = item.partition("\n")
85
+ try:
86
+ state[name.strip()] = int(value.strip())
87
+ except ValueError:
88
+ pass
89
+ return state
90
+
91
+
92
+ def clean_input(text):
93
+ """A player's words: no control characters, and no way to write a marker."""
94
+ text = "".join(c for c in text if c == " " or unicodedata.category(c)[0] != "C")
95
+ text = text.replace("<|", "<").replace("|>", ">")
96
+ return re.sub(r"\s+", " ", text).strip()[:MAX_INPUT]
97
+
98
+
99
+ def repair(raw):
100
+ return SPELLED_MARKER.sub(lambda m: f"<|{m[1].lower()}|>", raw)
101
+
102
+
103
+ def narration_so_far(raw):
104
+ """What a reader may see of a turn being written: up to the first marker, and never a stray "<" or "|"."""
105
+ visible = re.split(r"<\||\|", raw, maxsplit=1)[0]
106
+ return visible[:-1] if visible.endswith("<") else visible
107
+
108
+
109
+ def unique(choices):
110
+ seen, out = set(), []
111
+ for c in choices:
112
+ key = re.sub(r"\W+", " ", c.lower()).strip()
113
+ if key not in seen:
114
+ seen.add(key)
115
+ out.append(c)
116
+ return out
117
+
118
+
119
+ def parse_turn(raw):
120
+ """The model's output for one turn -> (narration, [(name, op, value)], [choices], problems)."""
121
+ problems = []
122
+ fixed = repair(raw)
123
+ if fixed != raw:
124
+ problems.append("a marker written as text")
125
+ raw = fixed
126
+ text, vars_part, choices_part = raw, "", ""
127
+ if "<|choices|>" in text:
128
+ text, choices_part = text.split("<|choices|>", 1)
129
+ if "<|vars|>" in text:
130
+ text, vars_part = text.split("<|vars|>", 1)
131
+ ops = []
132
+ for item in filter(None, vars_part.split("<|sep|>")):
133
+ m = OP_RE.match(item)
134
+ if m:
135
+ ops.append((canonical(m[1]), m[2], int(m[3].replace(" ", ""))))
136
+ else:
137
+ problems.append(f"unreadable change {item!r}")
138
+ choices = unique(story_choices([c.strip() for c in choices_part.split("<|sep|>") if c.strip()]))
139
+ leftover = re.findall(r"<\|[a-z_]+\|>", text)
140
+ if leftover:
141
+ problems.append(f"stray markers in the narration: {leftover}")
142
+ text = re.sub(r"<\|[a-z_]+\|>", " ", text)
143
+ return text.strip(), ops, choices, problems
144
+
145
+
146
+ # ----------------------------------------------------------------------------- steering
147
+
148
+ class LengthControl:
149
+ """Steers one story turn (the adjust_logits hook of generate) without retraining.
150
+
151
+ Narration: it cannot end before the model has written a sentence of its own after the opening; past a token budget
152
+ the markers that end it (<|vars|>, <|choices|>) get a growing boost, only right after a sentence ends, so text is
153
+ never cut mid-sentence; from twice the budget it ends at the next sentence end. <|end|> is only ever the model's
154
+ own choice (it ends the story).
155
+
156
+ Choices (once <|choices|> is written): at least MIN_CHOICES, none empty, none a copy of another, and a push away
157
+ from retracing an earlier choice word by word."""
158
+
159
+ MIN_CHOICES = 2
160
+ MAX_CHOICES = 5
161
+ MAX_CHOICE_TOKENS = 28
162
+ COPY = 1.5
163
+ COPY_MAX = 8.0
164
+ ECHO = 4.0
165
+ MIN_WORDS = 4 # a sentence of its own is at least this many words
166
+ GIVE_UP = 90 # tokens after which a narration with no sentence in it is left to the model
167
+
168
+ def __init__(self, tok, mode="medium", vars_weight=1.0):
169
+ self.tok = tok
170
+ self.vars_id = tok.specials["<|vars|>"]
171
+ self.choices_id = tok.specials["<|choices|>"]
172
+ self.sep_id = tok.specials["<|sep|>"]
173
+ self.go_on = [self.vars_id, self.choices_id]
174
+ self.stop = self.go_on + [tok.eos_id]
175
+ first = min(tok.specials.values())
176
+ self.silent = {i for i in range(first) if tok.vocab.id_to_token_decoded(i) == ""}
177
+ self.rep_free = False # read by generate(): no repetition penalty while choices are written
178
+ text_like = {self.sep_id, tok.eos_id, tok.specials["<|num|>"], tok.specials["<|snum|>"]}
179
+ self.no_specials = torch.tensor([i for i in range(first, 1 << 14) if i not in text_like], dtype=torch.long)
180
+ self.pipes = torch.tensor([i for i in range(first) if "|" in tok.vocab.id_to_token_decoded(i)], dtype=torch.long)
181
+ self.vars_bias = math.log(vars_weight) if vars_weight > 1 else 0.0
182
+ self.set(mode)
183
+
184
+ def set(self, mode):
185
+ self.mode, self.budget = mode, LENGTHS[mode]
186
+
187
+ def start_part(self, raw):
188
+ """Called before each generate() call of a turn; raw = the turn so far."""
189
+ self.before = raw
190
+ self.done = "<|" in raw
191
+ self.offset = 0 if self.done else len(self.tok.encode(raw)[0])
192
+ self.prior = None
193
+ if "<|choices|>" in raw:
194
+ texts = raw.split("<|choices|>", 1)[1].split("<|sep|>")
195
+ self.prior = [[int(i) for i in self.tok.encode(t)[0]] if t else [] for t in texts]
196
+ self.rep_free = False
197
+
198
+ def wrote_sentence(self, gen_ids):
199
+ if self.offset + len(gen_ids) >= self.GIVE_UP:
200
+ return True
201
+ text = (self.before + self.tok.decode(gen_ids)).strip()
202
+ return bool(SENTENCE_DONE.search(text)) and len(text.split()) >= self.MIN_WORDS
203
+
204
+ def __call__(self, gen_ids, logits):
205
+ logits = logits.clone()
206
+ logits[self.pipes.to(logits.device)] = float("-inf")
207
+ if self.prior is not None or self.choices_id in gen_ids:
208
+ self.rep_free = True
209
+ return self.steer_choices(gen_ids, logits)
210
+ if self.done or (gen_ids and any(i in self.stop for i in gen_ids)):
211
+ self.done = True
212
+ return logits
213
+ if not self.wrote_sentence(gen_ids):
214
+ logits[self.stop] = float("-inf")
215
+ if self.vars_bias:
216
+ logits[self.vars_id] -= self.vars_bias
217
+ if self.budget is None or not gen_ids:
218
+ return logits
219
+ n = self.offset + len(gen_ids)
220
+ if n < self.budget or not SENTENCE_END.search(self.tok.decode(gen_ids[-4:], [0] * 4)):
221
+ return logits
222
+ if n >= 2 * self.budget:
223
+ best = max(self.go_on, key=lambda i: float(logits[i]))
224
+ keep = logits[best].clone()
225
+ logits.fill_(float("-inf"))
226
+ logits[best] = keep
227
+ else:
228
+ logits[self.go_on] += 2.0 + 6.0 * (n - self.budget) / self.budget
229
+ return logits
230
+
231
+ def steer_choices(self, gen_ids, logits):
232
+ if self.prior is not None:
233
+ *before, head = self.prior
234
+ seq = list(gen_ids)
235
+ else:
236
+ before, head = [], []
237
+ seq = list(gen_ids[len(gen_ids) - gen_ids[::-1].index(self.choices_id):])
238
+ parts = [[]]
239
+ for i in seq:
240
+ if i == self.sep_id:
241
+ parts.append([])
242
+ else:
243
+ parts[-1].append(i)
244
+ parts[0] = head + parts[0]
245
+ earlier = [c for c in before + parts[:-1] if c]
246
+ current = parts[-1]
247
+ neg = float("-inf")
248
+ real = sum(1 for c in earlier if not META_CHOICE.search(self.tok.vocab.decode(c)))
249
+ if not current or real + 1 < self.MIN_CHOICES:
250
+ logits[self.tok.eos_id] = neg
251
+ if not current:
252
+ logits[self.sep_id] = neg
253
+ banned = self.no_specials.to(logits.device)
254
+ logits[banned[banned < logits.numel()]] = neg
255
+ if len(earlier) + 1 >= self.MAX_CHOICES:
256
+ logits[self.sep_id] = neg
257
+ if len(current) >= self.MAX_CHOICE_TOKENS:
258
+ closing = torch.full_like(logits, neg)
259
+ closing[[self.sep_id, self.tok.eos_id]] = logits[[self.sep_id, self.tok.eos_id]]
260
+ return logits if torch.isinf(closing).all() else closing
261
+ penalty = {}
262
+ k = len(current)
263
+ for c in earlier:
264
+ if c == current:
265
+ logits[self.sep_id] = logits[self.tok.eos_id] = neg
266
+ if k < len(c) and c[:k] == current and c[k] not in self.silent:
267
+ cut = min(self.COPY_MAX, self.COPY * (k + 1))
268
+ penalty[c[k]] = max(penalty.get(c[k], 0.0), cut)
269
+ if k >= 2:
270
+ pair = current[-2:]
271
+ for j in range(len(c) - 2):
272
+ if c[j:j + 2] == pair and c[j + 2] not in self.silent:
273
+ penalty[c[j + 2]] = max(penalty.get(c[j + 2], 0.0), self.ECHO)
274
+ for i, cut in penalty.items():
275
+ logits[i] -= cut
276
+ return logits
277
+
278
+
279
+ # ----------------------------------------------------------------------------- sampling
280
+
281
+ @torch.no_grad()
282
+ def generate(lm, tok, seed, max_new, ctx, rng, temperature=0.8, top_k=50, top_p=0.95, rep_penalty=1.1,
283
+ rep_window=128, adjust_logits=None):
284
+ """Yield (token id, packed number) as they are sampled. The seed is read once into a key/value cache; every step
285
+ then runs one token. Past `ctx` tokens the cache is rebuilt from the last 3/4 of it."""
286
+ device = lm.head.weight.device
287
+ seed_ids, seed_vals = tok.encode(seed)
288
+ ids = [tok.eos_id] + seed_ids.tolist()
289
+ vals = [0] + seed_vals.tolist()
290
+ banned = torch.zeros(lm.head.weight.shape[0], dtype=torch.bool, device=device)
291
+ banned[tok.vocab_size:] = True
292
+ first_special = min(tok.specials.values())
293
+ banned[first_special:tok.vocab_size] = True
294
+ allowed = {tok.eos_id, tok.num_id, tok.snum_id} | {i for t, i in tok.specials.items() if not t.startswith("<|start|>")}
295
+ for i in allowed:
296
+ banned[i] = False
297
+ cache = KVCache(lm.body)
298
+ fed = 0
299
+ gen_ids = []
300
+ for _ in range(max_new):
301
+ if cache.pos + len(ids) - fed > ctx:
302
+ cache.reset()
303
+ fed = max(0, len(ids) - (3 * ctx) // 4)
304
+ x = torch.tensor([ids[fed:]], device=device)
305
+ xv = torch.tensor([vals[fed:]], device=device)
306
+ h = lm.hidden(x, xv, cache=cache)[0, -1]
307
+ fed = len(ids)
308
+ logits = softcap(F.linear(h, lm.head.weight)).float()
309
+ logits[banned] = float("-inf")
310
+ if adjust_logits is not None:
311
+ adjusted = adjust_logits(gen_ids, logits)
312
+ logits = logits if torch.isinf(adjusted).all() else adjusted
313
+ if rep_penalty != 1.0 and not getattr(adjust_logits, "rep_free", False):
314
+ window = ids[max(0, len(ids) - rep_window):]
315
+ if window:
316
+ recent = torch.tensor(sorted(set(window)), device=device)
317
+ picked = logits[recent]
318
+ logits[recent] = torch.where(picked > 0, picked / rep_penalty, picked * rep_penalty)
319
+ logits = logits / temperature
320
+ if top_k:
321
+ kth = torch.topk(logits, min(top_k, logits.numel())).values[-1]
322
+ logits[logits < kth] = float("-inf")
323
+ probs = F.softmax(logits, -1)
324
+ if top_p < 1.0:
325
+ sorted_p, order = probs.sort(descending=True)
326
+ drop = sorted_p.cumsum(0) - sorted_p > top_p
327
+ probs[order[drop]] = 0.0
328
+ probs /= probs.sum()
329
+ nxt = int(torch.multinomial(probs, 1, generator=rng))
330
+ if nxt == tok.eos_id:
331
+ return
332
+ packed = 0
333
+ if nxt in (tok.num_id, tok.snum_id):
334
+ packed = int(lm.num_dec.generate(h[None], temperature)[0])
335
+ ids.append(nxt)
336
+ vals.append(packed)
337
+ gen_ids.append(nxt)
338
+ yield nxt, packed
339
+
340
+
341
+ # ----------------------------------------------------------------------------- tales
342
+
343
+ @dataclass
344
+ class Tale:
345
+ """A tale: the whole of it as one string in the model's format (`history`), and what the engine knows of it."""
346
+
347
+ history: str
348
+ state: dict = field(default_factory=dict)
349
+ title: str = ""
350
+ length: str = "medium"
351
+ text: str = "" # the last passage
352
+ choices: list = field(default_factory=list)
353
+ ended: bool = False
354
+ turns: int = 0
355
+ pending: str | None = None # an opening not yet continued by the model
356
+ changes: list = field(default_factory=list) # what the last turn did to the state: (name, old, new)
357
+ created: float = field(default_factory=time.time)
358
+
359
+ def to_dict(self):
360
+ return dict(self.__dict__)
361
+
362
+ @classmethod
363
+ def from_dict(cls, d):
364
+ return cls(**d)
365
+
366
+ def transcript(self):
367
+ """What a reader saw: [("story", text), ("player", text), ...]."""
368
+ out = []
369
+ for role, content in TURN.findall(self.history):
370
+ if role == "player":
371
+ out.append(("player", content))
372
+ elif role == "story":
373
+ out.append(("story", content.split("<|vars|>")[0].split("<|choices|>")[0].strip()))
374
+ return out
375
+
376
+
377
+ class StoryEngine:
378
+ def __init__(self, lm, tok, vars_weight, context):
379
+ self.lm, self.tok, self.vars_weight, self.context = lm, tok, vars_weight, context
380
+
381
+ def new_tale(self, opening, length, state):
382
+ opening = clean_input(opening) or DEFAULT_OPENING
383
+ state = dict(state)
384
+ return Tale(history=f"<|start|>state<|content|>{state_text(state)}<|end|>", state=state, title=opening,
385
+ length=length, pending=opening)
386
+
387
+ def _seed(self, tale, move):
388
+ if tale.pending is not None:
389
+ return tale.history + "<|start|>story<|content|>" + tale.pending, tale.pending
390
+ return tale.history + f"<|start|>player<|content|>{move}<|end|><|start|>story<|content|>", ""
391
+
392
+ @torch.no_grad()
393
+ def turn(self, tale, move, on_text=None, seed=None, max_new=450, max_parts=20, **sampling):
394
+ """Tell one turn of the tale (in place). move: the player's choice or own words (None for a new tale)."""
395
+ if tale.pending is None:
396
+ move = clean_input(move or "")
397
+ if not move:
398
+ raise ValueError("a move is needed: pick one of the choices, or write what you do")
399
+ prompt, prefix = self._seed(tale, move)
400
+ if prefix and on_text:
401
+ on_text(prefix)
402
+ device = self.lm.head.weight.device
403
+ rng = torch.Generator(device=device).manual_seed(seed if seed is not None else int(time.time() * 1000) % 2**31)
404
+ control = LengthControl(self.tok, tale.length, self.vars_weight)
405
+ params = {**SAMPLING, **sampling}
406
+ raw, shown = "", 0
407
+ for _ in range(max_parts):
408
+ control.start_part(raw)
409
+ gen_ids, gen_vals = [], []
410
+ for tid, val in generate(self.lm, self.tok, prompt + raw, max_new, self.context, rng,
411
+ adjust_logits=control, **params):
412
+ gen_ids.append(tid)
413
+ gen_vals.append(val)
414
+ if on_text:
415
+ visible = narration_so_far(raw + self.tok.decode(gen_ids, gen_vals)).rstrip("�")
416
+ if len(visible) > shown:
417
+ on_text(visible[shown:])
418
+ shown = len(visible)
419
+ raw += self.tok.decode(gen_ids, gen_vals)
420
+ if len(gen_ids) < max_new:
421
+ break
422
+ return self._resolve(tale, prompt, prefix, raw)
423
+
424
+ def _resolve(self, tale, prompt, prefix, raw):
425
+ text, ops, choices, problems = parse_turn(prefix + raw)
426
+ state, before = tale.state, dict(tale.state)
427
+ for name, op, v in ops:
428
+ old = state.get(name)
429
+ new = v if op == "set" else (old or 0) + v
430
+ if not believable(name, text):
431
+ continue # "money -10" for being eaten alive
432
+ if name in ANNOUNCE and op == "set" and v != 0:
433
+ continue # shown amounts are earned or spent, not set
434
+ if not sane(name, old, new):
435
+ continue
436
+ state[name] = new
437
+ tale.history = prompt + raw + "<|end|>" + f"<|start|>state<|content|>{state_text(state)}<|end|>"
438
+ tale.text, tale.choices, tale.ended = text, choices, not choices
439
+ tale.turns += 1
440
+ tale.pending = None
441
+ tale.changes = [(n, before.get(n), v) for n, v in state.items() if n in ANNOUNCE and before.get(n) != v]
442
+ return tale
bard_tokenizer.py ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The tokenizer of bard-small: tokenmonster (fiction-16000-strict-v1) plus the special tokens of the story format, and
2
+ numbers kept apart: every run of digits is one <|num|>/<|snum|> token whose value travels in a parallel stream."""
3
+ import os
4
+ import re
5
+
6
+ import numpy as np
7
+ import tokenmonster
8
+
9
+ EOS = "<|end|>"
10
+ NUM_MARKERS = ["<|num|>", "<|snum|>"] # a number, and a number preceded by one space
11
+ MAX_DIGITS = 8 # 10**8 - 1 < 2**27
12
+ LEN_SHIFT = 27
13
+ VALUE_MASK = (1 << LEN_SHIFT) - 1
14
+ NUMBER_RE = re.compile(r"( ?)([0-9]+)")
15
+
16
+
17
+ def pack(digits: str) -> int:
18
+ assert 0 < len(digits) <= MAX_DIGITS
19
+ return int(digits) | (len(digits) << LEN_SHIFT)
20
+
21
+
22
+ def unpack(packed: int) -> str:
23
+ return str(packed & VALUE_MASK).zfill(packed >> LEN_SHIFT)
24
+
25
+
26
+ def split_numbers(text):
27
+ """-> a list of str (text) and (spaced, packed) items, in order."""
28
+ out, pos = [], 0
29
+ for m in NUMBER_RE.finditer(text):
30
+ if m.start() > pos:
31
+ out.append(text[pos:m.start()])
32
+ spaced, digits = bool(m.group(1)), m.group(2)
33
+ for i in range(0, len(digits), MAX_DIGITS):
34
+ out.append((spaced and i == 0, pack(digits[i:i + MAX_DIGITS])))
35
+ pos = m.end()
36
+ if pos < len(text):
37
+ out.append(text[pos:])
38
+ return out
39
+
40
+
41
+ def parse_special_tokens(format_text):
42
+ markers = re.findall(r"<\|[a-z_]+\|>", format_text)
43
+ roles = re.findall(r"<\|start\|>([a-z_]+)<\|content\|>", format_text)
44
+ return list(dict.fromkeys(markers + [f"<|start|>{r}" for r in roles]))
45
+
46
+
47
+ class BardTokenizer:
48
+ def __init__(self, vocab_path, format_path):
49
+ self.vocab = tokenmonster.load(vocab_path)
50
+ self.specials = {t: self.vocab.token_to_id(t)
51
+ for t in parse_special_tokens(open(format_path, encoding="utf-8").read()) + NUM_MARKERS}
52
+ missing = [t for t, i in self.specials.items() if i is None]
53
+ assert not missing, f"the vocabulary lacks {missing}"
54
+ self.eos_id = self.specials[EOS]
55
+ self.num_id, self.snum_id = (self.specials[t] for t in NUM_MARKERS)
56
+ self._special_text = {i: t for t, i in self.specials.items()}
57
+
58
+ @property
59
+ def vocab_size(self):
60
+ return max(self.specials.values()) + 1
61
+
62
+ def encode(self, text):
63
+ """-> (ids, values): token ids, and at each <|num|>/<|snum|> the packed number (else 0)."""
64
+ plan = split_numbers(text)
65
+ segs = [item for item in plan if isinstance(item, str)]
66
+ seg_ids = iter(self.vocab.tokenize(segs) if segs else [])
67
+ ids, vals = [], []
68
+ for item in plan:
69
+ if isinstance(item, str):
70
+ t = next(seg_ids)
71
+ ids.append(t.astype(np.int64, copy=False))
72
+ vals.append(np.zeros(len(t), np.int64))
73
+ else:
74
+ spaced, packed = item
75
+ ids.append(np.array([self.snum_id if spaced else self.num_id], np.int64))
76
+ vals.append(np.array([packed], np.int64))
77
+ if not ids:
78
+ return np.zeros(0, np.int64), np.zeros(0, np.int64)
79
+ return np.concatenate(ids), np.concatenate(vals)
80
+
81
+ def decode(self, ids, vals=None):
82
+ ids = np.asarray(ids).tolist()
83
+ vals = np.asarray(vals).tolist() if vals is not None else [0] * len(ids)
84
+ parts, run = [], []
85
+ for i, v in zip(ids, vals):
86
+ if i in (self.num_id, self.snum_id):
87
+ if run:
88
+ parts.append(self.vocab.decode(run))
89
+ run = []
90
+ parts.append((" " if i == self.snum_id else "") + unpack(v))
91
+ elif i in self._special_text:
92
+ # a marker is its own text: decoded inside a run, the capitalisation state of the token before it
93
+ # can eat its first character
94
+ if run:
95
+ parts.append(self.vocab.decode(run))
96
+ run = []
97
+ parts.append(self._special_text[i])
98
+ else:
99
+ run.append(i)
100
+ if run:
101
+ parts.append(self.vocab.decode(run))
102
+ return "".join(parts)
103
+
104
+ @classmethod
105
+ def from_dir(cls, path):
106
+ return cls(os.path.join(path, "fictionet-16k.vocab"), os.path.join(path, "format.txt"))
config.json ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "model_type": "bard",
3
+ "architectures": [
4
+ "BardForStory"
5
+ ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_bard.BardConfig",
8
+ "AutoModel": "modeling_bard.BardForStory",
9
+ "AutoModelForCausalLM": "modeling_bard.BardForStory"
10
+ },
11
+ "vocab_size": 16128,
12
+ "d_model": 512,
13
+ "n_heads": 8,
14
+ "n_layers": 36,
15
+ "window": 256,
16
+ "global_every": 4,
17
+ "rope": "local",
18
+ "parallel": true,
19
+ "context": 4096,
20
+ "vars_weight": 4.0,
21
+ "torch_dtype": "bfloat16"
22
+ }
configuration_bard.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import PretrainedConfig
2
+
3
+
4
+ class BardConfig(PretrainedConfig):
5
+ """Architecture of bard-small: a 36-layer, 512-wide decoder (parallel attention/FFN blocks, sliding-window attention
6
+ with a global layer every fourth, RoPE on the windowed layers, QK-norm, gated attention, SwiGLU, logit softcap) with
7
+ a dedicated number encoder/decoder."""
8
+
9
+ model_type = "bard"
10
+
11
+ def __init__(
12
+ self,
13
+ vocab_size=16384,
14
+ d_model=512,
15
+ n_heads=8,
16
+ n_layers=36,
17
+ window=256,
18
+ global_every=4,
19
+ rope="local",
20
+ parallel=True,
21
+ context=4096,
22
+ vars_weight=4.0,
23
+ **kwargs,
24
+ ):
25
+ self.vocab_size = vocab_size
26
+ self.d_model = d_model
27
+ self.n_heads = n_heads
28
+ self.n_layers = n_layers
29
+ self.window = window
30
+ self.global_every = global_every
31
+ self.rope = rope
32
+ self.parallel = parallel
33
+ self.context = context
34
+ self.vars_weight = vars_weight # the weight state changes had in training: the story engine undoes it
35
+ super().__init__(**kwargs)
fictionet-16k.vocab ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:0e4b1364cff6a7492f78fff0e4f021d979bbf0a1c185e7281edd32f31e5ded6e
3
+ size 409254
format.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ <|start|>state<|content|>money
2
+ 10<|sep|>rusty key
3
+ 0<|end|><|start|>story<|content|>some story text<|choices|>I want to do X<|sep|>I want to do Y<|end|><|start|>player<|content|>I want to do X<|end|><|start|>story<|content|>some story content written by the model<|vars|>money<|add|>10<|sep|>rusty key<|set|>1<|choices|>I want to do Z<|sep|>I want to do W<|end|><|start|>state<|content|>money
4
+ 20<|sep|>rusty key
5
+ 1<|end|>
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:e6427abebbaba757a8ec4feb886ed12103dcb86e748f21bc75966409b43e334c
3
+ size 273464728
modeling_bard.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ import numpy as np
4
+ import torch
5
+ from transformers import PreTrainedModel
6
+ from transformers.modeling_outputs import CausalLMOutput
7
+
8
+ from .bard_core import LM, KVCache, softcap
9
+ from .bard_game import ANNOUNCE, DEFAULT_OPENING, LENGTHS, StoryEngine, Tale
10
+ from .bard_tokenizer import BardTokenizer
11
+ from .configuration_bard import BardConfig
12
+
13
+
14
+ class BardForStory(PreTrainedModel):
15
+ """bard-small: a small language model that tells interactive tales. Use `begin` and `act` to play one:
16
+
17
+ bard = AutoModelForCausalLM.from_pretrained("<repo>", trust_remote_code=True)
18
+ tale = bard.begin("You wake up in a dungeon.")
19
+ print(tale.text, tale.choices)
20
+ tale = bard.act(tale, tale.choices[0]) # or any words of your own
21
+ """
22
+
23
+ config_class = BardConfig
24
+ main_input_name = "input_ids"
25
+
26
+ def __init__(self, config: BardConfig):
27
+ super().__init__(config)
28
+ self.lm = LM(config.vocab_size, config.d_model, config.n_heads, config.n_layers, config.window,
29
+ config.global_every, parallel=config.parallel, rope=config.rope)
30
+ self._tokenizer = None
31
+ self._engine = None
32
+ self.post_init()
33
+
34
+ def _init_weights(self, module):
35
+ pass # the weights are loaded; the layers were initialised as they were trained
36
+
37
+ # ------------------------------------------------------------------------- the tokens
38
+
39
+ @property
40
+ def tokenizer(self) -> BardTokenizer:
41
+ """The tokenizer (tokenmonster plus the story format's special tokens), loaded from the repo's own files."""
42
+ if self._tokenizer is None:
43
+ where = getattr(self.config, "_name_or_path", "") or ""
44
+ if os.path.isdir(where):
45
+ self._tokenizer = BardTokenizer.from_dir(where)
46
+ else:
47
+ from huggingface_hub import hf_hub_download
48
+ vocab = hf_hub_download(where, "fictionet-16k.vocab")
49
+ fmt = hf_hub_download(where, "format.txt")
50
+ self._tokenizer = BardTokenizer(vocab, fmt)
51
+ return self._tokenizer
52
+
53
+ def forward(self, input_ids, number_values=None, **kwargs):
54
+ """Logits for every position. `number_values` holds, at each <|num|>/<|snum|> token, the packed number (see
55
+ BardTokenizer.encode); zeros elsewhere."""
56
+ if number_values is None:
57
+ number_values = torch.zeros_like(input_ids)
58
+ cache = KVCache(self.lm.body) # the cached path: ordinary attention with explicit masks, no flex_attention
59
+ h = self.lm.hidden(input_ids, number_values, cache=cache)
60
+ return CausalLMOutput(logits=softcap(torch.nn.functional.linear(h, self.lm.head.weight)))
61
+
62
+ # ------------------------------------------------------------------------- the game
63
+
64
+ @property
65
+ def engine(self) -> StoryEngine:
66
+ if self._engine is None:
67
+ self._engine = StoryEngine(self.lm, self.tokenizer, self.config.vars_weight, self.config.context)
68
+ return self._engine
69
+
70
+ def begin(self, opening: str = DEFAULT_OPENING, length: str = "medium", state: dict | None = None,
71
+ on_text=None, seed: int | None = None) -> Tale:
72
+ """Begin a tale. `opening` is how it starts (the model goes on from it); `length` is "short", "medium" or
73
+ "long"; `state` the variables the player carries (default: 100 money). `on_text(chunk)` is called with the
74
+ narration as it is written. Returns a Tale: .text (the passage), .choices, .state, .ended."""
75
+ if length not in LENGTHS:
76
+ raise ValueError(f"length must be one of {list(LENGTHS)}")
77
+ tale = self.engine.new_tale(opening, length, {"money": 100} if state is None else state)
78
+ return self.engine.turn(tale, None, on_text=on_text, seed=seed)
79
+
80
+ def act(self, tale: Tale, move: str, on_text=None, seed: int | None = None) -> Tale:
81
+ """Tell the next turn: `move` is one of tale.choices, or the player's own words. The tale is updated in place
82
+ and returned."""
83
+ if tale.ended:
84
+ raise ValueError("this tale has ended")
85
+ return self.engine.turn(tale, move, on_text=on_text, seed=seed)
86
+
87
+ def play(self, opening: str = DEFAULT_OPENING, length: str = "medium"):
88
+ """Play a tale in the terminal: pick a choice by its number, or type your own move; /short /medium /long set the
89
+ length of what is told, /quit leaves."""
90
+ say = lambda chunk: print(chunk, end="", flush=True) # noqa: E731
91
+ tale = self.begin(opening, length, on_text=say)
92
+ while True:
93
+ print()
94
+ for n, name in enumerate(tale.choices, 1):
95
+ print(f" {n}. {name}")
96
+ for name, old, new in tale.changes:
97
+ print(f" [{name}: {old} -> {new}]")
98
+ if tale.ended:
99
+ print("\nThe end.")
100
+ return tale
101
+ try:
102
+ move = input("\n> ").strip()
103
+ except (EOFError, KeyboardInterrupt):
104
+ return tale
105
+ if move == "/quit":
106
+ return tale
107
+ if move in ("/short", "/medium", "/long"):
108
+ tale.length = move[1:]
109
+ continue
110
+ if move.isdigit() and 1 <= int(move) <= len(tale.choices):
111
+ move = tale.choices[int(move) - 1]
112
+ if not move:
113
+ continue
114
+ print()
115
+ tale = self.act(tale, move, on_text=say)