local_inference/4bit_bnb.ipynb (125 lines of code) (raw):

{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Llama-3.1-8B-Instruct in 4-bit bitsandbytes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's first install the required libraries:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "! pip install transformers[torch] bitsandbytes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We import the required libraries : " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import torch\n", "from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's load the model. To quantize the model on the fly, we pass a `quantization_config`:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "model_name = \"meta-llama/Meta-Llama-3.1-8B-Instruct\"\n", "quantization_config = BitsAndBytesConfig(load_in_4bit=True,\n", " bnb_4bit_compute_dtype=torch.bfloat16,\n", " bnb_4bit_use_double_quant=True,\n", " bnb_4bit_quant_type= \"nf4\"\n", " )\n", "\n", "quantized_model = AutoModelForCausalLM.from_pretrained(\n", "\tmodel_name, device_map=\"auto\", torch_dtype=torch.bfloat16, quantization_config=quantization_config)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Then, we need to prepare the inputs: " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "tokenizer = AutoTokenizer.from_pretrained(model_name)\n", "input_text = \"What are we having for dinner?\"\n", "input_ids = tokenizer(input_text, return_tensors=\"pt\").to(\"cuda\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, we can generate the output ! " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "output = quantized_model.generate(**input_ids, max_new_tokens=10)\n", "\n", "print(tokenizer.decode(output[0], skip_special_tokens=True))" ] } ], "metadata": { "kernelspec": { "display_name": ".venv", "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.8.10" } }, "nbformat": 4, "nbformat_minor": 2 }