File size: 18,542 Bytes
05ffa5e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
{
 "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",
    "<task>\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 <stdio.h>\\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
}