<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Odunola Jenrola on Medium]]></title>
        <description><![CDATA[Stories by Odunola Jenrola on Medium]]></description>
        <link>https://medium.com/@jenrola_odun?source=rss-11f7f94634f6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XT-eMvBpZOWYSlOuMJwDqA.jpeg</url>
            <title>Stories by Odunola Jenrola on Medium</title>
            <link>https://medium.com/@jenrola_odun?source=rss-11f7f94634f6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 22:24:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jenrola_odun/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Exploring Knowledge Distillation in Large Language Models]]></title>
            <link>https://medium.com/@jenrola_odun/exploring-knowledge-distillation-in-large-language-models-9d9be2bff669?source=rss-11f7f94634f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d9be2bff669</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[generative-ai-tools]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Odunola Jenrola]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 19:10:01 GMT</pubDate>
            <atom:updated>2023-11-15T19:10:01.368Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Jv13JlNUSVa5yymR" /><figcaption>Photo by <a href="https://unsplash.com/@growtika?utm_source=medium&amp;utm_medium=referral">Growtika</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>AI companies continue to scale up language models , yet practical deployment of these large models remains a formidable challenge. In this article, we delve into an invaluable technique to address this issue: Knowledge distillation.</p><p>Knowledge distillation enables the transfer of expertise from a complex, large model, known as the “teacher,” to a more compact, lightweight model, the “student.” This is now a cornerstone in AI as it not only eases the computational burden of deploying complex models but also facilitates their application in real-world scenarios especially in resource constrained environment like edge devices and CPU-only environments.</p><p>In this article, Our goal is to distill a large BERT transformer model I already finetuned for text classification. Our student model is a more compact model also based on BERT but having fewer parameters and designed to be lightweight. You can check out its huggingface repo <a href="http://google/bert_uncased_L-10_H-256_A-4">here</a>. Google released this model alongside 23 other smaller pre-trained BERT-like models, as part of a research effort exploring the significance of training more compact models for natural language processing tasks with distillation in mind. After distillation we would evaluate and compare both models and test their speed and accuracy in a low-compute CPU environment.</p><p>While our teacher model may not be as extensive or computationally demanding as some state-of-the-art language models today with only about 100 million parameters, our goal is to illustrate how distillation actually works. As mentioned before, Our teacher model was finetuned using a Runpod A30 GPU instance for just two epochs. During this training we achieved the following results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*36xJ0_BznQlL7MpjuwwZWQ.png" /></figure><p>Since we only finetune the smaller teacher model in this article, you can follow along in a free Google Colab environment.</p><p>Now, let’s delve into the dataset we’re working with. We’ve chosen the <a href="https://huggingface.co/datasets/ag_news">AG’s news topic classification dataset</a>, a subset of the original AG-NEWS dataset curated by <a href="/service/mailto:xiang.zhang@nyu.edu">Xiang Zhang</a> for text classification benchmarks. This dataset comprises approximately 120,000 news topics categorized into four labels: WORLD, SPORTS, BUSINESS, and SCI/TECH. Given its manageable size, we won’t complicate things with an intricate data pipeline; instead, we’ll leverage PyTorch’s Dataset and DataLoader classes for our purposes. A lot of our code would be written in clean pytorch code for better understanding.</p><pre>dataset_ckpt = &#39;ag_news&#39;<br>teacher_model_ckpt = &#39;odunola/bert-base-uncased-ag-news-finetuned-2&#39; #our already finetuned teacher model<br>student_model_ckpt = &#39;google/bert_uncased_L-12_H-256_A-4&#39;</pre><p>Next we import torch and other neccessary dependencies.</p><pre>from huggingface_hub import notebook_login<br>from datasets import load_dataset<br>from torch.utils.data import Dataset<br>from torch.utils.data import DataLoader<br>import torch<br>from transformers import AutoModelForSequenceClassification<br>from torch import nn<br>from torch import optim<br>from torch.nn import functional as F<br>from transformers import AutoTokenizer<br>from tqdm import tqdm<br>from time import perf_counter<br>import pandas as pd</pre><p>We also declare our tokenizer with the AutoTokenizer class from huggingface’s <a href="https://github.com/huggingface/transformers">transformers</a> module.</p><pre><br>tokenizer = AutoTokenizer.from_pretrained(student_model_ckpt)</pre><p>Next we load or dataset with <a href="https://huggingface.co/">huggingface’</a>s dataset module and divide into train, validation and test sets. We also explore our dataset a bit.</p><pre>data = load_dataset(dataset_ckpt)<br>train_test = data[&#39;train&#39;].train_test_split(test_size = 0.2)<br>valid_data = train_test[&#39;test&#39;]<br>train_data = train_test[&#39;train&#39;]<br>test_data = data[&#39;test&#39;]<br><br>def get_num_rows(dataset):<br>  return dataset.num_rows<br><br>print(f&#39;Train set has {get_num_rows(train_data)} texts&#39;)<br>print(f&#39;Valid set has {get_num_rows(valid_data)} texts&#39;)<br>print(f&#39;Test set has {get_num_rows(test_data)} texts&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/495/1*H-PAFSveB2KVs1LezUPkFA.png" /></figure><p>Now we define a class that inherits from Pytorch’s Dataset class and construct our dataset.</p><pre>#now we would utilise pytorch&#39;s Dataset andDataloader classes to create our dataset<br><br>class MyData(Dataset):<br>  def __init__(self, data):<br>    targets = data[&#39;label&#39;]<br>    texts = data[&#39;text&#39;]<br><br>    tokens = tokenizer(texts, return_tensors = &#39;pt&#39;, truncation = True, padding = &#39;max_length&#39;, max_length = 150)<br>    self.input_ids = tokens[&#39;input_ids&#39;]<br>    self.attention_mask = tokens[&#39;attention_mask&#39;]<br>    self.targets = torch.tensor(targets)<br>    self.length = len(texts)<br>  def __len__(self):<br>    return self.length<br>  def __getitem__(self, index):<br>    return self.input_ids[index], self.attention_mask[index], self.targets[index]<br><br><br>train_data = MyData(train_data)<br>valid_data = MyData(valid_data)<br>test_data = MyData(test_data)<br><br># now we build our loaders<br>batch_size = 64<br>train_loader = DataLoader(train_data,batch_size = batch_size)<br>valid_loader = DataLoader(valid_data, batch_size = batch_size)<br>test_loader = DataLoader(test_data, batch_size = batch_size)</pre><p>Great! we seem to be progressing well!. Now let us write a simple function that helps us calculate accuracy. We would also test the accuracy and speed performance of our teacher model</p><pre>#first we install define our device and download our teacher model from huggingface<br>device = torch.device(&#39;cuda&#39;) if torch.cuda.is_available() else torch.device(&#39;cpu&#39;)<br>teacher_model = AutoModelForSequenceClassification.from_pretrained(teacher_model_ckpt).to(device)<br><br><br># we define a function to help us compute accuracy as we train, we would also define another function to measure time ellapsed<br>def accuracy_score(batch, model):<br>  with torch.no_grad():<br>    outputs = model(<br>        batch[0].to(device),<br>        batch[1].to(device)<br>    )<br>    logits = outputs.logits<br>    probabilities = torch.softmax(logits, dim = 1)<br>    class_predictions = torch.argmax(probabilities, dim = 1)<br>    acc = torch.mean((class_predictions == batch[2].to(device)).to(torch.float)).data.item()<br>    return acc<br><br>#now let us test!<br><br>accuracy = 0.0<br>time_taken = 0.0<br>count = 0<br>for batch in tqdm(test_loader):<br>  start_time = perf_counter()<br>  score = accuracy_score(batch, teacher_model)<br>  end_time = perf_counter()<br>  accuracy += score<br>  time_taken += end_time - start_time<br><br>print(&#39;\n\n&#39;)<br>print(f&quot;number of samples in each batch is {len(batch[0])}&quot;)<br>print(f&#39;number of batch is {len(test_loader)}&#39;)<br>print(f&quot;accuracy is {accuracy / len(test_loader):.2f}&quot;)<br>print(f&#39;time taken per batch is {time_taken / len(test_loader):.6f}&#39;)<br><br></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S45MTqNDKlNtq0OCTxcmJQ.png" /><figcaption>accuracy on the teacher model. Could be better but we trained for just two epochs</figcaption></figure><p>Now, we download our student model off of huggingface and also define our number of epochs, learning rate, losses and optimizer. We also increase dropout to help prevent overfitting.</p><pre>student_model = AutoModelForSequenceClassification.from_pretrained(student_model_ckpt, num_labels = 20).to(device)<br>student_model.dropout = nn.Dropout(0.3) #Increase dropout to improve generalization.<br>epochs = 5#we train for5epochs<br>learning_rate = 2e-5<br>entropy_loss = nn.CrossEntropyLoss() #cross entropy loss<br>temperature = 2.0<br>alpha = 0.5<br>criterion = nn.KLDivLoss(reduction = &#39;batchmean&#39;) #KL Divergence Loss<br>optimizer = optim.Adam(student_model.parameters(), lr = learning_rate)</pre><p>Let us also compare the number of parameters of each of our models</p><pre>def get_parameter_count(model):<br>  num_params = sum(p.numel() for p in model.parameters())<br>  return num_params<br><br>print(f&#39;teacher model has {(get_parameter_count(teacher_model)/1000000):.2f} parameters&#39;)<br>print(f&#39;student model has {(get_parameter_count(student_model)/1000000):.2f} parameters&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*bFZsLRflgffef1P3OV8MJw.png" /></figure><pre>epochs = 4<br>learning_rate = 2e-5<br>entropy_loss = nn.CrossEntropyLoss()<br>temperature = 1.0<br>alpha = 0.5 #test this<br>criterion = nn.KLDivLoss(reduction = &#39;batchmean&#39;)<br>optimizer = optim.AdamW(student_model.parameters(), lr = learning_rate)</pre><p>Let’s take a moment to discuss the process of distilling knowledge from our teacher model. As mentioned earlier, the fundamental idea is for a student model to learn not only from the correct answers provided by the teacher model but also from its probabilistic outputs. One effective method to achieve this is by measuring the disparities between the probability distributions of both the teacher and student models.</p><p>During the training process, our primary goal is to minimize the differences between the probability distributions of these two models. As a result, after a successful training run, both models will have very similar probabilities, and they will be focusing on the same aspects of the incoming data. In the context of this distillation approach, the Kullback-Leibler Divergence loss is the recommended choice for achieving this objective.</p><p>The Kullback-Leibler Divergence loss is a measure of how one probability istribution differs from another. In our context, this loss is perfect to quantify the difference between probability distributions of outputs of the teacher and student model and make it so that the student model not only captures the teacher’s prediction but also the uncertainty in those predictions too. Another approach to distillation is using plain mean square error loss which measures the squared difference between probabilities but this only means we are forcing the student model to output the exact probability value of the teacher. This is more rigid and strives for a closer match with the teacher’s predictions and can be preferred if what you need is to match the teacher’s predictions precisely.</p><p>Now back to code. Above we declared both cross entropy loss since we are dealing with classification and also PyTorch&#39;s implementation of the KL Divergence loss. Below we have our PyTorch training loop</p><pre>import pandas as pd<br><br># Lists to store training and validation metrics<br>training_loss_list = []<br>training_kd_loss_list = []<br>training_accuracy_list = []<br>valid_loss_list = []<br>valid_accuracy_list = []<br><br>#starting loop<br>for epoch in tqdm(range(epochs), total=epochs):<br>    student_model.train()<br>    train_loss = 0.0<br>    train_kd_loss = 0.0<br>    train_accuracy = 0.0<br>    valid_loss = 0.0<br>    valid_accuracy = 0.0<br><br>    for batch in train_loader:<br>        optimizer.zero_grad()<br>        input_ids = batch[0].to(device)<br>        attention_mask = batch[1].to(device)<br>        target_tensors = batch[2].to(device)<br><br>        # Student model predictions<br>        student_logits = student_model(input_ids=input_ids, attention_mask=attention_mask).logits<br>        ce_loss = entropy_loss(student_logits, target_tensors).data.item()<br><br>        # We extract teacher model logits<br>        with torch.no_grad():<br>            teacher_outputs = teacher_model(input_ids=input_ids, attention_mask=attention_mask)<br>            teacher_logits = teacher_outputs.logits<br><br>        # Knowledge distillation loss (KD divergence)<br>        kd_loss = temperature ** 2 * criterion(<br>            F.log_softmax(student_logits / temperature, dim=-1),<br>            F.softmax(teacher_logits / temperature, dim=-1)<br>        )<br><br>        # Combined loss<br>        loss = alpha * ce_loss + (1. - alpha) * kd_loss<br>        loss.backward()<br>        optimizer.step()<br><br>        # Update training metrics<br>        train_kd_loss += kd_loss.data.item()<br>        train_loss += loss<br>        accuracy = accuracy_score(batch, student_model)<br>        train_accuracy += accuracy<br><br>    student_model.eval()<br>    for batch in valid_loader:<br>        input_ids = batch[0].to(device)<br>        attention_mask = batch[1].to(device)<br>        target_tensors = batch[2].to(device)<br><br>        # Validation loss<br>        output = student_model(input_ids=input_ids, attention_mask=attention_mask)<br>        val_loss = entropy_loss(output.logits, target_tensors)<br>        valid_loss += val_loss.data.item()<br><br>        # Update validation accuracy<br>        accuracy = accuracy_score(batch, student_model)<br>        valid_accuracy += accuracy<br><br>    # Calculate average metrics<br>    train_accuracy /= len(train_loader)<br>    valid_accuracy /= len(valid_loader)<br>    train_loss /= len(train_loader)<br>    train_kd_loss /= len(train_loader)<br>    valid_loss /= len(valid_loader)<br><br>    # Append metrics to lists<br>    training_kd_loss_list.append(train_kd_loss)<br>    training_loss_list.append(train_loss.cpu().detach().numpy())<br>    training_accuracy_list.append(train_accuracy)<br>    valid_loss_list.append(valid_loss)<br>    valid_accuracy_list.append(valid_accuracy)<br><br>    # Print and store metrics<br>    print(f&quot;&quot;&quot;<br>    After epoch {epoch + 1}:<br>    Training loss (entropy): {train_loss}<br>    Kullback-Leibler (KL) divergence loss: {train_kd_loss}<br>    Validation loss (entropy): {valid_loss}<br>    Training accuracy: {train_accuracy}<br>    Validation accuracy: {valid_accuracy}<br>    &quot;&quot;&quot;)<br><br># Create a DataFrame to store the metrics<br>metrics = pd.DataFrame({<br>    &#39;training_loss&#39;: training_loss_list,<br>    &#39;training_kd_loss&#39;: training_kd_loss_list,<br>    &#39;training_accuracy&#39;: training_accuracy_list,<br>    &#39;valid_loss&#39;: valid_loss_list,<br>    &#39;valid_accuracy&#39;: valid_accuracy_list<br>})<br></pre><p>Let’s talk a bit about the details of this PyTorch training loop, which follows a standard structure but incorporates some unique aspects. Here’s a breakdown:</p><ol><li>Temperature Parameter: We introduce a “temperature” parameter in our loss calculations. This parameter scales the logits of both the student and teacher models. The purpose is to make these logits less extreme, and the temperature value influences the softness of the resulting probability distributions. A higher temperature leads to softer, more spread-out distributions. In deep learning, we use the temperature to strike a balance between favoring precise, sharp predictions and giving weight to softer, less confident predictions.</li><li>Alpha Parameter: We employ an “alpha” parameter to determine the balance between two different losses when calculating the overall training loss. This parameter controls how much each of these losses contributes to the final combined loss. It’s a critical part of the process. When alpha approaches 1, it highlights the importance of the cross-entropy loss, emphasizing exact match with target labels. Conversely, when alpha approaches 0, it emphasizes the KL divergence loss, focusing on capturing the broader knowledge and softer predictions. In our case, with an alpha set to 0.5, both losses are given equal importance in computing the final loss.</li><li>Also, just like we stated before we consider both the KL divergence loss and the cross-entropy loss when calculating the overall loss during training. The temperature parameter adjusts the logits, affecting the shape of probability distributions, while the alpha parameter dictates the balance between the two losses, ultimately guiding the model in achieving the desired trade-off between precision and soft knowledge capture.</li></ol><p>After training for 5 epochs, we record the following metrics. Not bad for a model almost 10x smaller than its teacher. We can definitely get better results by using different hyper-parameters or even a better student model. Recall the drastic difference in the number of trainable parameters of both models. You can experiment to get better results with dropout, learning rate, alpha, temperature parameters and also train for more epochs. Keep on the lookout for signs of overfitting though!. We also push our student model and tokenizer to a new huggingface repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*bnO-px5tzbMttVhwuwkOYA.png" /></figure><pre>student_model.push_to_hub(&#39;odunola/google-distilled-ag-news&#39;)<br>tokenizer.push_to_hub(&#39;odunola/google-distilled-ag-news&#39;)</pre><p>Now, with our test loader we write some code to help us do some bench marks. Take note that we reuse the accuracy_score function of earlier.</p><pre>accuracy_teacher = 0.0<br>time_taken_teacher = 0.0<br><br>accuracy_student = 0.0<br>time_taken_student = 0.0<br>count = 0<br>for batch in tqdm(test_loader):<br>  start_time = perf_counter()<br>  score = accuracy_score(batch, teacher_model)<br>  end_time = perf_counter()<br>  accuracy_teacher += score<br>  time_taken_teacher += end_time - start_time<br><br>  start_time = perf_counter()<br>  score = accuracy_score(batch, student_model)<br>  end_time = perf_counter()<br>  accuracy_student += score<br>  time_taken_student += end_time - start_time<br><br><br>print(&#39;\n\n&#39;)<br>print(f&quot;number of samples in each batch is {len(batch[0])}&quot;)<br>print(f&#39;total number of batches is {len(test_loader)}&#39;)<br>print(f&quot;teacher accuracy is {accuracy_teacher / len(test_loader):.2f}&quot;)<br>print(f&#39;time taken per batch for teacher is {time_taken_teacher / len(test_loader):.6f}&#39;)<br>print(&#39;\n\n\n&#39;)<br>print(f&quot;student accuracy is {accuracy_student / len(test_loader):.2f}&quot;)<br>print(f&#39;time taken per batch for student is {time_taken_student / len(test_loader):.6f}&#39;)Running this code on a T5 GPU we get the following scores.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/868/1*rLbi7z0z2YEDAbCMvIu81A.png" /></figure><p>The true evaluation, however, involves conducting the same benchmark in an environment that lacks substantial computing power or GPU acceleration. With the following code I test the performance and speed of both student and teacher model in a free Google Colab CPU-only instance. The subsequent results were documented as follows. (note that we only tested for 4 batches of the test loader because of time,);</p><pre>teach_model = AutoModelForSequenceClassification.from_pretrained(&#39;odunola/bert-base-uncased-ag-news-finetuned-2&#39;)<br>stud_model = AutoModelForSequenceClassification.from_pretrained(&#39;odunola/distillbert-distilled-ag-news&#39;)<br>device = &#39;cpu&#39;<br><br>accuracy_teacher = 0.0<br>time_taken_teacher = 0.0<br>teacher_model = teach_model.to(&#39;cpu&#39;)<br>student_model = stud_model.to(&#39;cpu&#39;)<br>accuracy_student = 0.0<br>time_taken_student = 0.0<br>count = 1<br>for batch in tqdm(test_loader):<br>  start_time = perf_counter()<br>  score = accuracy_score(batch, teach_model)<br>  end_time = perf_counter()<br>  accuracy_teacher += score<br>  time_taken_teacher += end_time - start_time<br><br>  start_time = perf_counter()<br>  score = accuracy_score(batch, stud_model)<br>  end_time = perf_counter()<br>  accuracy_student += score<br>  time_taken_student += end_time - start_time<br>  if count == 4:<br>    break<br>  count += 1<br><br><br>print(&#39;\n\n&#39;)<br>print(f&quot;number of samples in each batch is {len(batch[0])}&quot;)<br>print(f&#39;total number of batches is {len(test_loader)}&#39;)<br>print(f&quot;teacher accuracy is {accuracy_teacher / 4:.2f}&quot;)<br>print(f&#39;time taken per batch for teacher is {time_taken_teacher / 4:.6f}&#39;)<br>print(&#39;\n\n\n&#39;)<br>print(f&quot;student accuracy is {accuracy_student / 4:.2f}&quot;)<br>print(f&#39;time taken per batch for student is {time_taken_student / 4:.6f}&#39;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*xUrGvy4RRYwx7N2z4dXngg.png" /></figure><p>Please note that the time is in seconds.</p><p>In summary, I hope our journey with knowledge distillation has been a smooth one. We’ve cut down on memory usage and significantly sped things up, all while keeping up with our teacher model’s performance. These results speak volumes about how this technique can make things faster and lighter without sacrificing too much quality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d9be2bff669" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Problem with Open Source LLMs for Small and Medium Enterprises (SMEs) Adoption]]></title>
            <link>https://medium.com/@jenrola_odun/the-problem-with-open-source-llms-for-small-and-medium-enterprises-smes-adoption-f015b21a890e?source=rss-11f7f94634f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/f015b21a890e</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[large-language-models]]></category>
            <category><![CDATA[naturallanguageprocessing]]></category>
            <dc:creator><![CDATA[Odunola Jenrola]]></dc:creator>
            <pubDate>Wed, 27 Sep 2023 12:22:00 GMT</pubDate>
            <atom:updated>2023-09-27T12:22:00.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*P6CfkG6EXYbbrL-2OrFpkw.jpeg" /><figcaption>A cute llama</figcaption></figure><p>A few weeks ago, I set out to work on a project: building a basic search engine from scratch using a proprietary dataset. The foundational architecture of this search engine was rather straightforward. First, I divided the dataset into manageable segments. Next, I employed an encoder-only language model to generate vector embeddings from the text data. These embeddings and their corresponding data segments, were meticulously stored in a vector database. My plan was to streamline retrieval by utilizing cloud services such as Pinecone or Weaviate’s Weaviate Cloud Service. However, I decided to take on an additional challenge: constructing the entire application using exclusively open-source frameworks and models, eliminating options like OpenAI and Pinecone. Sounds exciting right? Please note that this is not a tutorial.</p><p>Open-source large language models like <a href="https://ai.meta.com/llama/">Llama2</a> and Falcon have made a significant impact on the field of AI. They have garnered widespread recognition for their exceptional response quality and impressive performance on various benchmarks. What sets them apart is their availability under a commercial license, making them a viable choice for enterprises seeking to harness the power of language models while ensuring data security. This becomes particularly crucial for companies dealing with sensitive data like healthcare records and personal information, as they can leverage this advanced technology without exposing their data to third-party risks.</p><p>Currently, <a href="https://huggingface.co/meta-llama/Llama-2-70b">Llama2 70B</a> and the recently launched <a href="https://huggingface.co/blog/falcon-180b">Falcon 180B</a> model dominate HuggingFace’s open LLM Leaderboard, a platform that monitors language model performance. These models, aside from being trained on extensive datasets and fine-tuned, also undergo Reinforcement Learning through human feedback. This technique involves using human-generated feedback to align the model’s responses more closely with human-like understanding.</p><p>While fine-tuned variants of Llama2 70B have demonstrated competitiveness with GPT-3.5 Turbo on specific tasks, there have been <a href="https://x.com/TheTuringPost/status/1699767503399034957?s=20">rumors suggesting that Falcon’s 160B model surpasses GPT-3.5 Turbo and achieves performance levels nearing that of GPT-4</a>. However, it’s essential to exercise caution when considering such claims, properly demonstrated in a <a href="https://youtu.be/l3oNsGtRjqo?si=b9g5zsKFYsXaC2ld">video by James Briggs on YouTube</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MyuBPscXqt4BKqtGvPsAFQ.png" /><figcaption>Finetuned Variants of LLama70B dominate the leaderboard</figcaption></figure><p>Now, let’s dive back into the project. Stick around; we’re about to reach a crucial milestone. The process of generating embeddings for my data proved to be relatively straightforward. To accomplish this, I opted for the <a href="https://huggingface.co/intfloat/e5-large-v2"><strong>`intfloat/e5-large-v2`</strong></a> model from Hugging Face. This model not only boasts high scores on <a href="https://huggingface.co/spaces/mteb/leaderboard">Hugging Face’s Text Embedding Leaderboard</a> but, based on my prior personal experiences, also appears to outperform OpenAI’s own text embedding model in open-source evaluations.</p><p>For ease of implementation, I harnessed the capabilities of the<a href="https://www.sbert.net/"> Sentence-Transformers library.</a> It’s worth noting that directly using the Hugging Face model with Sentence-Transformers can lead to errors, as the model lacks the specific tag required by Sentence-Transformers on its page. To circumvent this issue, I cloned the repository onto my own account, then edited the ReadMe file and included the necessary tag for the model to work with the Sentence-Transformers framework.</p><p>Moving on to the hardware aspect of things, deep learning models necessitate the computational power of a GPU. Fortunately, <a href="https://www.runpod.io/">RunPod</a> came to the rescue with their cost-effective GPU instances. I launched an instance equipped with a single L4 GPU and set it to work generating my embeddings. For detailed guidance on this step, you can refer to Pinecone’s tutorial on vector embeddings.</p><p>After generating the embeddings, I proceeded to upload both the text data and embeddings to a Weaviate Cloud Service Instance. With that, objective two was marked as complete.</p><p>Now I had gotten to the crucial part, and where i would make my points made. Right up the bat I started up testing Llama7B on RunPod instance with an L40 GPU and 48GB of VRAM. The model’s performed superbly as expected on simple vanilla code for text generation, no 4bit quantization, no deepspeed inference setup, nothing fancy but i did do 8bit quantization. And more importantly, it fit into the GPU.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rn61YKTLBCnlWQgUw1SOMA.png" /><figcaption>Result from LLama7b without context</figcaption></figure><p>However, after rewriting the code generation and giving it a context with the following prompt</p><pre>prompt = &quot;&quot;&quot;<br>### Instruction:<br>[INST] &lt;&lt;SYS&gt;&gt; YOu are given a request &quot;Request&quot; and a context &quot;Context&quot; that would help you respond to the request. You are a world renowned chef that is well versed in all forms of cuisine and food related content. you also understand how to create dishes that avoid peoples allergies like gluten and nuts. Answer the person&#39;s request as best as you can given the context as a mode of referenceto you. If the person&#39;s request isnt food related please reply with &quot;Please keep your request food-related&quot; only. If the context &quot;Context&quot; does not seem to help you answer the requestproperly you can do without the Context and answer the question with your memory alone&lt;&lt;/SYS&gt;&gt;<br>            Request: {request}<br>            Context: {context}<br>### Response:  [/INST]<br>            &quot;&quot;&quot;</pre><p>The output was a jumble of incoherent words, and it consumed a significant amount of time. My brief test was concluded, revealing that LLama2 7B, while relatively straightforward to implement and suitable for basic tasks, falls short when it comes to tasks demanding robust reasoning capabilities. Additionally, the execution time was considerably lengthy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o8BZ0BGJHHbKyQ43GV9rNg.png" /></figure><p>In pursuit of expedited results and reaching my conclusion swiftly, I opted quickly to try out the Llama 70B model. This is where the adventure truly began. Initially, setting it up and getting it to function smoothly turned into quite a daunting challenge. I lost count of the numerous out-of-memory errors that plagued me that day; they were numerous, to say the least.</p><p>The model demanded a whopping 160GB of VRAM to operate in full floating-point precision, equivalent to the resources of 2 A100 GPUs. In addition, inference times were notably extended. Nevertheless, it undeniably delivered impressive performance, accomplishing precisely what I had set out to achieve. Yet, this achievement came with a significant trade-off: the substantial resource and time investment.</p><p>Moving forward, I’d like to address two key points. Firstly, there are clear benefits to having ownership and control over your models. However, achieving peak performance during inference demands a substantial investment of time, expertise, and financial resources. Creating an efficient system architecture to serve your models while minimizing latency is a complex endeavor, especially for small and medium-sized enterprises with limited resources.</p><p>I am familiar with effective strategies for mitigating latency and reducing computational demands, such as using 8 or 4-bit precision and exploring libraries like <a href="https://github.com/ggerganov/llama.cpp">llama.cpp</a> that leverage C and C++ for faster inference. It’s important to note, though, that quantizing a model or reducing its precision can potentially degrade output quality. If you’re willing to accept a slight performance trade-off, these techniques can still be viable options. However, comprehensive testing is crucial to ensure they align with your specific requirements.</p><p>Now, let’s consider the cost aspect. When you opt to serve your model with a cloud provider, you pay for the exact amount of time your inference cloud instance is active. This approach can be problematic because what if your model doesn’t perform any inference for a significant portion of an hour? You would still be charged for the entire hour that the instance was active. This situation is particularly relevant for small businesses looking to integrate AI into their operations, as they often have fewer users interacting with their applications compared to larger tech companies. Comparing the way closed-model companies charges their clients by the exact amount of tokens that is sent and generated by the model you can see the one that can turn out to be more computationally expensive.</p><p>Consider the case of a healthcare startup that has accumulated a vast amount of confidential healthcare data from its users. This startup aims to integrate AI into its workflow but is wary of closed-source models due to the complexity of its data and the potential issues associated with sharing this data through third-party company APIs. This situation poses significant challenges and concerns for the healthcare startup.</p><p>As the debate between closed and open-source AI models continues, I personally see the current utility of open-source models primarily for accelerating AI research. However, it’s essential to recognize that we aren’t developing these models solely for researchers and AI practitioners. Instead, our goal is to create products that people can use and appreciate.</p><p>I commend projects like BentoML for their efforts in simplifying the deployment and serving of AI models. It’s time for the community to allocate more resources to make private models accessible to enterprises in a more cost-effective manner. This is especially crucial for businesses that handle confidential information such as customer data, financial records, research and development data, legal documents, marketing strategies, and trade secrets, as data security and cost efficiency become paramount concerns.</p><p>I firmly believe that the open-source community should extend its focus beyond just scaling and enhancing models; it should also pioneer novel deployment techniques. Exploring innovative ways to efficiently serve models can be a compelling strategy to excel in the ongoing debate between closed and open-source solutions.</p><p>Now, let’s return to the project. Although everything proceeded according to plan, there were still considerable challenges when it came to running the model. Thanks to RunPod’s instances, I managed to achieve a performance level that closely resembled that of GPT-3.5. Initially, I had considered experimenting with Falcon’s 180B model, but now I have reservations, given that this model requires a staggering 400GB of VRAM to operate.</p><p>I appreciate your company until the end and for taking the time to engage with my inner thoughts. Please feel free to connect with me on Twitter if you have any further thoughts on this topic or if you’re interested in potential collaborations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f015b21a890e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Extracting Reddit Data with the Reddit API and Python Requests Library]]></title>
            <link>https://medium.com/@jenrola_odun/extracting-reddit-data-with-the-reddit-api-and-python-requests-library-537bdea5e539?source=rss-11f7f94634f6------2</link>
            <guid isPermaLink="false">https://medium.com/p/537bdea5e539</guid>
            <dc:creator><![CDATA[Odunola Jenrola]]></dc:creator>
            <pubDate>Sat, 10 Sep 2022 19:01:55 GMT</pubDate>
            <atom:updated>2022-09-10T19:53:56.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_JPfX4l6HvlKLXCh" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=medium&amp;utm_medium=referral">Brett Jordan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Some weeks ago, i was getting started on a Machine learning Sentiment analysis and Named Entity Recognition finance project to determine real time investors most talked about stock. As for any machine learning projects one has to determine how to get data and enough of it to build a model of high accuracy. I first thought about <a href="https://twitter.com/home">Twitter</a> data but I felt it was going to be an hassle as it had no dedicated forum for stocks and investing tweets. Also getting access to the Twitter API had an application process and it was taking a while for that to be approved. Since this was a learning project, I thought I could make use of the <a href="https://www.reddit.com/r/investing/">r/Investing</a>, <a href="https://www.reddit.com/r/wallstreetbets/">r/WallStreetBets</a> and <a href="https://www.reddit.com/r/StockMarket/">r/StockMarket</a> subreddits.</p><p>The Investing, WallStreetBets and StockMarket subreddits are the go-to forums on the internet for real-time stock and investment news. These subreddits are very active and perfect for this project.</p><p>In this article though, we would only focus on extracting data from these subreddits with the request and reddit API.</p><p><strong>Getting a Reddit API key and Token</strong></p><ol><li>Log on to or create a <a href="https://www.reddit.com/">Reddit</a> account.</li><li>Reddit recently adopted a new look but allows a choice to revert to that old look. We would need to do this. Click on your reddit profile, navigate to <em>More</em> and then select <em>Visit Old Reddit</em>. You can also click <a href="https://old.reddit.com/"><em>here</em></a>.</li><li>We need to create an app for this project on reddit. Navigate to the <a href="https://old.reddit.com/prefs/">Preference</a> tab on your right hand side beside your profile name and then click on <a href="https://old.reddit.com/prefs/apps/">apps</a>. You should see the option to create a new app when you scroll all the way down.</li><li>Click on create new app. Give your app a name and remember it because you would need it later. Also type in a quick description on what your app does also. <em>Please make sure you select the SCRIPT radio button!</em> You could leave about blank but in the redirect text area you could put your <a href="https://www.linkedin.com/feed/">Linkedin</a> or <a href="https://twitter.com/home">Twitter</a> URL so in case a person wishes to know the creator of your app they would be redirected to your profile.</li><li>After creating the app, you would have both your <strong>client_id</strong> and <strong>secret key</strong> displayed…or you might have to click on <em>edit</em> to find them. Now we have all what we need: your reddit username and password, your client_id and secret key and the name of your app. For convenience, since we are going on to python, i suggest you save these credentials on a secure file in your current working directory and call them with the Open(I/O) python method in your script to prevent people from seeing them. Please keep your credentials very safe.</li></ol><p>Now we begin. Open a new python script with your favorite text editor and run the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ce6142b66be8c843a1cf8c6619083e7/href">https://medium.com/media/3ce6142b66be8c843a1cf8c6619083e7/href</a></iframe><p>We have not done anything super here. All we have done is to load our modules with import and retrieve our credentials with the open method. Now we can use the requests library. The first thing we would do is to get a temporary access token with our client_id and secret key. Check out the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a98449d854ff356d29d6d73c89f0b6c3/href">https://medium.com/media/a98449d854ff356d29d6d73c89f0b6c3/href</a></iframe><p>Noww we are getting there. Here we create out authentication with our client_id and secret key with requests, we also create a dictionary with our mode of authentication(password) and then the username and password. We are doing this to get our temporary access token. It is this access_token in the headers dictionary that would actually be used to get the data with a request.get_method. For now to make sure everything works let us try pulling data from the wallstreetbets subreddit. Check the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef223a838c7671e26afbf41ee3837b71/href">https://medium.com/media/ef223a838c7671e26afbf41ee3837b71/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1hjLyCKsQEXM3cElVnVqQ.png" /></figure><p>We have our data! Note that we have just messages from the wallstreetbet subreddit. And also we have just the first 100 tweets. The API only lets us get 100 messages at once. But we can always get a lot more with a loop! All what we need to do is use the ‘name’ attribute from the last row in our dataframe and pass that to our api requests telling it to get us the next 100 messages after that last message. We can do this over and over again and keep on concatenating our results until the API grows tired of us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a45a0f43753774b7b07d06b0ef7548d/href">https://medium.com/media/4a45a0f43753774b7b07d06b0ef7548d/href</a></iframe><p>Now we should have substantial data. The while loop runs until the api decides to not give us anymore data again. It may run for a while since we used a forever while loop but it should not take too long. So now for my project i could concatenate the title and selftext column to make a message column for my model since some messages in the subreddits dont have a selftext.</p><p>Finally, lets do a best of both worlds scenario, or perhaps a best of three worlds. A single script that downloads messages from all three subreddits at once. Check the code block below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d12bee9f1350ffdf3dcef1aaf7afae31/href">https://medium.com/media/d12bee9f1350ffdf3dcef1aaf7afae31/href</a></iframe><p>In conclusion, we have learnt how to create a developer app on reddit, and used the secret_key and client_id to generate a temporary access_token and with the request library collected data from subreddits.</p><p>Huge shoutout to <a href="https://twitter.com/jamescalam">James Briggs</a> as his Natural Language Proccessing with Transformers udemy course and <a href="https://www.youtube.com/c/JamesBriggs">Youtube videos</a> has been instrumental in my growth in the space. I got the idea for this article from his course.</p><p>Are you interesting in having a chat about this,questions, contributions and collaborations? Kindly reach out to me on <a href="https://twitter.com/Jenrola_odun">Twitter</a> and <a href="https://www.linkedin.com/in/odunolaoluwa-jenrola/">LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=537bdea5e539" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>