mirror of
https://github.com/wassname/prob_jsonformer.git
synced 2026-09-09 11:29:57 +08:00
working
This commit is contained in:
+118
-159
@@ -4,6 +4,17 @@
|
||||
"cell_type": "code",
|
||||
"execution_count": 1,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# autoreload your package\n",
|
||||
"%load_ext autoreload\n",
|
||||
"%autoreload 2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 2,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stderr",
|
||||
@@ -28,7 +39,7 @@
|
||||
" warnings.warn(\n",
|
||||
"`flash-attention` package not found, consider installing for better performance: No module named 'flash_attn'.\n",
|
||||
"Current `flash-attenton` does not support `window_size`. Either upgrade or use `attn_implementation='eager'`.\n",
|
||||
"Loading checkpoint shards: 100%|██████████| 4/4 [00:04<00:00, 1.10s/it]\n",
|
||||
"Loading checkpoint shards: 100%|██████████| 4/4 [00:02<00:00, 1.94it/s]\n",
|
||||
"/media/wassname/SGIronWolf/projects5/2024/prob_jsonformer/.venv/lib/python3.9/site-packages/huggingface_hub/file_download.py:1132: FutureWarning: `resume_download` is deprecated and will be removed in version 1.0.0. Downloads always resume when possible. If you want to force a new download, use `force_download=True`.\n",
|
||||
" warnings.warn(\n",
|
||||
"Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n"
|
||||
@@ -44,6 +55,7 @@
|
||||
],
|
||||
"source": [
|
||||
"from transformers import AutoModelForCausalLM, AutoTokenizer\n",
|
||||
"import torch\n",
|
||||
"\n",
|
||||
"print(\"Loading model and tokenizer...\")\n",
|
||||
"# model_name = \"databricks/dolly-v2-3b\"\n",
|
||||
@@ -51,8 +63,10 @@
|
||||
"model = AutoModelForCausalLM.from_pretrained(\n",
|
||||
" model_name,\n",
|
||||
" use_cache=True,\n",
|
||||
" torch_dtype=torch.float16,\n",
|
||||
" # device=\"cuda:0\",\n",
|
||||
" # device_map=\"auto\",\n",
|
||||
" attn_implementation='eager',\n",
|
||||
" trust_remote_code=True,\n",
|
||||
").to(\"cuda:0\")\n",
|
||||
"tokenizer = AutoTokenizer.from_pretrained(model_name, use_fast=True, use_cache=True)\n",
|
||||
@@ -68,189 +82,118 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 65,
|
||||
"execution_count": 3,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"from jaxtyping import Float, Int\n",
|
||||
"import torch\n",
|
||||
"from torch.nn import functional as F\n",
|
||||
"from torch import Tensor\n",
|
||||
"from typing import List, Callable, Tuple, Dict, Optional\n",
|
||||
"import pandas as pd"
|
||||
"# from jaxtyping import Float, Int\n",
|
||||
"# import torch\n",
|
||||
"# from torch.nn import functional as F\n",
|
||||
"# from torch import Tensor\n",
|
||||
"# from typing import List, Callable, Tuple, Dict, Optional\n",
|
||||
"# import pandas as pd"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 43,
|
||||
"execution_count": 4,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/plain": [
|
||||
"[tensor([ 1, 29871, 29896]),\n",
|
||||
" tensor([ 1, 278, 18109, 11285]),\n",
|
||||
" tensor([ 1, 278, 289, 4992, 12544])]"
|
||||
]
|
||||
},
|
||||
"execution_count": 43,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# initital state\n",
|
||||
"prompt = \"The necromancer in his tower, what's his top problem? \"\n",
|
||||
"choices = [\"1\", \"the skeleton\", \"the boney boys\"]\n",
|
||||
"choices_tokens = tokenizer(choices).input_ids\n",
|
||||
"choices_tokens = [torch.tensor(c) for c in choices_tokens]\n",
|
||||
"# current_tokens = torch.tensor([])\n",
|
||||
"# # initital state\n",
|
||||
"# prompt = \"The necromancer in his tower, what's his top problem? \"\n",
|
||||
"# choices = [\"1\", \"the skeleton\", \"the boney boys\"]\n",
|
||||
"# choices_tokens = tokenizer(choices).input_ids\n",
|
||||
"# choices_tokens = [torch.tensor(c) for c in choices_tokens]\n",
|
||||
"# # current_tokens = torch.tensor([])\n",
|
||||
"\n",
|
||||
"# next\n",
|
||||
"input_ids = tokenizer([prompt], return_tensors=\"pt\").to(model.device).input_ids[0]\n",
|
||||
"choices_tokens\n",
|
||||
"# # next\n",
|
||||
"# input_ids = tokenizer([prompt], return_tensors=\"pt\").to(model.device).input_ids[0]\n",
|
||||
"# choices_tokens\n",
|
||||
"\n",
|
||||
"# for each next choice, continue down the tree, recording the log probs"
|
||||
"# # for each next choice, continue down the tree, recording the log probs"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 70,
|
||||
"execution_count": 5,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"tensor([1]) current_tokens\n",
|
||||
"tensor([ 1, 278]) current_tokens\n",
|
||||
"tensor([ 1, 278, 289]) current_tokens\n",
|
||||
"tensor([ 1, 278, 289, 4992]) current_tokens\n",
|
||||
"tensor([ 1, 278, 289, 4992, 12544]) current_tokens\n",
|
||||
"tensor([ 1, 278, 18109]) current_tokens\n",
|
||||
"tensor([ 1, 278, 18109, 11285]) current_tokens\n",
|
||||
"tensor([ 1, 29871]) current_tokens\n",
|
||||
"tensor([ 1, 29871, 29896]) current_tokens\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"def get_valid_next_choices(choices_tokens, current_tokens):\n",
|
||||
" next_choices = []\n",
|
||||
" for choice_tokens in choices_tokens:\n",
|
||||
" # if we have some more slots left\n",
|
||||
" if len(current_tokens)<len(choice_tokens):\n",
|
||||
" # see if current_tokens matches\n",
|
||||
" if (choice_tokens[: len(current_tokens)] == current_tokens).all():\n",
|
||||
" c = choice_tokens[len(current_tokens)].item()\n",
|
||||
" next_choices.append(c)\n",
|
||||
"# def get_valid_next_choices(choices_tokens, current_tokens):\n",
|
||||
"# next_choices = []\n",
|
||||
"# for choice_tokens in choices_tokens:\n",
|
||||
"# # if we have some more slots left\n",
|
||||
"# if len(current_tokens)<len(choice_tokens):\n",
|
||||
"# # see if current_tokens matches\n",
|
||||
"# if (choice_tokens[: len(current_tokens)] == current_tokens).all():\n",
|
||||
"# c = choice_tokens[len(current_tokens)].item()\n",
|
||||
"# next_choices.append(c)\n",
|
||||
"\n",
|
||||
" next_choices = list(set(next_choices))\n",
|
||||
" return torch.LongTensor(next_choices)\n",
|
||||
"# next_choices = list(set(next_choices))\n",
|
||||
"# return torch.LongTensor(next_choices)\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"def next(\n",
|
||||
" input_ids: Int[Tensor, \"seq\"],\n",
|
||||
" choice: Optional[Int[Tensor, \"\"]] = None,\n",
|
||||
" prob: float = 1,\n",
|
||||
" current_tokens: Int[Tensor, \"seq\"] = torch.LongTensor([]),\n",
|
||||
" z=[],\n",
|
||||
"):\n",
|
||||
" if choice is not None:\n",
|
||||
" c = choice[None].to(current_tokens.device)\n",
|
||||
" current_tokens = torch.cat([current_tokens, c], dim=-1)\n",
|
||||
" print(current_tokens, 'current_tokens')\n",
|
||||
" c = choice[None].to(input_ids.device)\n",
|
||||
" input_ids = torch.cat([input_ids, c], dim=-1)\n",
|
||||
"# def gen_choice_probs(\n",
|
||||
"# model: AutoModelForCausalLM,\n",
|
||||
"# tokenizer: AutoTokenizer,\n",
|
||||
"# input_ids: Int[Tensor, \"seq\"],\n",
|
||||
"# choices_tokens: List[Int[Tensor, \"seq\"]],\n",
|
||||
"# choice: Optional[Int[Tensor, \"\"]] = None,\n",
|
||||
"# prob: float = 1,\n",
|
||||
"# current_tokens: Int[Tensor, \"seq\"] = torch.LongTensor([]),\n",
|
||||
"# z=[],\n",
|
||||
"# ):\n",
|
||||
"# if choice is not None:\n",
|
||||
"# c = choice[None].to(current_tokens.device)\n",
|
||||
"# current_tokens = torch.cat([current_tokens, c], dim=-1)\n",
|
||||
"# print(current_tokens, 'current_tokens')\n",
|
||||
"# c = choice[None].to(input_ids.device)\n",
|
||||
"# input_ids = torch.cat([input_ids, c], dim=-1)\n",
|
||||
"\n",
|
||||
" next_choices = get_valid_next_choices(choices_tokens, current_tokens)\n",
|
||||
" if len(next_choices) == 0:\n",
|
||||
" s = tokenizer.decode(current_tokens)\n",
|
||||
" r = dict(tokens=current_tokens.cpu(), prob=prob, choice=s)\n",
|
||||
" yield r\n",
|
||||
" else:\n",
|
||||
" o = model(input_ids[None])\n",
|
||||
" logits_constrained = o.logits[0, -1][next_choices]\n",
|
||||
" probs = F.softmax(logits_constrained, dim=-1)\n",
|
||||
" for i in range(len(next_choices)):\n",
|
||||
" next_choice = next_choices[i]\n",
|
||||
" next_prob = prob * probs[i].item()\n",
|
||||
" yield from next(\n",
|
||||
" input_ids=input_ids,\n",
|
||||
" choice=next_choice,\n",
|
||||
" prob=next_prob,\n",
|
||||
" current_tokens=current_tokens,\n",
|
||||
" z=z + [i],\n",
|
||||
" )\n",
|
||||
"# next_choices = get_valid_next_choices(choices_tokens, current_tokens)\n",
|
||||
"# if len(next_choices) == 0:\n",
|
||||
"# s = tokenizer.decode(current_tokens)\n",
|
||||
"# r = dict(tokens=current_tokens.cpu(), prob=prob, choice=s)\n",
|
||||
"# yield r\n",
|
||||
"# else:\n",
|
||||
"# o = model(input_ids[None])\n",
|
||||
"# logits_constrained = o.logits[0, -1][next_choices]\n",
|
||||
"# probs = F.softmax(logits_constrained, dim=-1)\n",
|
||||
"# for i in range(len(next_choices)):\n",
|
||||
"# next_choice = next_choices[i]\n",
|
||||
"# next_prob = prob * probs[i].item()\n",
|
||||
"# yield from gen_choice_probs(\n",
|
||||
"# model=model,\n",
|
||||
"# tokenizer=tokenizer,\n",
|
||||
"# choices_tokens=choices_tokens,\n",
|
||||
"# input_ids=input_ids,\n",
|
||||
"# choice=next_choice,\n",
|
||||
"# prob=next_prob,\n",
|
||||
"# current_tokens=current_tokens,\n",
|
||||
"# z=z + [i],\n",
|
||||
"# )\n",
|
||||
"\n",
|
||||
"\n",
|
||||
"r = list(next(input_ids=input_ids))"
|
||||
"# r = list(gen_choice_probs(model, tokenizer, input_ids, choices_tokens))"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 74,
|
||||
"execution_count": 6,
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
{
|
||||
"data": {
|
||||
"text/html": [
|
||||
"<div>\n",
|
||||
"<style scoped>\n",
|
||||
" .dataframe tbody tr th:only-of-type {\n",
|
||||
" vertical-align: middle;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe tbody tr th {\n",
|
||||
" vertical-align: top;\n",
|
||||
" }\n",
|
||||
"\n",
|
||||
" .dataframe thead th {\n",
|
||||
" text-align: right;\n",
|
||||
" }\n",
|
||||
"</style>\n",
|
||||
"<table border=\"1\" class=\"dataframe\">\n",
|
||||
" <thead>\n",
|
||||
" <tr style=\"text-align: right;\">\n",
|
||||
" <th></th>\n",
|
||||
" <th>prob</th>\n",
|
||||
" <th>choice</th>\n",
|
||||
" </tr>\n",
|
||||
" </thead>\n",
|
||||
" <tbody>\n",
|
||||
" <tr>\n",
|
||||
" <th>2</th>\n",
|
||||
" <td>0.995732</td>\n",
|
||||
" <td><s> 1</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>0</th>\n",
|
||||
" <td>0.004187</td>\n",
|
||||
" <td><s> the boney boys</td>\n",
|
||||
" </tr>\n",
|
||||
" <tr>\n",
|
||||
" <th>1</th>\n",
|
||||
" <td>0.000081</td>\n",
|
||||
" <td><s> the skeleton</td>\n",
|
||||
" </tr>\n",
|
||||
" </tbody>\n",
|
||||
"</table>\n",
|
||||
"</div>"
|
||||
],
|
||||
"text/plain": [
|
||||
" prob choice\n",
|
||||
"2 0.995732 <s> 1\n",
|
||||
"0 0.004187 <s> the boney boys\n",
|
||||
"1 0.000081 <s> the skeleton"
|
||||
]
|
||||
},
|
||||
"execution_count": 74,
|
||||
"metadata": {},
|
||||
"output_type": "execute_result"
|
||||
}
|
||||
],
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"pd.DataFrame(r).sort_values(\"prob\", ascending=False).drop(columns=[\"tokens\"])"
|
||||
"# r"
|
||||
]
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 7,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"# pd.DataFrame(r).sort_values(\"prob\", ascending=False).drop(columns=[\"tokens\"])"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -262,9 +205,24 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": null,
|
||||
"execution_count": 8,
|
||||
"metadata": {},
|
||||
"outputs": [],
|
||||
"outputs": [
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Generating...\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"You are not running the flash-attention implementation, expect numerical differences.\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"from prob_jsonformer.format import highlight_values\n",
|
||||
"from prob_jsonformer.main import Jsonformer\n",
|
||||
@@ -277,6 +235,7 @@
|
||||
" \"properties\": {\n",
|
||||
" \"name\": {\"type\": \"string\"},\n",
|
||||
" \"location\": {\"type\": \"string\"},\n",
|
||||
" \"choices\": {\"type\": \"choices\", \"enum\": [\"1\", \"the\", \"they walked the old dog\", \"1 the\"]},\n",
|
||||
" \"inventory\": {\n",
|
||||
" \"type\": \"array\",\n",
|
||||
" \"items\": {\n",
|
||||
@@ -286,9 +245,9 @@
|
||||
" \"name\": {\"type\": \"string\"},\n",
|
||||
" \"description\": {\"type\": \"string\"},\n",
|
||||
" \"category\": {\"type\": \"string\"},\n",
|
||||
" \"price\": {\"type\": \"number\"},\n",
|
||||
" # \"price\": {\"type\": \"number\"},\n",
|
||||
" \"inStock\": {\"type\": \"boolean\"},\n",
|
||||
" \"rating\": {\"type\": \"number\"},\n",
|
||||
" # \"rating\": {\"type\": \"number\"},\n",
|
||||
" \"images\": {\"type\": \"array\", \"items\": {\"type\": \"string\"}},\n",
|
||||
" },\n",
|
||||
" },\n",
|
||||
|
||||
Reference in New Issue
Block a user