lmscope 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
lmscope/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """lmscope: step through LSTM / Transformer language-model inference in the browser."""
2
+ from .inference import Inspector, load_checkpoint
3
+ from .server import create_app, serve
4
+
5
+ __all__ = ["serve", "create_app", "Inspector", "load_checkpoint"]
6
+ __version__ = "0.1.0"
lmscope/__main__.py ADDED
@@ -0,0 +1,30 @@
1
+ """CLI: lmscope serve --model ckpt.pt [--model-type ...] [--tokenizer ...] [--tokenizer-type ...]"""
2
+ import argparse
3
+
4
+ from .server import serve
5
+
6
+
7
+ def main(argv=None):
8
+ parser = argparse.ArgumentParser(prog="lmscope", description="Interactive LM inference visualizer")
9
+ sub = parser.add_subparsers(dest="command", required=True)
10
+ s = sub.add_parser("serve", help="load a checkpoint and open the browser UI")
11
+ s.add_argument("--model", required=True, help="checkpoint .pt in the lmscope format")
12
+ s.add_argument("--model-type", choices=["transformer", "lstm"], help="checked against the checkpoint")
13
+ s.add_argument("--tokenizer", help="tokenizer JSON (BPE: HuggingFace tokenizer file; char: char_to_idx)")
14
+ s.add_argument("--tokenizer-type", choices=["char", "bpe"], help="default: from the checkpoint")
15
+ s.add_argument("--port", type=int, default=8765)
16
+ s.add_argument("--host", default="127.0.0.1")
17
+ s.add_argument("--prompt", default="ROMEO:\n", help="initial prompt (\\n is a newline)")
18
+ s.add_argument("--seed", type=int, default=0, help="sampling seed, restored on reset")
19
+ s.add_argument("--reference", help="text file preloaded as the reference continuation for loss/perplexity")
20
+ s.add_argument("--device", help="cuda or cpu (default: cuda if available)")
21
+ s.add_argument("--no-browser", action="store_true", help="don't open a browser tab")
22
+ args = parser.parse_args(argv)
23
+ serve(model_path=args.model, model_type=args.model_type, tokenizer_path=args.tokenizer,
24
+ tokenizer_type=args.tokenizer_type, port=args.port, host=args.host,
25
+ prompt=args.prompt.replace("\\n", "\n"), seed=args.seed, reference_file=args.reference,
26
+ open_browser=not args.no_browser, device=args.device)
27
+
28
+
29
+ if __name__ == "__main__":
30
+ main()
lmscope/inference.py ADDED
@@ -0,0 +1,213 @@
1
+ """Step-by-step inference with access to model internals.
2
+
3
+ `Inspector` keeps one token sequence (the prompt plus generated tokens). "Position p" means the
4
+ prediction of token p from the tokens before it, so p runs from 1 to len(sequence); p = len(sequence)
5
+ is the next, not-yet-sampled token. The model always sees at most `context_len` tokens before p.
6
+ """
7
+ import math
8
+
9
+ import torch
10
+ import torch.nn.functional as F
11
+
12
+ from .models import CausalTransformer, CustomLSTMCell, LSTMModel, build_model, count_params
13
+ from .tokenizers import load_tokenizer
14
+
15
+ LN2 = math.log(2)
16
+
17
+
18
+ def load_checkpoint(path, model_type=None, tokenizer_path=None, tokenizer_type=None, device=None):
19
+ """Builds model and tokenizer from a checkpoint in the lmscope format (see README)."""
20
+ device = torch.device(device or ("cuda" if torch.cuda.is_available() else "cpu"))
21
+ ckpt = torch.load(path, map_location="cpu", weights_only=True)
22
+ if "model_state_dict" not in ckpt or "model_config" not in ckpt:
23
+ raise ValueError(f"{path} is not an lmscope checkpoint: it needs 'model_state_dict' and 'model_config'")
24
+ config = dict(ckpt["model_config"])
25
+ if model_type and model_type != config["model_type"]:
26
+ raise ValueError(f"--model-type {model_type} but the checkpoint holds a {config['model_type']}")
27
+ model = build_model(config)
28
+ model.load_state_dict(ckpt["model_state_dict"])
29
+ model.to(device).eval()
30
+ tokenizer = load_tokenizer(tokenizer_type, tokenizer_path, ckpt)
31
+ if tokenizer.vocab_size != config["vocab_size"]:
32
+ raise ValueError(f"tokenizer has {tokenizer.vocab_size} tokens, model expects {config['vocab_size']}")
33
+ return model, tokenizer, config
34
+
35
+
36
+ def _round(t, digits=4):
37
+ return [round(float(x), digits) for x in t]
38
+
39
+
40
+ class Inspector:
41
+ def __init__(self, model, tokenizer, config, seed=0):
42
+ self.model = model
43
+ self.tok = tokenizer
44
+ self.config = config
45
+ self.context_len = config["context_len"]
46
+ self.device = next(model.parameters()).device
47
+ self.seed = seed
48
+ self.prompt_ids = []
49
+ self.ids = []
50
+ self.records = {} # position -> how the generated token there was sampled
51
+ self._gen = torch.Generator().manual_seed(seed)
52
+
53
+ # ------------------------------------------------------------------ sequence state
54
+ def model_info(self):
55
+ c = self.config
56
+ return {"model_type": c["model_type"], "params": count_params(self.model), "n_layers": c["n_layers"],
57
+ "n_heads": c.get("n_heads"), "hidden_size": c.get("hidden_size"), "d_model": c["d_model"],
58
+ "vocab_size": c["vocab_size"], "context_len": self.context_len,
59
+ "tokenizer_type": self.tok.kind, "device": str(self.device)}
60
+
61
+ def set_prompt(self, text):
62
+ ids = self.tok.encode(text)
63
+ if not ids:
64
+ raise ValueError("the prompt is empty")
65
+ self.prompt_ids = ids
66
+ return self.reset()
67
+
68
+ def reset(self):
69
+ self.ids = list(self.prompt_ids)
70
+ self.records = {}
71
+ self._gen = torch.Generator().manual_seed(self.seed)
72
+ return self.state()
73
+
74
+ def state(self):
75
+ tokens = []
76
+ for p, i in enumerate(self.ids):
77
+ rec = self.records.get(p)
78
+ tokens.append({"id": i, "token": self.tok.token_str(i), "generated": p >= len(self.prompt_ids),
79
+ "prob": rec["prob"] if rec else None, "loss": rec["loss"] if rec else None})
80
+ losses = [r["loss"] for r in self.records.values()]
81
+ return {"tokens": tokens, "prompt_len": len(self.prompt_ids), "length": len(self.ids),
82
+ "generated": len(losses), "text": self.tok.decode(self.ids),
83
+ "perplexity": math.exp(sum(losses) / len(losses)) if losses else None}
84
+
85
+ def _window(self, position):
86
+ start = max(0, position - self.context_len)
87
+ return start, self.ids[start:position]
88
+
89
+ # ------------------------------------------------------------------ forward passes
90
+ @torch.no_grad()
91
+ def _logits(self, ids):
92
+ x = torch.tensor([ids], device=self.device)
93
+ out = self.model(x)
94
+ return (out[0] if isinstance(self.model, LSTMModel) else out)[0].float()
95
+
96
+ def _distribution(self, logits, temperature, top_k, chosen=None):
97
+ probs = F.softmax(logits / temperature, dim=-1).cpu()
98
+ entropy = float(-(probs * torch.log(probs.clamp_min(1e-12))).sum()) / LN2
99
+ top_p, top_i = probs.topk(min(top_k, probs.numel()))
100
+ mass = torch.cumsum(probs.sort(descending=True).values, 0)
101
+ out = {"temperature": temperature,
102
+ "top": [{"id": int(i), "token": self.tok.token_str(i), "prob": round(float(p), 6)}
103
+ for p, i in zip(top_p, top_i)],
104
+ "entropy_bits": round(entropy, 4), "max_entropy_bits": round(math.log2(probs.numel()), 4),
105
+ "topk_mass": {k: round(float(mass[k - 1]), 4) for k in (1, 5, 10, 20) if k <= probs.numel()},
106
+ "chosen": None}
107
+ if chosen is not None:
108
+ out["chosen"] = {"id": chosen, "token": self.tok.token_str(chosen),
109
+ "prob": round(float(probs[chosen]), 6),
110
+ "rank": int((probs > probs[chosen]).sum()) + 1}
111
+ return out, probs
112
+
113
+ @torch.no_grad()
114
+ def _transformer_internals(self, ids, layer, head):
115
+ """One forward pass with hooks: attention of every layer, residual-stream norms per layer."""
116
+ model = self.model
117
+ attn, norms, hooks = [], [], []
118
+ for block in model.blocks:
119
+ hooks.append(block.attn.softmax.register_forward_hook(lambda m, i, o: attn.append(o[0])))
120
+ hooks.append(block.register_forward_hook(lambda m, i, o: norms.append(o[0].norm(dim=-1))))
121
+ try:
122
+ x = torch.tensor([ids], device=self.device)
123
+ emb = model.tok_embed(x) + model.pos_embed(torch.arange(len(ids), device=self.device))
124
+ norms.append(emb[0].norm(dim=-1))
125
+ model(x)
126
+ finally:
127
+ for h in hooks:
128
+ h.remove()
129
+ # norms: embedding first, then the output of each block (hooks fire in block order).
130
+ a = attn[layer] # (heads, T, T)
131
+ matrix = a.mean(0) if head == "mean" else a[int(head)]
132
+ # Where each head of this layer looks, for the last query: mean attention distance in tokens.
133
+ T = len(ids)
134
+ dist = (torch.arange(T, device=a.device).flip(0).float() * a[:, -1, :]).sum(-1)
135
+ return {"kind": "attention", "layer": layer, "head": head, "n_layers": len(attn), "n_heads": a.shape[0],
136
+ "matrix": [_round(row, 4) for row in matrix.cpu()],
137
+ "last_row_by_head": [_round(row, 4) for row in a[:, -1, :].cpu()],
138
+ "head_mean_distance": _round(dist.cpu(), 2),
139
+ "norm_labels": ["embedding"] + [f"block {i + 1}" for i in range(len(attn))],
140
+ "norms": [_round(n.cpu(), 3) for n in norms]}
141
+
142
+ @torch.no_grad()
143
+ def _lstm_internals(self, ids, layer):
144
+ """Re-runs the LSTM layer by layer with CustomLSTMCell to expose gates and states."""
145
+ model = self.model
146
+ x = model.embed(torch.tensor(ids, device=self.device))
147
+ layers = []
148
+ for l in range(model.lstm.num_layers):
149
+ h, c, gates = CustomLSTMCell(model.lstm, l).run(x)
150
+ layers.append((h, c, gates))
151
+ x = h # inter-layer dropout is off in eval mode
152
+ h, c, gates = layers[layer]
153
+ return {"kind": "gates", "layer": layer, "n_layers": len(layers), "hidden_size": h.shape[1],
154
+ "gates": {name: _round(g[-1].cpu(), 3) for name, g in gates.items()},
155
+ "gate_means": {name: round(float(g[-1].mean()), 4) for name, g in gates.items()},
156
+ "gate_means_over_time": {name: _round(g.mean(-1).cpu(), 4) for name, g in gates.items()},
157
+ "norm_labels": [f"h, layer {i + 1}" for i in range(len(layers))],
158
+ "norms": [_round(hh.norm(dim=-1).cpu(), 3) for hh, _, _ in layers],
159
+ "cell_norms": [_round(cc.norm(dim=-1).cpu(), 3) for _, cc, _ in layers]}
160
+
161
+ # ------------------------------------------------------------------ public API
162
+ def analyze(self, position=None, temperature=1.0, layer=0, head="mean", top_k=20):
163
+ """Distribution and internals for predicting the token at `position` (default: the next one)."""
164
+ position = len(self.ids) if position is None else int(position)
165
+ if not 1 <= position <= len(self.ids):
166
+ raise ValueError(f"position must be between 1 and {len(self.ids)}")
167
+ start, window = self._window(position)
168
+ chosen = self.ids[position] if position < len(self.ids) else None
169
+ dist, _ = self._distribution(self._logits(window)[-1], temperature, top_k, chosen)
170
+ if isinstance(self.model, CausalTransformer):
171
+ internals = self._transformer_internals(window, int(layer), head)
172
+ else:
173
+ internals = self._lstm_internals(window, int(layer))
174
+ internals["labels"] = [self.tok.token_str(i) for i in window]
175
+ return {"position": position, "window_start": start, "distribution": dist, "internals": internals,
176
+ "chosen_generated": position in self.records, "record": self.records.get(position)}
177
+
178
+ def sample(self, temperature=1.0):
179
+ """Samples the next token, appends it and returns how it was chosen."""
180
+ position = len(self.ids)
181
+ _, window = self._window(position)
182
+ logits = self._logits(window)[-1].cpu()
183
+ probs = F.softmax(logits / temperature, dim=-1)
184
+ nxt = int(torch.multinomial(probs, 1, generator=self._gen))
185
+ p1 = F.softmax(logits, dim=-1)[nxt] # loss is always reported at T = 1
186
+ self.records[position] = {"prob": round(float(probs[nxt]), 6), "temperature": temperature,
187
+ "loss": round(float(-torch.log(p1)), 5)}
188
+ self.ids.append(nxt)
189
+ return {"position": position, "id": nxt, "token": self.tok.token_str(nxt), **self.records[position]}
190
+
191
+ @torch.no_grad()
192
+ def score(self, text):
193
+ """Per-token cross-entropy (T = 1) of a reference continuation of the prompt, teacher-forced."""
194
+ ref = self.tok.encode(text)
195
+ if not ref:
196
+ raise ValueError("the reference text is empty")
197
+ seq = self.prompt_ids + ref
198
+ n_prompt = len(self.prompt_ids)
199
+ if len(seq) - 1 <= self.context_len:
200
+ pred = self._logits(seq[:-1])[n_prompt - 1:] # one pass covers every prediction
201
+ else: # longer than the context: one sliding window per predicted token
202
+ pred = torch.stack([self._logits(seq[max(0, p - self.context_len):p])[-1]
203
+ for p in range(n_prompt, len(seq))])
204
+ targets = torch.tensor(seq[n_prompt:], device=pred.device)
205
+ losses = F.cross_entropy(pred, targets, reduction="none").tolist()
206
+ running, total = [], 0.0
207
+ for k, l in enumerate(losses, 1):
208
+ total += l
209
+ running.append(round(math.exp(total / k), 4))
210
+ return {"tokens": [self.tok.token_str(i) for i in ref], "losses": _round(losses, 5),
211
+ "running_perplexity": running, "mean_loss": round(total / len(losses), 5),
212
+ "perplexity": running[-1],
213
+ "bits_per_char": round(total / LN2 / len(self.tok.decode(ref)), 4)}
lmscope/models.py ADDED
@@ -0,0 +1,159 @@
1
+ """Model architectures, copied from the HW3 code so its checkpoints load unchanged.
2
+
3
+ Parameter names must stay identical to HW3 (`embed`, `lstm`, `head` for the LSTM; `tok_embed`,
4
+ `pos_embed`, `blocks.N.{ln1,attn.qkv,attn.proj,ln2,ff.net}`, `ln_f`, `head` for the Transformer).
5
+ Two additions that add no parameters:
6
+ * MultiHeadSelfAttention applies its softmax through an `AttentionSoftmax` submodule, so a forward
7
+ hook on that submodule sees the attention weights.
8
+ * CustomLSTMCell re-runs one nn.LSTM layer step by step from its weights and exposes the gates.
9
+ """
10
+ import math
11
+
12
+ import torch
13
+ import torch.nn as nn
14
+ import torch.nn.functional as F
15
+
16
+
17
+ class LSTMModel(nn.Module):
18
+ """Embedding -> multi-layer nn.LSTM -> dropout -> Linear."""
19
+
20
+ def __init__(self, vocab_size, d_model=512, hidden_size=1024, n_layers=3, dropout=0.3, **_):
21
+ super().__init__()
22
+ self.embed = nn.Embedding(vocab_size, d_model)
23
+ self.lstm = nn.LSTM(d_model, hidden_size, num_layers=n_layers, dropout=dropout, batch_first=True)
24
+ self.drop = nn.Dropout(dropout)
25
+ self.head = nn.Linear(hidden_size, vocab_size)
26
+
27
+ def forward(self, x, hidden=None):
28
+ out, hidden = self.lstm(self.embed(x), hidden)
29
+ return self.head(self.drop(out)), hidden
30
+
31
+
32
+ class CustomLSTMCell:
33
+ """One layer of an nn.LSTM, evaluated step by step with its gates exposed.
34
+
35
+ nn.LSTM stacks the gate weights in the order (input, forget, cell candidate, output):
36
+ gates = W_ih x_t + b_ih + W_hh h_{t-1} + b_hh
37
+ i, f, o = sigmoid(...), g = tanh(...)
38
+ c_t = f * c_{t-1} + i * g, h_t = o * tanh(c_t)
39
+ """
40
+
41
+ def __init__(self, lstm, layer):
42
+ self.w_ih = getattr(lstm, f"weight_ih_l{layer}")
43
+ self.w_hh = getattr(lstm, f"weight_hh_l{layer}")
44
+ self.b = getattr(lstm, f"bias_ih_l{layer}") + getattr(lstm, f"bias_hh_l{layer}")
45
+ self.hidden_size = lstm.hidden_size
46
+
47
+ @torch.no_grad()
48
+ def run(self, x):
49
+ """x: (T, input_size). Returns h (T, H), c (T, H) and gates {"input","forget","output"} each (T, H)."""
50
+ T, H = x.shape[0], self.hidden_size
51
+ h = x.new_zeros(H)
52
+ c = x.new_zeros(H)
53
+ x_proj = x @ self.w_ih.T + self.b # input part of all steps at once
54
+ hs, cs, gi, gf, go = [], [], [], [], []
55
+ for t in range(T):
56
+ gates = x_proj[t] + self.w_hh @ h
57
+ i, f, g, o = gates.split(H)
58
+ i, f, o, g = torch.sigmoid(i), torch.sigmoid(f), torch.sigmoid(o), torch.tanh(g)
59
+ c = f * c + i * g
60
+ h = o * torch.tanh(c)
61
+ hs.append(h); cs.append(c); gi.append(i); gf.append(f); go.append(o)
62
+ stack = torch.stack
63
+ return stack(hs), stack(cs), {"input": stack(gi), "forget": stack(gf), "output": stack(go)}
64
+
65
+
66
+ class AttentionSoftmax(nn.Module):
67
+ """Softmax over the key axis. A module of its own so forward hooks can read attention weights."""
68
+
69
+ def forward(self, scores):
70
+ return F.softmax(scores, dim=-1)
71
+
72
+
73
+ class MultiHeadSelfAttention(nn.Module):
74
+ def __init__(self, d_model, n_heads, context_len, dropout):
75
+ super().__init__()
76
+ assert d_model % n_heads == 0
77
+ self.n_heads = n_heads
78
+ self.d_k = d_model // n_heads
79
+ self.qkv = nn.Linear(d_model, 3 * d_model)
80
+ self.proj = nn.Linear(d_model, d_model)
81
+ self.softmax = AttentionSoftmax()
82
+ self.attn_drop = nn.Dropout(dropout)
83
+ self.resid_drop = nn.Dropout(dropout)
84
+ mask = torch.triu(torch.ones(context_len, context_len), diagonal=1).bool()
85
+ self.register_buffer("causal_mask", mask, persistent=False)
86
+
87
+ def forward(self, x):
88
+ B, T, C = x.shape
89
+ q, k, v = self.qkv(x).split(C, dim=2)
90
+ q = q.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
91
+ k = k.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
92
+ v = v.view(B, T, self.n_heads, self.d_k).transpose(1, 2)
93
+ scores = q @ k.transpose(-2, -1) / math.sqrt(self.d_k)
94
+ scores = scores.masked_fill(self.causal_mask[:T, :T], float("-inf"))
95
+ attn = self.softmax(scores) # (B, heads, T, T)
96
+ out = self.attn_drop(attn) @ v
97
+ out = out.transpose(1, 2).contiguous().view(B, T, C)
98
+ return self.resid_drop(self.proj(out))
99
+
100
+
101
+ class FeedForward(nn.Module):
102
+ def __init__(self, d_model, d_ff, dropout):
103
+ super().__init__()
104
+ self.net = nn.Sequential(nn.Linear(d_model, d_ff), nn.GELU(), nn.Linear(d_ff, d_model), nn.Dropout(dropout))
105
+
106
+ def forward(self, x):
107
+ return self.net(x)
108
+
109
+
110
+ class TransformerBlock(nn.Module):
111
+ """Pre-norm block: x + Attn(LN(x)), then x + FFN(LN(x))."""
112
+
113
+ def __init__(self, d_model, n_heads, d_ff, context_len, dropout):
114
+ super().__init__()
115
+ self.ln1 = nn.LayerNorm(d_model)
116
+ self.attn = MultiHeadSelfAttention(d_model, n_heads, context_len, dropout)
117
+ self.ln2 = nn.LayerNorm(d_model)
118
+ self.ff = FeedForward(d_model, d_ff, dropout)
119
+
120
+ def forward(self, x):
121
+ x = x + self.attn(self.ln1(x))
122
+ return x + self.ff(self.ln2(x))
123
+
124
+
125
+ class CausalTransformer(nn.Module):
126
+ """Decoder-only Transformer with learned positional embeddings."""
127
+
128
+ def __init__(self, vocab_size, d_model=512, n_heads=8, n_layers=6, d_ff=2048, context_len=256,
129
+ dropout=0.1, **_):
130
+ super().__init__()
131
+ self.context_len = context_len
132
+ self.tok_embed = nn.Embedding(vocab_size, d_model)
133
+ self.pos_embed = nn.Embedding(context_len, d_model)
134
+ self.drop = nn.Dropout(dropout)
135
+ self.blocks = nn.ModuleList(
136
+ [TransformerBlock(d_model, n_heads, d_ff, context_len, dropout) for _ in range(n_layers)])
137
+ self.ln_f = nn.LayerNorm(d_model)
138
+ self.head = nn.Linear(d_model, vocab_size)
139
+
140
+ def forward(self, x):
141
+ T = x.shape[1]
142
+ h = self.drop(self.tok_embed(x) + self.pos_embed(torch.arange(T, device=x.device)))
143
+ for block in self.blocks:
144
+ h = block(h)
145
+ return self.head(self.ln_f(h))
146
+
147
+
148
+ def build_model(config):
149
+ """Builds an untrained model from a checkpoint's model_config."""
150
+ kind = config["model_type"]
151
+ if kind == "lstm":
152
+ return LSTMModel(**config)
153
+ if kind == "transformer":
154
+ return CausalTransformer(**config)
155
+ raise ValueError(f"unknown model_type {kind!r}")
156
+
157
+
158
+ def count_params(model):
159
+ return sum(p.numel() for p in model.parameters())
lmscope/server.py ADDED
@@ -0,0 +1,91 @@
1
+ """Flask app: serves the single-page UI and a small JSON API around one Inspector."""
2
+ import threading
3
+ import webbrowser
4
+ from pathlib import Path
5
+
6
+ from flask import Flask, jsonify, request, send_from_directory
7
+
8
+ from .inference import Inspector, load_checkpoint
9
+
10
+ STATIC = Path(__file__).resolve().parent / "static"
11
+
12
+
13
+ def create_app(inspector, reference_text=None):
14
+ app = Flask(__name__, static_folder=None)
15
+ lock = threading.Lock() # one model, one sequence: serialize requests
16
+
17
+ def body():
18
+ return request.get_json(silent=True) or {}
19
+
20
+ def api(fn):
21
+ def wrapper():
22
+ try:
23
+ with lock:
24
+ return jsonify(fn(body()))
25
+ except ValueError as e:
26
+ return jsonify({"error": str(e)}), 400
27
+ wrapper.__name__ = fn.__name__
28
+ return wrapper
29
+
30
+ @app.get("/")
31
+ def index():
32
+ return send_from_directory(STATIC, "index.html")
33
+
34
+ @app.get("/api/model-info")
35
+ @api
36
+ def model_info(_):
37
+ return {**inspector.model_info(), "reference_text": reference_text}
38
+
39
+ @app.get("/api/state")
40
+ @api
41
+ def state(_):
42
+ return inspector.state()
43
+
44
+ @app.post("/api/set-prompt")
45
+ @api
46
+ def set_prompt(b):
47
+ return inspector.set_prompt(b.get("prompt", ""))
48
+
49
+ @app.post("/api/reset")
50
+ @api
51
+ def reset(_):
52
+ return inspector.reset()
53
+
54
+ @app.post("/api/step")
55
+ @api
56
+ def step(b):
57
+ """One forward pass: distribution + internals for predicting the token at `position`."""
58
+ return inspector.analyze(position=b.get("position"), temperature=float(b.get("temperature", 1.0)),
59
+ layer=int(b.get("layer", 0)), head=b.get("head", "mean"),
60
+ top_k=int(b.get("top_k", 20)))
61
+
62
+ @app.post("/api/sample")
63
+ @api
64
+ def sample(b):
65
+ """Samples and appends the next token; returns the choice and the updated sequence."""
66
+ chosen = inspector.sample(float(b.get("temperature", 1.0)))
67
+ return {"sampled": chosen, "state": inspector.state()}
68
+
69
+ @app.post("/api/score")
70
+ @api
71
+ def score(b):
72
+ return inspector.score(b.get("text", ""))
73
+
74
+ return app
75
+
76
+
77
+ def serve(model_path, model_type=None, tokenizer_path=None, tokenizer_type=None, port=8765,
78
+ host="127.0.0.1", prompt="ROMEO:\n", seed=0, reference_file=None, open_browser=True, device=None):
79
+ """Loads a checkpoint and starts the UI at http://host:port."""
80
+ model, tokenizer, config = load_checkpoint(model_path, model_type, tokenizer_path, tokenizer_type, device)
81
+ inspector = Inspector(model, tokenizer, config, seed=seed)
82
+ inspector.set_prompt(prompt)
83
+ reference_text = Path(reference_file).read_text(encoding="utf-8") if reference_file else None
84
+ app = create_app(inspector, reference_text)
85
+ url = f"http://{host}:{port}"
86
+ info = inspector.model_info()
87
+ print(f"lmscope: {info['model_type']} ({info['params'] / 1e6:.2f}M params, {info['tokenizer_type']} "
88
+ f"tokenizer, vocab {info['vocab_size']}) on {info['device']} -> {url}")
89
+ if open_browser:
90
+ threading.Timer(1.0, lambda: webbrowser.open(url)).start()
91
+ app.run(host=host, port=port, debug=False, threaded=True)
@@ -0,0 +1,452 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>lmscope</title>
7
+ <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
8
+ <style>
9
+ :root {
10
+ --bg: #f6f7f9; --panel: #ffffff; --ink: #1f2937; --muted: #6b7280; --line: #e5e7eb;
11
+ --accent: #2563eb; --chosen: #ea580c; --mask: #f1f2f4;
12
+ --mono: ui-monospace, "Cascadia Mono", Consolas, monospace;
13
+ }
14
+ * { box-sizing: border-box; }
15
+ body { margin: 0; background: var(--bg); color: var(--ink); font: 13px/1.4 system-ui, "Segoe UI", sans-serif; }
16
+ header { display: flex; flex-wrap: wrap; gap: 10px 16px; align-items: center; padding: 10px 16px;
17
+ background: var(--panel); border-bottom: 1px solid var(--line); position: sticky; top: 0; z-index: 5; }
18
+ header h1 { font-size: 16px; margin: 0; }
19
+ .badge { font-family: var(--mono); font-size: 12px; background: #eef2ff; color: #3730a3; padding: 3px 8px; border-radius: 4px; }
20
+ .group { display: flex; align-items: center; gap: 6px; }
21
+ textarea, input[type=text] { font-family: var(--mono); font-size: 12px; border: 1px solid var(--line); border-radius: 4px; padding: 4px 6px; }
22
+ #prompt { width: 220px; height: 40px; resize: vertical; }
23
+ button { font: inherit; padding: 4px 10px; border: 1px solid #cbd5e1; background: #fff; border-radius: 4px; cursor: pointer; }
24
+ button:hover { background: #f1f5f9; }
25
+ button.primary { background: var(--accent); border-color: var(--accent); color: #fff; }
26
+ button.primary:hover { background: #1d4ed8; }
27
+ .value { font-family: var(--mono); min-width: 3.5em; display: inline-block; }
28
+ #status { color: #b91c1c; font-size: 12px; }
29
+ main { display: grid; grid-template-columns: minmax(260px, 1fr) minmax(320px, 1.1fr) minmax(420px, 1.5fr); gap: 12px; padding: 12px 16px; }
30
+ @media (max-width: 1100px) { main { grid-template-columns: 1fr; } }
31
+ .panel { background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 10px 12px; min-width: 0; }
32
+ .panel h2 { font-size: 13px; margin: 0 0 8px; display: flex; justify-content: space-between; align-items: center; gap: 8px; }
33
+ .panel h3 { font-size: 12px; margin: 12px 0 4px; color: var(--muted); font-weight: 600; }
34
+ .export { font-size: 11px; padding: 1px 6px; color: var(--muted); }
35
+ .muted { color: var(--muted); }
36
+ #tokens { display: flex; flex-wrap: wrap; gap: 2px; align-content: flex-start; max-height: 52vh; overflow-y: auto;
37
+ padding: 4px; border: 1px solid var(--line); border-radius: 4px; }
38
+ .chip { font-family: var(--mono); font-size: 12px; padding: 1px 3px; border-radius: 3px; cursor: pointer;
39
+ border: 1px solid transparent; white-space: pre; min-width: 10px; text-align: center; }
40
+ .chip.prompt { background: #e5e7eb; color: #374151; }
41
+ .chip.first { cursor: default; }
42
+ .chip.view { outline: 2px solid var(--chosen); outline-offset: 0; }
43
+ .chip.next { border: 1px dashed #94a3b8; color: var(--muted); }
44
+ .chip.inctx { box-shadow: inset 0 -2px 0 #93c5fd; }
45
+ .br { flex-basis: 100%; height: 0; }
46
+ #seqtext { font-family: var(--mono); font-size: 12px; white-space: pre-wrap; max-height: 18vh; overflow-y: auto;
47
+ background: #fafafa; border: 1px solid var(--line); border-radius: 4px; padding: 6px; margin: 6px 0 0; }
48
+ .gauge { height: 10px; background: #e5e7eb; border-radius: 5px; overflow: hidden; }
49
+ .gauge > div { height: 100%; background: linear-gradient(90deg, #22c55e, #eab308, #ef4444); }
50
+ .stats { font-family: var(--mono); font-size: 12px; }
51
+ select { font: inherit; padding: 2px 4px; }
52
+ canvas { display: block; max-width: 100%; }
53
+ footer { padding: 0 16px 16px; }
54
+ #refText { width: 100%; height: 48px; }
55
+ .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; margin: 4px 0; }
56
+ #tip { position: fixed; pointer-events: none; background: #111827; color: #fff; font: 11px var(--mono);
57
+ padding: 3px 6px; border-radius: 3px; display: none; z-index: 10; white-space: pre; }
58
+ </style>
59
+ </head>
60
+ <body>
61
+ <header>
62
+ <h1>lmscope</h1>
63
+ <span class="badge" id="badge">loading…</span>
64
+ <div class="group">
65
+ <textarea id="prompt" title="Prompt (newlines allowed)"></textarea>
66
+ <button id="setPrompt">Set prompt</button>
67
+ </div>
68
+ <div class="group">T <input type="range" id="temp" min="0.1" max="2" step="0.05" value="1"><span class="value" id="tempVal">1.00</span></div>
69
+ <div class="group">
70
+ <button class="primary" id="stepBtn">Step</button>
71
+ <button id="playBtn">▶ Play</button>
72
+ delay <input type="range" id="speed" min="100" max="2000" step="50" value="400"><span class="value" id="speedVal">400ms</span>
73
+ <button id="resetBtn">Reset</button>
74
+ </div>
75
+ <button id="exportPage">Export page PNG</button>
76
+ <span id="status"></span>
77
+ </header>
78
+
79
+ <main id="main">
80
+ <section class="panel" id="panelTokens">
81
+ <h2>Token sequence <button class="export noexport" data-panel="panelTokens">PNG</button></h2>
82
+ <div id="tokens"></div>
83
+ <div class="stats" id="seqStats" style="margin-top:6px"></div>
84
+ <div class="muted" style="font-size:11px">Colour = probability of the sampled token. Click a token to see the step that produced it; the dashed chip is the next prediction. Blue underline = tokens the model sees for the selected step.</div>
85
+ <div id="seqtext"></div>
86
+ </section>
87
+
88
+ <section class="panel" id="panelDist">
89
+ <h2><span>Next-token distribution <span class="muted" id="distTitle"></span></span>
90
+ <button class="export noexport" data-panel="panelDist">PNG</button></h2>
91
+ <canvas id="distCanvas"></canvas>
92
+ <h3>Entropy</h3>
93
+ <div class="gauge"><div id="entropyBar" style="width:0"></div></div>
94
+ <div class="stats" id="entropyText"></div>
95
+ <h3>Probability mass</h3>
96
+ <div class="stats" id="massText"></div>
97
+ </section>
98
+
99
+ <section class="panel" id="panelInternals">
100
+ <h2><span id="internalsTitle">Model internals</span>
101
+ <button class="export noexport" data-panel="panelInternals">PNG</button></h2>
102
+ <div class="row">
103
+ layer <select id="layerSel"></select>
104
+ <span id="headWrap">head <select id="headSel"></select>
105
+ <label title="square-root colour scale: shows weak attention next to a strong sink"><input type="checkbox" id="sqrtScale"> √ colour scale</label></span>
106
+ <label id="sortWrap"><input type="checkbox" id="sortUnits"> sort units</label>
107
+ </div>
108
+ <div id="internalsBody"></div>
109
+ </section>
110
+ </main>
111
+
112
+ <footer>
113
+ <section class="panel" id="panelLoss">
114
+ <h2>Loss / perplexity (T = 1) <button class="export noexport" data-panel="panelLoss">PNG</button></h2>
115
+ <div class="stats" id="genLossText"></div>
116
+ <canvas id="genLossCanvas"></canvas>
117
+ <h3>Reference continuation (teacher-forced after the prompt)</h3>
118
+ <textarea id="refText" placeholder="Paste the true continuation of the prompt, e.g. from the validation set"></textarea>
119
+ <div class="row"><button id="scoreBtn">Score reference</button><span class="stats" id="refStats"></span></div>
120
+ <canvas id="refCanvas"></canvas>
121
+ </section>
122
+ </footer>
123
+ <div id="tip"></div>
124
+
125
+ <script>
126
+ "use strict";
127
+ const $ = s => document.querySelector(s);
128
+ const S = { info: null, seq: null, view: null, an: null, layer: 0, head: "mean", playing: false, ref: null };
129
+ const DPR = Math.max(2, window.devicePixelRatio || 1);
130
+ const MONO = 'ui-monospace, "Cascadia Mono", Consolas, monospace';
131
+ const PALETTE = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"];
132
+ const VIRIDIS = [[68,1,84],[72,40,120],[62,74,137],[49,104,142],[38,130,142],[31,158,137],[53,183,121],[109,205,89],[180,222,44],[253,231,37]];
133
+
134
+ // ---------------------------------------------------------------- helpers
135
+ async function api(path, body) {
136
+ const opts = body === undefined ? {} : { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) };
137
+ const r = await fetch(path, opts);
138
+ const j = await r.json();
139
+ if (!r.ok) throw new Error(j.error || r.statusText);
140
+ return j;
141
+ }
142
+ let chain = Promise.resolve();
143
+ function run(fn) { // serialize all requests so steps never interleave
144
+ chain = chain.then(fn).then(() => { $("#status").textContent = ""; })
145
+ .catch(e => { $("#status").textContent = e.message; stopPlay(); });
146
+ return chain;
147
+ }
148
+ const sleep = ms => new Promise(r => setTimeout(r, ms));
149
+ const T = () => parseFloat($("#temp").value);
150
+ const show = t => t === "" ? "∅" : t.replace(/\n/g, "↵").replace(/ /g, "␣").replace(/\t/g, "⇥");
151
+ function viridis(x) {
152
+ x = Math.min(1, Math.max(0, x)) * (VIRIDIS.length - 1);
153
+ const i = Math.min(VIRIDIS.length - 2, Math.floor(x)), f = x - i, a = VIRIDIS[i], b = VIRIDIS[i + 1];
154
+ return `rgb(${a.map((v, k) => Math.round(v + f * (b[k] - v))).join(",")})`;
155
+ }
156
+ function setup(cv, w, h) { // canvases are drawn at >= 2x so exported PNGs stay sharp
157
+ cv.width = Math.round(w * DPR); cv.height = Math.round(h * DPR);
158
+ cv.style.width = w + "px"; cv.style.height = h + "px";
159
+ const ctx = cv.getContext("2d");
160
+ ctx.setTransform(DPR, 0, 0, DPR, 0, 0);
161
+ ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, w, h);
162
+ return ctx;
163
+ }
164
+ const widthOf = el => Math.max(240, el.clientWidth - 24);
165
+ const fmtPct = p => (100 * p).toFixed(p < 0.001 ? 3 : 1) + "%";
166
+ function niceMax(v) { if (v <= 0) return 1; const e = Math.pow(10, Math.floor(Math.log10(v))); return Math.ceil(v / e * 2) / 2 * e; }
167
+
168
+ function lineChart(cv, width, height, series, opts = {}) {
169
+ const ctx = setup(cv, width, height);
170
+ const L = 44, R = 10, Tp = 18, B = 30, w = width - L - R, h = height - Tp - B;
171
+ const all = series.flatMap(s => s.values), n = Math.max(...series.map(s => s.values.length));
172
+ let lo = opts.min ?? Math.min(...all), hi = opts.max ?? Math.max(...all);
173
+ if (hi - lo < 1e-9) hi = lo + 1;
174
+ const X = i => L + (n <= 1 ? w / 2 : i / (n - 1) * w), Y = v => Tp + h - (v - lo) / (hi - lo) * h;
175
+ ctx.strokeStyle = "#e5e7eb"; ctx.fillStyle = "#6b7280"; ctx.font = "10px system-ui"; ctx.lineWidth = 1;
176
+ for (let k = 0; k <= 4; k++) {
177
+ const v = lo + (hi - lo) * k / 4, y = Y(v);
178
+ ctx.beginPath(); ctx.moveTo(L, y); ctx.lineTo(L + w, y); ctx.stroke();
179
+ ctx.textAlign = "right"; ctx.fillText(v.toFixed(hi - lo < 5 ? 2 : 0), L - 4, y + 3);
180
+ }
181
+ ctx.textAlign = "center"; ctx.fillText(opts.xlabel || "", L + w / 2, height - 4);
182
+ if (n > 0) for (const k of new Set([0, n - 1])) ctx.fillText(String((opts.x0 || 0) + k), X(k), Tp + h + 12);
183
+ series.forEach((s, si) => {
184
+ ctx.strokeStyle = s.color || PALETTE[si % 10]; ctx.lineWidth = 1.5; ctx.beginPath();
185
+ s.values.forEach((v, i) => i ? ctx.lineTo(X(i), Y(v)) : ctx.moveTo(X(i), Y(v)));
186
+ if (s.values.length === 1) ctx.arc(X(0), Y(s.values[0]), 2, 0, 7);
187
+ ctx.stroke();
188
+ });
189
+ let lx = L; ctx.textAlign = "left";
190
+ series.forEach((s, si) => {
191
+ ctx.fillStyle = s.color || PALETTE[si % 10]; ctx.fillRect(lx, 5, 10, 3);
192
+ ctx.fillStyle = "#374151"; ctx.fillText(s.name, lx + 13, 10);
193
+ lx += 20 + ctx.measureText(s.name).width;
194
+ });
195
+ if (opts.ylabel) { ctx.save(); ctx.translate(10, Tp + h / 2); ctx.rotate(-Math.PI / 2); ctx.textAlign = "center"; ctx.fillStyle = "#6b7280"; ctx.fillText(opts.ylabel, 0, 0); ctx.restore(); }
196
+ }
197
+
198
+ // ---------------------------------------------------------------- tokens
199
+ function renderTokens() {
200
+ const box = $("#tokens"), seq = S.seq, start = S.an ? S.an.window_start : 0;
201
+ box.innerHTML = "";
202
+ seq.tokens.forEach((t, i) => {
203
+ const c = document.createElement("span");
204
+ c.className = "chip" + (t.generated ? "" : " prompt") + (i === 0 ? " first" : "") + (i === S.view ? " view" : "")
205
+ + (i >= start && i < S.view ? " inctx" : "");
206
+ c.textContent = show(t.token);
207
+ if (t.generated) {
208
+ c.style.background = `rgba(37,99,235,${(0.12 + 0.88 * t.prob).toFixed(3)})`;
209
+ c.style.color = t.prob > 0.45 ? "#fff" : "#1e3a8a";
210
+ }
211
+ c.title = `#${i} ${JSON.stringify(t.token)}` + (t.generated ? `\np(sampled) = ${t.prob}\nloss (T=1) = ${t.loss}` : "\nprompt token");
212
+ if (i > 0) c.onclick = () => { S.view = i; run(analyze); };
213
+ box.appendChild(c);
214
+ if (t.token.endsWith("\n")) { const br = document.createElement("span"); br.className = "br"; box.appendChild(br); }
215
+ });
216
+ const nx = document.createElement("span");
217
+ nx.className = "chip next" + (S.view === seq.length ? " view" : "");
218
+ nx.textContent = "▸ next"; nx.title = "prediction for the next token";
219
+ nx.onclick = () => { S.view = seq.length; run(analyze); };
220
+ box.appendChild(nx);
221
+ if (S.view === seq.length) box.scrollTop = box.scrollHeight;
222
+ const ctx = S.info.context_len;
223
+ $("#seqStats").textContent = `prompt ${seq.prompt_len} · generated ${seq.generated} · length ${seq.length} tokens · `
224
+ + `${seq.text.length} chars · step ${S.view} sees ${Math.min(S.view, ctx)}/${ctx} tokens`;
225
+ $("#seqtext").textContent = seq.text;
226
+ }
227
+
228
+ // ---------------------------------------------------------------- distribution
229
+ function renderDist() {
230
+ const d = S.an.distribution, cv = $("#distCanvas"), width = widthOf($("#panelDist"));
231
+ const rows = d.top, chosen = d.chosen, chosenInTop = chosen && rows.some(r => r.id === chosen.id);
232
+ const rowH = 18, extra = chosen && !chosenInTop ? 1 : 0, height = (rows.length + extra) * rowH + 24;
233
+ const ctx = setup(cv, width, height);
234
+ const L = 64, R = 58, w = width - L - R, max = Math.max(...rows.map(r => r.prob), 1e-9);
235
+ ctx.font = "11px " + MONO;
236
+ rows.forEach((r, i) => {
237
+ const y = 4 + i * rowH, bw = Math.max(1, r.prob / max * w), isChosen = chosen && r.id === chosen.id;
238
+ ctx.fillStyle = isChosen ? "#ea580c" : "#2563eb";
239
+ ctx.fillRect(L, y + 2, bw, rowH - 5);
240
+ ctx.fillStyle = isChosen ? "#ea580c" : "#111827"; ctx.textAlign = "right";
241
+ ctx.fillText(show(r.token).slice(0, 9), L - 6, y + 13);
242
+ ctx.textAlign = "left"; ctx.fillStyle = "#374151";
243
+ ctx.fillText(fmtPct(r.prob), L + bw + 4, y + 13);
244
+ });
245
+ if (extra) {
246
+ ctx.fillStyle = "#ea580c"; ctx.textAlign = "left";
247
+ ctx.fillText(`chosen ${JSON.stringify(chosen.token)}: ${fmtPct(chosen.prob)} (rank ${chosen.rank})`, L, 4 + rows.length * rowH + 13);
248
+ }
249
+ ctx.fillStyle = "#6b7280"; ctx.textAlign = "center"; ctx.font = "10px system-ui";
250
+ ctx.fillText(`top ${rows.length} probabilities at T = ${d.temperature.toFixed(2)} · bars scaled to the top token`, L + w / 2, height - 4);
251
+ $("#distTitle").textContent = chosen
252
+ ? `· step ${S.an.position}, ${S.an.chosen_generated ? "sampled" : "prompt"} token ${JSON.stringify(chosen.token)} in orange (rank ${chosen.rank})`
253
+ : `· step ${S.an.position} (next token)`;
254
+ $("#entropyBar").style.width = (100 * d.entropy_bits / d.max_entropy_bits).toFixed(1) + "%";
255
+ $("#entropyText").textContent = `H = −Σ p log₂ p = ${d.entropy_bits.toFixed(3)} bits (max ${d.max_entropy_bits.toFixed(2)}) · 2^H = ${Math.pow(2, d.entropy_bits).toFixed(2)} effective choices`;
256
+ const m = d.topk_mass;
257
+ $("#massText").innerHTML = `top 5 tokens cover <b>${fmtPct(m[5] ?? m[1])}</b> of the probability mass<br>`
258
+ + Object.entries(m).map(([k, v]) => `top ${k}: ${fmtPct(v)}`).join(" · ");
259
+ }
260
+
261
+ // ---------------------------------------------------------------- internals
262
+ let heatGeom = null;
263
+ function renderAttention(it, body) {
264
+ body.innerHTML = `<canvas id="heat"></canvas><div class="stats" id="heatInfo"></div>
265
+ <h3>Mean attention distance of the current query, per head (tokens back)</h3><div class="stats" id="headDist"></div>
266
+ <h3>Residual-stream norm per position</h3><canvas id="normChart"></canvas>`;
267
+ const M = it.matrix, n = M.length, labels = it.labels, width = widthOf($("#panelInternals"));
268
+ const Lm = 46, Tm = 6, Bm = 46, Rm = 56, size = Math.min(width - Lm - Rm, 560), cell = size / n;
269
+ const cv = $("#heat"), ctx = setup(cv, Lm + size + Rm, Tm + size + Bm);
270
+ let max = 0; M.forEach(r => r.forEach(v => { if (v > max) max = v; }));
271
+ const sq = $("#sqrtScale").checked, scale = v => sq ? Math.sqrt(v / max) : v / max;
272
+ for (let i = 0; i < n; i++) for (let j = 0; j < n; j++) {
273
+ ctx.fillStyle = j > i ? "#f1f2f4" : viridis(scale(M[i][j]));
274
+ ctx.fillRect(Lm + j * cell, Tm + i * cell, Math.ceil(cell), Math.ceil(cell));
275
+ }
276
+ ctx.strokeStyle = "#ea580c"; ctx.lineWidth = 1.5;
277
+ ctx.strokeRect(Lm, Tm + (n - 1) * cell, size, cell);
278
+ const every = Math.max(1, Math.ceil(11 / cell));
279
+ ctx.font = `${Math.min(11, Math.max(8, cell - 1))}px ${MONO}`;
280
+ ctx.fillStyle = "#111827";
281
+ for (let k = 0; k < n; k++) {
282
+ if (k % every && k !== n - 1) continue;
283
+ ctx.textAlign = "right"; ctx.fillText(show(labels[k]).slice(0, 4), Lm - 4, Tm + (k + 0.5) * cell + 3);
284
+ ctx.save(); ctx.translate(Lm + (k + 0.5) * cell + 3, Tm + size + 4); ctx.rotate(-Math.PI / 2);
285
+ ctx.textAlign = "right"; ctx.fillText(show(labels[k]).slice(0, 4), 0, 0); ctx.restore();
286
+ }
287
+ ctx.fillStyle = "#6b7280"; ctx.font = "10px system-ui"; ctx.textAlign = "center";
288
+ ctx.fillText("key (attended-to) position →", Lm + size / 2, Tm + size + Bm - 4);
289
+ ctx.save(); ctx.translate(9, Tm + size / 2); ctx.rotate(-Math.PI / 2); ctx.fillText("← query position", 0, 0); ctx.restore();
290
+ const cx = Lm + size + 14;
291
+ for (let k = 0; k < size; k++) { ctx.fillStyle = viridis(1 - k / size); ctx.fillRect(cx, Tm + k, 12, 1.5); }
292
+ ctx.fillStyle = "#374151"; ctx.textAlign = "left";
293
+ ctx.fillText(max.toFixed(3), cx + 15, Tm + 8); ctx.fillText((sq ? max / 4 : max / 2).toFixed(3), cx + 15, Tm + size / 2 + 3); ctx.fillText("0", cx + 15, Tm + size);
294
+ heatGeom = { Lm, Tm, cell, n, M, labels, start: S.an.window_start };
295
+ const hd = it.head === "mean" ? "mean over heads" : `head ${+it.head + 1}`;
296
+ $("#heatInfo").textContent = `layer ${it.layer + 1}, ${hd} · ${n}×${n} · grey triangle = causal mask · orange row = current query · ${sq ? "√ " : ""}colour scaled to max ${max.toFixed(3)}`;
297
+ $("#headDist").textContent = it.head_mean_distance.map((d, h) => `h${h + 1} ${d.toFixed(1)}`).join(" ");
298
+ lineChart($("#normChart"), width, 170, it.norms.map((v, k) => ({ name: it.norm_labels[k], values: v })),
299
+ { xlabel: "position in sequence", ylabel: "‖h‖", x0: S.an.window_start });
300
+ cv.onmousemove = heatHover; cv.onmouseleave = () => { $("#tip").style.display = "none"; };
301
+ }
302
+ function heatHover(e) {
303
+ const g = heatGeom, tip = $("#tip"), r = e.target.getBoundingClientRect();
304
+ const j = Math.floor((e.clientX - r.left - g.Lm) / g.cell), i = Math.floor((e.clientY - r.top - g.Tm) / g.cell);
305
+ if (i < 0 || j < 0 || i >= g.n || j >= g.n) { tip.style.display = "none"; return; }
306
+ tip.textContent = j > i ? "masked (future)" :
307
+ `query #${g.start + i} ${JSON.stringify(g.labels[i])}\nkey #${g.start + j} ${JSON.stringify(g.labels[j])}\nweight ${g.M[i][j].toFixed(4)}`;
308
+ tip.style.left = e.clientX + 12 + "px"; tip.style.top = e.clientY + 12 + "px"; tip.style.display = "block";
309
+ }
310
+
311
+ function renderGates(it, body) {
312
+ body.innerHTML = ["forget", "input", "output"].map(g =>
313
+ `<h3>${g} gate · mean <span id="m_${g}"></span></h3><canvas id="g_${g}"></canvas>`).join("")
314
+ + `<div class="muted" style="font-size:11px">one bar per hidden unit (${it.hidden_size}) at the current position · height and colour = sigmoid activation (0–1)</div>
315
+ <h3>Gate means over the window</h3><canvas id="gateTime"></canvas>
316
+ <h3>Hidden-state norm per layer</h3><canvas id="normChart"></canvas>`;
317
+ const width = widthOf($("#panelInternals")), sorted = $("#sortUnits").checked;
318
+ for (const g of ["forget", "input", "output"]) {
319
+ const v = it.gates[g].slice(); if (sorted) v.sort((a, b) => a - b);
320
+ const ctx = setup($("#g_" + g), width, 64), L = 26, w = width - L - 4, h = 54, bw = w / v.length;
321
+ ctx.fillStyle = "#6b7280"; ctx.font = "10px system-ui"; ctx.textAlign = "right";
322
+ ctx.fillText("1", L - 4, 10); ctx.fillText("0", L - 4, h + 4);
323
+ ctx.strokeStyle = "#e5e7eb"; ctx.beginPath(); ctx.moveTo(L, 4 + h / 2); ctx.lineTo(L + w, 4 + h / 2); ctx.stroke();
324
+ v.forEach((x, k) => { ctx.fillStyle = viridis(x); ctx.fillRect(L + k * bw, 4 + h * (1 - x), Math.max(bw, 0.6), h * x); });
325
+ $("#m_" + g).textContent = it.gate_means[g].toFixed(3);
326
+ }
327
+ const gt = it.gate_means_over_time;
328
+ lineChart($("#gateTime"), width, 150, ["forget", "input", "output"].map((g, k) => ({ name: g, values: gt[g], color: PALETTE[k] })),
329
+ { xlabel: "position in sequence", ylabel: "mean", min: 0, max: 1, x0: S.an.window_start });
330
+ lineChart($("#normChart"), width, 160, it.norms.map((v, k) => ({ name: it.norm_labels[k], values: v })),
331
+ { xlabel: "position in sequence", ylabel: "‖h‖", x0: S.an.window_start });
332
+ }
333
+
334
+ function renderInternals() {
335
+ const it = S.an.internals;
336
+ $("#internalsTitle").textContent = it.kind === "attention" ? "Attention (query × key)" : `LSTM gates, layer ${it.layer + 1}`;
337
+ (it.kind === "attention" ? renderAttention : renderGates)(it, $("#internalsBody"));
338
+ }
339
+
340
+ // ---------------------------------------------------------------- loss
341
+ function lossBars(cv, labels, losses, ppl, width) {
342
+ const height = 150, ctx = setup(cv, width, height);
343
+ if (!losses.length) { ctx.fillStyle = "#6b7280"; ctx.font = "11px system-ui"; ctx.fillText("nothing to show yet", 10, 20); return; }
344
+ const L = 40, R = 44, Tp = 10, B = 26, w = width - L - R, h = height - Tp - B, n = losses.length, bw = w / n;
345
+ const lmax = niceMax(Math.max(...losses)), pmax = niceMax(Math.max(...ppl));
346
+ ctx.font = "10px system-ui"; ctx.fillStyle = "#6b7280";
347
+ ctx.textAlign = "right"; ctx.fillText(lmax.toFixed(1), L - 4, Tp + 8); ctx.fillText("0", L - 4, Tp + h);
348
+ ctx.textAlign = "left"; ctx.fillStyle = "#ea580c"; ctx.fillText(pmax.toFixed(1), L + w + 4, Tp + 8); ctx.fillText("ppl", L + w + 4, Tp + h / 2);
349
+ losses.forEach((l, k) => { ctx.fillStyle = "#93c5fd"; ctx.fillRect(L + k * bw, Tp + h * (1 - l / lmax), Math.max(bw - (bw > 3 ? 1 : 0), 0.6), h * l / lmax); });
350
+ ctx.strokeStyle = "#ea580c"; ctx.lineWidth = 1.5; ctx.beginPath();
351
+ ppl.forEach((p, k) => { const x = L + (k + 0.5) * bw, y = Tp + h * (1 - p / pmax); k ? ctx.lineTo(x, y) : ctx.moveTo(x, y); });
352
+ ctx.stroke();
353
+ if (bw >= 9) {
354
+ ctx.fillStyle = "#111827"; ctx.font = "10px " + MONO; ctx.textAlign = "center";
355
+ labels.forEach((t, k) => ctx.fillText(show(t).slice(0, Math.max(1, Math.floor(bw / 6))), L + (k + 0.5) * bw, Tp + h + 12));
356
+ }
357
+ ctx.fillStyle = "#6b7280"; ctx.font = "10px system-ui"; ctx.textAlign = "center";
358
+ ctx.fillText("bars: per-token cross-entropy (nats) · orange line: running perplexity", L + w / 2, height - 3);
359
+ }
360
+ function renderLoss() {
361
+ const gen = S.seq.tokens.filter(t => t.generated), width = widthOf($("#panelLoss"));
362
+ const losses = gen.map(t => t.loss); let tot = 0; const ppl = losses.map((l, k) => Math.exp((tot += l) / (k + 1)));
363
+ $("#genLossText").textContent = gen.length
364
+ ? `generated tokens, scored by the model at T = 1: mean loss ${(tot / gen.length).toFixed(3)} nats · perplexity ${ppl[ppl.length - 1].toFixed(2)}`
365
+ : "generated tokens: none yet";
366
+ lossBars($("#genLossCanvas"), gen.map(t => t.token), losses, ppl, width);
367
+ if (S.ref) {
368
+ const r = S.ref;
369
+ $("#refStats").textContent = `${r.tokens.length} tokens · mean loss ${r.mean_loss.toFixed(3)} nats · perplexity ${r.perplexity.toFixed(2)} · ${r.bits_per_char.toFixed(3)} bits/char`;
370
+ lossBars($("#refCanvas"), r.tokens, r.losses, r.running_perplexity, width);
371
+ } else { $("#refStats").textContent = ""; setup($("#refCanvas"), width, 1); }
372
+ }
373
+
374
+ // ---------------------------------------------------------------- actions
375
+ function renderAll() { renderTokens(); renderDist(); renderInternals(); renderLoss(); }
376
+ async function analyze() {
377
+ S.an = await api("/api/step", { position: S.view, temperature: T(), layer: S.layer, head: S.head });
378
+ renderAll();
379
+ }
380
+ async function stepOnce() {
381
+ const r = await api("/api/sample", { temperature: T() });
382
+ S.seq = r.state; S.view = r.sampled.position;
383
+ await analyze();
384
+ }
385
+ function stopPlay() { S.playing = false; $("#playBtn").textContent = "▶ Play"; }
386
+ async function playLoop() {
387
+ while (S.playing) {
388
+ await run(stepOnce);
389
+ if (S.playing) await sleep(+$("#speed").value);
390
+ }
391
+ }
392
+ function fillSelectors() {
393
+ const info = S.info, ls = $("#layerSel"), hs = $("#headSel"), tf = info.model_type === "transformer";
394
+ ls.innerHTML = Array.from({ length: info.n_layers }, (_, i) => `<option value="${i}">${i + 1}</option>`).join("");
395
+ ls.value = String(tf ? info.n_layers - 1 : 0); S.layer = +ls.value;
396
+ $("#headWrap").style.display = tf ? "" : "none";
397
+ $("#sortWrap").style.display = tf ? "none" : "";
398
+ if (tf) hs.innerHTML = `<option value="mean">mean</option>` + Array.from({ length: info.n_heads }, (_, i) => `<option value="${i}">${i + 1}</option>`).join("");
399
+ }
400
+ async function exportEl(el, name) {
401
+ let canvas;
402
+ if (window.html2canvas) {
403
+ canvas = await html2canvas(el, { scale: 2, backgroundColor: "#ffffff",
404
+ ignoreElements: n => n.classList && n.classList.contains("noexport") });
405
+ } else { // offline fallback: stack the panel's canvases
406
+ const cvs = [...el.querySelectorAll("canvas")].filter(c => c.height > DPR);
407
+ if (!cvs.length) throw new Error("html2canvas did not load (offline?) and this panel has no canvas");
408
+ canvas = document.createElement("canvas");
409
+ canvas.width = Math.max(...cvs.map(c => c.width)); canvas.height = cvs.reduce((s, c) => s + c.height, 0);
410
+ const ctx = canvas.getContext("2d"); ctx.fillStyle = "#fff"; ctx.fillRect(0, 0, canvas.width, canvas.height);
411
+ let y = 0; for (const c of cvs) { ctx.drawImage(c, 0, y); y += c.height; }
412
+ }
413
+ const a = document.createElement("a");
414
+ a.href = canvas.toDataURL("image/png"); a.download = `lmscope_${name}_step${S.view}.png`; a.click();
415
+ }
416
+
417
+ // ---------------------------------------------------------------- wiring
418
+ $("#temp").oninput = () => { $("#tempVal").textContent = T().toFixed(2); };
419
+ $("#temp").onchange = () => run(analyze);
420
+ $("#speed").oninput = () => { $("#speedVal").textContent = $("#speed").value + "ms"; };
421
+ $("#stepBtn").onclick = () => run(stepOnce);
422
+ $("#playBtn").onclick = () => {
423
+ if (S.playing) return stopPlay();
424
+ S.playing = true; $("#playBtn").textContent = "⏸ Pause"; playLoop();
425
+ };
426
+ $("#resetBtn").onclick = () => { stopPlay(); run(async () => { S.seq = await api("/api/reset", {}); S.view = S.seq.length; await analyze(); }); };
427
+ $("#setPrompt").onclick = () => { stopPlay(); run(async () => { S.seq = await api("/api/set-prompt", { prompt: $("#prompt").value }); S.view = S.seq.length; S.ref = null; await analyze(); }); };
428
+ $("#layerSel").onchange = e => { S.layer = +e.target.value; run(analyze); };
429
+ $("#headSel").onchange = e => { S.head = e.target.value; run(analyze); };
430
+ $("#sortUnits").onchange = () => renderInternals();
431
+ $("#sqrtScale").onchange = () => renderInternals();
432
+ $("#scoreBtn").onclick = () => run(async () => { S.ref = await api("/api/score", { text: $("#refText").value }); renderLoss(); });
433
+ $("#exportPage").onclick = () => run(() => exportEl(document.body, "page"));
434
+ document.querySelectorAll("button.export").forEach(b => b.onclick = () =>
435
+ run(() => exportEl($("#" + b.dataset.panel), b.dataset.panel.replace("panel", "").toLowerCase())));
436
+ let resizeTimer;
437
+ window.onresize = () => { clearTimeout(resizeTimer); resizeTimer = setTimeout(() => S.an && renderAll(), 150); };
438
+
439
+ run(async () => {
440
+ const i = S.info = await api("/api/model-info");
441
+ $("#badge").textContent = `${i.model_type === "lstm" ? "LSTM" : "Transformer"} · ${(i.params / 1e6).toFixed(2)}M params · `
442
+ + `${i.n_layers} layers · ${i.tokenizer_type} tokenizer · vocab ${i.vocab_size} · ctx ${i.context_len} · ${i.device}`;
443
+ if (i.reference_text) $("#refText").value = i.reference_text.slice(0, 4000);
444
+ fillSelectors();
445
+ S.seq = await api("/api/state");
446
+ $("#prompt").value = S.seq.tokens.slice(0, S.seq.prompt_len).map(t => t.token).join("");
447
+ S.view = S.seq.length;
448
+ await analyze();
449
+ });
450
+ </script>
451
+ </body>
452
+ </html>
lmscope/tokenizers.py ADDED
@@ -0,0 +1,81 @@
1
+ """Char and BPE tokenizers with one small interface: encode, decode, token_str, vocab_size."""
2
+ import json
3
+ from pathlib import Path
4
+
5
+ from tokenizers import Tokenizer
6
+
7
+
8
+ class CharTokenizer:
9
+ """One token per character, from a char_to_idx mapping."""
10
+
11
+ kind = "char"
12
+
13
+ def __init__(self, char_to_idx):
14
+ self.stoi = {c: int(i) for c, i in char_to_idx.items()}
15
+ self.itos = {i: c for c, i in self.stoi.items()}
16
+ self.vocab_size = len(self.stoi)
17
+
18
+ @classmethod
19
+ def from_file(cls, path):
20
+ """JSON file holding either {"char_to_idx": {...}} or the mapping itself."""
21
+ data = json.loads(Path(path).read_text(encoding="utf-8"))
22
+ return cls(data.get("char_to_idx", data))
23
+
24
+ def encode(self, text):
25
+ unknown = sorted(set(text) - set(self.stoi))
26
+ if unknown:
27
+ raise ValueError(f"characters not in the vocabulary: {unknown}")
28
+ return [self.stoi[c] for c in text]
29
+
30
+ def decode(self, ids):
31
+ return "".join(self.itos[int(i)] for i in ids)
32
+
33
+ def token_str(self, i):
34
+ return self.itos[int(i)]
35
+
36
+
37
+ class BPETokenizerWrapper:
38
+ """HuggingFace `tokenizers` BPE model (the byte-level BPE trained in HW3)."""
39
+
40
+ kind = "bpe"
41
+
42
+ def __init__(self, tokenizer):
43
+ self.tok = tokenizer
44
+ self.vocab_size = tokenizer.get_vocab_size()
45
+
46
+ @classmethod
47
+ def from_file(cls, path):
48
+ return cls(Tokenizer.from_file(str(path)))
49
+
50
+ @classmethod
51
+ def from_str(cls, json_str):
52
+ return cls(Tokenizer.from_str(json_str))
53
+
54
+ def encode(self, text):
55
+ return self.tok.encode(text).ids
56
+
57
+ def decode(self, ids):
58
+ return self.tok.decode([int(i) for i in ids])
59
+
60
+ def token_str(self, i):
61
+ # Decoding one id on its own turns byte-level symbols (Ġ, Ċ) back into real spaces/newlines.
62
+ return self.tok.decode([int(i)])
63
+
64
+
65
+ def load_tokenizer(tokenizer_type, path=None, checkpoint=None):
66
+ """Loads from `path` if given, otherwise from the tokenizer info stored in the checkpoint."""
67
+ checkpoint = checkpoint or {}
68
+ tokenizer_type = tokenizer_type or checkpoint.get("tokenizer_type")
69
+ if tokenizer_type == "char":
70
+ if path:
71
+ return CharTokenizer.from_file(path)
72
+ if "char_to_idx" in checkpoint:
73
+ return CharTokenizer(checkpoint["char_to_idx"])
74
+ raise ValueError("char tokenizer: pass a tokenizer JSON file or use a checkpoint with char_to_idx")
75
+ if tokenizer_type == "bpe":
76
+ if path:
77
+ return BPETokenizerWrapper.from_file(path)
78
+ if "bpe_tokenizer_json" in checkpoint:
79
+ return BPETokenizerWrapper.from_str(checkpoint["bpe_tokenizer_json"])
80
+ raise ValueError("bpe tokenizer: pass the tokenizer JSON file (e.g. results/bpe2000_tokenizer.json)")
81
+ raise ValueError(f"unknown tokenizer_type {tokenizer_type!r}")
@@ -0,0 +1,97 @@
1
+ Metadata-Version: 2.4
2
+ Name: lmscope
3
+ Version: 0.1.0
4
+ Summary: Step through LSTM / Transformer language-model inference in the browser
5
+ Author: Michael
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/Ashurali/lmscope
8
+ Project-URL: Issues, https://github.com/Ashurali/lmscope/issues
9
+ Keywords: language model,transformer,lstm,attention,visualization,interpretability
10
+ Classifier: Development Status :: 3 - Alpha
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Classifier: Topic :: Scientific/Engineering :: Visualization
16
+ Requires-Python: >=3.9
17
+ Description-Content-Type: text/markdown
18
+ License-File: LICENSE
19
+ Requires-Dist: flask>=2.0
20
+ Requires-Dist: numpy
21
+ Requires-Dist: torch>=2.0
22
+ Requires-Dist: tokenizers>=0.13
23
+ Dynamic: license-file
24
+
25
+ # lmscope
26
+
27
+ Step through token-by-token generation of a small LSTM or Transformer language model in the browser,
28
+ and watch the probability distribution, attention maps (Transformer) or gate activations (LSTM).
29
+
30
+ ```bash
31
+ pip install lmscope # from PyPI; or, from a clone: pip install -e .
32
+ lmscope serve --model transformer_char_best.pt --model-type transformer --tokenizer-type char
33
+ lmscope serve --model lstm_bpe2000_best.pt --model-type lstm \
34
+ --tokenizer bpe2000_tokenizer.json --tokenizer-type bpe
35
+ ```
36
+
37
+ ```python
38
+ import lmscope
39
+ lmscope.serve(model_path="transformer_char_best.pt", model_type="transformer", tokenizer_type="char", port=8765)
40
+ ```
41
+
42
+ Options: `--prompt "ROMEO:\n"`, `--seed 0` (sampling seed, restored on Reset), `--reference valid.txt`
43
+ (preloads a reference continuation for per-token loss / perplexity), `--device cpu`, `--no-browser`.
44
+
45
+ ## Checkpoint format
46
+
47
+ ```python
48
+ {
49
+ "model_state_dict": ...,
50
+ "model_config": {"model_type": "transformer" | "lstm", "vocab_size": int, "d_model": int,
51
+ "n_layers": int, "context_len": int, "dropout": float,
52
+ "n_heads": int, "d_ff": int, # Transformer
53
+ "hidden_size": int}, # LSTM
54
+ "tokenizer_type": "char" | "bpe",
55
+ "char_to_idx": {...}, "idx_to_char": {...}, # char
56
+ "bpe_tokenizer_json": str, # bpe (optional if --tokenizer is given)
57
+ }
58
+ ```
59
+
60
+ The tokenizer comes from `--tokenizer` if given, otherwise from the checkpoint.
61
+
62
+ ## API
63
+
64
+ | Endpoint | Body | Returns |
65
+ |---|---|---|
66
+ | `GET /api/model-info` | | model type, parameter count, layers, vocab size, context length |
67
+ | `GET /api/state` | | token sequence with per-token sampling probability and loss |
68
+ | `POST /api/set-prompt` | `{prompt}` | tokenized prompt (resets the sequence) |
69
+ | `POST /api/reset` | | back to the prompt; sampling seed restored |
70
+ | `POST /api/step` | `{position, temperature, layer, head, top_k}` | one forward pass: top-k distribution, entropy, top-k mass, attention matrix or LSTM gates, hidden-state norms |
71
+ | `POST /api/sample` | `{temperature}` | samples and appends the next token |
72
+ | `POST /api/score` | `{text}` | per-token cross-entropy and running perplexity of a reference continuation |
73
+
74
+ `position` p is the prediction of token p from the tokens before it (default: the next token).
75
+
76
+ ## Internals
77
+
78
+ - **Transformer**: each attention module applies its softmax through a small `AttentionSoftmax`
79
+ submodule; a forward hook on it records the weights `(heads, T, T)` of every layer.
80
+ - **LSTM**: `CustomLSTMCell` re-runs each `nn.LSTM` layer step by step from its weights
81
+ (gate order input, forget, cell, output) and exposes the input / forget / output gates and the states.
82
+
83
+ PNG export happens in the browser: per-panel buttons save each canvas, and "Export page" uses
84
+ html2canvas (loaded from cdnjs, so it needs internet access).
85
+
86
+ ## Releasing
87
+
88
+ The version lives in `lmscope/__init__.py` (`__version__`).
89
+
90
+ 1. Bump `__version__`, commit and push.
91
+ 2. Create a GitHub release with tag `vX.Y.Z`. The `Publish to PyPI` workflow builds the sdist and wheel,
92
+ runs `twine check`, and uploads with PyPI trusted publishing (no API token in the repo).
93
+
94
+ One-time setup on PyPI: under *Your projects → Publishing → Add a pending publisher*, enter owner `Ashurali`,
95
+ repository `lmscope`, workflow `publish.yml`, environment `pypi`.
96
+
97
+ Local build check: `python -m build && python -m twine check dist/*`.
@@ -0,0 +1,13 @@
1
+ lmscope/__init__.py,sha256=Ecv1NY3V-BFfb1PfmveMoH-dXnhHdXNpIPBuTsknQRs,265
2
+ lmscope/__main__.py,sha256=nSXhEUOcqY9zWCt8fMVHxJORlI1F47RaRIuAEOoAm2E,1799
3
+ lmscope/inference.py,sha256=wul6dNUuVch35-d7artvB0flqAMTyaUoeMrluhFytOg,11385
4
+ lmscope/models.py,sha256=KMuWdvZHzDXZX8Ogsbje3W_-PYIrexgVO5lg2ysRayY,6388
5
+ lmscope/server.py,sha256=ZOWplgQxI0wdGjkqNFGe84RCJJeZEzExROr5MM1PmtM,3221
6
+ lmscope/tokenizers.py,sha256=-8CzSSjQjbbMvI0Mwve4EuEz-27iNs2O-m-vQm1qiJU,2846
7
+ lmscope/static/index.html,sha256=oLYZu0CqwD-6hihaiyI3bdnHcgOSPoVyhmlookBv3Yg,27812
8
+ lmscope-0.1.0.dist-info/licenses/LICENSE,sha256=0uVeJfLU3mjdYwRrEGRh4X0RQC0fbqX3Hc8BjSaZSJg,1064
9
+ lmscope-0.1.0.dist-info/METADATA,sha256=UnXgxvN6vR1elP6NRiXKJVH2a2B7MzMBh9MzsxseO6s,4402
10
+ lmscope-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
11
+ lmscope-0.1.0.dist-info/entry_points.txt,sha256=0FPxztqKXXY_iYzwYInZONzXS2hqIEz8LSSBnRO7UPg,50
12
+ lmscope-0.1.0.dist-info/top_level.txt,sha256=3joU7fX-7O9oNFMjnbWCxTaQ7vco8_WO7wbwCz550cY,8
13
+ lmscope-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ lmscope = lmscope.__main__:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Michael
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ lmscope