{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:58:21.040680Z",
     "start_time": "2024-05-16T13:58:19.777010Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:46:24.540841Z",
     "iopub.status.busy": "2025-01-03T10:46:24.540695Z",
     "iopub.status.idle": "2025-01-03T10:46:26.296407Z",
     "shell.execute_reply": "2025-01-03T10:46:26.295872Z",
     "shell.execute_reply.started": "2025-01-03T10:46:24.540821Z"
    }
   },
   "outputs": [],
   "source": [
    "import ast\n",
    "import os\n",
    "import shutil\n",
    "import sys\n",
    "from collections import defaultdict\n",
    "\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "from preference_data_preparation_4min_30b_task import *\n",
    "from sklearn.model_selection import train_test_split\n",
    "from suno_utils.utils.s3 import download_s3_files\n",
    "from suno_utils.utils.text import read_json, read_jsonl, write_json, write_jsonl\n",
    "from tqdm import tqdm\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "pd.set_option(\"display.max_rows\", 500)\n",
    "pd.set_option(\"display.max_columns\", 500)\n",
    "pd.set_option(\"display.width\", 1000)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:58:21.082172Z",
     "start_time": "2024-05-16T13:58:21.041926Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:46:26.297164Z",
     "iopub.status.busy": "2025-01-03T10:46:26.296961Z",
     "iopub.status.idle": "2025-01-03T10:46:26.325721Z",
     "shell.execute_reply": "2025-01-03T10:46:26.325257Z",
     "shell.execute_reply.started": "2025-01-03T10:46:26.297149Z"
    }
   },
   "outputs": [],
   "source": [
    "OUT_DATA_DIR = \"/app/suno/data/dpo/13b_s31_v9/\"\n",
    "os.makedirs(OUT_DATA_DIR, exist_ok=True)\n",
    "shutil.copyfile(\n",
    "    \"/app/suno/data/dpo/7v_v20_full/tokenizer_60k.json\",\n",
    "    os.path.join(OUT_DATA_DIR, \"tokenizer_60k.json\"),\n",
    ")\n",
    "NPZ_DIR = \"/app/suno/data/dpo/13b_s31_npz\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:58:53.962528Z",
     "start_time": "2024-05-16T13:58:21.105919Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:46:26.326361Z",
     "iopub.status.busy": "2025-01-03T10:46:26.326224Z",
     "iopub.status.idle": "2025-01-03T10:46:52.608044Z",
     "shell.execute_reply": "2025-01-03T10:46:52.607464Z",
     "shell.execute_reply.started": "2025-01-03T10:46:26.326347Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Preference data shape (872584, 85)\n"
     ]
    }
   ],
   "source": [
    "# df = pd.read_csv(\n",
    "#     \"/home/tony/Data/Preference/13b_v0/interesting_clips_v3p5_s_8_20240813.csv\"\n",
    "# )  # , engine='python')\n",
    "df = pd.read_pickle(\n",
    "    \"/home/tony/Data/Preference/13b_v31/interesting_clips_v4_h_s_31_20241214_full.pkl\"\n",
    ")  # , engine='python')\n",
    "print(\"Preference data shape\", df.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:58:56.199480Z",
     "start_time": "2024-05-16T13:58:53.963687Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:46:52.608761Z",
     "iopub.status.busy": "2025-01-03T10:46:52.608609Z",
     "iopub.status.idle": "2025-01-03T10:47:38.874594Z",
     "shell.execute_reply": "2025-01-03T10:47:38.873849Z",
     "shell.execute_reply.started": "2025-01-03T10:46:52.608746Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "871055\n",
      "871055\n",
      "pre-downloaded df (872584, 85)\n",
      "downloaded df (871055, 85)\n"
     ]
    }
   ],
   "source": [
    "converted_paths = os.listdir(NPZ_DIR)\n",
    "print(len(converted_paths))\n",
    "\n",
    "converted_paths = set([f.replace(\".npz\", \"\") for f in converted_paths])\n",
    "print(len(converted_paths))\n",
    "\n",
    "if \"cycle\" in NPZ_DIR:\n",
    "    # hack in the cycle label\n",
    "    df[\"s3_id\"] += \"_gen_cycle\"\n",
    "\n",
    "print(\"pre-downloaded df\", df.shape)\n",
    "df[df[\"s3_id\"].isin(converted_paths)].shape\n",
    "df = df[df[\"s3_id\"].isin(converted_paths)].copy()\n",
    "print(\"downloaded df\", df.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:58:56.467253Z",
     "start_time": "2024-05-16T13:58:56.207647Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:38.875522Z",
     "iopub.status.busy": "2025-01-03T10:47:38.875350Z",
     "iopub.status.idle": "2025-01-03T10:47:39.022836Z",
     "shell.execute_reply": "2025-01-03T10:47:39.022281Z",
     "shell.execute_reply.started": "2025-01-03T10:47:38.875506Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "is_13b\n",
       "True    871055\n",
       "Name: count, dtype: int64"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df[\"is_13b\"] = df[\"model_name\"].str.contains(\"-s-\")\n",
    "df[\"is_13b\"].value_counts()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# LET's do the data prep"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:58:56.592883Z",
     "start_time": "2024-05-16T13:58:56.470781Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.025001Z",
     "iopub.status.busy": "2025-01-03T10:47:39.024506Z",
     "iopub.status.idle": "2025-01-03T10:47:39.150183Z",
     "shell.execute_reply": "2025-01-03T10:47:39.149521Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.024983Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "preference  model_name     \n",
      "False       chirp-v4-h-s-32    435528\n",
      "True        chirp-v4-h-s-32    435527\n",
      "Name: count, dtype: int64\n",
      "(871055, 86)\n",
      "(0, 86)\n"
     ]
    }
   ],
   "source": [
    "## for 13b this is easy for now\n",
    "print(df.groupby([\"preference\"])[\"model_name\"].value_counts())\n",
    "print(df.shape)\n",
    "df = df[df[\"model_name\"].isin([\"chirp-v4-h-s-31\"])]\n",
    "print(df.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:58:56.909539Z",
     "start_time": "2024-05-16T13:58:56.595736Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.151031Z",
     "iopub.status.busy": "2025-01-03T10:47:39.150866Z",
     "iopub.status.idle": "2025-01-03T10:47:39.157637Z",
     "shell.execute_reply": "2025-01-03T10:47:39.157072Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.151015Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(0, 86)\n",
      "(0, 86)\n",
      "Series([], Name: count, dtype: int64)\n"
     ]
    }
   ],
   "source": [
    "print(df.shape)\n",
    "df = df[\n",
    "    df[\"request_id\"].isin(\n",
    "        df[\"request_id\"].value_counts().index[df[\"request_id\"].value_counts() == 2]\n",
    "    )\n",
    "]\n",
    "print(df.shape)\n",
    "print(df.groupby([\"preference\"])[\"model_name\"].value_counts())\n",
    "assert df.shape[0] == df[\"request_id\"].nunique() * 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.158423Z",
     "iopub.status.busy": "2025-01-03T10:47:39.158266Z",
     "iopub.status.idle": "2025-01-03T10:47:39.200106Z",
     "shell.execute_reply": "2025-01-03T10:47:39.199622Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.158407Z"
    }
   },
   "outputs": [],
   "source": [
    "import json\n",
    "\n",
    "def custom_parse(x):\n",
    "    try:\n",
    "        return json.loads(x)\n",
    "    except:\n",
    "        return {}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:36.043975Z",
     "start_time": "2024-05-16T13:58:56.910958Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.201075Z",
     "iopub.status.busy": "2025-01-03T10:47:39.200657Z",
     "iopub.status.idle": "2025-01-03T10:47:39.238816Z",
     "shell.execute_reply": "2025-01-03T10:47:39.238277Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.201059Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "unique_requests 0\n"
     ]
    }
   ],
   "source": [
    "# Let's use the old selection for now -- for quality assurance\n",
    "# expand the metadata columns -- this takes forever...~ 6 mins\n",
    "# test_slice = df[\"metadata\"].apply(lambda x: ast.literal_eval(str(x)))\n",
    "test_slice = df[\"metadata\"] #.apply(lambda x: custom_parse(x))\n",
    "test_slice_series = test_slice.apply(pd.Series)\n",
    "df = pd.concat([df, test_slice_series], axis=1, join=\"inner\")\n",
    "print(\"unique_requests\", df[\"request_id\"].nunique())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:36.393047Z",
     "start_time": "2024-05-16T13:59:36.048831Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.239521Z",
     "iopub.status.busy": "2025-01-03T10:47:39.239377Z",
     "iopub.status.idle": "2025-01-03T10:47:39.273646Z",
     "shell.execute_reply": "2025-01-03T10:47:39.273130Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.239507Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "unique_requests 0\n"
     ]
    }
   ],
   "source": [
    "# GPT requests are also fine for now\n",
    "print(\"unique_requests\", df[\"request_id\"].nunique())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:40.799375Z",
     "start_time": "2024-05-16T13:59:36.394236Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.274352Z",
     "iopub.status.busy": "2025-01-03T10:47:39.274213Z",
     "iopub.status.idle": "2025-01-03T10:47:39.316681Z",
     "shell.execute_reply": "2025-01-03T10:47:39.316133Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.274339Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0\n",
      "Series([], Name: count, dtype: int64)\n",
      "\n",
      " Check some basics... \n",
      " Series([], Name: count, dtype: int64) Series([], Name: count, dtype: int64) Series([], Name: count, dtype: int64) Series([], Name: count, dtype: int64)\n",
      "Series([], Name: count, dtype: int64)\n"
     ]
    }
   ],
   "source": [
    "df = df.loc[:, ~df.columns.duplicated()].copy()\n",
    "# get the original duration of the clips, if they are concacted\n",
    "df[\"original_duration_s\"] = df[\"total_start_s\"] + df[\"duration\"]\n",
    "# classify the continue at behavoirs by the duration choice\n",
    "audio_prompt_id_to_continue_at = {}\n",
    "for _, row in df[~df[\"continued_parent\"].isna()].iterrows():\n",
    "    audio_prompt_id = row[\"continued_parent\"]\n",
    "    if audio_prompt_id not in audio_prompt_id_to_continue_at:\n",
    "        audio_prompt_id_to_continue_at[audio_prompt_id] = row[\"continue_at\"]\n",
    "    else:\n",
    "        # pick the max\n",
    "        audio_prompt_id = max(\n",
    "            audio_prompt_id_to_continue_at[audio_prompt_id], row[\"continue_at\"]\n",
    "        )\n",
    "print(len(audio_prompt_id_to_continue_at))\n",
    "df[\"has_continue_and_start_continue_at\"] = df[\"s3_id\"].apply(\n",
    "    lambda x: audio_prompt_id_to_continue_at.get(x)\n",
    ")\n",
    "# we want continue at to be at most of the clip...\n",
    "df[\"good_continue_at\"] = (\n",
    "    (df[\"has_continue_and_start_continue_at\"] / df[\"duration\"]) > 0.9\n",
    ") | df[\"has_continue_and_start_continue_at\"].isna()\n",
    "print(df[\"good_continue_at\"].value_counts())\n",
    "\n",
    "\n",
    "print(\n",
    "    \"\\n Check some basics... \\n\",\n",
    "    df[\"preference\"].value_counts(),\n",
    "    df[\"is_13b\"].value_counts(),\n",
    "    df[\"model_name\"].value_counts(),\n",
    "    df.groupby([\"preference\"])[\"model_name\"].value_counts(),\n",
    ")\n",
    "\n",
    "df = df.sort_values(by=[\"request_id\", \"preference\"])\n",
    "df[\"duration_rel_diff\"] = df[\"duration\"].diff()\n",
    "df[\"play_rel_diff\"] = df[\"reaction_play_count\"].diff()\n",
    "print(df[\"task\"].value_counts())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.317355Z",
     "iopub.status.busy": "2025-01-03T10:47:39.317213Z",
     "iopub.status.idle": "2025-01-03T10:47:39.355674Z",
     "shell.execute_reply": "2025-01-03T10:47:39.355184Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.317342Z"
    }
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "Series([], Name: count, dtype: int64)"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "df = df.sort_values(by=[\"request_id\", \"preference\", \"diff_preference\"])\n",
    "df[\"pos_diff_preference\"] = df[\"diff_preference\"].diff()\n",
    "# df[\"cer_diff_preference\"] = df[\"cer\"].diff()\n",
    "df[df[\"preference\"]][\"pos_diff_preference\"].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.356486Z",
     "iopub.status.busy": "2025-01-03T10:47:39.356342Z",
     "iopub.status.idle": "2025-01-03T10:47:39.391064Z",
     "shell.execute_reply": "2025-01-03T10:47:39.390589Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.356472Z"
    }
   },
   "outputs": [],
   "source": [
    "# df[df[\"preference\"]][\"cer_diff_preference\"].hist(bins=50)\n",
    "# print(df[df[\"preference\"]][\"cer_diff_preference\"].quantile(0.95))\n",
    "# plt.show()\n",
    "# print(df[df[\"preference\"]][\"cer\"].hist(bins=50))\n",
    "# plt.show()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.035167Z",
     "start_time": "2024-05-16T13:59:40.801098Z"
    },
    "execution": {
     "iopub.execute_input": "2025-01-03T10:47:39.392005Z",
     "iopub.status.busy": "2025-01-03T10:47:39.391656Z",
     "iopub.status.idle": "2025-01-03T10:47:41.167340Z",
     "shell.execute_reply": "2025-01-03T10:47:41.165709Z",
     "shell.execute_reply.started": "2025-01-03T10:47:39.391990Z"
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "negative 0 positive 0\n"
     ]
    },
    {
     "ename": "ZeroDivisionError",
     "evalue": "division by zero",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mZeroDivisionError\u001b[0m                         Traceback (most recent call last)",
      "Cell \u001b[0;32mIn[14], line 71\u001b[0m\n\u001b[1;32m     62\u001b[0m \u001b[38;5;66;03m# looking for very strong signal here:\u001b[39;00m\n\u001b[1;32m     63\u001b[0m \u001b[38;5;66;03m# listen to the positive/negative more than once\u001b[39;00m\n\u001b[1;32m     64\u001b[0m \u001b[38;5;66;03m# disliked one of the clips\u001b[39;00m\n\u001b[1;32m     65\u001b[0m unique_requests \u001b[38;5;241m=\u001b[39m \u001b[38;5;28mset\u001b[39m(pos_filter_requests)\u001b[38;5;241m.\u001b[39mintersection(neg_filter_requests)\n\u001b[1;32m     66\u001b[0m \u001b[38;5;28mprint\u001b[39m(\n\u001b[1;32m     67\u001b[0m     \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mtotal pair requests\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m     68\u001b[0m     df[\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mrequest_id\u001b[39m\u001b[38;5;124m\"\u001b[39m]\u001b[38;5;241m.\u001b[39mnunique(),\n\u001b[1;32m     69\u001b[0m     \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mselected pair requests\u001b[39m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m     70\u001b[0m     \u001b[38;5;28mlen\u001b[39m(unique_requests),\n\u001b[0;32m---> 71\u001b[0m     \u001b[38;5;124mf\u001b[39m\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mfrac \u001b[39m\u001b[38;5;132;01m{\u001b[39;00m\u001b[38;5;28;43mlen\u001b[39;49m\u001b[43m(\u001b[49m\u001b[43munique_requests\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;250;43m \u001b[39;49m\u001b[38;5;241;43m/\u001b[39;49m\u001b[38;5;250;43m \u001b[39;49m\u001b[43mdf\u001b[49m\u001b[43m[\u001b[49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[38;5;124;43mrequest_id\u001b[39;49m\u001b[38;5;124;43m'\u001b[39;49m\u001b[43m]\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mnunique\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;132;01m:\u001b[39;00m\u001b[38;5;124m.3f\u001b[39m\u001b[38;5;132;01m}\u001b[39;00m\u001b[38;5;124m\"\u001b[39m,\n\u001b[1;32m     72\u001b[0m )\n",
      "\u001b[0;31mZeroDivisionError\u001b[0m: division by zero"
     ]
    }
   ],
   "source": [
    "normal_pos_play_count = 10\n",
    "# this is lower, cause a concat is probably already ensuring that it is good\n",
    "concat_pos_play_count = 2\n",
    "# this is a filter on the concated clip\n",
    "concat_total_play_count = 10\n",
    "\n",
    "neg_filter_selection_mask = (\n",
    "    (df[\"preference\"] == False)  # get basics aligned\n",
    "    & (df[\"reaction_play_count\"] >= 1)  # has to be played once\n",
    "    # & (df[\"play_count\"] <= 3)  # if it is actually bad, shouldn't be listened often\n",
    "    & (df[\"duration\"] >= 10)  # can't be too short, otherwise it is obvious\n",
    "    # & (df[\"duration\"] <= 60)  # can't be badly long\n",
    "    & (df[\"has_continue_and_start_continue_at\"].isna())  # won't have any continues\n",
    "    & ((df[\"norm_play_frac\"] <= 2.1))\n",
    "    # & (df[\"dislike_count\"] >= 1) # this is kinda strict\n",
    "    #     & (\n",
    "    #         (df_slice[\"is_in_playlist\"] == False)\n",
    "    #         & (df_slice[\"concat_in_playlist\"] == False)\n",
    "    #     )  # can't be part of a playlist -- otherwise there are some like signal in it?\n",
    ")\n",
    "pos_filter_selectin_mask = (\n",
    "    (df[\"preference\"] == True)  # get basics aligned\n",
    "    & (\n",
    "        df[\"good_continue_at\"] == True\n",
    "    )  # if continue, needs to continue off a certain percentage\n",
    "    & (df[\"reaction_play_count\"] >= 1)\n",
    "    & (df[\"play_rel_diff\"] >= 0)  # this is more like quality assurance\n",
    "    & (df[\"duration\"] >= 10)  # can't be too short, otherwise it is obvious\n",
    "    # & (df[\"duration\"] <= 60)  # can't be badly long\n",
    "    & (df[\"dislike_count\"] == 0)  # can't have dislikes\n",
    "    & (df[\"flag_count\"] == 0)  # can't have issues\n",
    "    & (\n",
    "        (\n",
    "            (df[\"part_of_concat\"])\n",
    "            & (df[\"reaction_play_count\"] >= concat_pos_play_count)\n",
    "            & (df[\"concat_play_counts\"] >= concat_total_play_count)\n",
    "        )\n",
    "        | (\n",
    "            (~df[\"part_of_concat\"])\n",
    "            & (df[\"reaction_play_count\"] >= normal_pos_play_count)\n",
    "            & (df[\"norm_play_frac\"] >= 5.1)  # this is a bit of a luxury cut...\n",
    "        )\n",
    "    )\n",
    "    # & (df[\"norm_play_frac\"] >= 1.9)\n",
    "    # & (df[\"user_n_clips\"] >= 40)  # user needs to have genereated at least 20\n",
    "    # & (df[\"duration_rel_diff\"] < 10) # positive isn't just longer\n",
    "    & ((df[\"task\"] == \"\")|(df[\"task\"] == \"extend\"))\n",
    "    & ((df[\"upvote_count\"] >= 1) | (df[\"reaction_play_count\"] >= 5)| (df[\"concat_play_counts\"] >= 5))\n",
    "    # & (df[\"pos_diff_preference\"] == 2)\n",
    "    # & ((0 < df[\"similarity\"]) &  (df[\"similarity\"] <= 0.99))\n",
    "    # & ((df[\"cer_diff_preference\"] < 0.25) & (df[\"cer\"] < 0.8)) # cut on hoot cer difference and abs cer\n",
    ")\n",
    "print(\n",
    "    \"negative\",\n",
    "    sum(neg_filter_selection_mask),\n",
    "    \"positive\",\n",
    "    sum(pos_filter_selectin_mask),\n",
    ")\n",
    "\n",
    "neg_filter_requests = df[neg_filter_selection_mask][\"request_id\"].unique()\n",
    "pos_filter_requests = df[pos_filter_selectin_mask][\"request_id\"].unique()\n",
    "# looking for very strong signal here:\n",
    "# listen to the positive/negative more than once\n",
    "# disliked one of the clips\n",
    "unique_requests = set(pos_filter_requests).intersection(neg_filter_requests)\n",
    "print(\n",
    "    \"total pair requests\",\n",
    "    df[\"request_id\"].nunique(),\n",
    "    \"selected pair requests\",\n",
    "    len(unique_requests),\n",
    "    f\"frac {len(unique_requests) / df['request_id'].nunique():.3f}\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.250737Z",
     "start_time": "2024-05-16T13:59:41.036434Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.167985Z",
     "iopub.status.idle": "2025-01-03T10:47:41.168190Z",
     "shell.execute_reply": "2025-01-03T10:47:41.168094Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.168084Z"
    }
   },
   "outputs": [],
   "source": [
    "df_slice = df[df[\"request_id\"].isin(set(unique_requests))].copy()\n",
    "print(\n",
    "    f\"{os.path.basename(OUT_DATA_DIR)} requests\",\n",
    "    df_slice[\"request_id\"].nunique(),\n",
    "    \"clips\",\n",
    "    df_slice.shape[0],\n",
    "    f\"total khrs {sum(df_slice['duration'] / 3600 / 1000):.3f};\",\n",
    "    f\"N gpus for 1000 iters {df_slice.shape[0] / 8 / 2 / 1000:.3f};\",\n",
    "    f\"4 gpus for x iters {df_slice.shape[0] / 8 / 2 / 4:.3f};\",\n",
    "    f\"n unique users {df_slice['user_id'].nunique()}\",\n",
    "    f\"n pro users {df_slice[df_slice['is_pro_user']]['user_id'].nunique()}\",\n",
    ")\n",
    "# 76171 152342 total khrs 2.880 n gpus for 1250 iters 3.809\n",
    "# 29 v2 requests 22572 clips 45144 total khrs 2.252; N gpus for 1000 iters 2.821; 4 gpus for x iters 705.375; n unique users 18149 n pro users 10155\n",
    "# 29 v4 requests 32479 clips 64958 total khrs 3.248; N gpus for 1000 iters 4.060; 4 gpus for x iters 1014.969; n unique users 25192 n pro users 13547\n",
    "# samve for v5\n",
    "# 31 v1  requests 16489 clips 32978 total khrs 1.781; N gpus for 1000 iters 2.061; 4 gpus for x iters 515.281; n unique users 14216 n pro users 6664\n",
    "# 31 v2  requests 17239 clips 34478 total khrs 1.861; N gpus for 1000 iters 2.155; 4 gpus for x iters 538.719; n unique users 14807 n pro users 6927\n",
    "# 31 v3  requests 36228 clips 72456 total khrs 3.722; N gpus for 1000 iters 4.529; 4 gpus for x iters 1132.125; n unique users 17731 n pro users 17612\n",
    "# 31 v4  requests 68509 clips 137018 total khrs 7.053; N gpus for 1000 iters 8.564; 4 gpus for x iters 2140.906; n unique users 28351 n pro users 28064\n",
    "# 31 v6  requests 37003 clips 74006 total khrs 3.821; N gpus for 1000 iters 4.625; 4 gpus for x iters 1156.344; n unique users 16562 n pro users 16300\n",
    "# 31 v7  requests 41409 clips 82818 total khrs 4.279; N gpus for 1000 iters 5.176; 4 gpus for x iters 1294.031; n unique users 18062 n pro users 17751\n",
    "# 31 v8  requests 49108 clips 98216 total khrs 5.072; N gpus for 1000 iters 6.138; 4 gpus for x iters 1534.625; n unique users 20680 n pro users 20161\n",
    "# 31 v9  requests 63922 clips 127844 total khrs 6.631; N gpus for 1000 iters 7.990; 4 gpus for x iters 1997.562; n unique users 25461 n pro users 24396"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.277006Z",
     "start_time": "2024-05-16T13:59:41.252105Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.168903Z",
     "iopub.status.idle": "2025-01-03T10:47:41.169064Z",
     "shell.execute_reply": "2025-01-03T10:47:41.168991Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.168983Z"
    }
   },
   "outputs": [],
   "source": [
    "test_mask = (df_slice[\"preference\"] == True) & (\n",
    "    (df_slice[\"is_in_playlist\"] == True) | (df_slice[\"concat_in_playlist\"] == True)\n",
    ")\n",
    "print(\"positive in playlist\", df_slice[test_mask].shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.169776Z",
     "iopub.status.idle": "2025-01-03T10:47:41.169942Z",
     "shell.execute_reply": "2025-01-03T10:47:41.169865Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.169857Z"
    }
   },
   "outputs": [],
   "source": [
    "# BREAK"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.323409Z",
     "start_time": "2024-05-16T13:59:41.278278Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.170304Z",
     "iopub.status.idle": "2025-01-03T10:47:41.170455Z",
     "shell.execute_reply": "2025-01-03T10:47:41.170386Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.170379Z"
    }
   },
   "outputs": [],
   "source": [
    "# interesting_clips_must_be_positive_mask = (\n",
    "#     (df_slice[\"upvoted\"] == True)\n",
    "#     | (df_slice[\"has_action\"] == True)\n",
    "#     | (df_slice[\"part_of_concat\"] == True)\n",
    "# )\n",
    "# interesting_clips_must_be_not_negative_mask = (df_slice[\"downvoted\"] == False) # & (df_slice[\"dislike_count\"] < 1)\n",
    "# interesting_clips_mask = interesting_clips_must_be_positive_mask & interesting_clips_must_be_not_negative_mask\n",
    "# assert interesting_clips_mask.eq(df_slice[\"preference\"]).all()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.392244Z",
     "start_time": "2024-05-16T13:59:41.324472Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.170940Z",
     "iopub.status.idle": "2025-01-03T10:47:41.171091Z",
     "shell.execute_reply": "2025-01-03T10:47:41.171022Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.171014Z"
    }
   },
   "outputs": [],
   "source": [
    "# save positive ids\n",
    "# positive_preference_ids = df_slice[df_slice[\"preference\"] == False][\"s3_id\"].to_json(orient='values')\n",
    "# with open('/home/tony/Data/Preference/7b_v2/7v_v20_full_recut_id_negative.json', 'w') as file:\n",
    "#     file.write(positive_preference_ids)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T14:00:20.866354Z",
     "start_time": "2024-05-16T14:00:12.443344Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.171962Z",
     "iopub.status.idle": "2025-01-03T10:47:41.172141Z",
     "shell.execute_reply": "2025-01-03T10:47:41.172051Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.172044Z"
    }
   },
   "outputs": [],
   "source": [
    "# df_slice.to_csv(\"/home/tony/Data/Preference/13b_v0/interesting_clips_v3p5_s_8_20240828_slice.csv\")\n",
    "BREAK"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Need to kick out the ones has gpt prompt -- these are pairs with different text inputs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.932296Z",
     "start_time": "2024-05-16T13:59:41.932287Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.172599Z",
     "iopub.status.idle": "2025-01-03T10:47:41.172752Z",
     "shell.execute_reply": "2025-01-03T10:47:41.172682Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.172675Z"
    }
   },
   "outputs": [],
   "source": [
    "# don't have continue at\n",
    "# df_slice[df_slice[\"continue_at\"].isna()][\"request_id\"].nunique()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.932966Z",
     "start_time": "2024-05-16T13:59:41.932957Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.173309Z",
     "iopub.status.idle": "2025-01-03T10:47:41.173468Z",
     "shell.execute_reply": "2025-01-03T10:47:41.173393Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.173386Z"
    }
   },
   "outputs": [],
   "source": [
    "final_filtered_requests = df_slice[\"request_id\"].unique()\n",
    "print(len(final_filtered_requests))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.933558Z",
     "start_time": "2024-05-16T13:59:41.933550Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.173911Z",
     "iopub.status.idle": "2025-01-03T10:47:41.174067Z",
     "shell.execute_reply": "2025-01-03T10:47:41.173992Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.173985Z"
    }
   },
   "outputs": [],
   "source": [
    "# df_slice.to_csv(\"/home/tony/Data/Preference/7b_v2/7b_before_recode_20240412\", index=False)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.934277Z",
     "start_time": "2024-05-16T13:59:41.934268Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.174691Z",
     "iopub.status.idle": "2025-01-03T10:47:41.174850Z",
     "shell.execute_reply": "2025-01-03T10:47:41.174775Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.174767Z"
    }
   },
   "outputs": [],
   "source": [
    "train_requests, val_requests = train_test_split(\n",
    "    sorted(list(final_filtered_requests)), test_size=0.01, random_state=42\n",
    ")\n",
    "print(len(train_requests), len(val_requests))\n",
    "\n",
    "train_df = df_slice[df_slice[\"request_id\"].isin(set(train_requests))].copy()\n",
    "val_df = df_slice[df_slice[\"request_id\"].isin(set(val_requests))].copy()\n",
    "train_df = train_df.sort_values(by=[\"request_id\", \"preference\"])\n",
    "train_df = train_df# .reset_index()\n",
    "val_df = val_df.sort_values(by=[\"request_id\", \"preference\"])\n",
    "val_df = val_df#.reset_index()\n",
    "\n",
    "print(train_df.shape, val_df.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.175343Z",
     "iopub.status.idle": "2025-01-03T10:47:41.175502Z",
     "shell.execute_reply": "2025-01-03T10:47:41.175427Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.175420Z"
    }
   },
   "outputs": [],
   "source": [
    "# BREAK"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Actually make"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.934954Z",
     "start_time": "2024-05-16T13:59:41.934946Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.175990Z",
     "iopub.status.idle": "2025-01-03T10:47:41.176140Z",
     "shell.execute_reply": "2025-01-03T10:47:41.176069Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.176062Z"
    }
   },
   "outputs": [],
   "source": [
    "# val_df[[\"request_id\", \"metadata\", \"updated_at\", \"user_id\", \"preference\"]].head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.935620Z",
     "start_time": "2024-05-16T13:59:41.935613Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.176454Z",
     "iopub.status.idle": "2025-01-03T10:47:41.176738Z",
     "shell.execute_reply": "2025-01-03T10:47:41.176530Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.176523Z"
    }
   },
   "outputs": [],
   "source": [
    "total_duration = 0\n",
    "for i, row in tqdm(train_df.iterrows(), total=len(train_df)):\n",
    "    # we need to alternate between preference: neg, pos\n",
    "    # print(i, row)\n",
    "    try:\n",
    "        assert row[\"preference\"] == (i % 2 == 1)\n",
    "    except:\n",
    "        print(i, row)\n",
    "    total_duration += row[\"duration\"]\n",
    "print(\n",
    "    f\"{round(total_duration / 60 / 60):,} hours of {train_df.shape[0]} clips, {train_df.shape[0] / 8 / 2 / 1000} nodes, {train_df.shape[0] / 8 / 4 / 4} steps\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.936268Z",
     "start_time": "2024-05-16T13:59:41.936260Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.177399Z",
     "iopub.status.idle": "2025-01-03T10:47:41.177570Z",
     "shell.execute_reply": "2025-01-03T10:47:41.177491Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.177483Z"
    }
   },
   "outputs": [],
   "source": [
    "make_dataset(val_df, OUT_DATA_DIR, is_val=True, npz_dir=NPZ_DIR)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.936964Z",
     "start_time": "2024-05-16T13:59:41.936957Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.178110Z",
     "iopub.status.idle": "2025-01-03T10:47:41.178270Z",
     "shell.execute_reply": "2025-01-03T10:47:41.178197Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.178189Z"
    }
   },
   "outputs": [],
   "source": [
    "make_dataset(train_df, OUT_DATA_DIR, is_val=False, npz_dir=NPZ_DIR)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-01-29T19:46:47.549860Z",
     "start_time": "2024-01-29T19:46:47.548015Z"
    }
   },
   "source": [
    "# Validation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.937879Z",
     "start_time": "2024-05-16T13:59:41.937870Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.178829Z",
     "iopub.status.idle": "2025-01-03T10:47:41.178987Z",
     "shell.execute_reply": "2025-01-03T10:47:41.178914Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.178907Z"
    }
   },
   "outputs": [],
   "source": [
    "# verify\n",
    "mm = np.memmap(os.path.join(OUT_DATA_DIR, f\"data_val.bin\"), dtype=np.uint16, mode=\"r\")\n",
    "test_metas = read_jsonl(os.path.join(OUT_DATA_DIR, f\"meta_val.jsonl\"))\n",
    "test_info = read_json(os.path.join(OUT_DATA_DIR, f\"info_val.json\"))\n",
    "mm = mm.reshape(-1, 6016, 13)\n",
    "assert len(mm) == len(test_metas)\n",
    "assert mm[:100, :, 0].min() >= 0\n",
    "assert mm[:100, :, 0].max() <= 4000\n",
    "assert mm[:100, :, 1:].min() >= 0\n",
    "assert mm[:100, :, 1:].max() <= 2048"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.938629Z",
     "start_time": "2024-05-16T13:59:41.938621Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.179713Z",
     "iopub.status.idle": "2025-01-03T10:47:41.179870Z",
     "shell.execute_reply": "2025-01-03T10:47:41.179797Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.179790Z"
    }
   },
   "outputs": [],
   "source": [
    "# # randomly listen to some stuff\n",
    "# from suno_utils.tasks.dac_2c_12cb import preload_models as preload_codec_models\n",
    "# from suno_utils.tasks.dac_2c_12cb import (\n",
    "#     encode as codec_encode,\n",
    "#     decode_stream_to_full_audio as codec_decode,\n",
    "#     EMBEDDING_RATE as CODEC_EMBEDDING_RATE,\n",
    "#     decode as decode\n",
    "# )\n",
    "# os.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n",
    "# _ = preload_codec_models(\"/app/suno/data/dpo/models/dac_2c_25x12.pt\", device=\"cuda\")\n",
    "# assert len(test_metas) == len(mm)\n",
    "# idx_list = list(range(len(test_metas)))\n",
    "# # random.shuffle(idx_list)\n",
    "# # idx_list = [idx for idx in idx_list if \"text\" in test_metas[idx]]\n",
    "# print(len(mm))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.939205Z",
     "start_time": "2024-05-16T13:59:41.939198Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.180152Z",
     "iopub.status.idle": "2025-01-03T10:47:41.180309Z",
     "shell.execute_reply": "2025-01-03T10:47:41.180238Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.180230Z"
    }
   },
   "outputs": [],
   "source": [
    "# import random\n",
    "# idx = random.choice(test_info[\"perference_0\"][\"idx_list\"])\n",
    "# assert \"original_duration_s\" in test_metas[idx]\n",
    "# # positive index should be shifted by 1\n",
    "# pos_idx = idx + 1\n",
    "# print(\n",
    "#     \"tags:\",\n",
    "#     test_metas[idx].get(\"tags\") == test_metas[pos_idx].get(\"tags\"),\n",
    "#     test_metas[idx].get(\"tags\"),\n",
    "# )\n",
    "# arr = mm[idx, 1:].copy().astype(np.int16)[:, 1:]\n",
    "# pos_arr = mm[pos_idx, 1:].copy().astype(np.int16)[:, 1:]\n",
    "# pad_idx_arr = np.where(arr == COARSE_PAD_TOKEN)[0]\n",
    "# if len(pad_idx_arr) > 0:\n",
    "#     arr = arr[: pad_idx_arr[0], :]\n",
    "# pos_pad_idx_arr = np.where(pos_arr == COARSE_PAD_TOKEN)[0]\n",
    "# if len(pos_pad_idx_arr) > 0:\n",
    "#     pos_arr = pos_arr[: pos_pad_idx_arr[0], :]\n",
    "# a = decode(arr)\n",
    "# print(\"\\n negative example \\n\", test_metas[idx])\n",
    "# a.play(compress=False)\n",
    "# pos_a = decode(pos_arr)\n",
    "# print(\"\\n positive example \\n\", test_metas[pos_idx])\n",
    "# pos_a.play(compress=False)\n",
    "# print(\n",
    "#     \"text:\",\n",
    "#     test_metas[idx].get(\"text\") == test_metas[pos_idx].get(\"text\"),\n",
    "#     test_metas[idx].get(\"text\"),\n",
    "# )"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.939977Z",
     "start_time": "2024-05-16T13:59:41.939969Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.180856Z",
     "iopub.status.idle": "2025-01-03T10:47:41.181014Z",
     "shell.execute_reply": "2025-01-03T10:47:41.180941Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.180934Z"
    }
   },
   "outputs": [],
   "source": [
    "# val_df[val_df[\"tags\"] == 'a vibrant blend of experimental jazz fusion, drum-and-bass and swagger fuzzed-out guitars']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.940610Z",
     "start_time": "2024-05-16T13:59:41.940603Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.181541Z",
     "iopub.status.idle": "2025-01-03T10:47:41.181694Z",
     "shell.execute_reply": "2025-01-03T10:47:41.181623Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.181616Z"
    }
   },
   "outputs": [],
   "source": [
    "# from collections import Counter\n",
    "# c = Counter()\n",
    "# for _, row in df_slice.iterrows():\n",
    "#     # print(row[\"metadata\"])\n",
    "#     for k in ast.literal_eval(row[\"metadata\"]).keys():\n",
    "#         c[k] += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.941167Z",
     "start_time": "2024-05-16T13:59:41.941159Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.182311Z",
     "iopub.status.idle": "2025-01-03T10:47:41.182479Z",
     "shell.execute_reply": "2025-01-03T10:47:41.182393Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.182386Z"
    }
   },
   "outputs": [],
   "source": [
    "# original_npz_path = f\"/app/suno/data/dpo/7b_npz/{test_metas[idx]['id']}.npz\"\n",
    "# original_npz_path = \"/app/suno/data/dpo/7b_npz/729c3011-f672-4ccd-8d82-1cbf2b52ff69.npz\"\n",
    "# original_arr = np.load(original_npz_path)[\"v2_raw\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.941801Z",
     "start_time": "2024-05-16T13:59:41.941793Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.182783Z",
     "iopub.status.idle": "2025-01-03T10:47:41.182924Z",
     "shell.execute_reply": "2025-01-03T10:47:41.182859Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.182853Z"
    }
   },
   "outputs": [],
   "source": [
    "def validation_on_metas(input_metas):\n",
    "\n",
    "    total_bad = 0\n",
    "    total_good = 0\n",
    "    for idx in range(len(input_metas)):\n",
    "        if idx % 2 == 0:\n",
    "            pos_idx = idx + 1\n",
    "            if input_metas[idx].get(\"tags\") != input_metas[pos_idx].get(\"tags\"):\n",
    "                # print(test_metas[idx].get(\"text\") == test_metas[pos_idx].get(\"text\"), test_metas[idx].get(\"tags\"), test_metas[pos_idx].get(\"tags\"))\n",
    "                total_bad += 1\n",
    "            else:\n",
    "                total_good += 1\n",
    "    print(total_good, total_bad)\n",
    "    return\n",
    "\n",
    "\n",
    "validation_on_metas(test_metas)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.942520Z",
     "start_time": "2024-05-16T13:59:41.942511Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.183201Z",
     "iopub.status.idle": "2025-01-03T10:47:41.183342Z",
     "shell.execute_reply": "2025-01-03T10:47:41.183274Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.183267Z"
    }
   },
   "outputs": [],
   "source": [
    "train_info = read_json(os.path.join(OUT_DATA_DIR, f\"info_tr.json\"))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.943072Z",
     "start_time": "2024-05-16T13:59:41.943065Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.183845Z",
     "iopub.status.idle": "2025-01-03T10:47:41.183995Z",
     "shell.execute_reply": "2025-01-03T10:47:41.183924Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.183917Z"
    }
   },
   "outputs": [],
   "source": [
    "n_neg_tr = train_info[\"perference_0\"][\"idx_list\"]\n",
    "n_pos_tr = train_info[\"perference_1\"][\"idx_list\"]\n",
    "assert len(n_pos_tr) == len(n_neg_tr)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.944246Z",
     "start_time": "2024-05-16T13:59:41.944237Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.184553Z",
     "iopub.status.idle": "2025-01-03T10:47:41.184705Z",
     "shell.execute_reply": "2025-01-03T10:47:41.184633Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.184626Z"
    }
   },
   "outputs": [],
   "source": [
    "total_iters = len(n_neg_tr) + len(n_pos_tr)\n",
    "print(\"total samples\", total_iters, train_df.shape)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.945249Z",
     "start_time": "2024-05-16T13:59:41.945241Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.185273Z",
     "iopub.status.idle": "2025-01-03T10:47:41.185424Z",
     "shell.execute_reply": "2025-01-03T10:47:41.185353Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.185346Z"
    }
   },
   "outputs": [],
   "source": [
    "print(\"1 epoch per batch 4, total\", total_iters / 8 / 4 / 2)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.945972Z",
     "start_time": "2024-05-16T13:59:41.945964Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.185992Z",
     "iopub.status.idle": "2025-01-03T10:47:41.186142Z",
     "shell.execute_reply": "2025-01-03T10:47:41.186073Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.186065Z"
    }
   },
   "outputs": [],
   "source": [
    "!cd /home/tony/Work/tony/slurm/13b_dpo && sbatch sbatch_ipo_13b_s31"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.186673Z",
     "iopub.status.idle": "2025-01-03T10:47:41.186833Z",
     "shell.execute_reply": "2025-01-03T10:47:41.186758Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.186751Z"
    }
   },
   "outputs": [],
   "source": [
    "import shutil\n",
    "\n",
    "# Basic file copy\n",
    "shutil.copy('/home/tony/Work/tony/Preference/make_dataset_13b_v3p5data_s31.ipynb', os.path.join(OUT_DATA_DIR, \"make_dataset.ipynb\"))\n",
    "print(\"Cache kept!\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# some gymathtics loading prev data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2024-05-16T13:59:41.946562Z",
     "start_time": "2024-05-16T13:59:41.946555Z"
    },
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.187345Z",
     "iopub.status.idle": "2025-01-03T10:47:41.187496Z",
     "shell.execute_reply": "2025-01-03T10:47:41.187426Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.187419Z"
    }
   },
   "outputs": [],
   "source": [
    "# prev_v3_data = \"/app/suno/data/dpo/7v_v20_full/\"\n",
    "\n",
    "# test_val_metas = read_jsonl(os.path.join(prev_v3_data, f\"meta_val.jsonl\"))\n",
    "# test_tr_metas = read_jsonl(os.path.join(prev_v3_data, f\"meta_tr.jsonl\"))\n",
    "\n",
    "# all_ids = set()\n",
    "# for meta in test_val_metas:\n",
    "#     all_ids.add(meta[\"id\"])\n",
    "# for meta in test_tr_metas:\n",
    "#     all_ids.add(meta[\"id\"])\n",
    "# print(len(all_ids), len(test_val_metas) + len(test_tr_metas))\n",
    "\n",
    "# all_ids = list(all_ids)\n",
    "# with open(\"/home/tony/Data/Preference/7b_v2/7v_v20_full_recut_id.json\", \"w\") as fp:\n",
    "#     json.dump(all_ids, fp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "execution": {
     "iopub.status.busy": "2025-01-03T10:47:41.187825Z",
     "iopub.status.idle": "2025-01-03T10:47:41.187967Z",
     "shell.execute_reply": "2025-01-03T10:47:41.187901Z",
     "shell.execute_reply.started": "2025-01-03T10:47:41.187894Z"
    }
   },
   "outputs": [],
   "source": [
    "# train_df[\"lang\"].value_counts()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.15"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
