{"cells":[{"cell_type":"code","execution_count":1,"metadata":{"executionInfo":{"elapsed":476,"status":"ok","timestamp":1720679526275,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"uWKRSV6eZsCn"},"outputs":[],"source":["%load_ext autoreload\n","%autoreload 2"]},{"cell_type":"code","execution_count":2,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"eb33b19f-1206-41ee-84e2-e6258a12eef7","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":2534,"status":"ok","timestamp":1720679529344,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"xwFh14uiZBrI","outputId":"d767799c-34c2-46a5-f052-378146a55321"},"outputs":[],"source":["from pathlib import Path\n","\n","try:\n"," from google.colab import drive\n","\n"," drive.mount(\"/content/drive\")\n"," workding_dir = \"/content/drive/MyDrive/logical-reasoning/\"\n","except ModuleNotFoundError:\n"," workding_dir = str(Path.cwd().parent)"]},{"cell_type":"code","execution_count":3,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"6d394937-6c99-4a7c-9d32-7600a280032f","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":5,"status":"ok","timestamp":1720679529345,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"G5pNu3zgZBrL","outputId":"160a554f-fb08-4aa0-bc00-0422fb7c1fac"},"outputs":[{"name":"stdout","output_type":"stream","text":["workding dir: /home/inflaton/code/projects/courses/logical-reasoning\n"]}],"source":["import os\n","import sys\n","from pathlib import Path\n","\n","os.chdir(workding_dir)\n","sys.path.append(workding_dir)\n","print(\"workding dir:\", workding_dir)"]},{"cell_type":"code","execution_count":4,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"ac667aba-076e-4de6-9984-8f6a67cb09cd","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":4,"status":"ok","timestamp":1720679529345,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"0dVRAabNZBrL","outputId":"b977e116-df16-47cd-9160-a24f611da687"},"outputs":[{"data":{"text/plain":["False"]},"execution_count":4,"metadata":{},"output_type":"execute_result"}],"source":["need_to_setup_env = False\n","need_to_setup_env"]},{"cell_type":"code","execution_count":5,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"72f9cf79-7b0d-4d9e-90a0-1fa5251b947f","showTitle":false,"title":""},"executionInfo":{"elapsed":4,"status":"ok","timestamp":1720679529345,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"hKUOfP2HZBrL"},"outputs":[],"source":["if need_to_setup_env:\n"," %pip install -r requirements.txt\n"," %cd /content/\n"," %rm -rf LLaMA-Factory\n"," !git clone https://github.com/hiyouga/LLaMA-Factory.git\n"," %cd LLaMA-Factory\n"," %ls\n"," %pip install -e .[torch,bitsandbytes]\n"," \n"," os.chdir(workding_dir)\n"," sys.path.append(workding_dir)\n"," print(\"workding dir:\", workding_dir)"]},{"cell_type":"code","execution_count":6,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"9f67ec60-2f24-411c-84eb-0dd664b44775","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":3,"status":"ok","timestamp":1720679529345,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"hPCC-6m7ZBrM","outputId":"c7aa2c96-5e99-440a-c148-201d79465ff9"},"outputs":[{"name":"stdout","output_type":"stream","text":["loading env vars from: /home/inflaton/code/projects/courses/logical-reasoning/.env\n"]},{"data":{"text/plain":["True"]},"execution_count":6,"metadata":{},"output_type":"execute_result"}],"source":["from dotenv import find_dotenv, load_dotenv\n","\n","found_dotenv = find_dotenv(\".env\")\n","\n","if len(found_dotenv) == 0:\n"," found_dotenv = find_dotenv(\".env.example\")\n","print(f\"loading env vars from: {found_dotenv}\")\n","load_dotenv(found_dotenv, override=True)"]},{"cell_type":"code","execution_count":7,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"f1597656-8042-4878-9d3b-9ebfb8dd86dc","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":3,"status":"ok","timestamp":1720679529345,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"1M3IraVtZBrM","outputId":"29ab35f6-2970-4ade-d85d-3174acf8cda0"},"outputs":[{"name":"stdout","output_type":"stream","text":["internlm/internlm2_5-7b-chat-1m llama-factory/saves/internlm2_5_7b/lora/sft_bf16_p2_full/checkpoint-88 True datasets/mgtv results/mgtv-results_internlm_best.csv\n"]}],"source":["import os\n","\n","model_name = os.getenv(\"MODEL_NAME\")\n","adapter_name_or_path = os.getenv(\"ADAPTER_NAME_OR_PATH\")\n","load_in_4bit = os.getenv(\"LOAD_IN_4BIT\") == \"true\"\n","data_path = os.getenv(\"LOGICAL_REASONING_DATA_PATH\")\n","results_path = os.getenv(\"LOGICAL_REASONING_RESULTS_PATH\")\n","use_english_datasets = os.getenv(\"USE_ENGLISH_DATASETS\") == \"true\"\n","\n","print(model_name, adapter_name_or_path, load_in_4bit, data_path, results_path)"]},{"cell_type":"code","execution_count":8,"metadata":{"application/vnd.databricks.v1+cell":{"cellMetadata":{"byteLimit":2048000,"rowLimit":10000},"inputWidgets":{},"nuid":"b2a43943-9324-4839-9a47-cfa72de2244b","showTitle":false,"title":""},"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":564,"status":"ok","timestamp":1720679529907,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"UgMvt6dIZBrM","outputId":"ce37581c-fd26-46c2-ad87-d933d99f68f7"},"outputs":[{"name":"stdout","output_type":"stream","text":["Python 3.11.9\n","\u001b[33mWARNING: Package(s) not found: flash-attn\u001b[0m\u001b[33m\n","\u001b[0mCPU times: user 239 ms, sys: 103 ms, total: 342 ms\n","Wall time: 4.12 s\n"]}],"source":["%%time\n","!python --version\n","!pip show flash-attn"]},{"cell_type":"code","execution_count":9,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"elapsed":1685,"status":"ok","timestamp":1720679531591,"user":{"displayName":"HUANG DONGHAO _","userId":"00977795705617022768"},"user_tz":-480},"id":"ZuS_FsLyZBrN","outputId":"2cba0105-c505-4395-afbd-2f2fee6581d0"},"outputs":[{"name":"stdout","output_type":"stream","text":["loading /home/inflaton/code/projects/courses/logical-reasoning/llm_toolkit/logical_reasoning_utils.py\n","GPU is available\n"]}],"source":["from llm_toolkit.llm_utils import *\n","from llm_toolkit.logical_reasoning_utils import *\n","\n","device = check_gpu()"]},{"cell_type":"code","execution_count":10,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading model: internlm/internlm2_5-7b-chat-1m with adapter: llama-factory/saves/internlm2_5_7b/lora/sft_bf16_p2_full/checkpoint-88\n"]},{"name":"stderr","output_type":"stream","text":["[INFO|tokenization_utils_base.py:2161] 2024-07-20 13:26:56,525 >> loading file ./tokenizer.model from cache at /home/inflaton/.cache/huggingface/hub/models--internlm--internlm2_5-7b-chat-1m/snapshots/8d1a709a04d71440ef3df6ebbe204672f411c8b6/./tokenizer.model\n","[INFO|tokenization_utils_base.py:2161] 2024-07-20 13:26:56,530 >> loading file added_tokens.json from cache at None\n","[INFO|tokenization_utils_base.py:2161] 2024-07-20 13:26:56,534 >> loading file special_tokens_map.json from cache at /home/inflaton/.cache/huggingface/hub/models--internlm--internlm2_5-7b-chat-1m/snapshots/8d1a709a04d71440ef3df6ebbe204672f411c8b6/special_tokens_map.json\n","[INFO|tokenization_utils_base.py:2161] 2024-07-20 13:26:56,541 >> loading file tokenizer_config.json from cache at /home/inflaton/.cache/huggingface/hub/models--internlm--internlm2_5-7b-chat-1m/snapshots/8d1a709a04d71440ef3df6ebbe204672f411c8b6/tokenizer_config.json\n","[INFO|tokenization_utils_base.py:2161] 2024-07-20 13:26:56,545 >> loading file tokenizer.json from cache at None\n"]},{"name":"stdout","output_type":"stream","text":["07/20/2024 13:27:06 - INFO - llamafactory.data.template - Replace eos token: <|im_end|>\n","07/20/2024 13:27:06 - INFO - llamafactory.data.template - Add <|im_start|> to stop words.\n"]},{"name":"stderr","output_type":"stream","text":["[INFO|configuration_utils.py:733] 2024-07-20 13:27:07,295 >> loading configuration file config.json from cache at /home/inflaton/.cache/huggingface/hub/models--internlm--internlm2_5-7b-chat-1m/snapshots/8d1a709a04d71440ef3df6ebbe204672f411c8b6/config.json\n","[INFO|configuration_utils.py:733] 2024-07-20 13:27:09,367 >> loading configuration file config.json from cache at /home/inflaton/.cache/huggingface/hub/models--internlm--internlm2_5-7b-chat-1m/snapshots/8d1a709a04d71440ef3df6ebbe204672f411c8b6/config.json\n","[INFO|configuration_utils.py:800] 2024-07-20 13:27:09,376 >> Model config InternLM2Config {\n"," \"_name_or_path\": \"internlm/internlm2_5-7b-chat-1m\",\n"," \"architectures\": [\n"," \"InternLM2ForCausalLM\"\n"," ],\n"," \"attn_implementation\": \"eager\",\n"," \"auto_map\": {\n"," \"AutoConfig\": \"internlm/internlm2_5-7b-chat-1m--configuration_internlm2.InternLM2Config\",\n"," \"AutoModel\": \"internlm/internlm2_5-7b-chat-1m--modeling_internlm2.InternLM2ForCausalLM\",\n"," \"AutoModelForCausalLM\": \"internlm/internlm2_5-7b-chat-1m--modeling_internlm2.InternLM2ForCausalLM\"\n"," },\n"," \"bias\": false,\n"," \"bos_token_id\": 1,\n"," \"eos_token_id\": 2,\n"," \"hidden_act\": \"silu\",\n"," \"hidden_size\": 4096,\n"," \"initializer_range\": 0.02,\n"," \"intermediate_size\": 14336,\n"," \"max_position_embeddings\": 262144,\n"," \"model_type\": \"internlm2\",\n"," \"num_attention_heads\": 32,\n"," \"num_hidden_layers\": 32,\n"," \"num_key_value_heads\": 8,\n"," \"pad_token_id\": 2,\n"," \"pretraining_tp\": 1,\n"," \"rms_norm_eps\": 1e-05,\n"," \"rope_scaling\": {\n"," \"factor\": 2.5,\n"," \"type\": \"dynamic\"\n"," },\n"," \"rope_theta\": 50000000,\n"," \"tie_word_embeddings\": false,\n"," \"torch_dtype\": \"bfloat16\",\n"," \"transformers_version\": \"4.43.0.dev0\",\n"," \"use_cache\": true,\n"," \"vocab_size\": 92544\n","}\n","\n"]},{"name":"stdout","output_type":"stream","text":["07/20/2024 13:27:09 - INFO - llamafactory.model.model_utils.quantization - Quantizing model to 4 bit with bitsandbytes.\n","07/20/2024 13:27:09 - INFO - llamafactory.model.patcher - Using KV cache for faster generation.\n"]},{"name":"stderr","output_type":"stream","text":["[INFO|modeling_utils.py:3603] 2024-07-20 13:27:11,102 >> loading weights file model.safetensors from cache at /home/inflaton/.cache/huggingface/hub/models--internlm--internlm2_5-7b-chat-1m/snapshots/8d1a709a04d71440ef3df6ebbe204672f411c8b6/model.safetensors.index.json\n","[INFO|modeling_utils.py:1565] 2024-07-20 13:27:12,118 >> Instantiating InternLM2ForCausalLM model under default dtype torch.bfloat16.\n","[INFO|configuration_utils.py:1038] 2024-07-20 13:27:12,137 >> Generate config GenerationConfig {\n"," \"bos_token_id\": 1,\n"," \"eos_token_id\": 2,\n"," \"pad_token_id\": 2\n","}\n","\n"]},{"data":{"application/vnd.jupyter.widget-view+json":{"model_id":"9a2d94f457d64bdd9158219ca791840c","version_major":2,"version_minor":0},"text/plain":["Loading checkpoint shards: 0%| | 0/8 [00:00> All model checkpoint weights were used when initializing InternLM2ForCausalLM.\n","\n","[INFO|modeling_utils.py:4433] 2024-07-20 14:48:42,929 >> All the weights of InternLM2ForCausalLM were initialized from the model checkpoint at internlm/internlm2_5-7b-chat-1m.\n","If your task is similar to the task the model of the checkpoint was trained on, you can already use InternLM2ForCausalLM for predictions without further training.\n","[INFO|configuration_utils.py:993] 2024-07-20 14:48:43,569 >> loading configuration file generation_config.json from cache at /home/inflaton/.cache/huggingface/hub/models--internlm--internlm2_5-7b-chat-1m/snapshots/8d1a709a04d71440ef3df6ebbe204672f411c8b6/generation_config.json\n","[INFO|configuration_utils.py:1038] 2024-07-20 14:48:43,575 >> Generate config GenerationConfig {\n"," \"bos_token_id\": 1,\n"," \"eos_token_id\": [\n"," 2,\n"," 92542\n"," ],\n"," \"pad_token_id\": 2\n","}\n","\n"]},{"name":"stdout","output_type":"stream","text":["07/20/2024 14:48:45 - INFO - llamafactory.model.model_utils.attention - Using vanilla attention implementation.\n","07/20/2024 14:48:48 - INFO - llamafactory.model.adapter - Loaded adapter(s): llama-factory/saves/internlm2_5_7b/lora/sft_bf16_p2_full/checkpoint-88\n","07/20/2024 14:48:48 - INFO - llamafactory.model.loader - all params: 7,756,582,912\n","CPU times: user 3min 46s, sys: 11min 59s, total: 15min 45s\n","Wall time: 1h 22min 24s\n"]}],"source":["%%time\n","\n","model, tokenizer = load_model(model_name, adapter_name_or_path=adapter_name_or_path, using_llama_factory=True, load_in_4bit=load_in_4bit)"]},{"cell_type":"code","execution_count":11,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["loading train/test data files\n","DatasetDict({\n"," train: Dataset({\n"," features: ['text', 'label', 'answer', 'title', 'puzzle', 'truth', 'train_text', 'prompt'],\n"," num_rows: 25000\n"," })\n"," test: Dataset({\n"," features: ['text', 'label', 'answer', 'title', 'puzzle', 'truth', 'train_text', 'prompt'],\n"," num_rows: 3000\n"," })\n","})\n"]}],"source":["datasets = load_logical_reasoning_dataset(\n"," data_path,\n"," tokenizer=tokenizer,\n"," chinese_prompt=not use_english_datasets,\n"," using_p1=False,\n",")"]},{"cell_type":"code","execution_count":12,"metadata":{},"outputs":[],"source":["def evaluate_model(model, tokenizer, model_name, dataset, batch_size=1):\n"," print(f\"Evaluating model: {model_name} on {device}\")\n"," predictions = eval_model(\n"," model, tokenizer, dataset, device=device, batch_size=batch_size\n"," )\n","\n"," save_results(\n"," model_name,\n"," results_path,\n"," dataset,\n"," predictions,\n"," debug=False,\n"," )\n","\n"," metrics = calc_metrics(dataset[\"label\"], predictions, debug=False)\n"," print(metrics)"]},{"cell_type":"code","execution_count":13,"metadata":{},"outputs":[{"name":"stdout","output_type":"stream","text":["Evaluating model: internlm/internlm2_5-7b-chat-1m_llama-factory/saves/internlm2_5_7b/lora/sft_bf16_p2_full/checkpoint-88_lf_4bit on cuda\n"]},{"name":"stderr","output_type":"stream","text":[" 0%| | 0/375 [00:00