A ~9M parameter LLM that talks like a small fish.
Python
Add source code to HF model repo, simplify use notebook
Arman Hossainc4ca40eafb7c
diff --git a/tools/make_colab.py b/tools/make_colab.pyindex 35832bf..f20cc0d 100644--- a/tools/make_colab.py+++ b/tools/make_colab.py@@ -424,31 +424,26 @@ def build_use():"print(f'Working dir: {os.getcwd()}')"))- # ── Write source files ─────────────────────────────────────────+ # ── Download model ─────────────────────────────────────────────cells.append(md(- "## 2. Download Model & Write Source\n"+ "## 2. Download Model\n""\n"- "Download the pre-trained weights from HuggingFace and write the inference code."+ "Download everything from HuggingFace — weights, config, tokenizer, and inference code."))- # Write model source files needed for inference- for display_name in ["config.py", "model.py", "inference.py"]:- src_path = f"guppylm/{display_name}"- full_path = os.path.join(PROJECT_ROOT, src_path)- content = read_for_colab(full_path)- cells.append(code(f"%%writefile {display_name}\n{content}"))-cells.append(code(- "from huggingface_hub import hf_hub_download\n"+ "from huggingface_hub import snapshot_download\n""\n""HF_REPO = 'arman-bd/guppylm-9M'\n""\n"- "for filename in ['pytorch_model.bin', 'config.json', 'tokenizer.json']:\n"- " hf_hub_download(repo_id=HF_REPO, filename=filename, local_dir='.')\n"- " print(f' Downloaded {filename}')\n"+ "snapshot_download(repo_id=HF_REPO, local_dir='.')\n"+ "print(f'Downloaded {HF_REPO}')\n""\n"- "print(f'Model ready from {HF_REPO}')"+ "import os\n"+ "for f in os.listdir('.'):\n"+ " if not f.startswith('.'):\n"+ " print(f' {f}')"))# ── Chat ───────────────────────────────────────────────────────diff --git a/use_guppylm.ipynb b/use_guppylm.ipynbindex 68ca132..09166ef 100644--- a/use_guppylm.ipynb+++ b/use_guppylm.ipynb@@ -65,343 +65,26 @@"cell_type": "markdown","metadata": {},"source": [- "## 2. Download Model & Write Source\n",+ "## 2. Download Model\n","\n",- "Download the pre-trained weights from HuggingFace and write the inference code."+ "Download everything from HuggingFace \u2014 weights, config, tokenizer, and inference code."]},{"cell_type": "code","metadata": {},"source": [- "%%writefile config.py\n",- "\"\"\"GuppyLM configuration.\"\"\"\n",- "\n",- "from dataclasses import dataclass\n",- "\n",- "\n",- "@dataclass\n",- "class GuppyConfig:\n",- " vocab_size: int = 4096\n",- " max_seq_len: int = 128\n",- " d_model: int = 384\n",- " n_layers: int = 6\n",- " n_heads: int = 6\n",- " ffn_hidden: int = 768\n",- " dropout: float = 0.1\n",- "\n",- " # Special tokens\n",- " pad_id: int = 0\n",- " bos_id: int = 1 # <|im_start|>\n",- " eos_id: int = 2 # <|im_end|>\n",- "\n",- "\n",- "@dataclass\n",- "class TrainConfig:\n",- " batch_size: int = 32\n",- " learning_rate: float = 3e-4\n",- " min_lr: float = 3e-5\n",- " weight_decay: float = 0.1\n",- " warmup_steps: int = 200\n",- " max_steps: int = 10000\n",- " eval_interval: int = 200\n",- " save_interval: int = 500\n",- " grad_clip: float = 1.0\n",- " device: str = \"auto\"\n",- " seed: int = 42\n",- " data_dir: str = \"data\"\n",- " output_dir: str = \"checkpoints\"\n",- ""- ],- "outputs": [],- "execution_count": null- },- {- "cell_type": "code",- "metadata": {},- "source": [- "%%writefile model.py\n",- "\"\"\"\n",- "GuppyLM \u2014 a tiny fish brain.\n",- "\n",- "Vanilla transformer: multi-head attention, ReLU FFN, LayerNorm, learned positional embeddings.\n",- "No GQA, no SwiGLU, no parallel residual, no RoPE. As simple as it gets.\n",- "\"\"\"\n",- "\n",- "import math\n",- "import torch\n",- "import torch.nn as nn\n",- "import torch.nn.functional as F\n",- "from config import GuppyConfig\n",- "\n",- "\n",- "class Attention(nn.Module):\n",- " def __init__(self, config):\n",- " super().__init__()\n",- " self.n_heads = config.n_heads\n",- " self.head_dim = config.d_model // config.n_heads\n",- "\n",- " self.qkv = nn.Linear(config.d_model, 3 * config.d_model)\n",- " self.out = nn.Linear(config.d_model, config.d_model)\n",- " self.dropout = nn.Dropout(config.dropout)\n",- "\n",- " def forward(self, x, mask=None):\n",- " B, T, C = x.shape\n",- " qkv = self.qkv(x).reshape(B, T, 3, self.n_heads, self.head_dim).permute(2, 0, 3, 1, 4)\n",- " q, k, v = qkv[0], qkv[1], qkv[2]\n",- "\n",- " attn = (q @ k.transpose(-2, -1)) / math.sqrt(self.head_dim)\n",- " if mask is not None:\n",- " attn = attn.masked_fill(mask == 0, float(\"-inf\"))\n",- " attn = self.dropout(F.softmax(attn, dim=-1))\n",- " return self.out((attn @ v).transpose(1, 2).contiguous().view(B, T, C))\n",- "\n",- "\n",- "class FFN(nn.Module):\n",- " def __init__(self, config):\n",- " super().__init__()\n",- " self.up = nn.Linear(config.d_model, config.ffn_hidden)\n",- " self.down = nn.Linear(config.ffn_hidden, config.d_model)\n",- " self.dropout = nn.Dropout(config.dropout)\n",- "\n",- " def forward(self, x):\n",- " return self.dropout(self.down(F.relu(self.up(x))))\n",- "\n",- "\n",- "class Block(nn.Module):\n",- " def __init__(self, config):\n",- " super().__init__()\n",- " self.norm1 = nn.LayerNorm(config.d_model)\n",- " self.attn = Attention(config)\n",- " self.norm2 = nn.LayerNorm(config.d_model)\n",- " self.ffn = FFN(config)\n",- "\n",- " def forward(self, x, mask=None):\n",- " x = x + self.attn(self.norm1(x), mask)\n",- " x = x + self.ffn(self.norm2(x))\n",- " return x\n",- "\n",- "\n",- "class GuppyLM(nn.Module):\n",- " def __init__(self, config: GuppyConfig):\n",- " super().__init__()\n",- " self.config = config\n",- "\n",- " self.tok_emb = nn.Embedding(config.vocab_size, config.d_model)\n",- " self.pos_emb = nn.Embedding(config.max_seq_len, config.d_model)\n",- " self.drop = nn.Dropout(config.dropout)\n",- " self.blocks = nn.ModuleList([Block(config) for _ in range(config.n_layers)])\n",- " self.norm = nn.LayerNorm(config.d_model)\n",- " self.lm_head = nn.Linear(config.d_model, config.vocab_size, bias=False)\n",- " self.lm_head.weight = self.tok_emb.weight # tie weights\n",- "\n",- " self.apply(self._init_weights)\n",- "\n",- " def _init_weights(self, m):\n",- " if isinstance(m, nn.Linear):\n",- " nn.init.normal_(m.weight, mean=0.0, std=0.02)\n",- " if m.bias is not None:\n",- " nn.init.zeros_(m.bias)\n",- " elif isinstance(m, nn.Embedding):\n",- " nn.init.normal_(m.weight, mean=0.0, std=0.02)\n",- "\n",- " def forward(self, idx, targets=None):\n",- " B, T = idx.shape\n",- " pos = torch.arange(T, device=idx.device)\n",- " x = self.drop(self.tok_emb(idx) + self.pos_emb(pos))\n",- " mask = torch.tril(torch.ones(T, T, device=idx.device)).unsqueeze(0).unsqueeze(0)\n",- "\n",- " for block in self.blocks:\n",- " x = block(x, mask)\n",- "\n",- " logits = self.lm_head(self.norm(x))\n",- "\n",- " loss = None\n",- " if targets is not None:\n",- " loss = F.cross_entropy(\n",- " logits.view(-1, self.config.vocab_size),\n",- " targets.view(-1),\n",- " ignore_index=0,\n",- " )\n",- "\n",- " return logits, loss\n",- "\n",- " @torch.no_grad()\n",- " def generate(self, idx, max_new_tokens=64, temperature=0.7, top_k=50, **kwargs):\n",- " self.eval()\n",- " for _ in range(max_new_tokens):\n",- " idx_cond = idx[:, -self.config.max_seq_len:]\n",- " logits, _ = self(idx_cond)\n",- " logits = logits[:, -1, :] / temperature\n",- " if top_k > 0:\n",- " v, _ = torch.topk(logits, min(top_k, logits.size(-1)))\n",- " logits[logits < v[:, [-1]]] = float(\"-inf\")\n",- " probs = F.softmax(logits, dim=-1)\n",- " next_id = torch.multinomial(probs, num_samples=1)\n",- " idx = torch.cat([idx, next_id], dim=1)\n",- " if next_id.item() == self.config.eos_id:\n",- " break\n",- " return idx, []\n",- "\n",- " def param_count(self):\n",- " total = sum(p.numel() for p in self.parameters())\n",- " return total, 0\n",- "\n",- " def param_summary(self):\n",- " total, _ = self.param_count()\n",- " return f\"GuppyLM: {total:,} params ({total/1e6:.1f}M)\"\n",- ""- ],- "outputs": [],- "execution_count": null- },- {- "cell_type": "code",- "metadata": {},- "source": [- "%%writefile inference.py\n",- "\"\"\"GuppyLM inference \u2014 simple chat.\"\"\"\n",- "\n",- "import json\n",- "import time\n",- "import uuid\n",- "\n",- "import torch\n",- "from tokenizers import Tokenizer\n",- "\n",- "from config import GuppyConfig\n",- "from model import GuppyLM\n",- "\n",- "\n",- "class GuppyInference:\n",- " def __init__(self, checkpoint_path, tokenizer_path, device=\"cpu\"):\n",- " self.device = torch.device(device)\n",- " self.tokenizer = Tokenizer.from_file(tokenizer_path)\n",- "\n",- " import os\n",- " ckpt = torch.load(checkpoint_path, map_location=self.device, weights_only=False)\n",- "\n",- " # Load config.json from same directory as the model file\n",- " config_dir = os.path.dirname(os.path.abspath(checkpoint_path))\n",- " config_path = os.path.join(config_dir, \"config.json\")\n",- "\n",- " # Extract state_dict \u2014 handle both legacy and standard formats\n",- " if isinstance(ckpt, dict) and \"model_state_dict\" in ckpt:\n",- " state_dict = ckpt[\"model_state_dict\"]\n",- " else:\n",- " state_dict = ckpt\n",- "\n",- " # Load config \u2014 try config.json first, fall back to embedded config\n",- " if os.path.exists(config_path):\n",- " with open(config_path) as f:\n",- " cfg = json.load(f)\n",- " # Support both HF standard keys and our own keys\n",- " self.config = GuppyConfig(\n",- " vocab_size=cfg.get(\"vocab_size\", 4096),\n",- " max_seq_len=cfg.get(\"max_position_embeddings\", cfg.get(\"max_seq_len\", 128)),\n",- " d_model=cfg.get(\"hidden_size\", cfg.get(\"d_model\", 384)),\n",- " n_layers=cfg.get(\"num_hidden_layers\", cfg.get(\"n_layers\", 6)),\n",- " n_heads=cfg.get(\"num_attention_heads\", cfg.get(\"n_heads\", 6)),\n",- " ffn_hidden=cfg.get(\"intermediate_size\", cfg.get(\"ffn_hidden\", 768)),\n",- " dropout=cfg.get(\"hidden_dropout_prob\", cfg.get(\"dropout\", 0.1)),\n",- " pad_id=cfg.get(\"pad_token_id\", cfg.get(\"pad_id\", 0)),\n",- " bos_id=cfg.get(\"bos_token_id\", cfg.get(\"bos_id\", 1)),\n",- " eos_id=cfg.get(\"eos_token_id\", cfg.get(\"eos_id\", 2)),\n",- " )\n",- " elif isinstance(ckpt, dict) and \"config\" in ckpt:\n",- " valid_fields = {f.name for f in GuppyConfig.__dataclass_fields__.values()}\n",- " self.config = GuppyConfig(**{k: v for k, v in ckpt[\"config\"].items() if k in valid_fields})\n",- " else:\n",- " print(\"Warning: No config found, using defaults\")\n",- " self.config = GuppyConfig()\n",- "\n",- " self.model = GuppyLM(self.config).to(self.device)\n",- " filtered = {k: v for k, v in state_dict.items() if k in self.model.state_dict()}\n",- " self.model.load_state_dict(filtered)\n",- " self.model.eval()\n",- "\n",- " total, _ = self.model.param_count()\n",- " print(f\"GuppyLM loaded: {total/1e6:.1f}M params\")\n",- "\n",- " def chat_completion(self, messages, temperature=0.7, max_tokens=64,\n",- " top_k=50, **kwargs):\n",- " \"\"\"Chat completion \u2014 takes messages, returns response.\"\"\"\n",- " prompt = self._format_prompt(messages)\n",- " input_ids = self.tokenizer.encode(prompt).ids\n",- " prompt_tokens = len(input_ids)\n",- " input_t = torch.tensor([input_ids], dtype=torch.long, device=self.device)\n",- "\n",- " output_t, _ = self.model.generate(input_t, max_tokens, temperature, top_k)\n",- " output_text = self.tokenizer.decode(output_t[0].tolist()[prompt_tokens:])\n",- " # Truncate at first <|im_end|> \u2014 don't let the model leak into the next turn\n",- " if \"<|im_end|>\" in output_text:\n",- " output_text = output_text.split(\"<|im_end|>\")[0]\n",- " # Also strip any <|im_start|> fragments\n",- " if \"<|im_start|>\" in output_text:\n",- " output_text = output_text.split(\"<|im_start|>\")[0]\n",- " resp_text = output_text.strip()\n",- "\n",- " return {\n",- " \"choices\": [{\n",- " \"message\": {\"role\": \"assistant\", \"content\": resp_text},\n",- " }],\n",- " }\n",- "\n",- " def _format_prompt(self, messages):\n",- " parts = []\n",- " for msg in messages:\n",- " role = msg.get(\"role\", \"user\")\n",- " content = msg.get(\"content\") or \"\"\n",- " if role == \"system\":\n",- " continue\n",- " parts.append(f\"<|im_start|>{role}\\n{content}<|im_end|>\")\n",- " parts.append(\"<|im_start|>assistant\\n\")\n",- " return \"\\n\".join(parts)\n",- "\n",- "\n",- "def main():\n",- " import argparse\n",- " p = argparse.ArgumentParser(description=\"Chat with Guppy\")\n",- " p.add_argument(\"--checkpoint\", default=\"checkpoints/best_model.pt\")\n",- " p.add_argument(\"--tokenizer\", default=\"data/tokenizer.json\")\n",- " p.add_argument(\"--device\", default=\"cpu\")\n",- " args = p.parse_args()\n",- "\n",- " engine = GuppyInference(args.checkpoint, args.tokenizer, args.device)\n",- " print(\"\\nGuppy Chat (type 'quit' to exit)\")\n",- " msgs = []\n",- " while True:\n",- " inp = input(\"\\nYou> \").strip()\n",- " if inp.lower() in (\"quit\", \"exit\", \"q\"):\n",- " break\n",- " msgs.append({\"role\": \"user\", \"content\": inp})\n",- " result = engine.chat_completion(msgs)\n",- " msg = result[\"choices\"][0][\"message\"]\n",- " if msg.get(\"content\"):\n",- " print(f\"Guppy> {msg['content']}\")\n",- " msgs.append(msg)\n",- "\n",- "\n",- "if __name__ == \"__main__\":\n",- " main()\n",- ""- ],- "outputs": [],- "execution_count": null- },- {- "cell_type": "code",- "metadata": {},- "source": [- "from huggingface_hub import hf_hub_download\n",+ "from huggingface_hub import snapshot_download\n","\n","HF_REPO = 'arman-bd/guppylm-9M'\n","\n",- "for filename in ['pytorch_model.bin', 'config.json', 'tokenizer.json']:\n",- " hf_hub_download(repo_id=HF_REPO, filename=filename, local_dir='.')\n",- " print(f' Downloaded {filename}')\n",+ "snapshot_download(repo_id=HF_REPO, local_dir='.')\n",+ "print(f'Downloaded {HF_REPO}')\n","\n",- "print(f'Model ready from {HF_REPO}')"+ "import os\n",+ "for f in os.listdir('.'):\n",+ " if not f.startswith('.'):\n",+ " print(f' {f}')"],"outputs": [],"execution_count": null