Download cubit_chat.py from DCubo/Cubit-0.5-Line-undertrained: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/DCubo/Cubit-0.5-Line-undertrained/resolve/main/cubit_chat.py
- Command line
-
hf download hf://DCubo/Cubit-0.5-Line-undertrained/cubit_chat.py
-
curl -L -o cubit_chat.py https://huggingface.co/DCubo/Cubit-0.5-Line-undertrained/resolve/main/cubit_chat.py
22.4 kB
| """ | |
| Cubit Chat — a small window to talk to a Cubit language model. | |
| How to run: | |
| 1. Install Python 3.10 or newer. | |
| 2. Install the libraries (once): | |
| pip install torch safetensors tokenizers | |
| 3. Double-click this file, or run: python cubit_chat.py | |
| 4. Press "Open model" and pick the .safetensors file. | |
| Cubit is a small Russian model trained from scratch, so write to it in | |
| Russian. It is an experiment: it can talk, but it often makes mistakes. | |
| The whole program is in this one file: | |
| - Tokenizer turns text into numbers and back | |
| - CubitNet the neural network itself (a small GPT-style transformer) | |
| - load_model reads the model file | |
| - Generator picks the reply word by word | |
| - App the window | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import math | |
| import queue | |
| import re | |
| import threading | |
| import tkinter as tk | |
| from pathlib import Path | |
| from tkinter import filedialog, messagebox, ttk | |
| import torch | |
| import torch.nn as nn | |
| import torch.nn.functional as F | |
| # --------------------------------------------------------------------------- | |
| # Tokenizer: text <-> numbers | |
| # --------------------------------------------------------------------------- | |
| # Special tokens. They are always the first 8 entries of the vocabulary. | |
| PAD, BOS, EOS, UNK = "<pad>", "<bos>", "<eos>", "<unk>" | |
| USER, AI, INFO, THINK = "<user>", "<ai>", "<info>", "<think>" | |
| SPECIALS = (PAD, BOS, EOS, UNK, USER, AI, INFO, THINK) | |
| # Older Cubit models work with whole words in lower case. | |
| WORDS_RE = re.compile(r"[0-9]+|[^\W\d_]+|[^\s\w]", re.UNICODE) | |
| # "Code" models keep case, spaces and line breaks. | |
| CODE_RE = re.compile(r"\n[ ]*|```| ?\w+| ?[^\s\w]|[ ]+", re.UNICODE) | |
| FENCE = "```" | |
| class Tokenizer: | |
| """Three kinds exist: whole words, words for code, and word pieces (BPE).""" | |
| def __init__(self, vocab_json: str) -> None: | |
| raw = json.loads(vocab_json) | |
| self.bpe = None | |
| self.code = False | |
| if isinstance(raw, dict) and raw.get("bpe"): | |
| try: | |
| from tokenizers import Tokenizer as Pieces # only needed for newer models | |
| except ImportError: | |
| raise ValueError("This model needs the 'tokenizers' library. Install it once:\n\n" | |
| "pip install tokenizers") from None | |
| self.bpe = Pieces.from_str(raw["bpe"]) | |
| self.itos = [self.bpe.id_to_token(i) or f"<{i}>" for i in range(self.bpe.get_vocab_size())] | |
| self.code = True | |
| elif isinstance(raw, dict) and "itos" in raw: | |
| self.itos = list(raw["itos"]) | |
| self.code = bool(raw.get("code")) | |
| elif isinstance(raw, dict): | |
| self.itos = [word for word, _ in sorted(raw.items(), key=lambda kv: kv[1])] | |
| else: | |
| self.itos = list(raw) | |
| self.stoi = {word: i for i, word in enumerate(self.itos)} | |
| def kind(self) -> str: | |
| return "word pieces" if self.bpe else ("words for code" if self.code else "whole words") | |
| def special(self, name: str) -> int: | |
| return self.stoi[name] | |
| def encode(self, text: str) -> list[int]: | |
| if self.bpe is not None: | |
| return self.bpe.encode(text, add_special_tokens=False).ids | |
| if self.code: | |
| text = text.replace("\r\n", "\n").replace("\t", " ") | |
| words = CODE_RE.findall(text) | |
| if FENCE not in self.stoi: | |
| words = [p for w in words for p in (["`"] * 3 if w == FENCE else [w])] | |
| else: | |
| words = WORDS_RE.findall(text.lower()) | |
| unk = self.stoi[UNK] | |
| return [self.stoi.get(word, unk) for word in words] | |
| def decode(self, ids: list[int]) -> str: | |
| if self.bpe is not None: | |
| kept = [i for i in ids if len(SPECIALS) <= i < len(self.itos)] | |
| return self.bpe.decode(kept, skip_special_tokens=False).strip("\n") | |
| words = [self.itos[i] for i in ids if 0 <= i < len(self.itos)] | |
| words = [w for w in words if w not in SPECIALS or w == UNK] | |
| if self.code: | |
| return "".join(words).strip("\n") | |
| # Whole words: glue them back with spaces, no space before punctuation. | |
| out = "" | |
| for word in words: | |
| if not out: | |
| out = word | |
| elif word in ".,!?;:)»…%" or out[-1] in "(«": | |
| out += word | |
| else: | |
| out += " " + word | |
| return out[:1].upper() + out[1:] | |
| # --------------------------------------------------------------------------- | |
| # The network | |
| # --------------------------------------------------------------------------- | |
| class Block(nn.Module): | |
| """One transformer layer: look at earlier words (attention), then think (MLP).""" | |
| def __init__(self, width: int, heads: int) -> None: | |
| super().__init__() | |
| self.norm1 = nn.LayerNorm(width) | |
| self.attn = nn.MultiheadAttention(width, heads, batch_first=True) | |
| self.norm2 = nn.LayerNorm(width) | |
| self.mlp = nn.Sequential(nn.Linear(width, width * 4), nn.GELU(), nn.Linear(width * 4, width), nn.Dropout(0.0)) | |
| def forward(self, x: torch.Tensor, mask: torch.Tensor) -> torch.Tensor: | |
| normed = self.norm1(x) | |
| attended, _ = self.attn(normed, normed, normed, attn_mask=mask, need_weights=False) | |
| x = x + attended | |
| return x + self.mlp(self.norm2(x)) | |
| class CubitNet(nn.Module): | |
| def __init__(self, vocab_size: int, layers: int, heads: int, width: int, context: int) -> None: | |
| super().__init__() | |
| self.context = context | |
| self.tokens = nn.Embedding(vocab_size, width) # word number -> vector | |
| self.positions = nn.Embedding(context, width) # place in the text -> vector | |
| self.blocks = nn.ModuleList(Block(width, heads) for _ in range(layers)) | |
| self.norm = nn.LayerNorm(width) | |
| self.head = nn.Linear(width, vocab_size, bias=False) # vector -> score for every word | |
| self.head.weight = self.tokens.weight | |
| def forward(self, ids: torch.Tensor) -> torch.Tensor: | |
| ids = ids[:, -self.context:] | |
| length = ids.size(1) | |
| x = self.tokens(ids) + self.positions(torch.arange(length, device=ids.device)) | |
| # Each word may only look at the words before it. | |
| mask = torch.triu(torch.full((length, length), float("-inf"), device=ids.device), diagonal=1) | |
| for block in self.blocks: | |
| x = block(x, mask) | |
| return self.head(self.norm(x)) | |
| # --------------------------------------------------------------------------- | |
| # Loading a model file | |
| # --------------------------------------------------------------------------- | |
| class Model: | |
| def __init__(self, net: CubitNet, tokenizer: Tokenizer, info: dict, name: str) -> None: | |
| self.net = net | |
| self.tokenizer = tokenizer | |
| self.info = info | |
| self.name = name | |
| def device(self) -> torch.device: | |
| return next(self.net.parameters()).device | |
| def describe(self) -> str: | |
| params = sum(p.numel() for p in self.net.parameters()) / 1e6 | |
| shape = self.info["shape"] | |
| return (f"{self.name} · {params:.1f}M parameters · {shape['layers']} layers, " | |
| f"width {shape['width']} · memory {shape['context']} tokens · " | |
| f"{len(self.tokenizer.itos)} tokens ({self.tokenizer.kind})") | |
| def load_model(path: Path) -> Model: | |
| if path.suffix == ".safetensors": | |
| from safetensors import safe_open | |
| from safetensors.torch import load_file | |
| with safe_open(str(path), framework="pt") as handle: | |
| meta = handle.metadata() or {} | |
| if "vocab" not in meta: | |
| raise ValueError("This file has no vocabulary inside. Convert it again with в_safetensors.py.") | |
| info = json.loads(meta.get("extra", "{}")) | |
| weights = load_file(str(path)) | |
| vocab_json = meta["vocab"] | |
| else: | |
| payload = torch.load(path, map_location="cpu", weights_only=False) | |
| info = {k: v for k, v in payload.items() if k != "state"} | |
| weights = payload["state"] | |
| vocab_path = path.with_name(f"{path.stem}_vocab.json") | |
| if not vocab_path.exists(): | |
| raise ValueError(f"Vocabulary file not found: {vocab_path.name}") | |
| vocab_json = vocab_path.read_text(encoding="utf-8") | |
| if "shape" not in info: | |
| raise ValueError("This is not a Cubit text model.") | |
| tokenizer = Tokenizer(vocab_json) | |
| shape = info["shape"] | |
| net = CubitNet(info.get("vocab_size", len(tokenizer.itos)), | |
| shape["layers"], shape["heads"], shape["width"], shape["context"]) | |
| # Models that learned photos have an extra "eye"; this window does not use it. | |
| weights = {k: v for k, v in weights.items() if not k.startswith("eye.")} | |
| net.load_state_dict(weights, strict=False) | |
| net.eval() | |
| return Model(net, tokenizer, info, path.stem) | |
| # --------------------------------------------------------------------------- | |
| # Writing a reply | |
| # --------------------------------------------------------------------------- | |
| DEFAULT_THREADS = torch.get_num_threads() | |
| UNK_DAMPING = math.log(4.0) # makes "<unk>" (unknown word) 4 times less likely | |
| class Generator: | |
| def __init__(self, model: Model) -> None: | |
| self.model = model | |
| self.stop = threading.Event() | |
| def prompt_ids(self, history: list[tuple[str, str]], text: str, settings: dict) -> list[int]: | |
| tok = self.model.tokenizer | |
| ids = [tok.special(BOS)] | |
| if settings["mode"] == "Continue text": | |
| return ids + tok.encode(text) | |
| # Chat: <user> question <ai> answer <user> question <ai> ... | |
| memory = history[-settings["memory"] * 2:] if settings["memory"] > 0 else [] | |
| for role, said in memory + [("user", text)]: | |
| ids += [tok.special(USER if role == "user" else AI)] + tok.encode(said) | |
| return ids + [tok.special(AI)] | |
| def run(self, ids: list[int], settings: dict, on_text) -> str: | |
| net, tok = self.model.net, self.model.tokenizer | |
| eos, unk = tok.special(EOS), tok.special(UNK) | |
| window = net.context // 2 if settings["economy"] else net.context | |
| produced: list[int] = [] | |
| text = "" | |
| if settings["seed"] is not None: | |
| torch.manual_seed(settings["seed"]) | |
| for _ in range(settings["max_tokens"]): | |
| if self.stop.is_set(): | |
| break | |
| batch = torch.tensor([ids[-window:]], device=self.model.device) | |
| scores = net(batch)[0, -1].float() | |
| scores[unk] -= UNK_DAMPING | |
| # Repetition penalty: words already said become less likely. | |
| for token in set(produced): | |
| value = scores[token] | |
| scores[token] = value / settings["repetition"] if value > 0 else value * settings["repetition"] | |
| # Temperature: low = safe and repetitive, high = creative and random. | |
| scores = scores / max(1e-5, settings["temperature"]) | |
| # Top-k: choose only from the k best words. | |
| if settings["top_k"] > 0: | |
| cutoff = torch.topk(scores, min(settings["top_k"], scores.numel())).values[-1] | |
| scores[scores < cutoff] = float("-inf") | |
| # Top-p: keep the best words until their chances add up to p. | |
| probs = F.softmax(scores, dim=-1) | |
| if settings["top_p"] < 1.0: | |
| sorted_probs, order = torch.sort(probs, descending=True) | |
| drop = torch.cumsum(sorted_probs, dim=0) - sorted_probs > settings["top_p"] | |
| probs[order[drop]] = 0.0 | |
| probs = probs / probs.sum() | |
| nxt = int(torch.multinomial(probs, 1)) | |
| if nxt == eos: | |
| break | |
| ids.append(nxt) | |
| produced.append(nxt) | |
| text = tok.decode(produced) | |
| on_text(text) | |
| return text | |
| # --------------------------------------------------------------------------- | |
| # The window | |
| # --------------------------------------------------------------------------- | |
| class App: | |
| def __init__(self, root: tk.Tk) -> None: | |
| self.root = root | |
| self.model: Model | None = None | |
| self.generator: Generator | None = None | |
| self.history: list[tuple[str, str]] = [] | |
| self.updates: queue.Queue = queue.Queue() | |
| self.busy = False | |
| root.title("Cubit Chat") | |
| root.geometry("1000x640") | |
| root.minsize(760, 480) | |
| top = ttk.Frame(root, padding=8) | |
| top.pack(fill="x") | |
| ttk.Button(top, text="Open model…", command=self.open_model).pack(side="left") | |
| self.status = ttk.Label(top, text="No model loaded. Press \"Open model\" and pick a .safetensors file.") | |
| self.status.pack(side="left", padx=10) | |
| body = ttk.Frame(root, padding=(8, 0, 8, 8)) | |
| body.pack(fill="both", expand=True) | |
| # Left: the conversation. | |
| chat = ttk.Frame(body) | |
| chat.pack(side="left", fill="both", expand=True) | |
| self.log = tk.Text(chat, wrap="word", state="disabled", font=("Segoe UI", 11), padx=10, pady=10) | |
| self.log.tag_configure("you", foreground="#1a6fb5", font=("Segoe UI", 11, "bold")) | |
| self.log.tag_configure("cubit", foreground="#1e8a5a", font=("Segoe UI", 11, "bold")) | |
| self.log.tag_configure("note", foreground="#888888") | |
| self.log.pack(fill="both", expand=True) | |
| row = ttk.Frame(chat) | |
| row.pack(fill="x", pady=(8, 0)) | |
| self.entry = ttk.Entry(row, font=("Segoe UI", 11)) | |
| self.entry.pack(side="left", fill="x", expand=True) | |
| self.entry.bind("<Return>", lambda _: self.send()) | |
| self.send_button = ttk.Button(row, text="Send", command=self.send) | |
| self.send_button.pack(side="left", padx=(6, 0)) | |
| ttk.Button(row, text="Stop", command=self.stop).pack(side="left", padx=(6, 0)) | |
| ttk.Button(row, text="Clear", command=self.clear).pack(side="left", padx=(6, 0)) | |
| # Right: settings. | |
| side = ttk.Frame(body, padding=(12, 0, 0, 0), width=280) | |
| side.pack(side="right", fill="y") | |
| side.pack_propagate(False) | |
| self.mode = tk.StringVar(value="Chat") | |
| ttk.Label(side, text="Mode", font=("Segoe UI", 10, "bold")).pack(anchor="w") | |
| ttk.Radiobutton(side, text="Chat (answers you)", variable=self.mode, value="Chat").pack(anchor="w") | |
| ttk.Radiobutton(side, text="Continue text", variable=self.mode, value="Continue text").pack(anchor="w") | |
| self.temperature = self.slider(side, "Temperature", 0.1, 2.0, 0.55, 2, | |
| "Low = careful, high = creative and random") | |
| self.top_k = self.slider(side, "Top-k", 0, 200, 40, 0, "Pick only from the k best words (0 = all)") | |
| self.top_p = self.slider(side, "Top-p", 0.1, 1.0, 0.95, 2, "Keep best words until chances add up to p") | |
| self.repetition = self.slider(side, "Repetition penalty", 1.0, 2.0, 1.15, 2, "Higher = repeats itself less") | |
| self.max_tokens = self.slider(side, "Reply length", 10, 400, 80, 0, "Most tokens in one reply") | |
| self.memory = self.slider(side, "Chat memory", 0, 10, 0, 0, "How many past exchanges it remembers") | |
| ttk.Label(side, text="Seed", font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(8, 0)) | |
| self.seed = ttk.Entry(side) | |
| self.seed.pack(fill="x") | |
| ttk.Label(side, text="Same number = same reply. Empty = random", foreground="#888").pack(anchor="w") | |
| ttk.Label(side, text="Hardware", font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(8, 0)) | |
| self.device = tk.StringVar(value="Auto") | |
| devices = ttk.Combobox(side, textvariable=self.device, state="readonly", values=["Auto", "GPU", "CPU"]) | |
| devices.pack(fill="x") | |
| devices.bind("<<ComboboxSelected>>", lambda _: self.place_model()) | |
| self.economy = tk.BooleanVar(value=False) | |
| ttk.Checkbutton(side, text="Economy mode", variable=self.economy, command=self.place_model).pack(anchor="w") | |
| ttk.Label(side, text="For weak computers: CPU, 2 threads, shorter memory", foreground="#888", | |
| wraplength=260).pack(anchor="w") | |
| self.root.after(50, self.poll) | |
| def slider(self, parent, name, low, high, start, digits, hint): | |
| ttk.Label(parent, text=name, font=("Segoe UI", 10, "bold")).pack(anchor="w", pady=(8, 0)) | |
| var = tk.DoubleVar(value=start) | |
| row = ttk.Frame(parent) | |
| row.pack(fill="x") | |
| shown = ttk.Label(row, width=5) | |
| shown.pack(side="right") | |
| def show(*_): | |
| shown.config(text=f"{var.get():.{digits}f}") | |
| ttk.Scale(row, from_=low, to=high, variable=var, command=show).pack(side="left", fill="x", expand=True) | |
| show() | |
| ttk.Label(parent, text=hint, foreground="#888", wraplength=260).pack(anchor="w") | |
| return var | |
| # --- model --------------------------------------------------------------- | |
| def open_model(self) -> None: | |
| path = filedialog.askopenfilename( | |
| title="Pick a Cubit model", | |
| filetypes=[("Cubit model", "*.safetensors *.pt"), ("All files", "*.*")]) | |
| if not path: | |
| return | |
| try: | |
| self.model = load_model(Path(path)) | |
| except Exception as error: | |
| messagebox.showerror("Could not open the model", str(error)) | |
| return | |
| self.generator = Generator(self.model) | |
| self.place_model() | |
| self.clear() | |
| self.write(f"Loaded {self.model.name}. Write in Russian.\n\n", "note") | |
| def place_model(self) -> None: | |
| """Move the model to the chosen hardware.""" | |
| if self.model is None: | |
| return | |
| want_gpu = self.device.get() != "CPU" and not self.economy.get() and torch.cuda.is_available() | |
| if self.device.get() == "GPU" and not torch.cuda.is_available(): | |
| messagebox.showinfo("No GPU", "No NVIDIA GPU found, using CPU.") | |
| torch.set_num_threads(2 if self.economy.get() else DEFAULT_THREADS) | |
| self.model.net.to("cuda" if want_gpu else "cpu") | |
| where = "GPU" if want_gpu else "CPU" | |
| self.status.config(text=f"{self.model.describe()} · {where}") | |
| # --- chat ---------------------------------------------------------------- | |
| def settings(self) -> dict: | |
| seed = self.seed.get().strip() | |
| return { | |
| "mode": self.mode.get(), | |
| "temperature": self.temperature.get(), | |
| "top_k": int(self.top_k.get()), | |
| "top_p": self.top_p.get(), | |
| "repetition": self.repetition.get(), | |
| "max_tokens": int(self.max_tokens.get()), | |
| "memory": int(self.memory.get()), | |
| "seed": int(seed) if seed.lstrip("-").isdigit() else None, | |
| "economy": self.economy.get(), | |
| } | |
| def send(self) -> None: | |
| text = self.entry.get().strip() | |
| if not text or self.busy: | |
| return | |
| if self.generator is None: | |
| messagebox.showinfo("No model", "Open a model first.") | |
| return | |
| self.entry.delete(0, "end") | |
| settings = self.settings() | |
| continuing = settings["mode"] == "Continue text" | |
| self.write("You: ", "you") | |
| self.write(text + "\n") | |
| self.write("Cubit: ", "cubit") | |
| if continuing: | |
| self.write(text + " ") | |
| self.mark = self.log.index("end-1c") | |
| ids = self.generator.prompt_ids(self.history, text, settings) | |
| self.busy = True | |
| self.generator.stop.clear() | |
| self.send_button.config(state="disabled") | |
| def work(): | |
| try: | |
| reply = self.generator.run(ids, settings, lambda t: self.updates.put(("text", t))) | |
| self.updates.put(("done", (text, reply, continuing))) | |
| except Exception as error: | |
| self.updates.put(("error", str(error))) | |
| threading.Thread(target=work, daemon=True).start() | |
| def poll(self) -> None: | |
| """Show new words from the background thread.""" | |
| latest = None | |
| try: | |
| while True: | |
| kind, value = self.updates.get_nowait() | |
| if kind == "text": | |
| latest = value | |
| elif kind == "done": | |
| question, reply, continuing = value | |
| if latest is not None: | |
| self.replace(latest) | |
| latest = None | |
| if not continuing: | |
| self.history += [("user", question), ("ai", reply)] | |
| self.write("\n\n") | |
| self.finish() | |
| elif kind == "error": | |
| self.write(f"\n[error: {value}]\n\n", "note") | |
| self.finish() | |
| except queue.Empty: | |
| pass | |
| if latest is not None: | |
| self.replace(latest) | |
| self.root.after(50, self.poll) | |
| def finish(self) -> None: | |
| self.busy = False | |
| self.send_button.config(state="normal") | |
| def stop(self) -> None: | |
| if self.generator is not None: | |
| self.generator.stop.set() | |
| def clear(self) -> None: | |
| self.history.clear() | |
| self.log.config(state="normal") | |
| self.log.delete("1.0", "end") | |
| self.log.config(state="disabled") | |
| def write(self, text: str, tag: str | None = None) -> None: | |
| self.log.config(state="normal") | |
| self.log.insert("end", text, tag or ()) | |
| self.log.see("end") | |
| self.log.config(state="disabled") | |
| def replace(self, text: str) -> None: | |
| """Rewrite the reply being typed (word pieces can change the last word).""" | |
| self.log.config(state="normal") | |
| self.log.delete(self.mark, "end-1c") | |
| self.log.insert("end", text) | |
| self.log.see("end") | |
| self.log.config(state="disabled") | |
| if __name__ == "__main__": | |
| window = tk.Tk() | |
| App(window) | |
| window.mainloop() | |