Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,5 @@ src/__pycache__
src/wandb
models


*.ipynb
*.pyc
*.tar.gz
148 changes: 148 additions & 0 deletions src/LLM_noise_tasks/LLM_aug.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import json\n",
"import torch\n",
"import pandas as pd\n",
"\n",
"from transformers import AutoTokenizer, AutoModelForCausalLM"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_name = \"LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct\"\n",
"\n",
"device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
"\n",
"llm = AutoModelForCausalLM.from_pretrained(\n",
" model_name,\n",
" torch_dtype=torch.bfloat16,\n",
" device_map=\"auto\",\n",
" trust_remote_code=True \n",
").to(device)\n",
"tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
"llm.eval()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open(\"../data/12000cleanlab+nannoise_8564.csv\", \"r\") as f:\n",
" df = pd.read_csv(f)\n",
"df = df[7000:]"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def augmentation(text: str):\n",
" messages = [\n",
" {\"role\": \"system\", \n",
" \"content\": \"당신은 신문 기자입니다. 당신은 신문 기사 제목을 새롭게 만드는 임무를 부여받았습니다. 당신에게 신문 기사 컨텍스트 하나가 주어질 때 해당 컨텍스트와 비슷한 의미를 가지고 있는 신문 기사 스타일의 컨텍스트 한 개를 출력해야합니다. 이 때 모든 설명을 붙이지 말고 새로 만든 기사 제목 한 개만 출력하세요.\"},\n",
" {\"role\": \"user\", \"content\": text}\n",
" ]\n",
" inputs = tokenizer.apply_chat_template(\n",
" messages,\n",
" tokenize=True,\n",
" add_generation_prompt=True,\n",
" return_tensors=\"pt\"\n",
" )\n",
" outputs = llm.generate(\n",
" inputs.to(device),\n",
" max_new_tokens=256,\n",
" eos_token_id=tokenizer.eos_token_id,\n",
" do_sample=True,\n",
" temperature=0.9,\n",
" top_p=0.9,\n",
" )\n",
"\n",
" generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
" result = generated_text.split(\"[|assistant|]\")[-1].strip()\n",
"\n",
" return result"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from tqdm.notebook import tqdm \n",
"\n",
"augmented_data = []\n",
"for idx, row in tqdm(df.iterrows(), desc=\"Augmented\", total=len(df)):\n",
" text = row['text']\n",
" print(f\"########################### ORIGINAL TEXT {idx} \\\"{text}\\\"\")\n",
" for i in range(1):\n",
" result = augmentation(text)\n",
" augmented_data.append({\n",
" 'ID': row['ID'],\n",
" 'text': result,\n",
" 'target': row['target']\n",
" })\n",
" print(result)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"augmented_doc = pd.DataFrame(augmented_data).sample(frac=1).reset_index(drop=True)\n",
"augmented_df = pd.concat([df, augmented_doc]).sample(frac=1).reset_index(drop=True)\n",
"augmented_df.to_csv(\"../data/12000cleanlab+nannoise_8564_truc_aug.csv\", index=False, encoding=\"utf-8-sig\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open(\"../data/12000cleanlab+nannoise_8564_truc_aug.csv\", \"r\") as f:\n",
" df2 = pd.read_csv(f)\n",
"\n",
"print(len(df2))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"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.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
234 changes: 234 additions & 0 deletions src/LLM_noise_tasks/LLM_cleaning_noise.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,234 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import json\n",
"import torch\n",
"import pandas as pd\n",
"\n",
"from transformers import AutoTokenizer, AutoModelForCausalLM"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"model_name = \"LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct\" \n",
"\n",
"device = 'cuda' if torch.cuda.is_available() else 'cpu'\n",
"\n",
"llm = AutoModelForCausalLM.from_pretrained(\n",
" model_name,\n",
" torch_dtype=torch.bfloat16,\n",
" device_map=\"auto\",\n",
" trust_remote_code=True \n",
").to(device)\n",
"tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
"llm.eval()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"instruction1 = \"\"\"\n",
"당신은 신문 기자 입니다. 이런 근데 누군가가 신문 제목을 망쳐놨군요. 당신은 신문 기자의 경험을 살려 망가진 제목을 복구해야합니다. 설명을 붙이지 말고 복구한 제목만 출력하세요.\n",
"User Input: {}\n",
"\"\"\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"instruction2 = \"\"\"\n",
"당신은 주어진 컨텍스트를 파악해서 original 컨텍스트가 정말로 noise가 껴있던게 맞는 것인지 파악해야합니다. 왼쪽이 오리지널이고 오른쪽이 복구된 겁니다.\n",
"설명을 붙이지 말고 'noised' 나 노이즈가 아니라면 'nanoise' 중 하나를 출력하세요.\n",
"User Input: {}\n",
"\"\"\"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"with open(\"../data/train.csv\", \"r\") as f:\n",
" df = pd.read_csv(f)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def make_prompt(instruction: str, text: str):\n",
" return instruction.format(text)\n",
"\n",
"def find_pre_noise(text: str):\n",
" messages = [\n",
" {\"role\": \"system\", \n",
" \"content\": \"당신에게 컨텍스트 하나가 주어질 때 노이즈가 낀 상태인지 파악해야합니다. 노이즈의 종류는 특수문자와 영어 철자입니다. 단 '...', '·', '…' 과 한자는 노이즈가 아닙니다. 특히 '만루 안타·45...' 이렇게 끝이 '...' 있는 것은 기사 제목이 너무 길어서 나타나는 자연스러운 현상이므로 노이즈가 아니다. 또한 제목이 자연스럽게 해석이 되면은 노이즈가 아니다. 설명을 붙이지 말고 노이즈가 껴있던 거라면 'noised', 노이즈가 없는거라면 'nanoise'를 출력하세요.\"},\n",
" {\"role\": \"user\", \"content\": text}\n",
" ]\n",
" inputs = tokenizer.apply_chat_template(\n",
" messages,\n",
" tokenize=True,\n",
" add_generation_prompt=True,\n",
" return_tensors=\"pt\"\n",
" )\n",
"\n",
" outputs = llm.generate(\n",
" inputs.to(device),\n",
" max_new_tokens=256,\n",
" eos_token_id=tokenizer.eos_token_id,\n",
" do_sample=True,\n",
" temperature=0.1,\n",
" top_p=0.9,\n",
" )\n",
"\n",
" generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
" result = None\n",
" result = generated_text.split(\"[|assistant|]\")[-1].strip()\n",
" \n",
" return result\n",
"\n",
"def find_post_noise(text1: str, text2: str):\n",
" context = text1 + \" \" + text2\n",
" messages = [\n",
" {\"role\": \"system\", \n",
" \"content\": \"당신에게 컨텍스트 하나가 주어질 때 왼쪽과 오른쪽의 텍스트를 비교해서 오른쪽에 비해서 왼쪽이 노이즈가 많이 낀 상태인지 파악해야합니다. 설명을 붙이지 말고 노이즈가 껴있던 거라면 'noised', 노이즈가 없는거라면 'nanoise'를 출력하세요.\"},\n",
" {\"role\": \"user\", \"content\": context}\n",
" ]\n",
" inputs = tokenizer.apply_chat_template(\n",
" messages,\n",
" tokenize=True,\n",
" add_generation_prompt=True,\n",
" return_tensors=\"pt\"\n",
" )\n",
" outputs = llm.generate(\n",
" inputs.to(device),\n",
" max_new_tokens=256,\n",
" eos_token_id=tokenizer.eos_token_id,\n",
" do_sample=True,\n",
" temperature=0.5,\n",
" top_p=0.9,\n",
" )\n",
"\n",
" generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
" result = None\n",
" result = generated_text.split(\"[|assistant|]\")[-1].strip()\n",
" \n",
" return result"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def cleaning_noise(row: pd.DataFrame) -> list:\n",
" text = row['text']\n",
"\n",
" result = find_pre_noise(text)\n",
" if result != \"noised\": return None\n",
" \n",
" messages = [\n",
" {\"role\": \"system\", \n",
" \"content\": \"당신은 신문 기자 입니다. 이런 근데 누군가가 신문 제목을 망쳐놨군요. 당신은 신문 기자의 경험을 살려 망가진 제목을 말이되게 복구해야합니다. 설명을 붙이지 말고 복구한 제목 하나만 출력하세요.\"},\n",
" {\"role\": \"user\", \"content\": text}\n",
" ]\n",
" inputs = tokenizer.apply_chat_template(\n",
" messages,\n",
" tokenize=True,\n",
" add_generation_prompt=True,\n",
" return_tensors=\"pt\"\n",
" )\n",
" outputs = llm.generate(\n",
" inputs.to(device),\n",
" max_new_tokens=256,\n",
" eos_token_id=tokenizer.eos_token_id,\n",
" do_sample=True,\n",
" temperature=0.1,\n",
" top_p=0.9,\n",
" )\n",
"\n",
" generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
" restored_data = None\n",
" restored_text = generated_text.split(\"[|assistant|]\")[-1].strip()\n",
"\n",
" if result == 'noised':\n",
" restored_data = {\n",
" 'ID': row['ID'],\n",
" 'text': restored_text,\n",
" 'target': row['target']\n",
" }\n",
" \n",
" return restored_data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"from tqdm.notebook import tqdm \n",
"restored_datas = []\n",
"\n",
"for idx, row in tqdm(df.iterrows(), total=len(df), desc=\"Cleaning-noise\"):\n",
" restored_result = cleaning_noise(row)\n",
" if restored_result is None: \n",
" continue\n",
" restored_datas.append(restored_result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"df = pd.DataFrame(restored_datas)\n",
"df.to_csv(\"../data/restored_train_data5.csv\", index=False, encoding=\"utf-8-sig\")\n",
"\n",
"print(len(restored_datas))"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "base",
"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.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Loading