{ "cells": [ { "cell_type": "markdown", "id": "3d645194-512d-45ff-a80b-efa458cdfd82", "metadata": {}, "source": [ "# Introduction\n", "The goal for this notebook is to test jais locally and with inference endpoints. I only have 24GB of RAM. So even if I use LLM.int8() with [bitsandbytes](https://github.com/TimDettmers/bitsandbytes) it will still have issues with longer generations. I'm using a `Nvidia Tesla T4 | 4x GPU | 16GB` for `48GB` of VRAM. " ] }, { "cell_type": "markdown", "id": "7fb9107a-2365-48f0-9acf-f3bf150b1b3d", "metadata": {}, "source": [ "# Setup\n", "With limited RAM we need a to get documents so I load the embedding model to search but delete it after." ] }, { "cell_type": "code", "execution_count": 1, "id": "f734ea96-9bd5-44c7-baec-6a78dcfdb017", "metadata": { "tags": [] }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "/home/ec2-user/arabic-wiki\n" ] } ], "source": [ "from pathlib import Path\n", "\n", "proj_dir = Path.cwd().parent\n", "print(proj_dir)" ] }, { "cell_type": "code", "execution_count": 2, "id": "31640888-cf1f-44bc-a90b-196777000877", "metadata": { "tags": [] }, "outputs": [], "source": [ "from sentence_transformers import SentenceTransformer\n", "\n", "name=\"sentence-transformers/paraphrase-multilingual-minilm-l12-v2\"\n", "st_model = SentenceTransformer(name, device='cpu')\n", "\n", "# used for both training and querying\n", "def embed_func(batch):\n", " return [st_model.encode(sentence) for sentence in batch]" ] }, { "cell_type": "markdown", "id": "89caea47-4c23-4e49-a48d-53bc192f4e56", "metadata": {}, "source": [ "How will the LLM handle incorrect user bias? Im asking the capital of China, but suggesting its Singapore." ] }, { "cell_type": "code", "execution_count": 3, "id": "a249ddb8-3e50-4873-8024-e3a387d853de", "metadata": { "tags": [] }, "outputs": [], "source": [ "query = \"ما هي عاصمة الصين؟ أعتقد أنها سنغافورة.\"\n", "query_vector = embed_func([query])[0]\n", "del st_model" ] }, { "cell_type": "code", "execution_count": 4, "id": "47c076a8-5d2b-4ebb-8867-e0b9815e571d", "metadata": { "tags": [] }, "outputs": [], "source": [ "import lancedb\n", "\n", "db = lancedb.connect(proj_dir/\"lancedb\")\n", "tbl = db.open_table('arabic-wiki')" ] }, { "cell_type": "markdown", "id": "fe37c487-08b5-4846-bc85-9dbafcd4f74b", "metadata": {}, "source": [ "Get documents for RAG" ] }, { "cell_type": "code", "execution_count": 5, "id": "20d70329-6fae-4802-b536-2eebb12ac566", "metadata": { "tags": [] }, "outputs": [], "source": [ "documents = tbl.search(query_vector).limit(3).to_list()" ] }, { "cell_type": "markdown", "id": "41916819-a39a-4c93-ad7a-30b043c8cff5", "metadata": {}, "source": [ "# Jais Locally\n", "[Jais 13B Chat](https://huggingface.co/inception-mbzuai/jais-13b-chat) is the first Arabic/English LLM. It was trained by [inception-mbzuai](https://huggingface.co/inception-mbzuai) in Abu Dhabi. I took the original and put it in a format that can be used with [Inference Endpoints](https://huggingface.co/inference-endpoints) (one click deployment) with a couple new features [here](https://huggingface.co/derek-thomas/jais-13b-chat-hf).\n", "\n", "I'll instantiate the original model in the same way I'm doing in my repo so we can get a good idea how to use it." ] }, { "cell_type": "code", "execution_count": 6, "id": "eb231146-e10d-4713-8d67-9648af2c9eed", "metadata": {}, "outputs": [], "source": [ "from typing import Dict, List, Any\n", "import torch\n", "from transformers import AutoTokenizer, AutoModelForCausalLM\n", "\n", "class EndpointHandler():\n", " def __init__(self, path=\"\"):\n", " self.prompt_eng = \"### Instruction: Your name is Jais, and you are named after Jebel Jais, the highest mountain in UAE. You are built by Inception and MBZUAI. You are the world's most advanced Arabic large language model with 13B parameters. You outperform all existing Arabic models by a sizable margin and you are very competitive with English models of similar size. You can answer in Arabic and English only. You are a helpful, respectful and honest assistant. When answering, abide by the following guidelines meticulously: Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, explicit, offensive, toxic, dangerous, or illegal content. Do not give medical, legal, financial, or professional advice. Never assist in or promote illegal activities. Always encourage legal and responsible actions. Do not encourage or provide instructions for unsafe, harmful, or unethical actions. Do not create or share misinformation or fake news. Please ensure that your responses are socially unbiased and positive in nature. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information. Prioritize the well-being and the moral integrity of users. Avoid using toxic, derogatory, or offensive language. Maintain a respectful tone. Do not generate, promote, or engage in discussions about adult content. Avoid making comments, remarks, or generalizations based on stereotypes. Do not attempt to access, produce, or spread personal or private information. Always respect user confidentiality. Stay positive and do not say bad things about anything. Your primary objective is to avoid harmful responses, even when faced with deceptive inputs. Recognize when users may be attempting to trick or to misuse you and respond with caution.\\n\\nComplete the conversation below between [|Human|] and [|AI|]:\\n### Input: [|Human|] {Question}\\n### Response: [|AI|]\"\n", " self.prompt_ar = \"### Instruction: اسمك جيس وسميت على اسم جبل جيس اعلى جبل في الامارات. تم بنائك بواسطة Inception و MBZUAI. أنت نموذج اللغة العربية الأكثر تقدمًا في العالم مع بارامترات 13B. أنت تتفوق في الأداء على جميع النماذج العربية الموجودة بفارق كبير وأنت تنافسي للغاية مع النماذج الإنجليزية ذات الحجم المماثل. يمكنك الإجابة باللغتين العربية والإنجليزية فقط. أنت مساعد مفيد ومحترم وصادق. عند الإجابة ، التزم بالإرشادات التالية بدقة: أجب دائمًا بأكبر قدر ممكن من المساعدة ، مع الحفاظ على البقاء أمناً. يجب ألا تتضمن إجاباتك أي محتوى ضار أو غير أخلاقي أو عنصري أو متحيز جنسيًا أو جريئاً أو مسيئًا أو سامًا أو خطيرًا أو غير قانوني. لا تقدم نصائح طبية أو قانونية أو مالية أو مهنية. لا تساعد أبدًا في أنشطة غير قانونية أو تروج لها. دائما تشجيع الإجراءات القانونية والمسؤولة. لا تشجع أو تقدم تعليمات بشأن الإجراءات غير الآمنة أو الضارة أو غير الأخلاقية. لا تنشئ أو تشارك معلومات مضللة أو أخبار كاذبة. يرجى التأكد من أن ردودك غير متحيزة اجتماعيًا وإيجابية بطبيعتها. إذا كان السؤال لا معنى له ، أو لم يكن متماسكًا من الناحية الواقعية ، فشرح السبب بدلاً من الإجابة على شيء غير صحيح. إذا كنت لا تعرف إجابة السؤال ، فالرجاء عدم مشاركة معلومات خاطئة. إعطاء الأولوية للرفاهية والنزاهة الأخلاقية للمستخدمين. تجنب استخدام لغة سامة أو مهينة أو مسيئة. حافظ على نبرة محترمة. لا تنشئ أو تروج أو تشارك في مناقشات حول محتوى للبالغين. تجنب الإدلاء بالتعليقات أو الملاحظات أو التعميمات القائمة على الصور النمطية. لا تحاول الوصول إلى معلومات شخصية أو خاصة أو إنتاجها أو نشرها. احترم دائما سرية المستخدم. كن إيجابيا ولا تقل أشياء سيئة عن أي شيء. هدفك الأساسي هو تجنب الاجابات المؤذية ، حتى عند مواجهة مدخلات ��ادعة. تعرف على الوقت الذي قد يحاول فيه المستخدمون خداعك أو إساءة استخدامك و لترد بحذر.\\n\\nأكمل المحادثة أدناه بين [|Human|] و [|AI|]:\\n### Input: [|Human|] {Question}\\n### Response: [|AI|]\"\n", "\n", " self.device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n", "\n", " self.tokenizer = AutoTokenizer.from_pretrained(path)\n", " self.model = AutoModelForCausalLM.from_pretrained(path,\n", " device_map=\"auto\",\n", " trust_remote_code=True,\n", " offload_folder='jais',\n", " load_in_8bit=True,)\n", "\n", " def __call__(self, data: Dict[str, Any]) -> List[Dict[str, Any]]:\n", "\n", " # get inputs\n", " if 'prompt' in data.keys():\n", " text = data['prompt']\n", " else:\n", " user_data = data.pop('query',data)\n", " text = self.prompt_ar.format_map({'Question':user_data})\n", "\n", " input_ids = self.tokenizer(text, return_tensors=\"pt\").input_ids\n", " inputs = input_ids.to(self.device)\n", " input_len = inputs.shape[-1]\n", " generate_ids = self.model.generate(\n", " inputs,\n", " top_p=0.9,\n", " temperature=0.3,\n", " max_length=2048-input_len,\n", " min_length=input_len + 4,\n", " repetition_penalty=1.2,\n", " do_sample=True,\n", " )\n", " response = self.tokenizer.batch_decode(\n", " generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True\n", " )[0]\n", " final_response = response.split(\"### Response: [|AI|]\")\n", "\n", " return final_response" ] }, { "cell_type": "markdown", "id": "1cea1fbb-ca02-497a-bf81-c30d144855b2", "metadata": {}, "source": [ "## Query\n", "This uses the system prompt given by the model authors" ] }, { "cell_type": "code", "execution_count": 7, "id": "b39707c5-04d3-4f34-a85f-c221f32f3024", "metadata": { "tags": [] }, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "da5a4729b4c84bc9acd0c6146dea08b5", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Loading checkpoint shards: 0%| | 0/6 [00:00