{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# CodeGen-5.5 — Interactive Playground\n", "\n", "A 169-million-parameter, byte-level, tokenizer-free language model, continued-trained on source code and code instruction data on top of [NoTokenLM-Gen-5.5](https://huggingface.co/VeroLM/NoTokenLM-Gen-5.5). No subword vocabulary, no BPE: raw UTF-8 bytes in, raw UTF-8 bytes out. Internally the bytes are grouped into entropy-based patches (≈ 6 bytes each) and processed by a hybrid RWKV-7 / attention trunk.\n", "\n", "It is a **small research model**, not a chat assistant. It can continue code, and it understands a plain-text instruction template (`### Instruction:` / `### Response:`), but its output is often wrong: treat every result as untrusted and never run it without review. **Benchmark results: to be added.**\n", "\n", "This notebook lets you:\n", "- Load **CodeGen-5.5** directly from the Hugging Face Hub\n", "- Ask for code with the instruction template, or let the model **complete** code you started\n", "- Control **temperature**, **top-k**, **top-p** and **max new bytes** with an interactive panel\n", "- Re-run generation as many times as you like without reloading the model\n", "\n", "Works on **Google Colab**, **Kaggle Notebooks** and any standard Jupyter environment." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Setup\n", "\n", "Installs the required libraries. Safe to re-run — already-satisfied packages are skipped.\n", "\n", "Note: this intentionally does **not** force-upgrade `torch`. Colab and Kaggle ship a pre-matched `torch`/`torchvision` pair; upgrading only `torch` can break `transformers` imports. If you hit such an error, use `Runtime → Restart session` and re-run from the top." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "%pip install -q -U \"transformers>=4.44.0\" ipywidgets safetensors huggingface_hub" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Load the model\n", "\n", "Set `REPO_ID` if you point at a different repo (a fork or a local folder). By default this pulls **CodeGen-5.5** from the Hugging Face Hub (about 0.7 GB). The repository id below is a placeholder: replace it with the final id of the model.\n", "\n", "`trust_remote_code=True` is required — the model ships its own architecture code (byte encoder, entropy patching, RWKV-7 trunk, ROSA) alongside the weights. The model runs in float32." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "from transformers import AutoModelForCausalLM\n", "\n", "REPO_ID = \"VeroLM/CodeGen-5.5\" # placeholder: change this to the final repo id, a fork or a local folder\n", "\n", "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "print(f\"Loading model from '{REPO_ID}' ...\")\n", "model = AutoModelForCausalLM.from_pretrained(REPO_ID, trust_remote_code=True)\n", "model.eval()\n", "\n", "try:\n", " model.to(device)\n", " model.generate(prompt=\"Hi\", max_new_tokens=2, seed=0) # smoke test on the chosen device\n", "except Exception as e: # fall back to CPU if the GPU path misbehaves\n", " print(f\"Could not use '{device}' ({type(e).__name__}: {e}); falling back to CPU.\")\n", " device = \"cpu\"\n", " model.to(device)\n", "\n", "n_params = sum(p.numel() for p in model.parameters())\n", "print(f\"Model loaded: {n_params:,} parameters on {device}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Generation functions\n", "\n", "`run_generation()` is a thin wrapper around the model's own `generate()` method. The model works on bytes, so `max_new_tokens` counts **bytes** (most characters are 1 byte, accented letters 2, many other scripts 3–4) and decoding uses `errors=\"replace\"`, because a generation can legitimately end in the middle of a multi-byte character. Byte `0x00` is the *end-of-document* marker: generation stops when the model emits it, and the marker is dropped from the returned text. The context window is **4,096 bytes** (prompt + new bytes), so keep prompts short.\n", "\n", "`make_prompt()` builds the instruction template the model was fine-tuned on:\n", "\n", "```\n", "### Instruction:\n", "\n", "\n", "### Response:\n", "```\n", "\n", "After its answer the model may continue with further, self-invented `### Instruction:` blocks. `cut_at_next_instruction()` removes everything from the next such marker on." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def run_generation(prompt: str, max_new_tokens: int, temperature: float, top_k: int = 0, top_p: float = 1.0,\n", " do_sample: bool = True, seed: int | None = None, streamer=None):\n", " \"\"\"Generate a continuation for `prompt` and return the full text (prompt + completion).\"\"\"\n", " if not prompt:\n", " prompt = \" \" # avoid feeding a fully empty byte sequence\n", "\n", " input_ids = torch.tensor([list(prompt.encode(\"utf-8\"))], dtype=torch.long)\n", "\n", " output_ids = model.generate(\n", " input_ids,\n", " max_new_tokens=max_new_tokens,\n", " temperature=temperature,\n", " top_k=top_k if top_k > 0 else None,\n", " top_p=top_p,\n", " do_sample=do_sample,\n", " seed=seed,\n", " streamer=streamer,\n", " )\n", "\n", " byte_values = [b for b in output_ids[0].tolist() if 0 < b <= 255] # 0x00 = end-of-document marker\n", " return bytes(byte_values).decode(\"utf-8\", errors=\"replace\")\n", "\n", "\n", "def make_prompt(task: str, system: str = \"\") -> str:\n", " \"\"\"Instruction template used in the fine-tuning data (plain text, no special tokens).\"\"\"\n", " head = f\"### System:\\n{system.strip()}\\n\\n\" if system.strip() else \"\"\n", " return f\"{head}### Instruction:\\n{task.strip()}\\n\\n### Response:\\n\"\n", "\n", "\n", "def cut_at_next_instruction(text: str, prompt: str) -> str:\n", " \"\"\"Return only the first answer: drop a self-invented follow-up '### Instruction:' block.\"\"\"\n", " answer = text[len(prompt):] if text.startswith(prompt) else text\n", " i = answer.find(\"### Instruction:\")\n", " return (answer[:i] if i >= 0 else answer).rstrip()\n", "\n", "\n", "def ask(task: str, max_new_tokens: int = 400, temperature: float = 0.4, top_p: float = 0.95, seed: int | None = 0):\n", " \"\"\"Instruction mode: returns just the model's answer.\"\"\"\n", " prompt = make_prompt(task)\n", " text = run_generation(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_p=top_p, seed=seed)\n", " return cut_at_next_instruction(text, prompt)\n", "\n", "\n", "# Quick sanity check\n", "print(ask(\"Write a Python function that returns the n-th Fibonacci number.\", max_new_tokens=200))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Interactive generation panel\n", "\n", "Choose a **mode**, adjust the settings, then click **Generate**. Re-click any time — the model stays loaded in memory. The text appears progressively while it is being generated.\n", "\n", "- **Mode: Instruction** — your text is wrapped in the `### Instruction:` / `### Response:` template and only the first answer is shown.\n", "- **Mode: Completion** — your text is used as is; the model continues it (a function signature, a docstring, the first lines of a file).\n", "- **Temperature** — for code, lower values (0.2–0.5) are usually better; higher values are more varied but make syntax errors more likely.\n", "- **Top-k** — restricts sampling to the k most likely next bytes at each step (0 = off).\n", "- **Top-p** — nucleus sampling: keep the smallest set of bytes whose probability adds up to p (1.0 = off).\n", "- **Max new bytes** — how many new bytes to generate (the window is 4,096 bytes in total, prompt included).\n", "- **Greedy (no sampling)** — always picks the single most likely next byte. Deterministic, but prone to repetition.\n", "- **Seed** — a fixed integer for reproducible output, or -1 for a different result every time." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import ipywidgets as widgets\n", "from IPython.display import display, clear_output\n", "\n", "mode_toggle = widgets.ToggleButtons(\n", " options=[\"Instruction\", \"Completion\"], value=\"Instruction\",\n", " description=\"Mode:\", style={\"description_width\": \"100px\", \"button_width\": \"120px\"},\n", ")\n", "\n", "prompt_box = widgets.Textarea(\n", " value=\"Write a Python function that checks whether a string is a palindrome.\",\n", " placeholder=\"Describe the task, or type the beginning of some code...\",\n", " description=\"Prompt:\",\n", " layout=widgets.Layout(width=\"100%\", height=\"110px\"),\n", " style={\"description_width\": \"100px\"},\n", ")\n", "\n", "temperature_slider = widgets.FloatSlider(\n", " value=0.4, min=0.05, max=1.5, step=0.05,\n", " description=\"Temperature:\",\n", " style={\"description_width\": \"100px\"},\n", " layout=widgets.Layout(width=\"400px\"),\n", " readout_format=\".2f\",\n", ")\n", "\n", "top_k_slider = widgets.IntSlider(\n", " value=0, min=0, max=200, step=1,\n", " description=\"Top-k (0=off):\",\n", " style={\"description_width\": \"100px\"},\n", " layout=widgets.Layout(width=\"400px\"),\n", ")\n", "\n", "top_p_slider = widgets.FloatSlider(\n", " value=0.95, min=0.1, max=1.0, step=0.05,\n", " description=\"Top-p:\",\n", " style={\"description_width\": \"100px\"},\n", " layout=widgets.Layout(width=\"400px\"),\n", " readout_format=\".2f\",\n", ")\n", "\n", "max_tokens_slider = widgets.IntSlider(\n", " value=400, min=10, max=2048, step=10,\n", " description=\"Max new bytes:\",\n", " style={\"description_width\": \"100px\"},\n", " layout=widgets.Layout(width=\"400px\"),\n", ")\n", "\n", "greedy_checkbox = widgets.Checkbox(value=False, description=\"Greedy (no sampling)\", style={\"description_width\": \"initial\"})\n", "cut_checkbox = widgets.Checkbox(value=True, description=\"Instruction mode: cut at next '### Instruction:'\", style={\"description_width\": \"initial\"})\n", "\n", "seed_box = widgets.IntText(\n", " value=-1,\n", " description=\"Seed (-1 = random):\",\n", " style={\"description_width\": \"140px\"},\n", " layout=widgets.Layout(width=\"260px\"),\n", ")\n", "\n", "generate_button = widgets.Button(description=\"Generate\", button_style=\"primary\", icon=\"magic\")\n", "\n", "output_area = widgets.Output()\n", "\n", "def on_generate_clicked(_):\n", " generate_button.disabled = True\n", " try:\n", " with output_area:\n", " clear_output(wait=True)\n", " seed = None if seed_box.value < 0 else seed_box.value\n", " instruction_mode = mode_toggle.value == \"Instruction\"\n", " prompt = make_prompt(prompt_box.value) if instruction_mode else (prompt_box.value or \" \")\n", " produced = bytearray(prompt.encode(\"utf-8\"))\n", " print(\"Generating...\\n\")\n", "\n", " def show_progress(b): # called with every new byte\n", " if b != 0:\n", " produced.append(b)\n", " if len(produced) % 12 == 0:\n", " clear_output(wait=True)\n", " print(bytes(produced).decode(\"utf-8\", errors=\"replace\"))\n", "\n", " text = run_generation(\n", " prompt=prompt,\n", " max_new_tokens=max_tokens_slider.value,\n", " temperature=temperature_slider.value,\n", " top_k=top_k_slider.value,\n", " top_p=top_p_slider.value,\n", " do_sample=not greedy_checkbox.value,\n", " seed=seed,\n", " streamer=show_progress,\n", " )\n", " clear_output(wait=True)\n", " if instruction_mode and cut_checkbox.value:\n", " text = cut_at_next_instruction(text, prompt)\n", " print(text)\n", " finally:\n", " generate_button.disabled = False\n", "\n", "generate_button.on_click(on_generate_clicked)\n", "\n", "controls = widgets.VBox([\n", " mode_toggle,\n", " prompt_box,\n", " widgets.HBox([temperature_slider, top_k_slider]),\n", " widgets.HBox([top_p_slider, max_tokens_slider]),\n", " widgets.HBox([seed_box, greedy_checkbox]),\n", " cut_checkbox,\n", " generate_button,\n", " output_area,\n", "])\n", "\n", "display(controls)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Example prompts (optional)\n", "\n", "A few starting points for both modes (temperature 0.4, up to 400 new bytes). Sample generations for the model card are **to be added**; until then, expect code with the right overall shape but with logic errors, invented functions or syntax mistakes. Set `RUN = list(EXAMPLES)` to run all of them." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "EXAMPLES = {\n", " # instruction mode (wrapped in the template)\n", " \"fibonacci\": (\"instruct\", \"Write a Python function that returns the n-th Fibonacci number.\"),\n", " \"palindrome\": (\"instruct\", \"Write a Python function that checks whether a string is a palindrome.\"),\n", " \"sort_dicts\": (\"instruct\", \"Sort a list of dictionaries by the key 'age' in Python.\"),\n", " \"sql\": (\"instruct\", \"Write a SQL query that returns the 5 customers with the highest total order amount.\"),\n", " \"js_debounce\": (\"instruct\", \"Implement a debounce function in JavaScript.\"),\n", " # completion mode (text is continued as is)\n", " \"py_complete\": (\"completion\", 'def is_prime(n: int) -> bool:\\n \"\"\"Return True if n is a prime number.\"\"\"\\n'),\n", " \"c_complete\": (\"completion\", \"#include \\n\\nint main(void) {\\n\"),\n", " \"rust_complete\": (\"completion\", \"fn factorial(n: u64) -> u64 {\\n\"),\n", "}\n", "\n", "RUN = [\"fibonacci\", \"py_complete\"] # or: RUN = list(EXAMPLES)\n", "\n", "for name in RUN:\n", " kind, text = EXAMPLES[name]\n", " print(f\"=== {name} ({kind}) ===\")\n", " if kind == \"instruct\":\n", " print(ask(text, max_new_tokens=400, temperature=0.4, seed=42))\n", " else:\n", " print(run_generation(text, max_new_tokens=400, temperature=0.4, top_p=0.95, seed=42))\n", " print()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Batch generation (optional)\n", "\n", "Generate several answers to the same task — useful for comparing sampling settings or for seeing how much the answers vary. With code, it is often worth sampling a few candidates at low temperature and keeping the one that actually runs." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def batch_ask(task: str, n: int = 3, max_new_tokens: int = 300, temperature: float = 0.4, top_k: int = 0, top_p: float = 0.95):\n", " prompt = make_prompt(task)\n", " for i in range(n):\n", " text = run_generation(prompt, max_new_tokens=max_new_tokens, temperature=temperature, top_k=top_k, top_p=top_p)\n", " print(f\"[{i + 1}]\\n{cut_at_next_instruction(text, prompt)}\\n{'-' * 60}\")\n", "\n", "# Example — feel free to edit the arguments and re-run\n", "batch_ask(\"Write a Python function that reverses a linked list.\", n=3, max_new_tokens=300, temperature=0.4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## About this model\n", "\n", "**CodeGen-5.5** is [NoTokenLM-Gen-5.5](https://huggingface.co/VeroLM/NoTokenLM-Gen-5.5) (a ~169M-parameter byte-level model: byte embeddings plus hashed n-gram and suffix-match (ROSA) features, a small local encoder, entropy-based patching, a 20-layer hybrid RWKV-7 / gated-attention trunk working on patches, and a local byte decoder) continued-trained in a single pass on source-code files (Python-heavy, plus JavaScript, TypeScript, Java, C, C++, Go, Rust, SQL and Shell) and on code instruction data in a plain-text template. The architecture and the entropy patcher are unchanged.\n", "\n", "It is not meant for production code generation, security-sensitive code, factual questions or conversation, and it has no safety tuning. The context is 4,096 *bytes*, a few hundred lines at most. See the full model card on Hugging Face for training details and limitations. **Benchmark results: to be added.**" ] } ], "metadata": { "colab": { "provenance": [], "name": "CodeGen-5.5-Playground.ipynb" }, "kernelspec": { "display_name": "Python 3", "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.10.12" }, "accelerator": "GPU" }, "nbformat": 4, "nbformat_minor": 5 }