Advertisement
Guest User

Untitled

a guest
Mar 27th, 2023
666
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 37.17 KB | None | 0 0
  1. {
  2. "nbformat": 4,
  3. "nbformat_minor": 0,
  4. "metadata": {
  5. "colab": {
  6. "provenance": []
  7. },
  8. "kernelspec": {
  9. "name": "python3",
  10. "display_name": "Python 3"
  11. },
  12. "language_info": {
  13. "name": "python"
  14. },
  15. "accelerator": "GPU",
  16. "gpuClass": "standard"
  17. },
  18. "cells": [
  19. {
  20. "cell_type": "markdown",
  21. "source": [
  22. "First, install the CUDA extensions."
  23. ],
  24. "metadata": {
  25. "id": "ZUbS-f1DPXvV"
  26. }
  27. },
  28. {
  29. "cell_type": "code",
  30. "execution_count": null,
  31. "metadata": {
  32. "id": "1tVeqisMQ5wr"
  33. },
  34. "outputs": [],
  35. "source": [
  36. "#!apt-get -y update\n",
  37. "#!apt-get -y install python3.10-dev\n",
  38. "#!python -m pip install --upgrade pip\n",
  39. "#!git clone https://github.com/qwopqwop200/GPTQ-for-LLaMa.git\n",
  40. "!git clone https://github.com/MasterTaffer/GPTQ-for-LLaMa.git\n",
  41. "%cd 'GPTQ-for-LLaMa'\n",
  42. "!python setup_cuda.py install\n",
  43. "#!python test_kernel.py"
  44. ]
  45. },
  46. {
  47. "cell_type": "markdown",
  48. "source": [
  49. "Next, restart the runtime (but don't delete it). We'll need to do that in order for colab to be able to use the quant_cuda CPP extensions.\n",
  50. "\n",
  51. "Afterward, return to this this cell and execute it to clone the repo, install libraries and download your 4 bit LLaMA model of choice."
  52. ],
  53. "metadata": {
  54. "id": "R5-qdqtyPu1g"
  55. }
  56. },
  57. {
  58. "cell_type": "code",
  59. "source": [
  60. "import sys\n",
  61. "import torch\n",
  62. "import quant_cuda\n",
  63. "\n",
  64. "!pip install transformers\n",
  65. "!pip install sentencepiece\n",
  66. "weights_url = 'https://huggingface.co/wcde/llama-13b-4bit-gr128/resolve/main/llama-13b-4bit-gr128.pt' #@param {type:\"string\"}\n",
  67. "num_params = \"13b\" #@param [\"7b\", \"13b\", \"30b\", \"65b\"]\n",
  68. "group_size = 128 #@param {type:\"number\"}\n",
  69. "wbits = 4 #@param [\"2\", \"3\", \"4\", \"8\"]\n",
  70. "!wget {weights_url}\n",
  71. "!pip install git+https://github.com/zphang/transformers@llama_push\n",
  72. "sys.path.insert(0, 'GPTQ-for-LLaMa/')#sys.path.insert(0, '/content/GPTQ-for-LLaMa/')\n",
  73. "#!CUDA_VISIBLE_DEVICES=0 python llama_inference.py decapoda-research/llama-13b-hf --wbits 4 --load llama-13b-4bit.pt --text \"It was the best of times, it was the worst of times\""
  74. ],
  75. "metadata": {
  76. "id": "a4Q7JnyOZHB-"
  77. },
  78. "execution_count": null,
  79. "outputs": []
  80. },
  81. {
  82. "cell_type": "markdown",
  83. "source": [
  84. "Now execute this cell in order to load in the model. Additionally, you can specify your context size (if you're free tier and running 13B, you'll have to keep this pretty low or you may either run out of memory or have ridiculously slow generation times) and a flag denoting whether to load and split the model checkpoint in GPU VRAM before loading (also needed for free tier 13B)."
  85. ],
  86. "metadata": {
  87. "id": "3hBn0BoIQoNZ"
  88. }
  89. },
  90. {
  91. "cell_type": "code",
  92. "source": [
  93. "import time\n",
  94. "\n",
  95. "import torch\n",
  96. "import torch.nn as nn\n",
  97. "\n",
  98. "from gptq import *\n",
  99. "from modelutils import *\n",
  100. "from quant import *\n",
  101. "\n",
  102. "from transformers import LlamaTokenizer\n",
  103. "\n",
  104. "DEV = torch.device('cuda:0')\n",
  105. "#context_size = 1024 #@param {type:\"number\"}\n",
  106. "split_checkpoint = True #@param {type:\"boolean\"}\n",
  107. "\n",
  108. "def load_quant(model, checkpoint, wbits, group_size):\n",
  109. " from transformers import LlamaConfig, LlamaForCausalLM \n",
  110. " config = LlamaConfig.from_pretrained(model)\n",
  111. " def noop(*args, **kwargs):\n",
  112. " pass\n",
  113. " torch.nn.init.kaiming_uniform_ = noop \n",
  114. " torch.nn.init.uniform_ = noop\n",
  115. " torch.nn.init.normal_ = noop \n",
  116. "\n",
  117. " if split_checkpoint:\n",
  118. " print('Splitting checkpoint ...')\n",
  119. " ckpt = torch.load(checkpoint, map_location='cuda')\n",
  120. "\n",
  121. " d1 = dict(list(ckpt.items())[:len(ckpt)//2])\n",
  122. " torch.save(d1, checkpoint + '0')\n",
  123. " del(d1)\n",
  124. "\n",
  125. " d2 = dict(list(ckpt.items())[len(ckpt)//2:])\n",
  126. " torch.save(d2, checkpoint + '1')\n",
  127. " del(d2)\n",
  128. "\n",
  129. " del(ckpt)\n",
  130. "\n",
  131. " torch.set_default_dtype(torch.half)\n",
  132. " transformers.modeling_utils._init_weights = False\n",
  133. " torch.set_default_dtype(torch.half)\n",
  134. " model = LlamaForCausalLM(config)\n",
  135. " torch.set_default_dtype(torch.float)\n",
  136. " model = model.eval()\n",
  137. " layers = find_layers(model)\n",
  138. " for name in ['lm_head']:\n",
  139. " if name in layers:\n",
  140. " del layers[name]\n",
  141. " make_quant(model, layers, wbits, group_size)\n",
  142. "\n",
  143. " if split_checkpoint:\n",
  144. " print('Loading model ...')\n",
  145. " for i in range(2):\n",
  146. " ckpt = torch.load(checkpoint + str(i))\n",
  147. " model.load_state_dict(ckpt, strict=False)\n",
  148. " del(ckpt)\n",
  149. " print('Done.')\n",
  150. "\n",
  151. " else:\n",
  152. " ckpt = torch.load(checkpoint)\n",
  153. " print('Loading model ...')\n",
  154. " model.load_state_dict(torch.load(checkpoint))\n",
  155. " print('Done.')\n",
  156. "\n",
  157. " #model.seqlen = context_size\n",
  158. " return model\n",
  159. "\n",
  160. "model = load_quant('decapoda-research/llama-{}-hf'.format(num_params), 'llama-{}-{}bit-gr{}.pt'.format(num_params, wbits, group_size), wbits, group_size).cuda()\n",
  161. "model.to(DEV)\n",
  162. "tokenizer = LlamaTokenizer.from_pretrained('decapoda-research/llama-{}-hf'.format(num_params))"
  163. ],
  164. "metadata": {
  165. "id": "KleSQ3ziiQ3n"
  166. },
  167. "execution_count": null,
  168. "outputs": []
  169. },
  170. {
  171. "cell_type": "markdown",
  172. "source": [
  173. "Define our token generation functions (both normal and generator)."
  174. ],
  175. "metadata": {
  176. "id": "35GvK2M5BASW"
  177. }
  178. },
  179. {
  180. "cell_type": "code",
  181. "source": [
  182. "import torch\n",
  183. "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
  184. "\n",
  185. "def gen_next_tokens(model, tokenizer, tokenized, context_len, max_gen_len,\n",
  186. " mask_id, temperature=0.8, top_p=0.95, tfs=1.0, typical=1.0,\n",
  187. " penalty_range=1024, penalty_slope=0.7, penalty=1.1,\n",
  188. " past_key_values=None):\n",
  189. " #tokenized = tokenizer.encode(inp, return_tensors='pt').to(DEV)\n",
  190. " total_len = min(context_len, max_gen_len + tokenized.shape[1])\n",
  191. "\n",
  192. " tokens = torch.full((1, total_len), mask_id).to(DEV)\n",
  193. " tokens[0, :tokenized.shape[1]] = tokenized[0]\n",
  194. "\n",
  195. " if past_key_values:\n",
  196. " output_past_key_values = past_key_values\n",
  197. "\n",
  198. " for cur_id in range(tokenized.shape[1], total_len):\n",
  199. " #print(cur_id - tokenized.shape[1])\n",
  200. " if past_key_values:\n",
  201. " output = model(tokens[:, cur_id-1:cur_id], past_key_values=past_key_values, use_cache=True)\n",
  202. " else:\n",
  203. " output = model(tokens[:, :cur_id], use_cache=True)\n",
  204. "\n",
  205. " if not past_key_values:\n",
  206. " logits = output.logits[:, cur_id-1, :]\n",
  207. " output_past_key_values = output.past_key_values\n",
  208. " else:\n",
  209. " logits = output.logits[:, 0, :]\n",
  210. " \n",
  211. " past_key_values = output.past_key_values\n",
  212. " input_ids = tokens[:, cur_id-1:cur_id]\n",
  213. "\n",
  214. " # Apply samplers - do greedy sampling if temperature is 0.\n",
  215. " if temperature > 0:\n",
  216. " next_token_scores = sample_top_p_actual(input_ids, logits,\n",
  217. " top_p)\n",
  218. " next_token_scores = sample_tail_free(input_ids,\n",
  219. " next_token_scores, tfs)\n",
  220. " next_token_scores = sample_typical(input_ids, next_token_scores,\n",
  221. " typical)\n",
  222. " next_token_scores = sample_temperature(input_ids,\n",
  223. " next_token_scores,\n",
  224. " temperature)\n",
  225. " next_token_scores = sample_advanced_repetition_penalty(input_ids,\n",
  226. " next_token_scores,\n",
  227. " penalty_range,\n",
  228. " penalty_slope,\n",
  229. " penalty)\n",
  230. "\n",
  231. " next_token_scores = torch.nn.functional.softmax(next_token_scores,\n",
  232. " dim=-1)\n",
  233. "\n",
  234. " next_token = torch.multinomial(next_token_scores,\n",
  235. " num_samples=1).squeeze(1)\n",
  236. " else:\n",
  237. " next_token = torch.argmax(logits, axis=-1)[0]\n",
  238. "\n",
  239. " tokens[0, cur_id] = next_token\n",
  240. " if next_token.item() == tokenizer.eos_token_id:\n",
  241. " return tokens[:, :cur_id], output_past_key_values\n",
  242. " \n",
  243. " return tokens, output_past_key_values\n",
  244. "\n",
  245. "def stm_next_tokens(model, tokenizer, tokenized, context_len, max_gen_len,\n",
  246. " mask_id, temperature=0.8, top_p=0.95, tfs=1.0, typical=1.0,\n",
  247. " penalty_range=1024, penalty_slope=0.7, penalty=1.1,\n",
  248. " past_key_values=None):\n",
  249. " #tokenized = tokenizer.encode(inp, return_tensors='pt').to(DEV)\n",
  250. " total_len = min(context_len, max_gen_len + tokenized.shape[1])\n",
  251. "\n",
  252. " tokens = torch.full((1, total_len), mask_id).to(DEV)\n",
  253. " tokens[0, :tokenized.shape[1]] = tokenized[0]\n",
  254. "\n",
  255. " if past_key_values:\n",
  256. " output_past_key_values = past_key_values\n",
  257. "\n",
  258. " for cur_id in range(tokenized.shape[1], total_len):\n",
  259. " #print(cur_id - tokenized.shape[1])\n",
  260. " if past_key_values:\n",
  261. " output = model(tokens[:, cur_id-1:cur_id], past_key_values=past_key_values, use_cache=True)\n",
  262. " else:\n",
  263. " output = model(tokens[:, :cur_id], use_cache=True)\n",
  264. "\n",
  265. " if not past_key_values:\n",
  266. " logits = output.logits[:, cur_id-1, :]\n",
  267. " output_past_key_values = output.past_key_values\n",
  268. " else:\n",
  269. " logits = output.logits[:, 0, :]\n",
  270. " \n",
  271. " past_key_values = output.past_key_values\n",
  272. " input_ids = tokens[:, cur_id-1:cur_id]\n",
  273. "\n",
  274. " # Apply samplers - do greedy sampling if temperature is 0.\n",
  275. " if temperature > 0:\n",
  276. " next_token_scores = sample_top_p_actual(input_ids, logits,\n",
  277. " top_p)\n",
  278. " next_token_scores = sample_tail_free(input_ids,\n",
  279. " next_token_scores, tfs)\n",
  280. " next_token_scores = sample_typical(input_ids, next_token_scores,\n",
  281. " typical)\n",
  282. " next_token_scores = sample_temperature(input_ids,\n",
  283. " next_token_scores,\n",
  284. " temperature)\n",
  285. " next_token_scores = sample_advanced_repetition_penalty(input_ids,\n",
  286. " next_token_scores,\n",
  287. " penalty_range,\n",
  288. " penalty_slope,\n",
  289. " penalty)\n",
  290. "\n",
  291. " next_token_scores = torch.nn.functional.softmax(next_token_scores,\n",
  292. " dim=-1)\n",
  293. "\n",
  294. " next_token = torch.multinomial(next_token_scores,\n",
  295. " num_samples=1).squeeze(1)\n",
  296. " else:\n",
  297. " next_token = torch.argmax(logits, axis=-1)[0]\n",
  298. "\n",
  299. " tokens[0, cur_id] = next_token\n",
  300. " yield next_token, None\n",
  301. "\n",
  302. " if next_token.item() == tokenizer.eos_token_id:\n",
  303. " yield None, output_past_key_values\n",
  304. " return\n",
  305. " \n",
  306. " yield None, output_past_key_values\n",
  307. " return\n",
  308. "\n",
  309. "# taken from Kobold and transformers so this stuff is AGPL I guess\n",
  310. "def sample_temperature(input_ids, scores, tempt):\n",
  311. " scores = scores / tempt\n",
  312. " return scores\n",
  313. "\n",
  314. "def sample_typical(input_ids, scores, typical, filter_value = -float(\"Inf\"),\n",
  315. " min_tokens_to_keep = 1):\n",
  316. " if filter_value >= 1.0:\n",
  317. " return scores\n",
  318. "\n",
  319. " probs = scores.softmax(dim=-1)\n",
  320. " log_probs = probs.log()\n",
  321. "\n",
  322. " neg_entropy = (probs * log_probs).nansum(dim=-1, keepdim=True)\n",
  323. "\n",
  324. " entropy_deviation = (neg_entropy - log_probs).abs()\n",
  325. "\n",
  326. " _, sorted_indices = torch.sort(entropy_deviation)\n",
  327. " sorted_logits = probs.gather(-1, sorted_indices)\n",
  328. " sorted_indices_to_remove = sorted_logits.cumsum(dim=-1) >= typical\n",
  329. " sorted_indices_to_remove = sorted_indices_to_remove.roll(1, dims=-1)\n",
  330. "\n",
  331. " min_tokens_to_keep = max(min_tokens_to_keep, 1)\n",
  332. " # Keep at least min_tokens_to_keep\n",
  333. " sorted_indices_to_remove[..., : min_tokens_to_keep] = 0\n",
  334. "\n",
  335. " indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)\n",
  336. " scores = scores.masked_fill(indices_to_remove, filter_value)\n",
  337. " return scores \n",
  338. "\n",
  339. "def sample_top_p_actual(input_ids, scores, top_p, filter_value = -float(\"Inf\"),\n",
  340. " min_tokens_to_keep = 1):\n",
  341. " sorted_logits, sorted_indices = torch.sort(scores, descending=False)\n",
  342. " cumulative_probs = sorted_logits.softmax(dim=-1).cumsum(dim=-1)\n",
  343. "\n",
  344. " # Remove tokens with cumulative top_p above the threshold (token with 0 are kept)\n",
  345. " sorted_indices_to_remove = cumulative_probs <= (1 - top_p)\n",
  346. " if min_tokens_to_keep > 1:\n",
  347. " # Keep at least min_tokens_to_keep\n",
  348. " sorted_indices_to_remove[..., -min_tokens_to_keep :] = 0\n",
  349. "\n",
  350. " # scatter sorted tensors to original indexing\n",
  351. " indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices,\n",
  352. " sorted_indices_to_remove)\n",
  353. " scores = scores.masked_fill(indices_to_remove, filter_value)\n",
  354. " return scores\n",
  355. "\n",
  356. "def sample_advanced_repetition_penalty(input_ids, scores, penalty_range,\n",
  357. " penalty_slope, penalty):\n",
  358. " penalty_range = int(penalty_range)\n",
  359. " clipped_penalty_range = min(input_ids.shape[-1], penalty_range)\n",
  360. "\n",
  361. " if penalty != 1.0:\n",
  362. " if penalty_range > 0:\n",
  363. " if clipped_penalty_range < input_ids.shape[1]:\n",
  364. " input_ids = input_ids[..., -clipped_penalty_range:]\n",
  365. "\n",
  366. " if penalty_slope != 0:\n",
  367. " _penalty = (torch.arange(penalty_range, dtype=scores.dtype,\n",
  368. " device=scores.device)/(penalty_range - 1)) * 2. - 1\n",
  369. " _penalty = (penalty_slope * _penalty) / (1 + torch.abs(_penalty) * (penalty_slope - 1))\n",
  370. " _penalty = 1 + ((_penalty + 1) / 2).unsqueeze(0) * (penalty - 1)\n",
  371. " penalty = _penalty[..., -clipped_penalty_range:]\n",
  372. "\n",
  373. " score = torch.gather(scores, 1, input_ids)\n",
  374. " score = torch.where(score <= 0, score * penalty, score / penalty)\n",
  375. " scores.scatter_(1, input_ids, score)\n",
  376. "\n",
  377. " return scores \n",
  378. "\n",
  379. "def sample_top_a(input_ids, scores, top_a, filter_value = -float(\"Inf\"),\n",
  380. " min_tokens_to_keep = 1):\n",
  381. " if filter_value >= 1.0:\n",
  382. " return scores\n",
  383. "\n",
  384. " sorted_logits, sorted_indices = torch.sort(scores, descending=True)\n",
  385. " probs = sorted_logits.softmax(dim=-1)\n",
  386. "\n",
  387. " # Remove tokens with probability less than top_a*(max(probs))^2 (token with 0 are kept)\n",
  388. " probs_max = probs[..., 0, None]\n",
  389. " sorted_indices_to_remove = probs < probs_max * probs_max * top_a\n",
  390. "\n",
  391. " if min_tokens_to_keep > 1:\n",
  392. " # Keep at least min_tokens_to_keep\n",
  393. " sorted_indices_to_remove[..., : min_tokens_to_keep] = 0\n",
  394. "\n",
  395. " indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices,\n",
  396. " sorted_indices_to_remove)\n",
  397. " scores = scores.masked_fill(indices_to_remove, filter_value)\n",
  398. " return scores \n",
  399. "\n",
  400. "def sample_tail_free(input_ids, scores, tfs, filter_value = -float(\"Inf\"),\n",
  401. " min_tokens_to_keep = 1):\n",
  402. " if filter_value >= 1.0:\n",
  403. " return scores\n",
  404. " sorted_logits, sorted_indices = torch.sort(scores, descending=True)\n",
  405. " probs = sorted_logits.softmax(dim=-1)\n",
  406. "\n",
  407. " # Compute second derivative normalized CDF\n",
  408. " d2 = probs.diff().diff().abs()\n",
  409. " normalized_d2 = d2 / d2.sum(dim=-1, keepdim=True)\n",
  410. " normalized_d2_cdf = normalized_d2.cumsum(dim=-1)\n",
  411. "\n",
  412. " # Remove tokens with CDF value above the threshold (token with 0 are kept)\n",
  413. " sorted_indices_to_remove = normalized_d2_cdf > tfs\n",
  414. "\n",
  415. " # Centre the distribution around the cutoff as in the original implementation of the algorithm\n",
  416. " sorted_indices_to_remove = torch.cat(\n",
  417. " (\n",
  418. " torch.zeros(scores.shape[0], 1, dtype=torch.bool,\n",
  419. " device=scores.device),\n",
  420. " sorted_indices_to_remove,\n",
  421. " torch.ones(scores.shape[0], 1, dtype=torch.bool,\n",
  422. " device=scores.device),\n",
  423. " ),\n",
  424. " dim=-1,\n",
  425. " )\n",
  426. "\n",
  427. " if min_tokens_to_keep > 1:\n",
  428. " # Keep at least min_tokens_to_keep\n",
  429. " sorted_indices_to_remove[..., : min_tokens_to_keep] = 0\n",
  430. "\n",
  431. " indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices,\n",
  432. " sorted_indices_to_remove)\n",
  433. " scores = scores.masked_fill(indices_to_remove, filter_value)\n",
  434. " return scores"
  435. ],
  436. "metadata": {
  437. "id": "9ZWJd4lzLjkP"
  438. },
  439. "execution_count": null,
  440. "outputs": []
  441. },
  442. {
  443. "cell_type": "markdown",
  444. "source": [
  445. "Main GUI."
  446. ],
  447. "metadata": {
  448. "id": "nZ44wSJGNoDY"
  449. }
  450. },
  451. {
  452. "cell_type": "code",
  453. "source": [
  454. "import ipywidgets as widgets\n",
  455. "from IPython.display import display\n",
  456. "import time\n",
  457. "from enum import Enum\n",
  458. "\n",
  459. "context_size = 1024 #@param {type:\"number\"}\n",
  460. "max_gen_len = 160 #@param {type:\"number\"}\n",
  461. "temperature = 1.0 #@param {type:\"number\"}\n",
  462. "top_p = 0.95 #@param {type:\"number\"}\n",
  463. "tfs = 1.0 #@param {type:\"number\"}\n",
  464. "typical = 1.0 #@param {type:\"number\"}\n",
  465. "penalty_range = 1024 #@param {type:\"number\"}\n",
  466. "penalty_slope = 0.7 #@param {type:\"number\"}\n",
  467. "penalty = 1.1 #@param {type:\"number\"}\n",
  468. "output_streaming = True #@param {type:\"boolean\"}\n",
  469. "kv_cache_size = 1 #@param {type:\"number\"}\n",
  470. "\n",
  471. "input_text_area = widgets.Textarea(placeholder='Enter a prompt...',\n",
  472. " layout=widgets.Layout(width='900px',\n",
  473. " height='600px'))\n",
  474. "model.seqlen = context_size\n",
  475. "send_button = widgets.Button(description='Send')\n",
  476. "undo_button = widgets.Button(description='Undo')\n",
  477. "redo_button = widgets.Button(description='Redo')\n",
  478. "retry_button = widgets.Button(description='Retry')\n",
  479. "prev_retry_button = widgets.Button(description='Previous Retry')\n",
  480. "memory_button = widgets.ToggleButton(description='Memory')\n",
  481. "context_button = widgets.ToggleButton(description='Context')\n",
  482. "\n",
  483. "hbox = widgets.HBox([input_text_area,\n",
  484. " widgets.VBox([send_button, undo_button, redo_button,\n",
  485. " retry_button, prev_retry_button, memory_button,\n",
  486. " context_button])])\n",
  487. "output = widgets.Output()\n",
  488. "\n",
  489. "Mode = Enum('Mode', ['INPUT', 'MEMORY', 'GENERATING', 'CONTEXT'])\n",
  490. "\n",
  491. "class State:\n",
  492. " def __init__(self, pos, mode):\n",
  493. " self.pos = pos\n",
  494. " self.mode = mode\n",
  495. " self.mem = ''\n",
  496. " self.saved_input = ''\n",
  497. " self.kv_dict = {}\n",
  498. " self.kv_queue = []\n",
  499. " \n",
  500. " def get_kv(self, id):\n",
  501. " if id in self.kv_dict:\n",
  502. " return self.kv_dict[id]\n",
  503. " else:\n",
  504. " return None\n",
  505. " \n",
  506. " def delete_kv(self, id):\n",
  507. " if id in self.kv_dict:\n",
  508. " self.kv_queue.remove(id)\n",
  509. " del self.kv_dict[id]\n",
  510. " \n",
  511. " '''\n",
  512. " def add_kv(self, id, kv):\n",
  513. " if id in self.kv_dict:\n",
  514. " self.kv_queue.remove(id)\n",
  515. " self.kv_queue.insert(0, id)\n",
  516. " else:\n",
  517. " if len(self.kv_queue) == kv_cache_size:\n",
  518. " old_id = self.kv_queue.pop()\n",
  519. " del self.kv_dict[old_id]\n",
  520. " self.kv_queue.insert(0, id)\n",
  521. " self.kv_dict[id] = kv\n",
  522. " '''\n",
  523. "\n",
  524. " def add_kv(self, id, kv):\n",
  525. " if id in self.kv_dict:\n",
  526. " self.kv_queue.remove(id)\n",
  527. " self.kv_queue.insert(0, id)\n",
  528. " elif self.get_len_kv() < kv_cache_size:\n",
  529. " self.kv_queue.insert(0, id)\n",
  530. " self.kv_dict[id] = kv\n",
  531. " \n",
  532. " def remove_last_kv(self):\n",
  533. " if self.kv_queue:\n",
  534. " old_id = self.kv_queue.pop()\n",
  535. " del self.kv_dict[old_id]\n",
  536. " \n",
  537. " def get_len_kv(self):\n",
  538. " return len(self.kv_queue)\n",
  539. " \n",
  540. " def clear_kv(self):\n",
  541. " for id in self.kv_queue:\n",
  542. " del self.kv_dict[id]\n",
  543. " self.kv_queue = []\n",
  544. "\n",
  545. "class Position:\n",
  546. " cur_id = 0\n",
  547. " def __init__(self):\n",
  548. " self.id = Position.cur_id\n",
  549. " self.pred = None\n",
  550. " self.succs = []\n",
  551. " self.succ_idx = -1\n",
  552. " self.text = ''\n",
  553. " Position.cur_id += 1\n",
  554. "\n",
  555. "init_pos = Position()\n",
  556. "cur_state = State(init_pos, Mode.INPUT)\n",
  557. "\n",
  558. "def build_context():\n",
  559. " # When creating the context, first, place the full memory followed by a\n",
  560. " # newline.\n",
  561. " #\n",
  562. " # Next, taking the last (max_seq_len-1-max_gen_len-len(mem)) tokens,\n",
  563. " # place these tokens in the context.\n",
  564. "\n",
  565. " if cur_state.mem:\n",
  566. " mem_tokenized = tokenizer.encode(cur_state.mem + '\\n', return_tensors='pt')[0].tolist()\n",
  567. " else:\n",
  568. " mem_tokenized = []\n",
  569. " \n",
  570. " inp_tokenized = tokenizer.encode(input_text_area.value, return_tensors='pt')[0].tolist()\n",
  571. " num_inp_tokens = max(model.seqlen-1-max_gen_len-len(mem_tokenized), 0)\n",
  572. "\n",
  573. " if num_inp_tokens > 0:\n",
  574. " tokenized = mem_tokenized + inp_tokenized[-num_inp_tokens:]\n",
  575. " elif len(mem_tokenized) > 0:\n",
  576. " num_mem_tokens = model.seqlen-1-max_gen_len\n",
  577. " tokenized = mem_tokenized[-num_mem_tokens:]\n",
  578. " else:\n",
  579. " tokenized = []\n",
  580. "\n",
  581. " detokenized = tokenizer.decode(tokenized)\n",
  582. " return detokenized\n",
  583. "\n",
  584. "def generate():\n",
  585. " # Create the context and send it to the model, update the text area.\n",
  586. " \n",
  587. " gen_context = build_context()\n",
  588. " retokenized = tokenizer.encode(gen_context, return_tensors='pt').to(DEV)\n",
  589. " prev_num_tokens = len(retokenized[0])\n",
  590. "\n",
  591. " output = ''\n",
  592. " past_key_values = None\n",
  593. " num_characters = 0\n",
  594. "\n",
  595. " if output_streaming:\n",
  596. " with torch.no_grad():\n",
  597. " out_tokens = retokenized[0].tolist()\n",
  598. " gen = stm_next_tokens(model, tokenizer, retokenized, model.seqlen,\n",
  599. " max_gen_len, 1, temperature=temperature, top_p=top_p, tfs=tfs,\n",
  600. " typical=typical, penalty_range=penalty_range,\n",
  601. " penalty_slope=penalty_slope, penalty=penalty,\n",
  602. " past_key_values=cur_state.get_kv(cur_state.pos.id))\n",
  603. " for tkn, pkv in gen:\n",
  604. " if pkv is not None:\n",
  605. " past_key_values = pkv\n",
  606. " else:\n",
  607. " out_tokens.append(tkn.item())\n",
  608. " output = tokenizer.decode(out_tokens)\n",
  609. " num_characters = len(output) - len(gen_context) - 1\n",
  610. " input_text_area.value = cur_state.pos.text + output[-num_characters:]\n",
  611. " else:\n",
  612. " with torch.no_grad():\n",
  613. " output_tokenized, past_key_values = gen_next_tokens(model, tokenizer,\n",
  614. " retokenized, model.seqlen, max_gen_len, 1, temperature=temperature,\n",
  615. " top_p=top_p, tfs=tfs, typical=typical, penalty_range=penalty_range,\n",
  616. " penalty_slope=penalty_slope, penalty=penalty,\n",
  617. " past_key_values=cur_state.get_kv(cur_state.pos.id))\n",
  618. " output = tokenizer.decode(output_tokenized[0].tolist())\n",
  619. " num_characters = len(output) - len(gen_context) - 1\n",
  620. " input_text_area.value = cur_state.pos.text + output[-num_characters:]\n",
  621. " return output[-num_characters:], past_key_values\n",
  622. "\n",
  623. "def on_update_input_text_area(change):\n",
  624. " # Input mode: Destroy all successors in the node list.\n",
  625. " #\n",
  626. " # Memory mode: n/a.\n",
  627. " #\n",
  628. " # Action allowed criterion: state.mode == 'input' or state.mode == 'memory'.\n",
  629. "\n",
  630. " if cur_state.mode == Mode.INPUT and (cur_state.pos.succs or cur_state.get_kv(cur_state.pos.id)) and cur_state.pos.text != input_text_area.value:\n",
  631. " if cur_state.pos.succs:\n",
  632. " del cur_state.pos.succs\n",
  633. " cur_state.pos.succs = []\n",
  634. " cur_state.pos.succ_idx = -1\n",
  635. " update_buttons_visible()\n",
  636. " if cur_state.get_kv(cur_state.pos.id):\n",
  637. " cur_state.delete_kv(cur_state.pos.id)\n",
  638. "\n",
  639. "def send():\n",
  640. " cur_state.pos.text = input_text_area.value\n",
  641. " cur_state.mode = Mode.GENERATING\n",
  642. " update_buttons_visible()\n",
  643. "\n",
  644. " if cur_state.get_len_kv() == kv_cache_size and not cur_state.get_kv(cur_state.pos.id):\n",
  645. " cur_state.remove_last_kv()\n",
  646. "\n",
  647. " generation, past_key_values = generate()\n",
  648. "\n",
  649. " new_succ = Position()\n",
  650. " new_succ.pred = cur_state.pos\n",
  651. " #new_succ.text = input_text_area.value + generation\n",
  652. " new_succ.text = input_text_area.value\n",
  653. " cur_state.pos.succs.append(new_succ)\n",
  654. " cur_state.pos.succ_idx = len(cur_state.pos.succs) - 1\n",
  655. " cur_state.add_kv(cur_state.pos.id, past_key_values)\n",
  656. " \n",
  657. " jump_to(new_succ)\n",
  658. "\n",
  659. " cur_state.mode = Mode.INPUT\n",
  660. " update_buttons_visible()\n",
  661. "\n",
  662. "def send_button_clicked(b):\n",
  663. " # Set text in current node to whatever is in the input area, generate text\n",
  664. " # (setting mode to 'generating' in the meantime), create a new successor at\n",
  665. " # head of list with text, set successor position to it, jump to it.\n",
  666. " #\n",
  667. " # Action allowed criterion: state.mode == 'input'.\n",
  668. "\n",
  669. " send()\n",
  670. " \n",
  671. "def undo_button_clicked(b):\n",
  672. " # Jump to predecessor.\n",
  673. " #\n",
  674. " # Action allowed criterion: state.mode == 'input', state.predecessor != nil.\n",
  675. "\n",
  676. " jump_to(cur_state.pos.pred)\n",
  677. "\n",
  678. "def redo_button_clicked(b):\n",
  679. " # Jump to current successor.\n",
  680. " #\n",
  681. " # Action allowed criterion: state.mode == 'input', state.successor_list !=\n",
  682. " # nil.\n",
  683. "\n",
  684. " jump_to(cur_state.pos.succs[cur_state.pos.succ_idx])\n",
  685. "\n",
  686. "def retry_button_clicked(b):\n",
  687. " # Jump to predecessor, then set successor position to next in the list if\n",
  688. " # it exists and jump to it, otherwise send_button_clicked().\n",
  689. " #\n",
  690. " # Action allowed criterion: state.mode == 'input', state.predecessor != nil.\n",
  691. "\n",
  692. " jump_to(cur_state.pos.pred)\n",
  693. "\n",
  694. " if cur_state.pos.succ_idx < len(cur_state.pos.succs) - 1:\n",
  695. " cur_state.pos.succ_idx += 1\n",
  696. " jump_to(cur_state.pos.succs[cur_state.pos.succ_idx])\n",
  697. " else:\n",
  698. " send()\n",
  699. "\n",
  700. "def prev_retry_button_clicked(b):\n",
  701. " # Jump to predecessor, then set successor position to prev in the list and\n",
  702. " # jump to it.\n",
  703. " #\n",
  704. " # Action allowed criterion: state.mode == 'input', state.predecessor != nil,\n",
  705. " # state.predecessor.succ_idx > 0.\n",
  706. "\n",
  707. " jump_to(cur_state.pos.pred)\n",
  708. " cur_state.pos.succ_idx -= 1\n",
  709. " jump_to(cur_state.pos.succs[cur_state.pos.succ_idx])\n",
  710. "\n",
  711. "def memory_button_clicked(b):\n",
  712. " # Input mode: switch modes to 'memory', save current state.\n",
  713. " #\n",
  714. " # Memory mode: switch modes to 'input', save memory, restore current state.\n",
  715. " #\n",
  716. " # Action allowed criterion: state.mode == 'input' or state.mode == 'memory'.\n",
  717. "\n",
  718. " if cur_state.mode == Mode.INPUT:\n",
  719. " cur_state.mode = Mode.MEMORY\n",
  720. " cur_state.saved_input = input_text_area.value\n",
  721. " input_text_area.value = cur_state.mem\n",
  722. " update_buttons_visible()\n",
  723. " elif cur_state.mode == Mode.MEMORY:\n",
  724. " if cur_state.mem != input_text_area.value:\n",
  725. " cur_state.clear_kv()\n",
  726. " cur_state.mode = Mode.INPUT\n",
  727. " cur_state.mem = input_text_area.value\n",
  728. " input_text_area.value = cur_state.saved_input\n",
  729. " update_buttons_visible()\n",
  730. "\n",
  731. "def context_button_clicked(b):\n",
  732. " # Input mode: switch modes to 'context', save current state.\n",
  733. " #\n",
  734. " # Context mode: switch mode to 'input', restore current state.\n",
  735. " #\n",
  736. " # Action allowed criterion: state.mode == 'input' or state.mode == 'context'.\n",
  737. "\n",
  738. " if cur_state.mode == Mode.INPUT:\n",
  739. " cur_state.mode = Mode.CONTEXT\n",
  740. " cur_state.saved_input = input_text_area.value\n",
  741. " input_text_area.value = build_context()\n",
  742. " update_buttons_visible()\n",
  743. " elif cur_state.mode == Mode.CONTEXT:\n",
  744. " cur_state.mode = Mode.INPUT\n",
  745. " input_text_area.value = cur_state.saved_input\n",
  746. " update_buttons_visible()\n",
  747. "\n",
  748. "def jump_to(pos):\n",
  749. " cur_state.pos = pos\n",
  750. " input_text_area.value = pos.text\n",
  751. " update_buttons_visible()\n",
  752. "\n",
  753. "def update_buttons_visible():\n",
  754. " send_button.disabled = cur_state.mode != Mode.INPUT\n",
  755. " undo_button.disabled = cur_state.mode != Mode.INPUT or not cur_state.pos.pred\n",
  756. " redo_button.disabled = cur_state.mode != Mode.INPUT or not cur_state.pos.succs\n",
  757. " retry_button.disabled = cur_state.mode != Mode.INPUT or not cur_state.pos.pred\n",
  758. " prev_retry_button.disabled = cur_state.mode != Mode.INPUT or not cur_state.pos.pred or not cur_state.pos.pred.succ_idx > 0\n",
  759. " memory_button.disabled = cur_state.mode != Mode.INPUT and cur_state.mode != Mode.MEMORY\n",
  760. " context_button.disabled = cur_state.mode != Mode.INPUT and cur_state.mode != Mode.CONTEXT\n",
  761. " input_text_area.disabled = cur_state.mode == Mode.GENERATING or cur_state.mode == Mode.CONTEXT\n",
  762. "\n",
  763. "send_button.on_click(send_button_clicked)\n",
  764. "undo_button.on_click(undo_button_clicked)\n",
  765. "redo_button.on_click(redo_button_clicked)\n",
  766. "retry_button.on_click(retry_button_clicked)\n",
  767. "prev_retry_button.on_click(prev_retry_button_clicked)\n",
  768. "memory_button.observe(memory_button_clicked, names='value')\n",
  769. "context_button.observe(context_button_clicked, names='value')\n",
  770. "input_text_area.observe(on_update_input_text_area, names='value')\n",
  771. "update_buttons_visible()\n",
  772. "\n",
  773. "display(hbox, output)"
  774. ],
  775. "metadata": {
  776. "id": "uYX2FVP4BlVC"
  777. },
  778. "execution_count": null,
  779. "outputs": []
  780. }
  781. ]
  782. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement