{ "cells": [ { "cell_type": "markdown", "id": "93064172", "metadata": {}, "source": [ "# Group QKAN for Transformers\n", "\n", "To demonstrate the generative capabilities of the QKAN model, we adapt the excellent [karpathy/nanoGPT](https://github.com/karpathy/nanoGPT) implementation and replace the standard MLP components with QKAN-based modules. This variant is referred to as **Kansformer**.\n", "\n", "> **Note:** Although our main paper introduces a different method, the Kansformer variant shown here provides a much more efficient implementation.\n", "\n", "## Motivation\n", "\n", "Previously, we introduced **Hybrid QKAN (HQKAN)** — a variant that retains the expressive power of QKAN while using significantly fewer parameters than standard MLPs.\n", "\n", "While HQKAN addresses the **parameter scalability** challenge of KAN-family models, a new issue arises as the model grows in size:\n", "\n", "> Having too many **learnable variational activation functions (VAFs)** in a single layer can make optimization difficult and unstable.\n", "\n", "To solve this, **X. Yang et al.**, in *\"Kolmogorov–Arnold Transformer\"*, proposed **grouping the VAFs** within each layer. In this approach, VAFs are **shared across groups**, which reduces the number of independent parameters and improves training efficiency.\n", "\n", "## Our Implementation\n", "\n", "We implement the **GPT-2** architecture with **Hybrid Grouped QKAN (HG-QKAN)** modules and train the model on the **WebText** dataset.\n", "\n", "> **Note:** However, if we have already used Hybrid architecture to reduce the number of VAFs, grouping may not be necessary. In our previous experiments, we found that **HQKAN without grouping** performed better than HG-QKAN, if the number of VAFs was not significantly large." ] }, { "cell_type": "code", "execution_count": 1, "id": "ba745dd3", "metadata": {}, "outputs": [], "source": [ "import inspect\n", "import math\n", "import os\n", "import pickle\n", "import time\n", "import warnings\n", "from ast import literal_eval\n", "from collections import defaultdict\n", "from dataclasses import dataclass\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import torch\n", "import torch.nn as nn\n", "from torch.nn import functional as F\n", "from torch.utils.data import Dataset\n", "from torch.utils.data.dataloader import DataLoader\n", "from tqdm import tqdm\n", "from transformers import GPT2Tokenizer\n", "\n", "from qkan import QKAN\n", "\n", "warnings.filterwarnings(\"ignore\", category=FutureWarning)\n", "device = \"cuda\"" ] }, { "cell_type": "code", "execution_count": 2, "id": "2f08cd7b", "metadata": {}, "outputs": [], "source": [ "# Define dataset\n", "class WebTextDataset(Dataset):\n", " \"\"\"\n", " WebText Dataset\n", " \"\"\"\n", "\n", " def __init__(self, split, model_type, block_size=1024, vocab_size=50257):\n", " assert split in {\"train\", \"test\", \"valid\"}\n", "\n", " self.split = split\n", " self.block_size = block_size\n", " self.vocab_size = vocab_size\n", " self.tokenizer = GPT2Tokenizer.from_pretrained(model_type)\n", "\n", " self.tokenized_dataset_path = f\"./datasets/webtext/webtext.{split}.pkl\"\n", "\n", " if not os.path.isfile(self.tokenized_dataset_path):\n", " self.tokenized_dataset = []\n", "\n", " self.json_path = f\"./datasets/webtext/webtext.{split}.jsonl\"\n", "\n", " assert os.path.isfile(self.json_path)\n", "\n", " self.data = pd.read_json(path_or_buf=self.json_path, lines=True)\n", "\n", " tokenized_data = []\n", " tokenized_lengths = []\n", "\n", " for _, row in tqdm(\n", " self.data.iterrows(), desc=\"Tokenizing\", total=len(self.data)\n", " ):\n", " text = row[\"text\"]\n", "\n", " tokenized = self.tokenizer.encode(\n", " text=text, add_special_tokens=False\n", " )\n", " tokenized_length = len(tokenized)\n", "\n", " tokenized_data.append(tokenized)\n", " tokenized_lengths.append(tokenized_length)\n", "\n", " self.tokenized_dataset += tokenized\n", "\n", " with open(self.tokenized_dataset_path, \"wb\") as f:\n", " pickle.dump(self.tokenized_dataset, f)\n", "\n", " with open(self.tokenized_dataset_path, \"rb\") as f:\n", " self.tokenized_dataset = pickle.load(f)\n", "\n", " def __len__(self):\n", " return len(self.tokenized_dataset) - 2 * self.block_size\n", "\n", " def get_vocab_size(self):\n", " return self.vocab_size\n", "\n", " def get_block_size(self):\n", " return self.block_size\n", "\n", " def __getitem__(self, idx):\n", "\n", " x = self.tokenized_dataset[idx : idx + self.block_size]\n", " y = self.tokenized_dataset[\n", " idx + self.block_size : idx + 2 * self.block_size\n", " ]\n", "\n", " assert len(x) == self.block_size, f\"Unexpected len: {len(x)}\"\n", " assert len(y) == self.block_size, f\"Unexpected len: {len(y)}\"\n", "\n", " x = torch.tensor(x, dtype=torch.long)\n", " y = torch.tensor(y, dtype=torch.long)\n", "\n", " return x, y" ] }, { "cell_type": "code", "execution_count": null, "id": "71afa2ca", "metadata": {}, "outputs": [], "source": [ "class LayerNorm(nn.Module):\n", " \"\"\"LayerNorm but with an optional bias. PyTorch doesn't support simply bias=False\"\"\"\n", " def __init__(self, ndim, bias):\n", " super().__init__()\n", " self.weight = nn.Parameter(torch.ones(ndim))\n", " self.bias = nn.Parameter(torch.zeros(ndim)) if bias else None\n", "\n", " def forward(self, input):\n", " return F.layer_norm(input, self.weight.shape, self.weight, self.bias, 1e-5)\n", "\n", "\n", "class CN:\n", " \"\"\"a lightweight configuration class inspired by yacs\"\"\"\n", " def __init__(self, **kwargs):\n", " self.__dict__.update(kwargs)\n", "\n", " def __str__(self):\n", " return self._str_helper(0)\n", "\n", " def _str_helper(self, indent):\n", " \"\"\"need to have a helper to support nested indentation for pretty printing\"\"\"\n", " parts = []\n", " for k, v in self.__dict__.items():\n", " if isinstance(v, CN):\n", " parts.append(\"%s:\\n\" % k)\n", " parts.append(v._str_helper(indent + 1))\n", " else:\n", " parts.append(\"%s: %s\\n\" % (k, v))\n", " parts = [\" \" * (indent * 4) + p for p in parts]\n", " return \"\".join(parts)\n", "\n", " def to_dict(self):\n", " \"\"\"return a dict representation of the config\"\"\"\n", " return {\n", " k: v.to_dict() if isinstance(v, CN) else v for k, v in self.__dict__.items()\n", " }\n", "\n", " def merge_from_dict(self, d):\n", " self.__dict__.update(d)\n", "\n", " def merge_from_args(self, args):\n", " \"\"\"\n", " update the configuration from a list of strings that is expected\n", " to come from the command line, i.e. sys.argv[1:].\n", "\n", " The arguments are expected to be in the form of `--arg=value`, and\n", " the arg can use . to denote nested sub-attributes. Example:\n", "\n", " --model.n_layer=10 --trainer.batch_size=32\n", " \"\"\"\n", " for arg in args:\n", "\n", " keyval = arg.split(\"=\")\n", " assert len(keyval) == 2, (\n", " \"expecting each override arg to be of form --arg=value, got %s\" % arg\n", " )\n", " key, val = keyval # unpack\n", "\n", " # first translate val into a python object\n", " try:\n", " val = literal_eval(val)\n", " \"\"\"\n", " need some explanation here.\n", " - if val is simply a string, literal_eval will throw a ValueError\n", " - if val represents a thing (like an 3, 3.14, [1,2,3], False, None, etc.) it will get created\n", " \"\"\"\n", " except ValueError:\n", " pass\n", "\n", " # find the appropriate object to insert the attribute into\n", " assert key[:2] == \"--\"\n", " key = key[2:] # strip the '--'\n", " keys = key.split(\".\")\n", " obj = self\n", " for k in keys[:-1]:\n", " obj = getattr(obj, k)\n", " leaf_key = keys[-1]\n", "\n", " # ensure that this attribute exists\n", " assert hasattr(\n", " obj, leaf_key\n", " ), f\"{key} is not an attribute that exists in the config\"\n", "\n", " # overwrite the attribute\n", " print(\"command line overwriting config attribute %s with %s\" % (key, val))\n", " setattr(obj, leaf_key, val)\n", "\n", "\n", "class CausalSelfAttention(nn.Module):\n", " def __init__(self, config):\n", " super().__init__()\n", " assert config.n_embd % config.n_head == 0\n", " # key, query, value projections for all heads, but in a batch\n", " self.c_attn = nn.Linear(config.n_embd, 3 * config.n_embd, bias=config.bias)\n", " # output projection\n", " self.c_proj = nn.Linear(config.n_embd, config.n_embd, bias=config.bias)\n", " # regularization\n", " self.attn_dropout = nn.Dropout(config.dropout)\n", " self.resid_dropout = nn.Dropout(config.dropout)\n", " self.n_head = config.n_head\n", " self.n_embd = config.n_embd\n", " self.dropout = config.dropout\n", " # flash attention make GPU go brrrrr but support is only in PyTorch >= 2.0\n", " self.flash = hasattr(torch.nn.functional, \"scaled_dot_product_attention\")\n", " if not self.flash:\n", " print(\n", " \"WARNING: using slow attention. Flash Attention requires PyTorch >= 2.0\"\n", " )\n", " # causal mask to ensure that attention is only applied to the left in the input sequence\n", " self.register_buffer(\n", " \"bias\",\n", " torch.tril(torch.ones(config.block_size, config.block_size)).view(\n", " 1, 1, config.block_size, config.block_size\n", " ),\n", " )\n", "\n", " def forward(self, x):\n", " B, T, C = (\n", " x.size()\n", " ) # batch size, sequence length, embedding dimensionality (n_embd)\n", "\n", " # calculate query, key, values for all heads in batch and move head forward to be the batch dim\n", " q, k, v = self.c_attn(x).split(self.n_embd, dim=2)\n", " k = k.view(B, T, self.n_head, C // self.n_head).transpose(\n", " 1, 2\n", " ) # (B, nh, T, hs)\n", " q = q.view(B, T, self.n_head, C // self.n_head).transpose(\n", " 1, 2\n", " ) # (B, nh, T, hs)\n", " v = v.view(B, T, self.n_head, C // self.n_head).transpose(\n", " 1, 2\n", " ) # (B, nh, T, hs)\n", "\n", " # causal self-attention; Self-attend: (B, nh, T, hs) x (B, nh, hs, T) -> (B, nh, T, T)\n", " if self.flash:\n", " # efficient attention using Flash Attention CUDA kernels\n", " y = torch.nn.functional.scaled_dot_product_attention(\n", " q,\n", " k,\n", " v,\n", " attn_mask=None,\n", " dropout_p=self.dropout if self.training else 0,\n", " is_causal=True,\n", " )\n", " else:\n", " # manual implementation of attention\n", " att = (q @ k.transpose(-2, -1)) * (1.0 / math.sqrt(k.size(-1)))\n", " att = att.masked_fill(self.bias[:, :, :T, :T] == 0, float(\"-inf\"))\n", " att = F.softmax(att, dim=-1)\n", " att = self.attn_dropout(att)\n", " y = att @ v # (B, nh, T, T) x (B, nh, T, hs) -> (B, nh, T, hs)\n", " y = (\n", " y.transpose(1, 2).contiguous().view(B, T, C)\n", " ) # re-assemble all head outputs side by side\n", "\n", " # output projection\n", " y = self.resid_dropout(self.c_proj(y))\n", " return y\n", "\n", "\n", "class Block(nn.Module):\n", " def __init__(self, config):\n", " super().__init__()\n", " self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)\n", " self.attn = CausalSelfAttention(config)\n", " self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)\n", " els = math.ceil(math.log2(config.n_embd))\n", " self.mlp = nn.ModuleDict(\n", " dict(\n", " c=nn.Sequential(\n", " nn.Linear(config.n_embd, els),\n", " QKAN(\n", " width=[els, els],\n", " reps=1,\n", " group=3,\n", " preact_trainable=True,\n", " postact_weight_trainable=True,\n", " postact_bias_trainable=True,\n", " ba_trainable=True,\n", " device=device,\n", " ),\n", " nn.Linear(els, config.n_embd),\n", " ),\n", " dropout=nn.Dropout(config.dropout),\n", " )\n", " )\n", " m = self.mlp\n", " self.mlpf = lambda x: m.dropout(m.c(x))\n", "\n", " def forward(self, x):\n", " x = x + self.attn(self.ln_1(x))\n", " x = x + self.mlpf(self.ln_2(x))\n", " return x\n", "\n", "\n", "@dataclass\n", "class GPTConfig:\n", " block_size: int = 1024\n", " vocab_size: int = (\n", " 50304 # GPT-2 vocab_size of 50257, padded up to nearest multiple of 64 for efficiency\n", " )\n", " n_layer: int = 12\n", " n_head: int = 12\n", " n_embd: int = 768\n", " dropout: float = 0.0\n", " bias: bool = (\n", " True # True: bias in Linears and LayerNorms, like GPT-2. False: a bit better and faster\n", " )\n", "\n", "\n", "class GPT(nn.Module):\n", " def __init__(self, config):\n", " super().__init__()\n", " assert config.vocab_size is not None\n", " assert config.block_size is not None\n", " self.config = config\n", "\n", " self.transformer = nn.ModuleDict(\n", " dict(\n", " wte=nn.Embedding(config.vocab_size, config.n_embd),\n", " wpe=nn.Embedding(config.block_size, config.n_embd),\n", " drop=nn.Dropout(config.dropout),\n", " h=nn.ModuleList([Block(config) for _ in range(config.n_layer)]),\n", " ln_f=LayerNorm(config.n_embd, bias=config.bias),\n", " )\n", " )\n", " self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)\n", " # with weight tying when using torch.compile() some warnings get generated:\n", " # \"UserWarning: functional_call was passed multiple values for tied weights.\n", " # This behavior is deprecated and will be an error in future versions\"\n", " # not 100% sure what this is, so far seems to be harmless. TODO investigate\n", " self.transformer.wte.weight = (\n", " self.lm_head.weight\n", " ) # https://paperswithcode.com/method/weight-tying\n", "\n", " # init all weights\n", " self.apply(self._init_weights)\n", " # apply special scaled init to the residual projections, per GPT-2 paper\n", " for pn, p in self.named_parameters():\n", " if pn.endswith(\"c_proj.weight\"):\n", " torch.nn.init.normal_(\n", " p, mean=0.0, std=0.02 / math.sqrt(2 * config.n_layer)\n", " )\n", "\n", " # report number of parameters\n", " print(\"number of parameters: %.2fM\" % (self.get_num_params() / 1e6,))\n", "\n", " def get_num_params(self, non_embedding=True):\n", " \"\"\"\n", " Return the number of parameters in the model.\n", " For non-embedding count (default), the position embeddings get subtracted.\n", " The token embeddings would too, except due to the parameter sharing these\n", " params are actually used as weights in the final layer, so we include them.\n", " \"\"\"\n", " n_params = sum(p.numel() for p in self.parameters())\n", " if non_embedding:\n", " n_params -= self.transformer.wpe.weight.numel()\n", " return n_params\n", "\n", " def _init_weights(self, module):\n", " if isinstance(module, nn.Linear):\n", " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n", " if module.bias is not None:\n", " torch.nn.init.zeros_(module.bias)\n", " elif isinstance(module, nn.Embedding):\n", " torch.nn.init.normal_(module.weight, mean=0.0, std=0.02)\n", "\n", " def forward(self, idx, targets=None):\n", " device = idx.device\n", " b, t = idx.size()\n", " assert (\n", " t <= self.config.block_size\n", " ), f\"Cannot forward sequence of length {t}, block size is only {self.config.block_size}\"\n", " pos = torch.arange(0, t, dtype=torch.long, device=device) # shape (t)\n", "\n", " # forward the GPT model itself\n", " tok_emb = self.transformer.wte(idx) # token embeddings of shape (b, t, n_embd)\n", " pos_emb = self.transformer.wpe(pos) # position embeddings of shape (t, n_embd)\n", " x = self.transformer.drop(tok_emb + pos_emb)\n", " for block in self.transformer.h:\n", " x = block(x)\n", " x = self.transformer.ln_f(x)\n", "\n", " if targets is not None:\n", " # if we are given some desired targets also calculate the loss\n", " logits = self.lm_head(x)\n", " loss = F.cross_entropy(\n", " logits.view(-1, logits.size(-1)), targets.view(-1), ignore_index=-1\n", " )\n", " else:\n", " # inference-time mini-optimization: only forward the lm_head on the very last position\n", " logits = self.lm_head(\n", " x[:, [-1], :]\n", " ) # note: using list [-1] to preserve the time dim\n", " loss = None\n", "\n", " return logits, loss\n", "\n", " def crop_block_size(self, block_size):\n", " # model surgery to decrease the block size if necessary\n", " # e.g. we may load the GPT2 pretrained model checkpoint (block size 1024)\n", " # but want to use a smaller block size for some smaller, simpler model\n", " assert block_size <= self.config.block_size\n", " self.config.block_size = block_size\n", " self.transformer.wpe.weight = nn.Parameter(\n", " self.transformer.wpe.weight[:block_size]\n", " )\n", " for block in self.transformer.h:\n", " if hasattr(block.attn, \"bias\"):\n", " block.attn.bias = block.attn.bias[:, :, :block_size, :block_size]\n", "\n", " @classmethod\n", " def from_pretrained(cls, model_type, override_args=None):\n", " assert model_type in {\"gpt2\", \"gpt2-medium\", \"gpt2-large\", \"gpt2-xl\"}\n", " override_args = override_args or {} # default to empty dict\n", " # only dropout can be overridden see more notes below\n", " assert all(k == \"dropout\" for k in override_args)\n", " from transformers import GPT2LMHeadModel\n", "\n", " print(\"loading weights from pretrained gpt: %s\" % model_type)\n", "\n", " # n_layer, n_head and n_embd are determined from model_type\n", " config_args = {\n", " \"gpt2\": dict(n_layer=12, n_head=12, n_embd=768), # 124M params\n", " \"gpt2-medium\": dict(n_layer=24, n_head=16, n_embd=1024), # 350M params\n", " \"gpt2-large\": dict(n_layer=36, n_head=20, n_embd=1280), # 774M params\n", " \"gpt2-xl\": dict(n_layer=48, n_head=25, n_embd=1600), # 1558M params\n", " }[model_type]\n", " print(\"forcing vocab_size=50257, block_size=1024, bias=True\")\n", " config_args[\"vocab_size\"] = 50257 # always 50257 for GPT model checkpoints\n", " config_args[\"block_size\"] = 1024 # always 1024 for GPT model checkpoints\n", " config_args[\"bias\"] = True # always True for GPT model checkpoints\n", " # we can override the dropout rate, if desired\n", " if \"dropout\" in override_args:\n", " print(f\"overriding dropout rate to {override_args['dropout']}\")\n", " config_args[\"dropout\"] = override_args[\"dropout\"]\n", " # create a from-scratch initialized minGPT model\n", " config = GPTConfig(**config_args)\n", " model = GPT(config)\n", " sd = model.state_dict()\n", " sd_keys = sd.keys()\n", " sd_keys = [\n", " k for k in sd_keys if not k.endswith(\".attn.bias\")\n", " ] # discard this mask / buffer, not a param\n", "\n", " # init a huggingface/transformers model\n", " model_hf = GPT2LMHeadModel.from_pretrained(model_type)\n", " sd_hf = model_hf.state_dict()\n", "\n", " # copy while ensuring all of the parameters are aligned and match in names and shapes\n", " sd_keys_hf = sd_hf.keys()\n", " sd_keys_hf = [\n", " k for k in sd_keys_hf if not k.endswith(\".attn.masked_bias\")\n", " ] # ignore these, just a buffer\n", " sd_keys_hf = [\n", " k for k in sd_keys_hf if not k.endswith(\".attn.bias\")\n", " ] # same, just the mask (buffer)\n", " transposed = [\n", " \"attn.c_attn.weight\",\n", " \"attn.c_proj.weight\",\n", " \"mlp.c_fc.weight\",\n", " \"mlp.c_proj.weight\",\n", " ]\n", " # basically the openai checkpoints use a \"Conv1D\" module, but we only want to use a vanilla Linear\n", " # this means that we have to transpose these weights when we import them\n", " assert len(sd_keys_hf) == len(\n", " sd_keys\n", " ), f\"mismatched keys: {len(sd_keys_hf)} != {len(sd_keys)}\"\n", " for k in sd_keys_hf:\n", " if any(k.endswith(w) for w in transposed):\n", " # special treatment for the Conv1D weights we need to transpose\n", " assert sd_hf[k].shape[::-1] == sd[k].shape\n", " with torch.no_grad():\n", " sd[k].copy_(sd_hf[k].t())\n", " else:\n", " # vanilla copy over the other parameters\n", " assert sd_hf[k].shape == sd[k].shape\n", " with torch.no_grad():\n", " sd[k].copy_(sd_hf[k])\n", "\n", " return model\n", "\n", " def configure_optimizers(self, weight_decay, learning_rate, betas, device_type):\n", " # start with all of the candidate parameters\n", " param_dict = {pn: p for pn, p in self.named_parameters()}\n", " # filter out those that do not require grad\n", " param_dict = {pn: p for pn, p in param_dict.items() if p.requires_grad}\n", " # create optim groups. Any parameters that is 2D will be weight decayed, otherwise no.\n", " # i.e. all weight tensors in matmuls + embeddings decay, all biases and layernorms don't.\n", " decay_params = [p for n, p in param_dict.items() if p.dim() >= 2]\n", " nodecay_params = [p for n, p in param_dict.items() if p.dim() < 2]\n", " optim_groups = [\n", " {\"params\": decay_params, \"weight_decay\": weight_decay},\n", " {\"params\": nodecay_params, \"weight_decay\": 0.0},\n", " ]\n", " num_decay_params = sum(p.numel() for p in decay_params)\n", " num_nodecay_params = sum(p.numel() for p in nodecay_params)\n", " print(\n", " f\"num decayed parameter tensors: {len(decay_params)}, with {num_decay_params:,} parameters\"\n", " )\n", " print(\n", " f\"num non-decayed parameter tensors: {len(nodecay_params)}, with {num_nodecay_params:,} parameters\"\n", " )\n", " # Create AdamW optimizer and use the fused version if it is available\n", " fused_available = \"fused\" in inspect.signature(torch.optim.AdamW).parameters\n", " use_fused = fused_available and device_type == \"cuda\"\n", " extra_args = dict(fused=True) if use_fused else dict()\n", " optimizer = torch.optim.AdamW(\n", " optim_groups, lr=learning_rate, betas=betas, **extra_args\n", " )\n", " print(f\"using fused AdamW: {use_fused}\")\n", "\n", " return optimizer\n", "\n", " def estimate_mfu(self, fwdbwd_per_iter, dt):\n", " \"\"\"estimate model flops utilization (MFU) in units of A100 bfloat16 peak FLOPS\"\"\"\n", " # first estimate the number of flops we do per iteration.\n", " # see PaLM paper Appendix B as ref: https://arxiv.org/abs/2204.02311\n", " N = self.get_num_params()\n", " cfg = self.config\n", " L, H, Q, T = cfg.n_layer, cfg.n_head, cfg.n_embd // cfg.n_head, cfg.block_size\n", " flops_per_token = 6 * N + 12 * L * H * Q * T\n", " flops_per_fwdbwd = flops_per_token * T\n", " flops_per_iter = flops_per_fwdbwd * fwdbwd_per_iter\n", " # express our flops throughput as ratio of A100 bfloat16 peak flops\n", " flops_achieved = flops_per_iter * (1.0 / dt) # per second\n", " flops_promised = 312e12 # A100 GPU bfloat16 peak flops is 312 TFLOPS\n", " mfu = flops_achieved / flops_promised\n", " return mfu\n", "\n", " @torch.no_grad()\n", " def generate(self, idx, max_new_tokens, temperature=1.0, top_k=None):\n", " \"\"\"\n", " Take a conditioning sequence of indices idx (LongTensor of shape (b,t)) and complete\n", " the sequence max_new_tokens times, feeding the predictions back into the model each time.\n", " Most likely you'll want to make sure to be in model.eval() mode of operation for this.\n", " \"\"\"\n", " for _ in range(max_new_tokens):\n", " # if the sequence context is growing too long we must crop it at block_size\n", " idx_cond = (\n", " idx\n", " if idx.size(1) <= self.config.block_size\n", " else idx[:, -self.config.block_size :]\n", " )\n", " # forward the model to get the logits for the index in the sequence\n", " logits, _ = self(idx_cond)\n", " # pluck the logits at the final step and scale by desired temperature\n", " logits = logits[:, -1, :] / temperature\n", " # optionally crop the logits to only the top k options\n", " if top_k is not None:\n", " v, _ = torch.topk(logits, min(top_k, logits.size(-1)))\n", " logits[logits < v[:, [-1]]] = -float(\"Inf\")\n", " # apply softmax to convert logits to (normalized) probabilities\n", " probs = F.softmax(logits, dim=-1)\n", " # sample from the distribution\n", " idx_next = torch.multinomial(probs, num_samples=1)\n", " # append sampled index to the running sequence and continue\n", " idx = torch.cat((idx, idx_next), dim=1)\n", "\n", " return idx" ] }, { "cell_type": "code", "execution_count": 4, "id": "526336ab", "metadata": {}, "outputs": [], "source": [ "def metrics(y, y_pred):\n", " \"\"\"\n", " y: (B, T) INT - True labels\n", " y_pred: (B, T, C) FLOAT - Predicted probabilities\n", "\n", " Returns:\n", " - Perplexity\n", " - F1 Score\n", " - Precision\n", " - Recall\n", " - Cross Entropy\n", " \"\"\"\n", "\n", " # Make sure y_pred is between 0 and 1\n", " if not (np.all(y_pred >= 0) and np.all(y_pred <= 1)):\n", " # Softmax\n", " y_pred = np.exp(y_pred) / np.sum(np.exp(y_pred), axis=-1, keepdims=True)\n", "\n", " assert np.all(y_pred >= 0) and np.all(y_pred <= 1), \"y_pred must be between 0 and 1\"\n", "\n", " # Add a small epsilon for numerical stability\n", " epsilon = 1e-9\n", " y_pred = np.clip(y_pred, epsilon, 1 - epsilon)\n", "\n", " # Cross Entropy\n", " y_one_hot = np.eye(y_pred.shape[-1])[y]\n", " cross_entropy = -np.mean(np.sum(y_one_hot * np.log(y_pred), axis=-1))\n", "\n", " # Perplexity\n", " perplexity = 2**cross_entropy\n", "\n", " # Predicted classes\n", " y_pred_class = np.argmax(y_pred, axis=-1)\n", "\n", " # True Positives, False Positives, and False Negatives\n", " TP = np.sum(y == y_pred_class)\n", " FP = np.sum(y != y_pred_class)\n", " FN = FP # Binary setup, false positives and false negatives are equivalent\n", "\n", " # Precision, Recall\n", " precision = TP / (TP + FP)\n", " recall = TP / (TP + FN)\n", "\n", " # F1 Score\n", " f1 = 2 * (precision * recall) / (precision + recall)\n", "\n", " return perplexity, f1, precision, recall, cross_entropy\n", "\n", "\n", "def eval_split(\n", " trainer, split, max_batches, batch_size, model, train_dataset, test_dataset\n", "):\n", " dataset = {\"train\": train_dataset, \"test\": test_dataset}[split]\n", " results = []\n", "\n", " loader = DataLoader(dataset, batch_size=batch_size, num_workers=0, drop_last=False)\n", " for b, (x, y) in enumerate(loader):\n", " x = x.to(trainer.device)\n", " y = y.to(trainer.device)\n", "\n", " block_size = y.shape[1]\n", "\n", " logits, loss = model(x, y)\n", "\n", " probs = F.softmax(logits, dim=-1)\n", "\n", " _, y_pred = torch.topk(probs, k=block_size, dim=-1)\n", "\n", " perplexity, f1, precision, recall, cross_entropy = metrics(\n", " y=y.cpu().numpy(), y_pred=probs.cpu().numpy()\n", " )\n", "\n", " results.append((loss, perplexity, f1, precision, recall, cross_entropy))\n", "\n", " if max_batches is not None and b + 1 >= max_batches:\n", " break\n", " rt = torch.tensor(results, dtype=torch.float)\n", " print(\"%s loss: %.2f\" % (split, rt.mean(dim=0)[0]))\n", " return rt.mean(dim=0)\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "175bd27e", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "test_dataset: 2898230\n", "train_dataset: 146323009\n", "number of parameters: 67.19M\n", "Number of parameters: 67.97M\n" ] } ], "source": [ "Dataset = WebTextDataset\n", "test_dataset = Dataset(\"test\", \"gpt2\")\n", "train_dataset = Dataset(\"train\", \"gpt2\")\n", "\n", "print(\"test_dataset: \", len(test_dataset))\n", "print(\"train_dataset: \", len(train_dataset))\n", "\n", "# create a GPT instance\n", "model_config = GPTConfig()\n", "model_config.model_type = \"gpt2\"\n", "model_config.vocab_size = train_dataset.get_vocab_size()\n", "model_config.block_size = train_dataset.get_block_size()\n", "model = GPT(model_config)\n", "\n", "print(\n", " \"Number of parameters: %.2fM\"\n", " % (sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6,)\n", ")" ] }, { "cell_type": "code", "execution_count": 6, "id": "7b856225", "metadata": {}, "outputs": [], "source": [ "class Trainer:\n", " @staticmethod\n", " def get_default_config():\n", " C = CN()\n", " # device to train on\n", " C.device = \"auto\"\n", " # dataloder parameters\n", " C.num_workers = 4\n", " # optimizer parameters\n", " C.max_iters = None\n", " C.batch_size = 64\n", " C.learning_rate = 3e-4\n", " C.betas = (0.9, 0.95)\n", " C.weight_decay = 0.1 # only applied on matmul weights\n", " C.grad_norm_clip = 1.0\n", " return C\n", "\n", " def __init__(self, config, model, train_dataset):\n", " self.config = config\n", " self.model = model\n", " self.optimizer = None\n", " self.train_dataset = train_dataset\n", " self.callbacks = defaultdict(list)\n", "\n", " # determine the device we'll train on\n", " if config.device == \"auto\":\n", " self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", " else:\n", " self.device = config.device\n", " self.model = self.model.to(self.device)\n", " print(\"running on device\", self.device)\n", "\n", " # variables that will be assigned to trainer class later for logging and etc\n", " self.iter_num = 0\n", " self.iter_time = 0.0\n", " self.iter_dt = 0.0\n", "\n", " def add_callback(self, onevent: str, callback):\n", " self.callbacks[onevent].append(callback)\n", "\n", " def set_callback(self, onevent: str, callback):\n", " self.callbacks[onevent] = [callback]\n", "\n", " def trigger_callbacks(self, onevent: str):\n", " for callback in self.callbacks.get(onevent, []):\n", " callback(self)\n", "\n", " def run(self):\n", " model, config = self.model, self.config\n", "\n", " # setup the optimizer\n", " self.optimizer = model.configure_optimizers(config.weight_decay, config.learning_rate, config.betas, self.device)\n", "\n", " # setup the dataloader\n", " train_loader = DataLoader(\n", " self.train_dataset,\n", " sampler=torch.utils.data.RandomSampler(\n", " self.train_dataset, replacement=True, num_samples=int(1e10)\n", " ),\n", " shuffle=False,\n", " pin_memory=True,\n", " batch_size=config.batch_size,\n", " num_workers=config.num_workers,\n", " )\n", "\n", " model.train()\n", " self.iter_num = 0\n", " self.iter_time = time.time()\n", " data_iter = iter(train_loader)\n", " while True:\n", "\n", " # fetch the next batch (x, y) and re-init iterator if needed\n", " try:\n", " batch = next(data_iter)\n", " except StopIteration:\n", " data_iter = iter(train_loader)\n", " batch = next(data_iter)\n", " batch = [t.to(self.device) for t in batch]\n", " x, y = batch\n", "\n", " # forward the model\n", " logits, self.loss = model(x, y)\n", "\n", " # backprop and update the parameters\n", " model.zero_grad(set_to_none=True)\n", " self.loss.backward()\n", " torch.nn.utils.clip_grad_norm_(model.parameters(), config.grad_norm_clip)\n", " self.optimizer.step()\n", "\n", " self.trigger_callbacks(\"on_batch_end\")\n", " self.iter_num += 1\n", " tnow = time.time()\n", " self.iter_dt = tnow - self.iter_time\n", " self.iter_time = tnow\n", "\n", " # termination conditions\n", " if config.max_iters is not None and self.iter_num >= config.max_iters:\n", " break" ] }, { "cell_type": "code", "execution_count": 7, "id": "148f82ea", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "running on device cuda\n" ] } ], "source": [ "# create a Trainer object\n", "train_config = Trainer.get_default_config()\n", "train_config.learning_rate = 3e-4\n", "train_config.max_iters = 2000\n", "train_config.num_workers = 0\n", "train_config.batch_size = 1\n", "train_config.device = device\n", "trainer = Trainer(train_config, model, train_dataset)" ] }, { "cell_type": "code", "execution_count": 8, "id": "b6a43f0f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "num decayed parameter tensors: 122, with 67,885,824 parameters\n", "num non-decayed parameter tensors: 98, with 84,600 parameters\n", "using fused AdamW: True\n", "iter_dt 0.00ms; iter 0: train loss 10.95520\n", "iter_dt 37.84ms; iter 100: train loss 8.03499\n", "iter_dt 37.37ms; iter 200: train loss 8.12177\n", "iter_dt 37.87ms; iter 300: train loss 7.91832\n", "iter_dt 37.83ms; iter 400: train loss 8.11329\n", "iter_dt 37.46ms; iter 500: train loss 8.05757\n", "iter_dt 37.92ms; iter 600: train loss 7.64972\n", "iter_dt 37.87ms; iter 700: train loss 7.60039\n", "iter_dt 37.85ms; iter 800: train loss 7.94277\n", "iter_dt 37.84ms; iter 900: train loss 7.85295\n", "iter_dt 37.84ms; iter 1000: train loss 10.16237\n", "iter_dt 37.88ms; iter 1100: train loss 8.37014\n", "iter_dt 37.87ms; iter 1200: train loss 7.67977\n", "iter_dt 37.90ms; iter 1300: train loss 8.22389\n", "iter_dt 37.85ms; iter 1400: train loss 8.00896\n", "iter_dt 37.92ms; iter 1500: train loss 9.33540\n", "iter_dt 37.94ms; iter 1600: train loss 7.94113\n", "iter_dt 37.47ms; iter 1700: train loss 8.19066\n", "iter_dt 37.93ms; iter 1800: train loss 7.85500\n", "iter_dt 37.92ms; iter 1900: train loss 7.81131\n" ] } ], "source": [ "def batch_end_callback(trainer):\n", " if trainer.iter_num % 100 == 0:\n", " print(f\"iter_dt {trainer.iter_dt * 1000:.2f}ms; iter {trainer.iter_num}: train loss {trainer.loss.item():.5f}\")\n", "trainer.set_callback('on_batch_end', batch_end_callback)\n", "\n", "trainer.run()" ] }, { "cell_type": "code", "execution_count": 9, "id": "30ed3f56", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "train loss: 7.63\n", "test loss: 7.59\n", "train_loss: tensor(7.6327)\n", "train_perplexity: tensor(198.4565)\n", "train_f1: tensor(0.0475)\n", "train_precision: tensor(0.0475)\n", "train_recall: tensor(0.0475)\n", "train_cross_entropy: tensor(7.6327)\n", "test_loss: tensor(7.5937)\n", "test_perplexity: tensor(193.1681)\n", "test_f1: tensor(0.0312)\n", "test_precision: tensor(0.0312)\n", "test_recall: tensor(0.0312)\n", "test_cross_entropy: tensor(7.5937)\n" ] } ], "source": [ "model.eval()\n", "with torch.no_grad():\n", " train_score = eval_split(\n", " trainer,\n", " \"train\",\n", " max_batches=5,\n", " batch_size=1,\n", " model=model,\n", " train_dataset=train_dataset,\n", " test_dataset=test_dataset,\n", " )\n", " test_score = eval_split(\n", " trainer,\n", " \"test\",\n", " max_batches=5,\n", " batch_size=1,\n", " model=model,\n", " train_dataset=train_dataset,\n", " test_dataset=test_dataset,\n", " )\n", "\n", " (\n", " train_loss,\n", " train_perplexity,\n", " train_f1,\n", " train_precision,\n", " train_recall,\n", " train_cross_entropy,\n", " ) = train_score\n", " (\n", " test_loss,\n", " test_perplexity,\n", " test_f1,\n", " test_precision,\n", " test_recall,\n", " test_cross_entropy,\n", " ) = test_score\n", "\n", "print(\"train_loss: \", train_loss)\n", "print(\"train_perplexity: \", train_perplexity)\n", "print(\"train_f1: \", train_f1)\n", "print(\"train_precision: \", train_precision)\n", "print(\"train_recall: \", train_recall)\n", "print(\"train_cross_entropy: \", train_cross_entropy)\n", "\n", "print(\"test_loss: \", test_loss)\n", "print(\"test_perplexity: \", test_perplexity)\n", "print(\"test_f1: \", test_f1)\n", "print(\"test_precision: \", test_precision)\n", "print(\"test_recall: \", test_recall)\n", "print(\"test_cross_entropy: \", test_cross_entropy)" ] }, { "cell_type": "markdown", "id": "8341f1a7", "metadata": {}, "source": [ "Compare to MLP" ] }, { "cell_type": "code", "execution_count": 10, "id": "1c3b154c", "metadata": {}, "outputs": [], "source": [ "class MLP(nn.Module):\n", "\n", " def __init__(self, config):\n", " super().__init__()\n", " self.c_fc = nn.Linear(config.n_embd, 4 * config.n_embd, bias=config.bias)\n", " self.gelu = nn.GELU()\n", " self.c_proj = nn.Linear(4 * config.n_embd, config.n_embd, bias=config.bias)\n", " self.dropout = nn.Dropout(config.dropout)\n", "\n", " def forward(self, x):\n", " x = self.c_fc(x)\n", " x = self.gelu(x)\n", " x = self.c_proj(x)\n", " x = self.dropout(x)\n", " return x\n", "\n", "class Block(nn.Module):\n", "\n", " def __init__(self, config):\n", " super().__init__()\n", " self.ln_1 = LayerNorm(config.n_embd, bias=config.bias)\n", " self.attn = CausalSelfAttention(config)\n", " self.ln_2 = LayerNorm(config.n_embd, bias=config.bias)\n", " self.mlp = MLP(config)\n", "\n", " def forward(self, x):\n", " x = x + self.attn(self.ln_1(x))\n", " x = x + self.mlp(self.ln_2(x))\n", " return x" ] }, { "cell_type": "code", "execution_count": 11, "id": "7e50a29a", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "number of parameters: 123.65M\n", "Number of parameters: 124.44M\n" ] } ], "source": [ "# create a GPT instance\n", "model_config = GPTConfig()\n", "model_config.model_type = \"gpt2\"\n", "model_config.vocab_size = train_dataset.get_vocab_size()\n", "model_config.block_size = train_dataset.get_block_size()\n", "model = GPT(model_config)\n", "\n", "print(\n", " \"Number of parameters: %.2fM\"\n", " % (sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6,)\n", ")" ] }, { "cell_type": "code", "execution_count": 12, "id": "ebac3b5d", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "running on device cuda\n", "num decayed parameter tensors: 50, with 124,318,464 parameters\n", "num non-decayed parameter tensors: 98, with 121,344 parameters\n", "using fused AdamW: True\n", "iter_dt 0.00ms; iter 0: train loss 10.96399\n", "iter_dt 38.10ms; iter 100: train loss 7.46826\n", "iter_dt 38.00ms; iter 200: train loss 7.66300\n", "iter_dt 38.00ms; iter 300: train loss 7.95232\n", "iter_dt 37.63ms; iter 400: train loss 7.66633\n", "iter_dt 37.67ms; iter 500: train loss 8.46683\n", "iter_dt 38.03ms; iter 600: train loss 7.43420\n", "iter_dt 37.69ms; iter 700: train loss 7.37517\n", "iter_dt 37.76ms; iter 800: train loss 8.08870\n", "iter_dt 37.90ms; iter 900: train loss 7.54975\n", "iter_dt 37.37ms; iter 1000: train loss 7.96053\n", "iter_dt 38.32ms; iter 1100: train loss 7.61653\n", "iter_dt 37.92ms; iter 1200: train loss 7.84077\n", "iter_dt 37.52ms; iter 1300: train loss 7.86578\n", "iter_dt 37.99ms; iter 1400: train loss 8.13120\n", "iter_dt 37.65ms; iter 1500: train loss 7.99749\n", "iter_dt 38.02ms; iter 1600: train loss 7.91518\n", "iter_dt 37.67ms; iter 1700: train loss 7.84328\n", "iter_dt 37.97ms; iter 1800: train loss 7.89387\n", "iter_dt 37.39ms; iter 1900: train loss 7.96062\n" ] } ], "source": [ "trainer = Trainer(train_config, model, train_dataset)\n", "trainer.set_callback('on_batch_end', batch_end_callback)\n", "\n", "trainer.run()" ] }, { "cell_type": "code", "execution_count": 13, "id": "be946040", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "train loss: 7.70\n", "test loss: 7.67\n", "train_loss: tensor(7.7001)\n", "train_perplexity: tensor(207.9543)\n", "train_f1: tensor(0.0475)\n", "train_precision: tensor(0.0475)\n", "train_recall: tensor(0.0475)\n", "train_cross_entropy: tensor(7.7001)\n", "test_loss: tensor(7.6732)\n", "test_perplexity: tensor(204.1052)\n", "test_f1: tensor(0.0312)\n", "test_precision: tensor(0.0312)\n", "test_recall: tensor(0.0312)\n", "test_cross_entropy: tensor(7.6732)\n" ] } ], "source": [ "model.eval()\n", "with torch.no_grad():\n", " train_score = eval_split(\n", " trainer,\n", " \"train\",\n", " max_batches=5,\n", " batch_size=1,\n", " model=model,\n", " train_dataset=train_dataset,\n", " test_dataset=test_dataset,\n", " )\n", " test_score = eval_split(\n", " trainer,\n", " \"test\",\n", " max_batches=5,\n", " batch_size=1,\n", " model=model,\n", " train_dataset=train_dataset,\n", " test_dataset=test_dataset,\n", " )\n", "\n", " (\n", " train_loss,\n", " train_perplexity,\n", " train_f1,\n", " train_precision,\n", " train_recall,\n", " train_cross_entropy,\n", " ) = train_score\n", " (\n", " test_loss,\n", " test_perplexity,\n", " test_f1,\n", " test_precision,\n", " test_recall,\n", " test_cross_entropy,\n", " ) = test_score\n", "\n", "print(\"train_loss: \", train_loss)\n", "print(\"train_perplexity: \", train_perplexity)\n", "print(\"train_f1: \", train_f1)\n", "print(\"train_precision: \", train_precision)\n", "print(\"train_recall: \", train_recall)\n", "print(\"train_cross_entropy: \", train_cross_entropy)\n", "\n", "print(\"test_loss: \", test_loss)\n", "print(\"test_perplexity: \", test_perplexity)\n", "print(\"test_f1: \", test_f1)\n", "print(\"test_precision: \", test_precision)\n", "print(\"test_recall: \", test_recall)\n", "print(\"test_cross_entropy: \", test_cross_entropy)" ] }, { "cell_type": "markdown", "id": "aeaaf756", "metadata": {}, "source": [ "## Results\n", "\n", "The HG-QKAN model achieves **better performance than the MLP-based baseline**, while using:\n", "- **Only half the number of parameters**\n", "- **The same training time**\n", "\n", "This result is both surprising and promising, demonstrating the power and efficiency of QKAN-based architectures, especially when enhanced with grouping and hybrid techniques." ] } ], "metadata": { "kernelspec": { "display_name": "venv", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.11.5" } }, "nbformat": 4, "nbformat_minor": 5 }