File size: 12,699 Bytes
42ee639
2a943d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42ee639
 
 
 
 
 
 
 
 
2a943d9
 
 
 
 
 
 
42ee639
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aa3ba77
42ee639
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2a943d9
fa0da4d
 
2a943d9
fa0da4d
2a943d9
 
 
 
 
42ee639
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0da4d
2a943d9
 
 
 
 
 
 
42ee639
 
 
 
 
aa3ba77
42ee639
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0da4d
42ee639
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fa0da4d
42ee639
 
 
 
 
 
2a943d9
 
 
 
 
 
 
42ee639
 
 
 
 
 
 
 
 
 
 
 
 
2a943d9
 
 
 
 
 
 
fa0da4d
2a943d9
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "#Quantizing huggingface models to exl2\n",
        "This version of my exl2 quantize colab creates a single quantizaion to upload privatly.\\\n",
        "To calculate an estimate for VRAM size use: [NyxKrage/LLM-Model-VRAM-Calculator](https://huggingface.co/spaces/NyxKrage/LLM-Model-VRAM-Calculator)\\\n",
        "Not all models and architectures are compatible with exl2.\\\n",
        "I've only tested with llama-7b and mistral-7b, not sure if higher size models work with free colab.\\\n",
        "#Outdated\n",
        "More recent stuff in [Anthonyg5005/hf-scripts](https://huggingface.co/Anthonyg5005/hf-scripts)\\\n",
        "If you need to quant a model to exl2 for free, check out the bot from the [Exllama Discord server](https://discord.gg/NSFwVuCjRq)"
      ],
      "metadata": {
        "id": "Ku0ezvyD42ng"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "G7zSk2LWHtPU"
      },
      "outputs": [],
      "source": [
        "#@title Download and install environment\n",
        "!git clone https://github.com/turboderp/exllamav2\n",
        "%cd exllamav2\n",
        "print(\"Installing pip dependencies\")\n",
        "!pip install -q -r requirements.txt\n",
        "!pip install -q huggingface_hub requests tqdm accelerate transformers\n",
        "!pip install . -q\n",
        "#@markdown Uses [download-model.py](https://github.com/oobabooga/text-generation-webui/blob/main/download-model.py) and [convert-to-safetensors.py](https://github.com/oobabooga/text-generation-webui/blob/main/convert-to-safetensors.py) by [oobabooga](https://github.com/oobabooga)\n",
        "!wget https://raw.githubusercontent.com/oobabooga/text-generation-webui/main/download-model.py\n",
        "!wget https://raw.githubusercontent.com/oobabooga/text-generation-webui/main/convert-to-safetensors.py\n",
        "model = \"none\"\n",
        "dsd = 'false'"
      ]
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Login to HF (Required to upload files)\n",
        "#@markdown From my Colab/Kaggle login script on [Anthonyg5005/hf-scripts](https://huggingface.co/Anthonyg5005/hf-scripts/blob/main/HF%20Login%20Snippet%20Kaggle.py)\n",
        "#import required functions\n",
        "import os\n",
        "from huggingface_hub import login, get_token, whoami\n",
        "\n",
        "#get token\n",
        "if os.environ.get('KAGGLE_KERNEL_RUN_TYPE', None) is not None: #check if user in kaggle\n",
        "    from kaggle_secrets import UserSecretsClient\n",
        "    from kaggle_web_client import BackendError\n",
        "    try:\n",
        "        login(UserSecretsClient().get_secret(\"HF_TOKEN\")) #login if token secret found\n",
        "    except BackendError:\n",
        "        print('''\n",
        "            When using Kaggle, make sure to use the secret key HF_TOKEN with a 'WRITE' token.\n",
        "                   This will prevent the need to login every time you run the script.\n",
        "                   Set your secrets with the secrets add-on on the top of the screen.\n",
        "             ''')\n",
        "if get_token() is not None:\n",
        "    #if the token is found then log in:\n",
        "    login(get_token())\n",
        "else:\n",
        "    #if the token is not found then prompt user to provide it:\n",
        "    login(input(\"API token not detected. Enter your HuggingFace (WRITE) token: \"))\n",
        "\n",
        "#if the token is read only then prompt user to provide a write token (Only required if user needs a WRITE token, remove if READ is enough):\n",
        "while True:\n",
        "    if whoami().get('auth', {}).get('accessToken', {}).get('role', None) != 'write':\n",
        "        if os.environ.get('HF_TOKEN', None) is not None: #if environ finds HF_TOKEN as read-only then display following text and exit:\n",
        "            print('''\n",
        "          You have the environment variable HF_TOKEN set.\n",
        "          You cannot log in.\n",
        "          Either set the environment variable to a 'WRITE' token or remove it.\n",
        "                  ''')\n",
        "            input(\"Press enter to continue.\")\n",
        "            exit()\n",
        "        if os.environ.get('COLAB_BACKEND_VERSION', None) is not None:\n",
        "            print('''\n",
        "                              Your Colab secret key is read-only\n",
        "                Please switch your key to 'write' or disable notebook access on the left.\n",
        "                               For now, you are stuck in a loop\n",
        "                  ''')\n",
        "        elif os.environ.get('KAGGLE_KERNEL_RUN_TYPE', None) is not None:\n",
        "            print('''\n",
        "                                      Your Kaggle secret key is read-only\n",
        "                Please switch your key to 'write' or unattach from notebook in add-ons at the top.\n",
        "                          Having a read-only key attched will require login every time.\n",
        "                ''')\n",
        "        print(\"You do not have write access to this repository. Please use a valid token with (WRITE) access.\")\n",
        "        login(input(\"Enter your HuggingFace (WRITE) token: \"))\n",
        "        continue\n",
        "    break"
      ],
      "metadata": {
        "cellView": "form",
        "id": "8Hl3fQmRLybp"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@title ##Choose HF model to download\n",
        "#@markdown ###Repo should be formatted as user/repo\n",
        "#@markdown Weights must be stored in safetensors\n",
        "if model != \"none\":\n",
        "    !rm -r {model}-exl2-{BPW}bpw\n",
        "repo_url = \"mistralai/Mistral-7B-Instruct-v0.2\" # @param {type:\"string\"}\n",
        "model = repo_url.replace(\"/\", \"_\")\n",
        "!python download-model.py {repo_url}\n",
        "print(\"Model downloaded\")\n",
        "#@markdown Convert Pytorch weights to Safetensors\n",
        "convert_safetensors = False # @param {type:\"boolean\"}\n",
        "if convert_safetensors == True:\n",
        "    !python convert-to-safetensors.py models/{model} --output models/{model}-st\n",
        "    !rm -r models/{model}\n",
        "    !mv models/{model}-st models/{model}\n",
        "    print(\"Finished converting\")\n",
        "#@markdown If model files are stored in a pytorch .bin extention then enable convert_safetensors above.\\\n",
        "#@markdown ![Example Image](https://huggingface.co/Anthonyg5005/hf-scripts/resolve/main/ipynb/pytorch-example.jpg \"File extension is .bin\")"
      ],
      "metadata": {
        "id": "NI1LUMD7H-Zx",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Quantize the model\n",
        "#@markdown ###Quantization time will last based on model size\n",
        "#@markdown Target bits per weight:\n",
        "BPW = \"4.125\" # @param {type:\"string\"}\n",
        "!mkdir {model}-exl2-{BPW}bpw-WD\n",
        "!mkdir {model}-exl2-{BPW}bpw\n",
        "!cp models/{model}/config.json {model}-exl2-{BPW}bpw-WD\n",
        "#@markdown Calibrate with dataset, may improve model output (optional):\n",
        "Calibrate = False # @param {type:\"boolean\"}\n",
        "#@markdown Calibration dataset, enable calibrate above (must be filled out if calibrating):\n",
        "if Calibrate == True:\n",
        "    dataset_url = \"https://huggingface.co/datasets/wikitext/resolve/refs%2Fconvert%2Fparquet/wikitext-103-v1/test/0000.parquet?download=true\" # @param {type:\"string\"}\n",
        "    dataset_url = dataset_url.replace(\"?download=true\", \"\")\n",
        "    if dsd == 'false':\n",
        "        !wget {dataset_url}\n",
        "        dsd = 'true'\n",
        "    dataset = dataset_url.split(\"/\")[-1]\n",
        "    dataset_jtp = dataset.split(\".\")[0]\n",
        "#@markdown To use a calibration dataset, enter the huggingface resolve url. Right click the download button and copy the link. Afterwards, paste the link into dataset_url. So far only supports public datasets.\\\n",
        "#@markdown ![Example Image](https://huggingface.co/Anthonyg5005/hf-scripts/resolve/main/ipynb/dataset-example.jpg \"Copy from download button\")\\\n",
        "#@markdown If dataset is jsonl then convert to parquet. (Not always reliable, must be formatted correctly)\n",
        "convert_parquet = False # @param {type:\"boolean\"}\n",
        "if convert_parquet == True:\n",
        "    import pandas as pd #GitHub Copilot generated\n",
        "    import pyarrow as pa #GitHub Copilot generated\n",
        "    import pyarrow.parquet as pq #GitHub Copilot generated\n",
        "    import json #GitHub Copilot generated\n",
        "\n",
        "    def jsonl_to_parquet(jsonl_file, parquet_file): #GitHub Copilot generated\n",
        "        # Read JSONL file line by line with explicit encoding\n",
        "        with open(jsonl_file, 'r', encoding='utf-8') as f: #GitHub Copilot generated\n",
        "            lines = f.readlines() #GitHub Copilot generated\n",
        "\n",
        "        # Parse JSON lines and store as list of dictionaries\n",
        "        data = [json.loads(line.strip()) for line in lines] #GitHub Copilot generated\n",
        "\n",
        "        # Convert to Pandas DataFrame\n",
        "        df = pd.DataFrame(data) #GitHub Copilot generated\n",
        "\n",
        "        # Convert DataFrame to PyArrow Table\n",
        "        table = pa.Table.from_pandas(df) #GitHub Copilot generated\n",
        "\n",
        "        # Write PyArrow Table to Parquet file\n",
        "        pq.write_table(table, parquet_file) #GitHub Copilot generated\n",
        "\n",
        "    jsonl_to_parquet(dataset, f\"{dataset_jtp}.parquet\") #GitHub Copilot generated\n",
        "    dataset = f\"{dataset_jtp}.parquet\"\n",
        "#@markdown Quantizing only allows for parquet datasets to be used. Enable convert_parquet if your dataset ends in a .jsonl extention.\\\n",
        "#@markdown ![Example Image](https://huggingface.co/Anthonyg5005/hf-scripts/resolve/main/ipynb/jsonl-example.jpg \"File extension is .jsonl\")\\\n",
        "#@markdown pippa is used as an example in this image. This dataset contains content that is not suitable for users under 18. This dataset also may or may not be against colab TOS. It won't be allowed under free colab usage although you're able to use it with paid compute units.\n",
        "if Calibrate == True:\n",
        "    quant = f\"convert.py -i models/{model} -o {model}-exl2-{BPW}bpw-WD -cf {model}-exl2-{BPW}bpw -c {dataset} -b {BPW}\"\n",
        "else:\n",
        "    quant = f\"convert.py -i models/{model} -o {model}-exl2-{BPW}bpw-WD -cf {model}-exl2-{BPW}bpw -b {BPW}\"\n",
        "!python {quant}"
      ],
      "metadata": {
        "id": "8anbEbGyNmBI",
        "cellView": "form"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "source": [
        "#@title Upload to huggingface privately\n",
        "#@markdown You may also set it to public but I'd recommend waiting for my next ipynb that will create mutliple quants and place them all into individual branches.\n",
        "!rm -r {model}-exl2-{BPW}bpw-WD\n",
        "!rm -r models/{model}\n",
        "print(\"Uploading to Huggingface. May take a while\")\n",
        "from huggingface_hub import HfApi, whoami, create_repo\n",
        "create_repo(f\"{whoami().get('name', None)}/{model}-exl2-{BPW}bpw\", private=True)\n",
        "HfApi().upload_folder(folder_path=f\"{model}-exl2-{BPW}bpw\", repo_id=f\"{whoami().get('name', None)}/{model}-exl2-{BPW}bpw\", repo_type=\"model\", commit_message=\"Upload from Colab automation\")\n",
        "print(f\"uploaded to https://huggingface.co/{whoami().get('name', None)}/{model}-exl2-{BPW}bpw\")"
      ],
      "metadata": {
        "cellView": "form",
        "id": "XORLS2uPrbma"
      },
      "execution_count": null,
      "outputs": []
    }
  ]
}