<?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 Marina Sedinkina on Medium]]></title>
        <description><![CDATA[Stories by Marina Sedinkina on Medium]]></description>
        <link>https://medium.com/@sedimarina01?source=rss-b58612057533------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1-lhR6pM9N1Ypulm9FckjA.jpeg</url>
            <title>Stories by Marina Sedinkina on Medium</title>
            <link>https://medium.com/@sedimarina01?source=rss-b58612057533------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:19:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sedimarina01/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[Data Harmonization using Machine Learning and Language Models]]></title>
            <link>https://medium.com/datareply/data-harmonization-using-machine-learning-and-language-models-4e215da19e3f?source=rss-b58612057533------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e215da19e3f</guid>
            <dc:creator><![CDATA[Marina Sedinkina]]></dc:creator>
            <pubDate>Fri, 21 Jul 2023 10:19:26 GMT</pubDate>
            <atom:updated>2023-10-09T13:38:28.581Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction and Motivation</h3><p>In today’s data-driven world, organizations are accumulating vast amounts of information from diverse sources across multiple countries and regions. However, one significant challenge that arises in such scenarios is the inconsistency and lack of standardization in how data is tagged and labeled. This variability hinders the ability of data scientists to effectively utilize the data for building machine learning (ML) use cases, resulting in lost opportunities for valuable insights and actionable outcomes.</p><p>The conventional approach to tackling this challenge has been through rule-based Extract, Transform, Load (ETL) processes. However, these methods often require manual intervention and are highly dependent on explicit rules, making them less scalable and time-consuming. To overcome these limitations, an innovative and more efficient solution is needed — one that leverages <strong>the power of artificial intelligence (AI) and machine learning</strong>.</p><p>Let’s explore the key reasons why AI and ML techniques are the preferred choice in harmonizing data with multiple labels:</p><ol><li><strong>Scalability and Efficiency</strong>: Manual data harmonization processes are labor-intensive and time-consuming, especially when dealing with a large number of labels. Machine learning offers the potential to automate this process, significantly reducing the time and effort required to normalize the data.</li><li><strong>Adaptability to Changing Data</strong>: As companies expand their operations globally, the diversity of data sources, languages, and variations in label representation increases. Machine learning models can adapt to these variations and learn patterns from the data, making them robust and flexible in handling different labeling conventions.</li><li><strong>Improved Accuracy and Consistency</strong>: Manual harmonization processes are prone to human errors and inconsistencies, especially when dealing with a large number of labels. Machine learning models, on the other hand, can learn from the existing labeled data and apply statistical techniques to harmonize new labels automatically. This leads to improved accuracy, consistency, and reliability in the harmonized data.</li><li><strong>Language and Contextual Understanding</strong>: Labels in datasets may be written in different languages or represent similar concepts differently. Machine learning models can utilize Natural Language Processing (NLP) techniques to understand the semantics and context of the labels. This empowers companies to efficiently process and utilize data from diverse sources, regardless of the language barrier.</li><li><strong>Cost Reduction and Time Savings</strong>: Implementing an unsupervised data harmonization approach based on machine learning can result in significant cost savings for organizations. By automating the process, companies can reduce manual effort, increase efficiency, and free up valuable resources for other critical tasks.</li></ol><p>Data harmonization using machine learning holds tremendous potential for organizations facing the challenge of inconsistent and non-standardized labeling across diverse data sources. Let’s explore the construction of data harmonization models by utilizing an unsupervised approach using Natural Language Processing (NLP) techniques.</p><h3>Dataset Generation</h3><p>In order to simulate a data harmonization problem scenario, we will construct a dataset to showcase the challenges associated with harmonizing data sources. To accomplish this, we will utilize the powerful features and capabilities offered by <a href="https://wordnet.princeton.edu/">WordNet</a>. <strong>WordNet is an extensive lexical database that organizes words into semantic hierarchies</strong> and groups them into synsets based on shared meanings. WordNet captures the relationships between words, including synonyms, antonyms, hyponyms, hypernyms, and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PIEPsW37ZAqLAONLkq_b6w.png" /><figcaption>WordNet</figcaption></figure><p>These synsets serve as proxies for different labeling conventions or variations in how data is tagged, reflecting the challenges faced during data harmonization. With this simulated dataset, we can explore and develop unsupervised data harmonization approaches and evaluate the effectiveness of different machine learning models and techniques.</p><p>We are going to create a dataset by iterating through all the noun synsets available in WordNet, which comprises a total of 82,115 synsets.</p><pre>from nltk.corpus import wordnet<br>all_noun_synsets = list(wordnet.all_synsets(&#39;n&#39;))<br>print(len(all_noun_synsets))<br>&gt;&gt;&gt; 82115</pre><p>During each iteration, we extract all the synonyms associated with each synset. Subsequently, we filter and retain only the synsets with the highest number of synonyms, resulting in a subset of 1,000 synsets. Consequently, we obtain a comprehensive list of synonyms, with each synset containing a minimum of 6 and a maximum of 28 items.</p><p>For instance, consider the concept of “<em>noon</em>.” The synonyms associated with this concept include <em>“twelve_noon,” “high_noon,” “midday,” “noonday,” and “noontide.”</em> These synonyms exemplify the variety of terms that are captured within a synset, showcasing the range of linguistic expressions associated with a particular concept.</p><pre>#extract the synonyms (lemma names)<br>all_lemmas = [synset.lemma_names() for synset in all_noun_synsets]<br>most_synonyms = sorted(all_lemmas, key= lambda x: len(x), reverse = True)[:1000]<br>print(max([len(el) for el in most_synonyms]))<br>&gt;&gt;&gt; 28<br>print(min([len(el) for el in most_synonyms]))<br>&gt;&gt;&gt; 6<br>print(most_synonyms[-2])<br>&gt;&gt;&gt; [&#39;noon&#39;, &#39;twelve_noon&#39;, &#39;high_noon&#39;, &#39;midday&#39;, &#39;noonday&#39;, &#39;noontide&#39;]</pre><p>To ensure there are no overlaps among synonyms, we apply a filtering step to the synonyms. Specifically, we exclude any synonyms that appear more than once within our dataset. This filtering process guarantees that each synonym is unique and avoids redundancy in the data.</p><p>Thus, we create a <strong>dataset</strong> that maps each concept to its corresponding list of potential synonyms. This serves as a useful reference, enabling easy access and retrieval of the synonyms associated with a specific concept.</p><pre>dataset, existing = [], set()<br>for syn_list in most_synonyms:<br>    keep = []<br>    for syn in syn_list:<br>        if not syn in existing:<br>            keep.append(syn)<br>        existing.add(syn)        <br>    if keep:    <br>        dataset.append((keep[0], keep))<br>print(dataset[-2])<br>&gt;&gt;&gt; (&#39;noon&#39;, [&#39;noon&#39;, &#39;twelve_noon&#39;, &#39;high_noon&#39;, &#39;midday&#39;, &#39;noonday&#39;, &#39;noontide&#39;])</pre><p>Here are some additional examples from the dataset:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F4DxlodG966vE-VG-yu3Mw.png" /><figcaption>Snippet of the harmonization dataset created using WordNet</figcaption></figure><p>These examples provide a glimpse into the dataset, showcasing the variety of concepts and their corresponding synonyms. The dataset captures the diverse range of terms associated with different concepts, highlighting the challenges of data harmonization.</p><h3>Unsupervised (zero-shot) harmonization ML model</h3><p>Now, we can construct an unsupervised harmonization model utilizing a pre-trained<strong> </strong><a href="https://huggingface.co/sentence-transformers"><strong>Sentence Transformers</strong></a><strong> model</strong>. The model enables us to perform the following steps:</p><p>Firstly, we <strong>embed our labels</strong> by leveraging the capabilities of the Sentence Transformers model. This process involves representing each label as a dense vector that captures its semantic meaning and context.</p><p>Secondly, we <strong>store these label embeddings</strong>, employing a library such as FAISS for efficient storage and retrieval.</p><p>Finally, we proceed <strong>to normalize our synonyms by calculating the cosine similarity score</strong> between the vector representation of the label and the vector representation of each synonym. This similarity score quantifies the degree of semantic similarity between the label and each synonym. Consequently, we identify and select the label with the highest similarity score as the harmonized representation.</p><p>Now, let’s examine the results of applying this approach to the concept of “Dostoyevsky”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*xPX3WD6D1UMu0WWBWa2c1w.png" /><figcaption>The synonyms for the concept “Dostoyevsky” are predicted to be “Dostoyewsky”.</figcaption></figure><p>Here is the code snippet to perform the classification:</p><pre>#choose the model<br>from sentence_transformers import SentenceTransformer<br>def generate_embedding(model, sentences):<br>    return model.encode(sentences, batch_size=len(sentences), show_progress_bar=True)<br><br>model = SentenceTransformer(&#39;sentence-transformers/paraphrase-mpnet-base-v2&#39;)<br><br>#create index<br>import faiss<br>import numpy as np<br>def create_index(labels):  # normalization function<br>    # normalize with faiss: 1. embed labels<br>    gold_vectors = generate_embedding(model, labels) <br>    print(&quot;shape of vectors:&quot;, gold_vectors.shape)<br>    # normalize with faiss: 2 build the index with labels<br>    gold_vectors_norm = gold_vectors / np.expand_dims(np.linalg.norm(gold_vectors, axis=1), axis=1)<br>    index = faiss.index_factory(gold_vectors.shape[1], &quot;Flat&quot;, faiss.METRIC_INNER_PRODUCT)<br>    index.add(gold_vectors_norm)<br>    return index<br><br>#set of labels<br>labels = list(dict(dataset).keys())<br>index = create_index(labels)<br><br>#run inference for test words<br>test_words = [&#39;Dostoyevsky&#39;, &#39;Dostoevski&#39;, &#39;Dostoevsky&#39;, &#39;Feodor_Dostoyevsky&#39;, <br>              &#39;Fyodor_Dostoyevsky&#39;, &#39;Feodor_Dostoevski&#39;, &#39;Fyodor_Dostoevski&#39;, <br>              &#39;Feodor_Dostoevsky&#39;, &#39;Fyodor_Dostoevsky&#39;, &#39;Feodor_Mikhailovich_Dostoyevsky&#39;, <br>              &#39;Fyodor_Mikhailovich_Dostoyevsky&#39;, &#39;Feodor_Mikhailovich_Dostoevski&#39;, <br>              &#39;Fyodor_Mikhailovich_Dostoevski&#39;, &#39;Feodor_Mikhailovich_Dostoevsky&#39;, <br>              &#39;Fyodor_Mikhailovich_Dostoevsky&#39;]<br>test_embeddings = generate_embedding(model, test_words)<br>test_embeddings_norm = test_embeddings / np.expand_dims(<br>    np.linalg.norm(test_embeddings, axis=1), axis=1<br>)<br>#predictions for test words<br>cos_dist, indices = index.search(test_embeddings_norm, 1)<br>cos_dist = cos_dist.flatten()<br>indices = indices.flatten()<br>threshold = 0.8<br>for i, idx in enumerate(indices):<br>    cos_sim = round(cos_dist[i], 3)<br>    print(cos_sim, test_words[i],  &quot;-&gt;&quot;, labels[idx])<br>&gt;&gt;&gt;<br>  1.0 Dostoyevsky -&gt; Dostoyevsky<br>  0.726 Dostoevski -&gt; Dostoyevsky<br>  0.954 Dostoevsky -&gt; Dostoyevsky<br>  0.83 Feodor_Dostoyevsky -&gt; Dostoyevsky<br>  0.856 Fyodor_Dostoyevsky -&gt; Dostoyevsky<br>  0.586 Feodor_Dostoevski -&gt; Dostoyevsky<br>  0.724 Fyodor_Dostoevski -&gt; Dostoyevsky<br>  0.81 Feodor_Dostoevsky -&gt; Dostoyevsky<br>  0.833 Fyodor_Dostoevsky -&gt; Dostoyevsky<br>  0.794 Feodor_Mikhailovich_Dostoyevsky -&gt; Dostoyevsky<br>  0.794 Fyodor_Mikhailovich_Dostoyevsky -&gt; Dostoyevsky<br>  0.623 Feodor_Mikhailovich_Dostoevski -&gt; Dostoyevsky<br>  0.666 Fyodor_Mikhailovich_Dostoevski -&gt; Dostoyevsky<br>  0.78 Feodor_Mikhailovich_Dostoevsky -&gt; Dostoyevsky<br>  0.789 Fyodor_Mikhailovich_Dostoevsky -&gt; Dostoyevsky</pre><p>For the example of “Dostoyevsky,” we achieved a 100% accuracy. However, when running predictions for all the labels and comparing them to our gold labels, we anticipate encountering numerous challenging problems:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OX0GftoSMj-SnfPQ-UUxDg.png" /><figcaption>Set of challenging synonyms</figcaption></figure><p>When we ran the model to predict all 1,000 labels, we obtained an accuracy of approximately 43%. This performance can be considered relatively poor as no supervision was utilized, and some labels pose challenges for accurate prediction using only a pre-trained model. In an attempt to improve the results, we narrowed down the prediction to a smaller set of 162 labels that are relatively easier to predict. With this subset, we achieved an accuracy of around 53%. However, despite this improvement, we are still not satisfied with the results and acknowledge the need for further enhancements in the harmonization model.</p><h3>Unsupervised (few-shot) harmonization ML model.</h3><h4>Language models are also few-shot learners!</h4><p>We will utilize the <a href="https://github.com/huggingface/setfit"><strong>SetFit</strong></a> model, which leverages <strong>Few-shot Learning with Sentence Transformers</strong>, enabling high accuracy even with limited labeled data. An intriguing fact about this model is its <strong>competitiveness when compared to fine-tuning RoBERTa Large</strong> on a full training set of 3,000 examples. We are eager to explore its potential for our harmonization task.</p><p>To train the ML model, we <strong>only require 8 samples per class</strong>, making it a few-shot learning approach. To adapt our dataset for training, we will treat the problem as a <strong>multi-class classification task</strong> and make slight modifications accordingly.</p><p>An additional advantage of SetFit is its <strong>multilingual support</strong>. It can be utilized in conjunction with any Sentence Transformer available on the Hub, including multilingual variants. This feature proves beneficial in the context of the harmonization problem, especially <strong>when dealing with labels present in multiple languages</strong>.</p><p>By harnessing the capabilities of SetFit and its multilingual support, we aim to enhance the performance and effectiveness of our harmonization task, utilizing a few-shot learning approach with limited labeled data.</p><p>Let’s proceed with modifying our dataset by constructing training, evaluation, and test data. In this particular experiment, we will work with a total of 162 labels. To split our synonym list for each label into training and evaluation sets, we will assign the first 8 synonyms for training and the last 8 synonyms for evaluation.</p><p>It is important to note that the size of the synonym list may vary, resulting in some overlap between the evaluation set and the training set. This scenario closely reflects real-world situations where there might be instances where evaluation samples appear in the training set. However, to mimic real-world conditions accurately, it is crucial to include samples in the evaluation set that have never been encountered by the model before.</p><p>For testing, we will utilize the entire dataset, encompassing the labels included in both the training and evaluation sets. This approach aims to simulate real-world scenarios where the model encounters both known labels (from training) and unseen labels during inference. It is essential to ensure that the model can handle normalizing both familiar and previously unseen labels effectively.</p><p>Taking the example of “<em>Dostoevsky</em>,” we observe only one overlap between the training and evaluation sets. Specifically, “<em>Feodor_Dostoevsky</em>” appears in both the training and evaluation sets.</p><pre>from datasets import Dataset<br>train_dataset = Dataset.load_from_disk(&quot;my_dict_train&quot;)<br>eval_dataset = Dataset.load_from_disk(&quot;my_dict_eval&quot;)<br><br>train_dataset<br>&gt;&gt;&gt;<br>Dataset({<br>    features: [&#39;idx&#39;, &#39;sentence&#39;, &#39;label&#39;],<br>    num_rows: 1071<br>})<br><br>train_dataset.data.to_pandas().head(8)<br>&gt;&gt;&gt; idx sentence label<br>0 Dostoyevsky Dostoyevsky<br>1 Dostoevski Dostoyevsky<br>2 Dostoevsky Dostoyevsky<br>3 Feodor_Dostoyevsky Dostoyevsky<br>4 Fyodor_Dostoyevsky Dostoyevsky<br>5 Feodor_Dostoevski Dostoyevsky<br>6 Fyodor_Dostoevski Dostoyevsky<br>7 Feodor_Dostoevsky Dostoyevsky<br><br>eval_dataset.data.to_pandas().head(8)<br>&gt;&gt;&gt; idx sentence label<br>0 Feodor_Dostoevsky Dostoyevsky<br>1 Fyodor_Dostoevsky Dostoyevsky<br>2 Feodor_Mikhailovich_Dostoyevsky Dostoyevsky<br>3 Fyodor_Mikhailovich_Dostoyevsky Dostoyevsky<br>4 Feodor_Mikhailovich_Dostoevski Dostoyevsky<br>5 Fyodor_Mikhailovich_Dostoevski Dostoyevsky<br>6 Feodor_Mikhailovich_Dostoevsky Dostoyevsky<br>7 Fyodor_Mikhailovich_Dostoevsky Dostoyevsky</pre><p>First, we load the SetFit model from the Hub, which provides us with the pre-trained weights and architecture necessary for few-shot learning. We then instantiate a Trainer object, which handles the training process and model evaluation.</p><p>Next, we train the model using our modified dataset, which includes the training and evaluation sets. The Trainer orchestrates the training procedure, fine-tuning the SetFit model on our specific task of data harmonization.</p><p>Once the model is trained, we can utilize it for inference. Let’s take the example of predicting the label for the synonym “F<em>yodor_Mikhailovich_Dostoevsky</em>”. We input this synonym into the trained model, and it will output the predicted label associated with it.</p><pre>from setfit import SetFitModel, SetFitTrainer<br>from sentence_transformers.losses import CosineSimilarityLoss<br><br>model = SetFitModel.from_pretrained(&quot;sentence-transformers/paraphrase-mpnet-base-v2&quot;)<br><br>trainer = SetFitTrainer(<br>    model=model,<br>    train_dataset=train_dataset,<br>    eval_dataset=eval_dataset,<br>    loss_class=CosineSimilarityLoss,<br>    metric=&quot;accuracy&quot;,<br>    batch_size=16,<br>    num_iterations=20, # The number of text pairs to generate for contrastive learning<br>    num_epochs=1, # The number of epochs to use for contrastive learning<br>    column_mapping={&quot;sentence&quot;: &quot;text&quot;, &quot;label&quot;: &quot;label&quot;} # Map dataset columns to text/label expected by trainer<br>)<br>trainer.train()<br><br># Run inference<br>preds = model([&quot;Fyodor_Mikhailovich_Dostoevsky&quot;])<br>preds <br>&gt;&gt;&gt; array([&#39;Dostoyevsky&#39;], dtype=&#39;&lt;U38&#39;)</pre><p>Now, let’s proceed with running the inference for all synonyms across our 162 labels and calculate the corresponding accuracy:</p><pre>total_words = [w for gold, words in dataset for w in words]<br>gold_labels = [gold for gold, words in dataset for _ in words]<br><br># Run inference<br>preds = model(total_words)<br><br>#Calculate accuracy<br>from sklearn.metrics import accuracy_score<br>acc = accuracy_score(gold_labels, preds)<br>print(acc)<br>&gt;&gt;&gt; 0.9270568278201866</pre><p>The results demonstrate significant improvement, indicating a substantial enhancement in performance.</p><h3>Supervised harmonization ML model</h3><p>Finally, it’s important to mention the supervised approach, particularly when training data is available. This approach can <strong>yield high accuracy</strong>; however, it <strong>necessitates a sufficient amount of training data</strong>. In this scenario, the problem is treated in a manner similar to few-shot classification, where we address <strong>a multi-class classification task</strong> involving either 162 or 1000 labels to predict. Due to the larger number of labels, this approach is often referred to as “Extreme classification”.</p><p>One advantage of the supervised approach is the ability to utilize both textual data and the values associated with the labels as features for the model. This means that numerical features can be extracted and incorporated into the model, enabling the development of a powerful model that can learn not only from synonyms but also from the characteristics of the labels themselves. When training data is readily available, this approach is highly recommended for achieving optimal results.</p><p>By leveraging the supervised approach, organizations can benefit from a robust model that exploits both textual and numerical features, ensuring accurate predictions and comprehensive insights.</p><h3>Summary</h3><p>Data harmonization is a critical task in organizations where data from various sources, regions, or countries need to be normalized to ensure consistency and enable effective analysis. Traditional rule-based and ETL approaches are time-consuming and not scalable for large datasets, calling for more advanced machine learning (ML) techniques.</p><p>Unsupervised ML approaches, such as leveraging NLP techniques and semantic similarities, offer automated solutions for data harmonization. By using language models and similarity scores, labels and synonyms can be harmonized, enabling effective data normalization.</p><p>Few-shot learning models, like SetFit, excel in scenarios with limited labeled data. These models achieve high accuracy by leveraging the concept of transfer learning and adapting to new label sets with minimal examples.</p><p>Supervised ML approaches, on the other hand, are suitable when training data is available. They treat data harmonization as a multi-class classification problem, and by incorporating textual and numerical features, these models can learn from both synonyms and label characteristics, resulting in powerful models.</p><p>Additionally, multilingual language models can be advantageous in data harmonization tasks where labels exist in multiple languages, allowing for cross-lingual harmonization.</p><p>Choosing the appropriate ML approach for data harmonization depends on the specific requirements, available data, and scalability needs. By leveraging ML techniques, organizations can automate the harmonization process, improve data quality, and enhance decision-making based on harmonized and normalized data.</p><p>Data harmonization, the process of standardizing and unifying diverse datasets, holds immense potential for <strong>addressing the challenges of data compliance and standardization.</strong> By automating the process of standardization, machine learning can reduce manual effort, enhance data accuracy, and streamline regulatory reporting. As organizations face increasing demands for data compliance, leveraging machine learning for data harmonization can greatly reduce the effort required to become standards compliant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e215da19e3f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datareply/data-harmonization-using-machine-learning-and-language-models-4e215da19e3f">Data Harmonization using Machine Learning and Language Models</a> was originally published in <a href="https://medium.com/datareply">DataReply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[History of GPT-4]]></title>
            <link>https://medium.com/datareply/history-of-gpt-4-a71d4705b3d2?source=rss-b58612057533------2</link>
            <guid isPermaLink="false">https://medium.com/p/a71d4705b3d2</guid>
            <dc:creator><![CDATA[Marina Sedinkina]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 15:57:26 GMT</pubDate>
            <atom:updated>2023-04-04T15:57:26.869Z</atom:updated>
            <content:encoded><![CDATA[<h3>In the beginning was a Word Embedding, the path to the human-level performance.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kEe6kPG83z3kwW4NEgUe0w.png" /><figcaption>NLP Evolution</figcaption></figure><h3>Introduction</h3><p><a href="https://openai.com/blog/chatgpt">ChatGPT</a> is the latest milestone in the development of language-based systems — this is a Large Language Model (LLM) which achieves strong performance from no (zero-shot) or only a few examples (few-shot) — something which previous NLP systems struggled to do. The model was created by OpenAI, artificial intelligence research laboratory. It can be accessed via an API interface, allowing users to try it on any language (not limited to English) task from content generation to semantic search and classification. Despite its name, <strong>ChatGPT has not been primarily used as a chatbot. Its dialog ability serves as the user interface to the underlying Large Language Model.</strong></p><p>This model was <strong>trained with humans in the loop</strong> — using a dialogue dataset where human AI trainers provided conversations in which they played both sides — the user and an AI assistant. Thus, it is much <strong>better at following user intentions</strong> than the original GPT-3 model while also making them more truthful and less toxic. Furthermore, ChatGPT can intelligently answer follow-up questions and recognize if a question is offensive or vulgar. In March 2023, OpenAI released an even better model than ChatGPT — <a href="https://openai.com/research/gpt-4%7D">GPT-4</a>. <strong>It is a large <em>multimodal</em> model which exhibits human-level performance on various professional and academic benchmarks and supports any computer vision tasks as well. </strong>It provides best-ever results on factuality, steerability, and refusing to go outside of guardrails. Text input availability of GPT-4 is now available via ChatGPT.</p><p>The surprisingly strong capabilities of ChatGPT have raised many interests, as well as concerns: people are curious about ChatGPT capabilities and are worried about the potential risks. Probably the first and the most interesting thing you always wanted to know about ChatGPT (but were afraid to ask) — <strong>which algorithm is actually used behind ChatGPT/GPT-4 that made this model so powerful?</strong> In this post, we are going to talk about <strong>how the Natural Language Processing (NLP) methods evolved over time</strong> and to reveal why ChatGPT became so successful.</p><h3>NLP Evolution</h3><p>Representation of words as continuous vectors has always been a key approach for NLP systems. These representations, also known as <em>word embeddings</em>, are high dimensional vector space representations that encode the semantics of words. The models used to obtain these representations are based on the idea of the distributional hypothesis, which suggests that the meaning of the word can be induced from <em>a large number of texts</em>. Up until 2018, a typical NLP workflow consisted of constructing the word embeddings (algorithms like Word2Vec) and using them as input features for various NLP applications. Let’s recap what is Word2Vec before we talk about what has now changed.</p><h4>- Word Embeddings, 2013</h4><p><a href="https://arxiv.org/abs/1301.3781">Word2vec</a> is the one of the first successful attempts to encode the semantics of words. This is an algorithm to represent words as vectors in a way that it captures semantics as well as syntactic and grammatical relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*o23oOpPRNvlmeEnyuzviGA.png" /><figcaption>Word embeddings are high dimensional vector space representations<br>of words that can capture semantical meaning.</figcaption></figure><p>The algorithm was trained to predict the word based on the context words in a sentence (Continuous Bag-of-Words Model), or to predict context words given the current word (Continuous Skip-gram Model). Simple algebraic operations can be performed afterwards on the word vectors , e.g., using cosine similarity we can see for example that the word <em>“France”</em> is similar to <em>“Italy”, </em>and the<em> </em>word <em>“big”</em> is similar to <em>“bigger”</em> or <em>“small”</em> is similar to <em>“smaller”</em>. Somewhat surprisingly, it was shown that vector(<em>”King”</em>) — vector(<em>”Man”</em>) + vector(<em>”Woman”</em>) results in a vector that is closest to the vector representation of the word “Queen”. Word vectors with such semantic relationships improved many NLP applications, such as machine translation, information retrieval and question answering systems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M-D4Q6_Bg8QHmFGFmvW5SQ.png" /></figure><p>The word vectors are usually pre-trained on large amounts of text data (such as Wikipedia or Common Crawl) and are used in NLP applications as input features in a range of different downstream tasks.<br>One of the main drawbacks of this approach is that these embeddings are <strong>static </strong>— the word has a fixed vector representation containing all possible ambiguous word meanings presented in the in-domain data (e.g., Wikipedia). It means these word embeddings might not be applicable for other domains. In the Figure above on the right, Word2Vec was trained on Wikipedia with the nearest neighbors of the word <em>“God”</em> being <em>“Jesus”</em> and <em>“Almighty”</em>, while Word2Vec trained on financial corpus has the nearest neighbors <em>“war”</em> and <em>“violence”</em> of the same word <em>“God”</em> (Figure above on the left). <a href="https://arxiv.org/abs/2006.14209">In finance, this word is mostly used in the phrase “act of God”, indicating that the company cannot fulfill obligations due to unforeseen occurrences</a>. Thus, this word has a completely different meaning in the financial domain — it is considered to be negative. To take into account the domain related meanings, one needs to train these domain-specific word embeddings using a large amount of unsupervised data. This is another drawback of this approach — the data is not always available, especially in industrial and business real-world scenarios.</p><h4>- Contextualized Word Embeddings, 2018</h4><ul><li><a href="https://arxiv.org/abs/1802.05365"><strong>ELMo</strong></a><strong> — based on LSTM</strong><br>In 2018, researchers have finally found an answer to the question how to embed a word solely based on the context it’s used in — <strong>contextualized (dynamic) word embeddings</strong>. These embeddings allow a word to have different vector representations depending on the context it is used in (e.g., word vectors of the word <em>“bank”</em> are different in phrases <em>“sitting on a river bank”</em> and <em>“money in a bank”</em>). The first algorithm to generate contextualized word embeddings is known as <strong>ELMo (Embeddings from Language Model) based on a bi-directional LSTM architecture</strong>. This algorithm was trained to predict the next word in a sequence of words — a task called <strong>Language Modeling</strong>.</li></ul><h4><strong>- Improving Contextualized Word Embeddings since 2018</strong></h4><p>In the year 2018, <a href="https://arxiv.org/abs/1706.03762">the Transformer (“attention is all you need”)</a> architecture was released allowing to achieve state-of-the-art performance in machine translation task.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*J0k9UaVEj1nJ0Aru9R03_g.png" /><figcaption>Transformer architecture</figcaption></figure><p>Transformer is an encoder-decoder architecture — the encoder maps an input sequence to a sequence of continuous representations, and the decoder then generates an output sequence of symbols one element at a time. At each step the model consumes the previously generated symbols as additional input when generating the next. Each encoder layer has two sub-layers. The first is <strong>a multi-head self-attention mechanism</strong>, and the second is a simple, position-wise fully connected feed-forward network. The decoder has the same structure plus a third sub-layer, which performs multi-head attention over the output of the encoder. A multi-head self-attention mechanism is the main and the most important component in this architecture — as the model processes each word, self-attention looks at other positions in the input sequence, finds the relevant words and uses this information to encode the currently processing word. If we consider the sentence <em>“The cat sat on a mat because it was too tired.”</em>, we will associate <em>“it”</em> with <em>“cat”</em> and not with <em>“mat”</em>. This is exactly what self-attention does — it allows to associate <em>“it”</em> with <em>“cat”</em>, when the model is processing the word <em>“it”</em>. Multi-head attention further improves the architecture — it allows the model to “jointly attend to information from different representation subspaces at different positions”. In other words, as we process the word <em>“it”</em>, one attention head will be focusing on the <em>“cat”</em>, while another might be focusing on <em>“tired”</em> — as a result, <em>“it”</em> will contain both <em>“cat”</em> and <em>“tired”</em> in its representation.</p><p>This architecture based on an <em>attention mechanism</em> became a breakthrough in Natural Language Processing — models based on Transformer outperformed previous state-of-the-art on a range of tasks such as classification and question answering.</p><ul><li><strong>GPT — based on Transformer Decoder</strong></li></ul><p>Generative Pre-Training (GPT) is the autoregressive (predict the next word only) generative model based on the <strong>Transformer</strong> architecture. <br>Just a decoder of the Transformer is used since it’s a natural choice for language modeling (predicting the next word only). Such a model can perform all generative tasks — translation, summarization, or question answering. Besides, the pre-trained model can be further fine-tuned on a downstream task such as sentence classification — and this is how <strong>transfer learning to downstream tasks </strong>was born. Since the language model is pre-trained on large unlabeled text corpora, it already knows a lot about the language: it captures many language relevant aspects, such as long-term dependencies or hierarchical relations. This knowledge can be easily transferred to the downstream task by simply <strong>fine-tuning</strong> all pre-trained parameters using task specific datasets — a very well known approach in NLP to adapt the language model for a given task.</p><ul><li><a href="https://d4mucfpksywv.cloudfront.net/better-language-models/language-models.pdf"><strong>GPT-2</strong></a><strong> 2018</strong></li></ul><p>GPT-2 is an improved version of the GPT model where the data for pre-training increased to 40GB, and the total number of model parameters also increased from 117M (GPT) to 1.5B (GPT-2). As a result, the model achieved state of the art results on a set of different language modeling tasks (summarization, translation, question answering) in a zero-shot setting — using zero training examples, i.e., without a dedicated training dataset for each task, without any parameter or architecture modification (no fine tuning anymore). These outstanding results confirmed the fact that language models are unsupervised multitask learners — a language model with sufficient capacity learns to infer and perform the tasks demonstrated in natural language. This finding has laid t<strong>he foundation<br>for building NLP systems which learn to perform tasks from natural language instructions (prompts)</strong> — either in a zero-shot setting with no training data or in a few-shot setting when just a few demonstrations are presented to the model.</p><ul><li><a href="https://arxiv.org/pdf/2005.14165.pdf"><strong>GPT-3</strong></a><strong> 2020</strong></li></ul><p>GPT-3 is the next generation of pre-trained models that <strong>scales up language models greatly</strong> — it has 175 billion parameters!!! The model is only given a natural language instruction describing the task and this is often enough to match the performance of state-of-the-art systems such as translation and question-answering. This is very similar to what human do — they do not require large supervised datasets to learn most language tasks — a brief instruction in natural language is often enough to enable a human to perform a new task. The model performs even better in a few-shot learning setup and also achieves strong qualitative performance at tasks defined on-the-fly. Scaling up the language model plays a very important role here — it allowed to improved task-agnostic and few-shot performance, even reaching competitiveness with prior state-of-the-art fine-tuning approaches.</p><ul><li><strong>InstructGPT 2021</strong></li></ul><p>Despite the strong performance of GPT-3, the model sometimes produces untruthful, toxic or biased outputs. The model can also make up facts and generate sexual and violent content. For example, occupations demonstrating higher levels of education such as legislator, banker, or professor emeritus are heavily male-leaning in GPT-3, while occupations that are more likely to be followed by female identifiers (woman, female etc.) include midwife, nurse, receptionist, housekeeper etc. To improve the model, OpenAI introduced <strong>InstructGPT, a model trained with humans in the loop</strong>. It uses a technique called reinforcement learning from human feedback (RLHF) and the prompts submitted to the API as training data. In addition, it uses <strong>human feedback: demonstrations of the desired model behavior</strong>. As a result, the new model is much better at following instructions than GPT-3, it <strong>makes up facts less often, and shows a small decrease in toxic output generation</strong>.</p><ul><li><strong>ChatGPT November 2022</strong></li></ul><p>ChatGPT is <strong>a sibling model to InstructGPT</strong>, which is trained to follow an instruction in a prompt and provide a detailed response. This model was also trained using RLHF and the InstructGPT dataset, which was transformed into a dialogue format. In addition, <strong>a new dialogue dataset was used</strong> — human AI trainers provided conversations in which they played both sides — the user and an AI assistant, wheares the trainers had access to the model-written suggestions to compose their responses quicker. As a result, a dialogue format made it possible for ChatGPT to answer follow-up questions, admit its mistakes, challenge incorrect premises, and reject inappropriate requests.</p><ul><li><a href="https://cdn.openai.com/papers/gpt-4.pdf"><strong>GPT-4</strong></a><strong> March 2023</strong></li></ul><p>GPT-4 is the latest large <strong><em>multimodal</em> model that has unprecedented scale of compute and data</strong>. It accepts both images and text inputs and responds with textual outputs. It <strong>was iteratively aligned using lessons from ChatGPT</strong>, resulting in performance exhibiting human-level on various professional and academic benchmarks. OpenAI does not reveal the details about the architecture (including model size), hardware, training compute, dataset construction, training method, or similar. Instead, it performs an extensive <a href="https://arxiv.org/pdf/2303.12712.pdf">study on capabilities of GPT-4</a> — a set of experiments to test GPT-4’s language, coding, mathematical, and computer vision abilities. The main takeaway from this study —<strong> in addition to language tasks, GPT-4 can solve now very difficult and novel tasks that span mathematics, coding, computer vision, medicine, law, psychology and more, without needing any special prompting. </strong>GPT-4 tends to be more reliable, creative, and able to handle much more nuanced instructions. It passes a bunch of exams that were originally designed for humans — in psychology, chemistry, history, literature, biology, etc. It passes mock technical interviews on LeetCode. It better translates low-resource languages. It generates images and describes them in natural language. Most importantly, it also incorporates an additional security layer — the model refuses harmful requests e.g., on how to synthesize dangerous chemicals. One general hypothesis for the remarkable intelligence achieved by GPT-4 is that “<a href="https://arxiv.org/pdf/2303.12712.pdf">the large amount of data forces neural networks to learn generic and useful “neural circuits”, while the large size provides enough redundancy and diversity for the neural circuits to specialize and fine-tune to specific tasks</a>. Given the breadth and depth of GPT-4’s capabilities, this LLM could reasonably be viewed as <strong>an early version of an artificial general intelligence (AGI) system.</strong></p><ul><li><strong>What is next?</strong></li></ul><p>The capacity of GPT-3 made it possible to develop a broad set of skills and pattern recognition abilities at training time, and then to use those abilities at inference time to rapidly adapt to or recognize the desired task. Larger models like GPT-3 also showed improved ability to learn a task from contextual information (few-shot learning). This was the reason why<br><strong>increasing capacity has become a new trend in language modeling</strong> — each increase has brought improvements in downstream NLP tasks and this is how a new era of <strong>Large Language Models (LLMs)</strong> has begun. In 2021, NVIDIA and Microsoft developed <strong>Megatron-Turing</strong>, 530-billion-parameter LLM for reading comprehension and natural language inference. In 2022, HuggingFace introduced <strong>BLOOM</strong>, an open-access multilingual LLM (176B) that is able to generate text in 46 natural languages. Companies are increasingly starting to build LLMs and offering them mostly only via API access. In addition, the latest large language model — OpenAI’s GPT-4 — has no information on its model architecture, training data, training hardware, or hyperparameters. <strong>It becomes more and more difficult and expensive to access these models.</strong> It requires millions of dollars to build such a model and months of training time, resulting in<strong> a large carbon footprint</strong>. Maintaining and deploying large language models becomes also difficult and expensive. That is why, more and more researchers ask a question —<strong> It’s just size that matters? And the answer is no! </strong>There are already successful attempts to build <strong>smaller scale models which are also few-shot learners</strong> (<a href="https://aclanthology.org/2021.naacl-main.185.pdf">Pattern-Exploiting Training (PET)</a>) that even don’t require prompting (<a href="https://arxiv.org/abs/2209.11055">SetFit (Sentence Transformer Finetuning)</a>). They also achieve high accuracy with little labeled data but they are faster to train and run inference with. They are open source and easier to maintain and to deploy. Wouldn’t it be better if we start looking into something that is much “greener” in their parameter count? Hopefully, soon we will see more work in the area of <a href="https://dl.acm.org/doi/10.1145/3381831">Green AI</a> which focuses on reducing the amount of compute while improving the model efficiency.</p><p>ChatGPT and LLMs revolutionized NLP. They will no doubt have <strong>significant social and societal influences</strong>. We may witness the development of numerous applications across major sectors such as healthcare, education, engineering, and the arts and sciences. Specifically, we will see how the system can diagnose diseases, discover new molecules, teach students, and argue about challenging topics in interactive sessions. This suggests a larger trend that <strong>AI systems could complement or even displace human workers</strong>. The scope of tasks that are suitable for automation by AI may expand considerably. Along with the potential benefits, AI also poses potential risks to society, such as generating harmful or fake information, disinformation, or cyberattacks against computing infrastructure. This will probably push a new direction in research — AI-generated content detection. Another possible research direction would be the development of smaller scale models that aim to improve model efficiency while decreasing their carbon footprint. While LLMs carry potential risks and have a large carbon footprint, they represent <strong>an exciting opportunity for innovation that has the potential to transform our lives</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a71d4705b3d2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/datareply/history-of-gpt-4-a71d4705b3d2">History of GPT-4</a> was originally published in <a href="https://medium.com/datareply">DataReply</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>