<?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 Rabia Eda Yılmaz on Medium]]></title>
        <description><![CDATA[Stories by Rabia Eda Yılmaz on Medium]]></description>
        <link>https://medium.com/@rabiaedayilmaz?source=rss-779b7e5cea5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*7jOnUWOi3BO3BvB9A9o5WA.jpeg</url>
            <title>Stories by Rabia Eda Yılmaz on Medium</title>
            <link>https://medium.com/@rabiaedayilmaz?source=rss-779b7e5cea5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 23:09:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rabiaedayilmaz/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[Manga Panel Arama Motoru: Görsel Benzerlik, Metinle Rerank ve VLM ile Açıklama]]></title>
            <link>https://medium.com/@rabiaedayilmaz/manga-panel-arama-motoru-g%C3%B6rsel-benzerlik-metinle-rerank-ve-vlm-ile-a%C3%A7%C4%B1klama-6a326a400842?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a326a400842</guid>
            <category><![CDATA[rags]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[multimodal-rag]]></category>
            <category><![CDATA[vlm]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Fri, 29 Aug 2025 15:07:37 GMT</pubDate>
            <atom:updated>2025-09-04T20:47:04.716Z</atom:updated>
            <content:encoded><![CDATA[<p>Bu yazıda <em>Frieren: Beyond Journey’s End</em> mangasının ilk cildini (vol 01) kullanarak, panel düzeyinde benzer sahneleri arayabilen ve seçili bir panele metinsel sorular yöneltebileceğiniz çok modlu (multimodal) bir sistem geliştirme sürecimi anlatacağım. Amacım; hem görsel hem metinsel sorgularla manga içinde hızlı ve anlamlı arama yapabilmek, hem de görseller üzerine açıklama üretebilen güçlü bir yapay zeka (VLM) entegrasyonu sağlamak oldu.</p><p>Örnek olarak “What is the scene where Frieren and Fern discovered the statue of Himmel?” diye sorduğumuzda, ilgili mangadaki sayfayı bulabilmek istiyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRbKIgkf4cRca1RjPPhuaQ.png" /><figcaption>Görsel 1: Hazırladığım Sistemde Soruya Cevaben Getirilen Sayfalar</figcaption></figure><h3>Görsel İçerikte Arama Yöntemleri Arasından ve Multimodal RAG</h3><p>Bilgiye dayalı görsel arama sistemleri geliştirirken birkaç farklı yaklaşım denenebilir. Her birinin avantajları ve sınırları vardır. Bu projede neden <em>Multimodal Retrieval-Augmented Generation (RAG)</em> mimarisini tercih ettiğimi anlamak için bu alternatifleri ve RAG’in sunduğu farkı net biçimde ortaya koymak gerekiyor.</p><h4>1. Anahtar Kelime (Keyword) Tabanlı Arama</h4><p>En basit yaklaşım, görsellerle ilişkili metinsel açıklamalar (örneğin OCR çıktısı, caption, etiketler) üzerinden klasik anahtar kelime eşleşmesi yapmaktır.</p><p><strong>Sorun:</strong></p><ul><li>Manga gibi çizgi romanlarda çoğu panelde metin bulunmaz veya yetersizdir.</li><li>OCR hataları ve konuşma balonlarının eksikliği aramayı boşa düşürür.</li><li>Görsel içeriğe dayalı sahneleri tanımlamak mümkün olmaz.</li></ul><h4>2. Görsel Özellik Benzerliği (CNN / CLIP tabanlı k-NN)</h4><p>Bu yöntemde, her görsel embedding vektörüne dönüştürülür ve sorgu görseliyle en yakın komşular (k-NN) seçilir.</p><p><strong>Avantaj:</strong> Hızlı ve metinden bağımsızdır.</p><p><strong>Sorun:</strong></p><ul><li>Kullanıcıdan gelen <em>metinsel</em> sorgulara cevap veremez.</li><li>Görsel benzerlik “semantik yakınlık” anlamına gelmeyebilir (örneğin görselin kompozisyonu benzer ama anlamı farklı olabilir).</li><li>Her zaman bağlam bilgisi eksik kalır.</li></ul><h4>3. Caption Generation + Text RAG</h4><p>Bir diğer yaklaşım, her panele otomatik açıklama (caption) üretip bu metinleri klasik metinsel RAG sistemine sokmaktır.</p><p><strong>Avantaj:</strong> Text-text retrieval mimarileri doğrudan kullanılabilir.</p><p><strong>Sorun:</strong></p><ul><li>Görsel caption modelleri sınırlı ve hataya açıktır.</li><li>Aynı panel için farklı kullanıcılar farklı tanımlar yazabilir.</li><li>Bu yöntemde arama kalitesi doğrudan caption kalitesine bağlıdır.</li></ul><h4>4. Multimodal RAG</h4><p>Bu projede uyguladığım <strong>Multimodal RAG</strong>, hem görsel hem metin embed’lerini aynı vektör uzayında işleyen bir sistemdir.</p><ul><li>Kullanıcı ister görsel yükleyebilir, isterse serbest metinle bir sahneyi tarif edebilir</li><li>Her iki durumda da aynı embedding alanında arama yapılır.</li></ul><p><strong>Neden Avantajlı?</strong></p><ul><li>Görseli <em>doğrudan</em> anlayabilen bir sistem kurmuş oluruz (caption’a ihtiyaç duymadan).</li><li>Metinsel sorgular da semantik olarak gömülür ve görsellerle karşılaştırılabilir.</li><li>Geri getirme işlemi sadece şekilsel değil, anlam düzeyinde yapılır.</li><li>Sonuçları daha da rafine etmek için bir reranker (MaxSim, ColBERT) entegre edilebilir.</li></ul><p>Bu nedenle, <em>hem metinsel açıklamaları olan hem de sadece görselle ifade edilen sahneleri desteklemek için</em>, Multimodal RAG mimarisi bu proje için en uygun seçenekti.</p><p>Ayrıca, VLM (Vision Language Model) entegrasyonu ile sadece panel bulmakla kalmayıp, bu panelleri anlamlandırmak ve açıklamak da mümkün hale geldi.</p><h3>Mimarinin Genel Hatları</h3><p>Projenin genel akışını şu şekilde tasarladım:</p><ol><li><strong>PDF’ten Görsellere</strong></li></ol><p>Her manga cildini, sayfa başına 1 PNG olacak şekilde parçalayarak temel görsel veri setini oluşturdum.</p><p>2. <strong>Görsel Embedding (Jina v4)</strong></p><p>Sayfa görselleri, Jina&#39;nın çok modlu embedding modeliyle 1024 boyutlu vektörlere dönüştürüldü.</p><p><strong>3. Vektör Veritabanı (Qdrant)</strong></p><p>Tüm vektörler volume, page_number, image_path gibi payload’larla Qdrant üzerinde depolandı.</p><p><strong>4. Benzerlik Arama</strong></p><ul><li><strong>Görsel → Görsel:</strong> Kullanıcının yüklediği panel benzer panellerle eşleştirilir.</li><li><strong>Metin → Görsel:</strong> “Mezar sahnesi” gibi cümlelerle ilgili paneller bulunur.</li></ul><p><strong>5. Rerank (MaxSim)</strong></p><p>İlk 10 aday panel, sorguya göre MaxSim benzerliği ile yeniden sıralanabilir.</p><p><strong>6. Görsel Açıklama (VLM: MiniCPM-V-4)</strong></p><p>Seçilen panel için güçlü bir Vision-Language Model (VLM) ile sahne açıklaması ve gerekirse “Hangi chapter olabilir?” tahmini üretilir.</p><p><strong>Kullanılan Modeller</strong></p><ul><li>Embedding için jinaai/jina-embeddings-v3,</li><li>Reranker için colbert-ir/colbertv2.0,</li><li>VLM için openbmb/MiniCPM-V-4,</li><li>Patching openai/clip-vit-base-patch16.</li></ul><h4>1. PDF’den Görsele Dönüşüm</h4><p>Veriyi işlerken her sayfayı tekil görseller olarak çıkardım. Bunun için PyMuPDF kullandım. Panel segmentasyonu gibi gelişmiş işler şimdilik yapılmadı; her sayfa bir “panel” gibi işlendi.</p><p>Her görsele eşlik eden bilgiler volume (şu anlık sadece ilk kitap var ama tüm serinin 10 kitabı eklenebilir), sayfa numarası ve görsel yolu. Bu görsel üzerinden örnekleri vereceğim.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UvEk_3WEJSKzOINMNRKpdw.png" /><figcaption>Görsel 2: Örnekler için Kullanılacak Manga Sayfası</figcaption></figure><h3>2. Embedding ve Qdrant ile Benzerlik Arama</h3><p>Jina Embeddings sayesinde hem görsel hem metin vektörleri aynı uzaya gömülebiliyor. Bu sayede görselden görsele veya metinden görsele arama yapabiliyorum. Benzerlikler kosinüs uzaklığı üzerinden hesaplanıyor. Arama sonuçları görsel olarak gösteriliyor ve kullanıcı seçtiği paneli açıklatabiliyor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TztcGCPUuzf1DT8fNv1_ZA.png" /><figcaption>Görsel 3: Qdrant Arayüzü ve Örnek Vektör</figcaption></figure><p>Ayrıca Qdrant arayüzünde graph ilişkilerini görsel olarak izlemenizi kolaylaştırıyor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0gjl3IWjvDH9DeQLS11Zmg.png" /><figcaption>Görsel 4: Qdrant ve Graph Gösterimi</figcaption></figure><h4>3. MaxSim Reranker: Daha İsabetli Eşleşme</h4><p>Embedding vektörleriyle yapılan ilk top_k arama hızlı bir başlangıç sunar; ancak özellikle metinsel sorgularda içerik açısından daha anlamlı panelleri seçmek için MaxSim (Maximum Similarity) tabanlı bir yeniden sıralama (reranking) aşaması kritik hale gelir.</p><p>Bu yaklaşımda, hem sorgu metni hem de panel görseli token düzeyinde gömülür:</p><ul><li>Metin tarafından gelen her token embedding,</li><li>Görsel tarafında ise patch düzeyinde çıkarılan görsel token embedding’ler kullanılır.</li></ul><p>Her metin token’ı için en benzer görsel token’ı seçilir ve bu maksimum benzerlikler ortalanarak genel skor hesaplanır:</p><p>score = mean(max_sim(query_token_i, panel_tokens))</p><p>Bu yöntem sayesinde:</p><ul><li>Yüzeyde benzer ama içerik olarak farklı sahneler ayırt edilebilir,</li><li>Görselin sorguyla anlamsal örtüşmesi daha doğru şekilde ölçülür.</li></ul><p>Projede bu yapıyı desteklemek için görsel encoder’a özel <strong>patch’ler</strong> uygulandı. Böylece klasik tek vektör yerine <strong>patch-level embedding</strong> alınması sağlandı ve görsel-metin karşılaştırması token bazında mümkün hale geldi. Bu, bir nevi görselin “tokenize edilmesi” anlamına gelmektedir. Patch oluşturmak için openai/clip-vit-base-patch16, reranker olarak da colbert-ir/colbertv2.0 kullanıldı.</p><p>Sonuç olarak, MaxSim reranker, sadece benzer görsel kompozisyonlara değil, metinsel bağlamla örtüşen panellere odaklanmayı mümkün kılmıştır. Özellikle “Bu sahnede Frieren ne yapıyordu?” gibi sorularda belirgin başarı sağlamaktadır.</p><h3>4. Görsel Anlatım: MiniCPM-V-4 ile Panel Açıklama</h3><p>Görsel arama ve eşleştirme adımlarından sonra, seçilen manga panelinin <strong>anlamını açıklamak</strong> ve kullanıcıya daha fazla bağlam sunmak istedim. Bu amaçla, güçlü bir görsel-dil modeli olan <a href="https://huggingface.co/openbmb/MiniCPM-V-4"><strong>MiniCPM-V 2.0–Vision (MiniCPM-V-4)</strong></a> modelini entegre ettim. InternVL3-VLM-1B denediğimde yetersiz performans ile karşılaştığım için buna yöneldim.</p><p>Bu model, hem görsel girdiyi (RGB panel görüntüsü), hem de metinsel bir istemi (prompt) birlikte alarak <strong>açıklayıcı ve bağlamsal cevaplar üretebilen</strong> bir Vision-Language Model (VLM). Model, OpenBMB ekibinin geliştirdiği ve internetteki pek çok benchmark’ta güçlü sonuçlar veren, düşük parametreli ama yüksek performanslı bir encoder-decoder mimarisi üzerine kurulu.</p><p>Kullanıcı, daha önce arama ile bulduğu bir paneli seçtiğinde aşağıdaki iki senaryodan biri uygulanabilir:</p><ul><li><strong>VLM ile Açıklama: </strong>“Bu sahnede ne oluyor?” veya “Bu paneldeki duyguyu açıkla.” gibi serbest istemlerle panelin içeriği modellenebilir. Model, karakterlerin duruşları, yüz ifadeleri ve arka plan gibi görsel detaylara dayanarak anlamlı açıklamalar üretir.</li><li><strong>Hedefli Sorgu: </strong>“Frieren burada neye bakıyor?” gibi doğrudan sorularla, görseldeki öğelerin ilişkilendirilmesi yapılabilir.</li></ul><p>MiniCPM-V-4 modelini seçmemin nedeni, hafif ve hızlı olmasına rağmen görsel içerikleri anlamlı şekilde açıklayabilmesiydi.</p><h3>Demo — Örnekler</h3><p><strong>Görsel Arama:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FXgXIeDhmTgUDzWociG-LA.png" /><figcaption>Görsel 5: Görsel Arama Sonucu</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OMLesx35gl3ipLpFXvPIZA.png" /><figcaption>Görsel 6: Görsel 5&#39;in Devamı (Sayfa numarası ve benzerlik skorları her görselin altında)</figcaption></figure><p><strong>Görsel Arama + Text Reranker:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AMUhIvX5GeXct0YpHkSDAA.png" /><figcaption>Görsel 7: Görsel Aramaya Reranker Eklenince Sonuçlar İyileşir</figcaption></figure><p><strong>VLM ile Görsel Yorumlama:</strong></p><p><strong>Prompt:</strong> <em>Describe this manga panel in detail: characters, setting, and events. If possible, guess the chapter/volume and justify briefly. Give a word that describes the emotions in this scene.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6bNGDcqzl2tNjOK7fmrHQ.png" /><figcaption>Görsel 8: VLM Cevabı</figcaption></figure><p><strong>Cevap: </strong><em>This manga panel depicts a moment of parting between two characters. The setting is an open landscape with rolling hills and sparse vegetation, suggesting a rural or wilderness area. In the first panel, one character wearing a horned helmet appears to be speaking to another character who has long hair tied back in twin tails. Their dialogue indicates they are saying goodbye, as evidenced by phrases like ‘RIGHT.’, ‘LATER.’, ‘ALL RIGHT, SEE YOU LATER…’, and ‘Eigen’ (which could be their name).</em></p><p><em>The second panel shows these characters walking away from each other down a dirt path surrounded by nature. This scene conveys a sense of departure and perhaps bittersweet farewells, common themes in narratives that explore relationships and journeys. Given the style and content, this might belong to a chapter/volume focusing on personal growth, friendship, or adventure within a fantasy context.</em></p><p><em>The word that describes the emotions in this scene is likely ‘bittersweet,’ reflecting both the finality of separation and the hope for future encounters.</em></p><p>Bu paneli tanımlayan duygu olarak <strong>bittersweet</strong> seçmesi çok yerindeydi ve Eisen ismini okumakta zorlansa da oldukça başarılı buldum :)</p><h3>Çıkarımlarım</h3><ul><li>Görsel ağırlıklı içeriklerde metin tabanlı RAG yetersiz kalıyor; görsel embedding kritik önemde.</li><li>ColBERT tabanlı token-level MaxSim reranking, metinle yapılan aramalarda isabeti belirgin şekilde artırıyor.</li><li>Jina gibi modellerle aynı uzayda metin ve görsel embedding yapılabilmesi esneklik sağlıyor.</li><li>Qdrant gibi vektör veritabanları hızlı ve filtrelenebilir multimodal arama için ideal.</li><li>MiniCPM-V gibi hafif VLM’ler bile doğru promptlarla tatmin edici açıklamalar sunabiliyor.</li><li>Türkçe metin sorgularında model pek de iyi performans gösteremiyor.</li><li>Bazen harfleri yanlış okumakta ama bunun nedeni başka harflere de yakınlık göstermesi ile alakalı.</li></ul><h3>Gelecekte Yapılabilecek Adımlar</h3><p>Projenin mevcut hali güçlü bir temel sunsa da, aşağıdaki geliştirme başlıkları sistemin kapsamını genişletebilir:</p><ul><li><strong>Panel Segmentasyonu:</strong> Sayfa yerine panel düzeyinde görsel indeksleme yapılması ile YOLO gibi modellerle otomatik panel kesitleri çıkarılarak daha hassas arama sağlanması.</li><li><strong>Anlamsal Zenginleştirme:</strong> Karakter tanıma, duygu analizi ve sahne sınıflandırma ile panellere semantik etiketler eklenerek tematik ve bağlamsal aramaların önü açılması.</li><li><strong>Hikaye Takibi:</strong> Karakterlerin zaman içindeki görsel izlerini takip ederek olay akışını modelleyen bir zaman çizelgesi (timeline) sistemi tasarlanması. (Narrative Graphs veya CLIP-based Event Similarity gibi yöntemler ile mümkün.)</li></ul><h3>Sonuç</h3><p>Görsellerden anlam çıkarmak, doğru sahneleri bulmak ve hatta bunları açıklatmak artık sadece metinle sınırlı değil.</p><p>Hem teknik olarak hem ürün mantığı olarak büyütülebilir bir yapı inşa ettim. Kodu açık kaynak yapıyorum tabii ki :)</p><p>GitHub reposu: <a href="https://github.com/rabiaedayilmaz/manga-multimodal-rag">https://github.com/rabiaedayilmaz/manga-multimodal-rag</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a326a400842" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Empowering Albert with Retrieval Augmented Generation (RAG)]]></title>
            <link>https://medium.com/albert-health/empowering-albert-with-retrieval-augmented-generation-rag-5d60348cfd9e?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d60348cfd9e</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[retrieval-augmented]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[gpt]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Fri, 05 Apr 2024 11:33:38 GMT</pubDate>
            <atom:updated>2024-04-05T11:34:35.923Z</atom:updated>
            <content:encoded><![CDATA[<h3>Table of Contents</h3><ol><li><a href="#1443">Introduction</a></li><li><a href="#4e21">Retrieval Augmented Generation (RAG)</a></li><li><a href="#f3ae">Customer Support and FAQs with RAG</a></li><li><a href="#ef61">Evaluation</a></li><li><a href="#a71e">Conclusion</a></li></ol><h3>1. Introduction</h3><p>In our <a href="https://medium.com/albert-health/albert-and-diabetes-care-utilizing-large-language-models-in-healthcare-solutions-c8122b3132cd">previous article</a>, we discussed how Albert utilizes large language models with disease-focused websites in the field of healthcare. However, large language models may encounter various challenges. One notable challenge is <strong><em>hallucination</em></strong>, which refers to a model generating incorrect or misleading information. This can affect the reliability and performance of the model in practice. To address this issue, a technique called <strong><em>Retrieval Augmented Generation</em></strong> (RAG) has become popular recently. RAG ensures fidelity to the information in the provided document by reducing the hallucination tendency of large language models, thereby producing more consistent and accurate outputs.</p><p>In this article, we will examine in detail how Albert uses large language models and RAG technique together to improve customer support and the process of answering frequently asked questions in our mobile application.</p><h3>2. Retrieval Augmented Generation (RAG)</h3><p>Hallucination is a challenge frequently encountered during text generation by large language models. This is because this situation can lead the large language model to produce texts that, although unrealistic, are convincingly crafted. The RAG techniques is an effective method developed to address this issue.</p><p>RAG reduces the risk of hallucination by ensuring that large language models adhere closely to text documents. By using information retrieval or semantic search methods, it selects the most relevant text snippets by establishing connections within and between texts. As a result, the text generated by the model becomes more consistent and reliable by adhering to the most relevant text snippet found.</p><p>We used the <strong><em>LangChain</em> </strong>framework, which is preferred for developing applications that can make judgments based on documents supported and nourished by large language models and are knowledgeable about the subject, to implement this feature. This approach stands out as an important step to reduce consistency and reliability issues in text generation, allowing large language models to produce more reliable and higher-quality content.</p><h3>3. Customer Support and FAQs with RAG</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ccUDmYWFIe1Dy1A0GtpCJw.jpeg" /><figcaption>Figure 1. Albert Customer Support QA Pipeline with RAG</figcaption></figure><p>The first step in successfully implementing the RAG technique in Albert’s customer support operations is to choose an <strong>embedding model</strong>. An embedding model is an algorithm that helps represent texts as mathematical vectors. Representing texts with mathematical vectors is highly important in the fields of artificial intelligence and natural language processing.</p><p>Many algorithms have been developed for this purpose, and among the most commonly used ones are <em>Word2Vec</em> and <em>GloVe</em>. Word2Vec is an algorithm used to represent relationships between words in texts. This algorithm utilizes the surrounding words of a word to emphasize its context. For example, while the word “king” is often associated with words like “kingdom” or “throne,” the word “queen” can be associated with words like “princess” or “crown.” These relationships can be utilized to capture semantic similarities and relationships in texts. GloVe (Global Vectors for Word Representation), on the other hand, utilizes statistical information to generate word vectors. By directly measuring possible relationships between words, it captures connections between a word and other words more accurately. This method creates word vectors by utilizing statistical information obtained from large text datasets, resulting in a better representation of word meanings.</p><p>We prefer to use <strong><em>ada model </em></strong>one of the embeddings offered by OpenAI as a tool. The reason for this choice is its specialized design for measuring relationships between texts and its suitability for deep analysis of our data. Additionally, embeddings are a good option for various tasks such as searching, clustering, recommendation, anomaly detection, and classification. These features support Albert in better-understanding texts and achieving high performance in various natural language processing tasks.</p><p>When creating a vector database, chunk size, and chunk overlap hyper-parameters are determined. <strong><em>Chunk size</em></strong> is a term used during text processing or model training. It refers to dividing a text into pieces of a certain size for processing or training a model. For example, you can use 1000 words as a chunk size to divide a text into chunks of 1000 words each. Chunk size is important for determining how processing will be done in larger or smaller pieces and can affect performance. Overlap is a concept used during text processing or model training. <strong><em>Chunk overlap</em></strong> specifies how much each chunk overlaps with the next. For instance, when dividing a text into 100-word chunks, chunk overlap can be used to ensure each chunk overlaps with the previous one by a certain amount of words. This can help achieve more consistent and balanced handling of information during text processing or model training.</p><p>Later, a <strong><em>vectorial database</em></strong> is created using documents generated based on the experiences of the customer support team and existing documents. This database consists of vectors containing customer inquiries and their relationship to the documents. Each document text is transformed into a vectorial form using an embedding tool. These vector representations are utilized to measure similarities between documents and to select the most appropriate documents.</p><p>Afterward, the user query is also transformed into a vector using an embedding tool, and the vector of the nearest document fragment in the vector database is determined through mathematical calculation. There are different algorithms for vector proximity calculation. While <em>Euclidean distance</em> measures the shortest distance between two vectors, <em>Manhattan distance</em> calculates the sum of absolute differences. <em>Jaccard similarity</em> is particularly useful for sparse data because it measures the ratio of common elements to the total number of elements. <strong><em>Cosine similarity</em></strong> is ideal and widely preferred for sparse text data due to its insensitivity to scale changes and sensitivity to the directions of vectors. The closest fragment found using the selected cosine similarity algorithm is added to the designated location in the designed prompt. Then, this prompt is passed to the Large Language Model (LLM).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0nGDZHumXKYmkvKKdveEpA.jpeg" /><figcaption>Figure 2. User Question Answering Flow Diagram</figcaption></figure><p>LLM, following the instructions specified in the prompt and staying faithful to the given document excerpt, must answer the question. This method ensures that the model remains consistent with a certain reality and increases traceability by revealing which document excerpt the given answer is based on.</p><p>RAG determines the text fragment most closely related to the user’s question. By feeding this fragment and the user’s question into a large language model, the LLM provides a more natural language response to the user’s question. This way, the risk of hallucination is reduced by using text fragments taken from the document. This process makes customer support operations faster, more effective, and more reliable.</p><h3>4. Evaluation</h3><p>LLM evaluating systems with metrics is an important way to track them objectively. Although there are ongoing efforts to evaluate RAG systems, there are some prominent tools that stand out. One of these tools, RAGAS, has categorized metric types into two: generation and retrieval. For generation, there is faithfulness, which measures how relevant and accurate the generated response is to reality, and answer relevancy, which measures how relevant the generated response is to the question. For retrieval, there is context precision, which measures the signal-to-noise ratio of the retrieved text, and context recall, which measures how much information the system can extract to answer the question given. Thus, the developed RAG system can be visually monitored and tracked.</p><h3>5. Conclusion</h3><p>The Retrieval Augmented Generation (RAG) technique is implemented in Albert’s customer support operations, and enables more effective and reliable answers to users’ questions. This technique begins with converting documents into a vectorized database using an embedding tool, and then selecting the most relevant fragment with user questions. Subsequently, a process involving adding the selected fragment to a prompt designed for an LLM is followed to answer the questions.</p><p>Apart from the RAG system described and implemented in this text, there are also advanced-level RAG systems. These systems include additional operations in the pre-retrieval, retrieval, and post-retrieval steps. Additionally, modular RAG systems exist, which incorporate techniques such as hybrid search exploration, sub-queries, and recursive retrieval.</p><p>Certainly, this method has some disadvantages. Its performance is highly dependent on the quality of the selected closest fragment. This technique requires existing data, such as a document. Additionally, there is a limited context length that the model can process, and a well-designed prompt is necessary to stay within this limit.</p><p>Albert’s constantly updated and improved user guide also plays a fundamental role in providing the assistance users need. Therefore, there is a process that requires ensuring that the current document is fed into the embedding model. Additionally, as the number of documents increases, a clean and well-designed process is required due to the impact on the sustainability and consistency of the system. Furthermore, sometimes the most relevant text fragment may not be precisely identified, negatively affecting the response given by the LLM.</p><p>In this article, the feature supported by the GPT model using the RAG technique, aimed at making Albert’s customer support operations more effective, reliable, and user-centric while reducing the risk of hallucination and increasing customer satisfaction, is described.</p><p>Until our next writing, take care!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d60348cfd9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/albert-health/empowering-albert-with-retrieval-augmented-generation-rag-5d60348cfd9e">Empowering Albert with Retrieval Augmented Generation (RAG)</a> was originally published in <a href="https://medium.com/albert-health">albert-health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Albert and Diabetes Care: Utilizing Large Language Models in Healthcare Solutions]]></title>
            <link>https://medium.com/albert-health/albert-and-diabetes-care-utilizing-large-language-models-in-healthcare-solutions-c8122b3132cd?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8122b3132cd</guid>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[healthcare]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[diabetes]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Wed, 27 Mar 2024 09:24:23 GMT</pubDate>
            <atom:updated>2024-03-27T09:24:52.583Z</atom:updated>
            <content:encoded><![CDATA[<h3>Albert: Utilizing Large Language Models in Healthcare Solutions</h3><h3>Table of Contents</h3><ol><li>Introduction</li></ol><p>2. Albert in Health Management</p><p>3. Albert and Large Language Models</p><p>4. Generating a Prompt</p><p>5. Diabetes Website</p><p>6. Conclusion</p><h3>1. Introduction</h3><p>Digital transformation, especially after the pandemic, has gained great momentum in the healthcare sector. This evolution offers significant advantages in critical areas of healthcare processes, especially in fundamental processes such as patient history tracking, diagnosis, research, and treatment planning based on theoretical knowledge. For example, if a patient receives services from different healthcare institutions, they can quickly and securely share all their information with healthcare professionals thanks to digital health records. This digitalization provides healthcare professionals with the opportunity to manage data management, patient monitoring and treatment processes more effectively.</p><p>Within the scope of digitalization, artificial intelligence technologies that have entered our lives are increasingly demonstrating their benefits in every sector, and they have the potential to revolutionize the healthcare sector as well. One of the potential benefits offered by artificial intelligence is its ability to communicate and interact with users. For example, thanks to this communication ability, a practical tool can be provided to patients to easily access the information they need, thereby providing support in better understanding and managing diseases.</p><p>One of the most important components for effective health management is that patients are aware of their health. In this context, health literacy is of great importance. As Albert Health, we have developed disease-specific AI-based websites where users can ask their health questions and get information about everything they are curious about about their health, in order to support individuals to better understand their health, manage it effectively and live a healthier life.</p><h3>2. Albert in Healthcare Management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SC8dfr9IsC50NzBD" /><figcaption>Figure 1. Albert in Health Management</figcaption></figure><p><strong>Albert</strong> is a clinical outcomes-driven and AI based chronic disease management platform. Albert to users; It offers customized disease management programs for various chronic diseases, including diabetes, asthma, hypertension, MS, and cancer, through a mobile device. Users can set medication reminders, access drug package insert information, and receive warnings about drug interactions. You can access healthy living, nutrition and exercise recommendations. Important health metrics such as blood sugar level, blood pressure values, weight changes, daily amount of water drunk, daily step count can be recorded in Albert and the measurements can be easily tracked. They can store their health data in one place and share it with their relatives and healthcare professionals.</p><p>On the other hand, Albert is an voice-based AI health assistant who is always with patients and whom they can consult. Users can control the application with voice commands and ask Albert their health questions by voice or text. Albert also finds the most appropriate answers by understanding the needs of the patients according to their diseases.</p><p>One of the most important components for effectively managing healthcare is for patients to be conscious about their health. In this context, health literacy holds great importance. With this aim in mind, at Albert Health, we have developed artificial intelligence-based websites where individuals can ask their health questions and obtain information on any aspect of their health to better understand, manage effectively, and lead a healthier life.</p><h3>3. Albert and Large Language Models</h3><p>Websites offer us the opportunity to address and support a wide audience by quickly reaching people in different geographies. However, it is inevitable that there will be incorrect, insufficient or incomplete information on the internet. Overcoming such problems, language models that can perform various functions on human language occupy a special place in this field of artificial intelligence.</p><p>Many applications are used and developed in the healthcare industry, such as virtual nurses that can communicate with patients and models that can keep clinical notes for doctors. Especially in this sector, these models, which enable patients to communicate interactively, have a critical role in patient communication and contribute to public health by increasing the accuracy and accessibility of health information.</p><p>As Albert Health, we eliminate the mobile application registration process and offer individuals with chronic diseases a tool to obtain reliable information anonymously, with a user-friendly interface and websites developed with an artificial intelligence language model. Then, we direct individuals who have gained awareness about their health to our<a href="https://apps.apple.com/tr/app/albert-health-assistant/id1440082441"> mobile application</a> so that they can manage their health effectively.</p><p>The main objective of these websites is to enable individuals to acquire information more effectively, reliably, and easily, and to provide them with an interactive experience in health-related topics. Developed by our AI engineers and validated by our medical team, these websites allow individuals to freely ask their questions anonymously at any time. Additionally, users are reminded in each session to consult a healthcare professional for the most accurate guidance when conversing with an artificial intelligence, thereby encouraging them to always access the most accurate information. Individuals who can obtain reliable information can make more informed decisions about their health and maintain more effective communication with healthcare professionals.</p><h4>4. Generating a Prompt</h4><p>Large Language Models (LLMs) is a general term given to machine learning models that understand complex language structures, handle various text tasks, and generate human-like text.</p><p>Generative Pre-trained Transformer (GPT) is an advanced language model utilized to achieve predetermined objectives within its scope. This model is based on the Transformer architecture, which forms the foundation of language processing models, and it has been pre-trained on a large dataset.</p><p><strong>Prompt</strong> is a term used in LLMs. It is typically a text provided as an initial input to the model, containing instructions or guidelines for it to perform a specific task. This text enables the model to generate the desired output and accomplish a particular task.</p><p>Users convey their questions to GPT via a <strong>prompt</strong> specifically developed by Albert Health. The instructions contained within this prompt are designed using a technique called <strong>prompt engineering</strong>. This technique ensures that the responses meet a certain quality and standard. The developed system was initially tested using a dataset containing frequently asked questions from within the mobile application and questions about diseases. The responses provided by GPT to the test dataset were recorded. Subsequently, our medical team examined the responses, and it was observed that the developed GPT prompt effectively provided responses to user needs, demonstrating high performance in real-life scenarios.</p><p>Following the validation conducted by our medical team, the quality of responses has been evaluated in terms of reliability, comprehensibility, medical accuracy, and risk. It has been observed that the system meets these criteria adequately. Subsequently, the website has been made available to users. After its launch, the quality and consistency of responses are monitored, and any anomalies detected are addressed promptly by revising the system if necessary.</p><p>Through the developed prompts, it is of great importance, especially in health-focused and artificial intelligence-supported website projects, to verify and evaluate the accuracy and clarity of every response generated by GPT. In this context, regular review of responses aims to ensure users’ continuous access to reliable information. Throughout the project development process, the use of real user data and its validation by our medical team, prioritizing data security and privacy principles in the information gathering and processing processes, maintaining user anonymity, and continuously observing response performance for improvements are crucial.</p><h4>5. Diabetes Website</h4><p>The Republic of Turkey Ministry of Health is meticulously working to control the financial burden of diabetes on the healthcare system in our country. According to the “Sixth Diabetes Atlas” report published by the International Diabetes Federation (IDF) in 2013, Turkey’s diabetic population will rank among the top 10 countries with the highest diabetic population by the year 2035. Globally, it is expected that by 2035, there will be 592 million people with diabetes [1]. Therefore, it has been decided to create a website to increase access to information about diabetes and raise awareness among the public. This website aims to enhance the public’s awareness of health by providing information obtained from reliable sources on the prevention, treatment, and management of diabetes.</p><p>Individuals with diabetes often struggle to access fast, accurate, and reliable information. Therefore, we aim to support those living with diabetes by providing access to a reliable source of information through the first website we have developed specifically for diabetes. Users can access the Albert Diabetes website through an interface created to submit their questions. They can receive responses generated by GPT using an enhanced prompt. This way, a platform is provided for individuals with diabetes to quickly access reliable information about their condition and effectively manage their diabetes.</p><p>The website can be accessed through this<a href="https://diyabet.albert.health/"> link</a>. It supports both Turkish and English languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAiVueRm9vrySK68_YDB4A.png" /></figure><h3>6. Conclusion</h3><p>Albert Diabetes website aims to provide fast and reliable information without adding layers such as signing up for a mobile application. This approach allows users to easily find answers to their diabetes-related questions and access health information more quickly. GPT is quite successful in providing answers to questions specific to diabetes.</p><p>Analyses conducted to evaluate the effectiveness of the Albert Diabetes website indicate that the platform has been successfully embraced by users. According to the data obtained by examining the responses provided by GPT, it has been determined that a total of <strong>347</strong> different sessions occurred, with <strong>795</strong> requests made. On average, <strong>2.29</strong> interactions took place in each session. Thus, we can observe that the platform is actively used.</p><p>However, while the Albert Diabetes website aims to provide a fast and effective user experience, it may encounter some challenges. For instance, when addressing sensitive health-related issues, it is crucial to maintain red lines such as user privacy and security. Even if no information is collected from the user, care should be taken not to share the user’s personal information when posing questions to the model.</p><p>However, the Albert platform plans to expand in the near future with a new website providing information on sexually transmitted diseases. This site aims to prioritize privacy, allowing users to find answers to their health-related questions while protecting their privacy. Additionally, it directs users to the Albert mobile application to effectively manage their health.</p><p>Albert makes a significant contribution to the digital health sector with its innovative and technology-driven approach. Observing how AI-powered websites transform interaction and information sharing in the healthcare field is quite exciting for the future of the healthcare system.</p><p>Hope to meet again in our next writings…</p><h3>References</h3><p>[1] <em>IDF Diabetes Atlas</em>. (n.d.). Copyright © IDF Diabetes Atlas 2024. All Rights Reserved.<a href="https://diabetesatlas.org/"> https://diabetesatlas.org/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8122b3132cd" width="1" height="1" alt=""><hr><p><a href="https://medium.com/albert-health/albert-and-diabetes-care-utilizing-large-language-models-in-healthcare-solutions-c8122b3132cd">Albert and Diabetes Care: Utilizing Large Language Models in Healthcare Solutions</a> was originally published in <a href="https://medium.com/albert-health">albert-health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aslan Parçası Optimizer: Lion]]></title>
            <link>https://medium.com/@rabiaedayilmaz/aslan-par%C3%A7as%C4%B1-optimizer-lion-95ba51cfe5c2?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/95ba51cfe5c2</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[optimizer]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Tue, 17 Oct 2023 14:33:34 GMT</pubDate>
            <atom:updated>2023-10-17T14:33:34.567Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F7nB171MgnpkhzJE8aRK5A.jpeg" /><figcaption>Lady Placing A Wreath Of Flowers On A Lion by Frederick Stuart Church</figcaption></figure><p>Optimizer, bir modeli eğitirken kullanılan temel fonksiyonlardan biridir. Ana amacı, hata fonksiyonunu minimize etmektir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1-3UpV0bR66P3GQT.png" /><figcaption>Minimize Edilmesi Hedeflenen Örnek Bir Loss Fonksiyonunun Görselleştirilmesi [1]</figcaption></figure><p>Yakınsama hızı, lokal minimaya ulaşma, stabilite, ölçeklenebilirliği, seyrek veri ile başa çıkabilme, bellek efektifliği, hiperparametre duyarlılığı ve genelleme özelliği gibi birçok noktada etkisi bulunmaktadır. Bu yüzden optimizer seçimi modelin performansı açısından etkisi büyük parçalardan biridir. Çeşitli optimizer türleri bulunmaktadır. Bunlardan en sık kullanılanları Stochastic Gradient Descent (SGD), Mini-Batch Gradient Descent, SGD with Momentum, AdaGrad (Adaptive Gradient Descent), RMS-Prop (Root Mean Square Propagation), AdaDelta, Adam (Adaptive Moment Estimation), AdamW.</p><p>Bu yazıda, Google Brain ekibinin genetik algoritma kullanarak geliştirdiği ve AdamW’dan daha iyi olduğunu raporladığı Lion optimizer’ı inceleyeceğiz.</p><h3>Lion (Evo<strong>L</strong>ved S<strong>i</strong>gn M<strong>o</strong>me<strong>n</strong>tum) 🦁</h3><p><a href="https://arxiv.org/abs/2302.06675">Symbolic Discovery of Optimization Algorithms</a></p><p>Lion (Evo<strong>L</strong>ved S<strong>i</strong>gn M<strong>o</strong>me<strong>n</strong>tum) bir optimizasyon algoritmasıdır. Sadece momentumu takip ettiği için bellek açısından Adam algoritmasından daha verimlidir. Adaptif algoritmalardan farklı olarak, her parametre aynı büyüklükte işaret operasyonu ile hesaplandıktan sonrası güncellenir. Lion, başta Adam ve Adafactor olmak üzere birçok optimizer ile kıyaslanmıştır. Yapılan deneyler sonucu:</p><ul><li>Görüntü sınıflandırma görevinde ImageNet veri setinde ViT model doğruluk performansını %2 oranında iyileştirdiği ve JFT veri setinde ise 5 kata kadar hesaplama tasarrufu yaptığı gözlemlenmiştir.</li><li>Görüntü-dil kontrastif öğrenmede, ImageNet veri setinde, zero-shot %88.3 (öncekilerden %2 daha iyi) ve fine-tuning %91.1 (öncekilerden %0.1 daha iyi) doğruluk oranlarını vermiştir.</li><li>Difüzyon modellerinde ise, FID skoru olarak Adam’dan daha iyi performans sergilemiş ve 2.3 kat model eğitim maliyetini düşürmüştür.</li><li>Autoregressive, maskelenmiş dil modeli ve fine-tuning için ise Adam ile karşılaştırıldığında benzer veya daha iyi sonuçlar elde edilmiştir.</li></ul><p>Yapılan analiz sonucu, Lion daha büyük batch size verildiğinde performans olarak daha büyük kazanç sağlamaktadır. Ayrıca, Adam’a kıyasla daha küçük bir learning rate’e ihtiyaç duymaktadır [2].</p><p><strong>🤔 Lion, Google’ın search ads kısmında Click-Through Rate Prediction (CTR) modelinde kullanılmaktadır.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rfrlqbP2w-pXEPGn2oXBDQ.png" /><figcaption>AdamW ve Lion için Pseudocode [2]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UeYo75SBfQFJFr4j2PtctA.png" /><figcaption>ViT-S/16 ve ViT-B/16 Modellerinin Doğruluk Eğrileri [3]</figcaption></figure><blockquote>Resmi PyTorch implementasyonu: <a href="https://github.com/google/automl/blob/master/lion/lion_pytorch.py">https://github.com/google/automl/blob/master/lion/lion_pytorch.py</a></blockquote><h3>Kaynakça</h3><p>[1] <a href="https://www.cs.umd.edu/~tomg/projects/landscapes/">https://www.cs.umd.edu/~tomg/projects/landscapes/</a></p><p>[2] Chen, X., Liang, C., Huang, D., Real, E., Wang, K., Liu, Y., … &amp; Le, Q. V. (2023). Symbolic discovery of optimization algorithms. <em>arXiv preprint arXiv:2302.06675</em>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=95ba51cfe5c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dil Modelleri Mayın Tarlası Oynamaya Benzer]]></title>
            <link>https://medium.com/@rabiaedayilmaz/dil-modelleri-may%C4%B1n-tarlas%C4%B1-oynamaya-benzer-ad6524931c37?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad6524931c37</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Fri, 13 Oct 2023 18:34:28 GMT</pubDate>
            <atom:updated>2023-10-13T18:34:28.985Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/680/0*d5t0teW_uLhXdtPn.jpg" /><figcaption>Eski Windows Mayın Tarlası Oyunu [1]</figcaption></figure><p>Geliştirilen bir araç veya sistemin test edilmesi büyük önem taşır. Bu yüzden, yazılan bir koda test case yazmak da vazgeçilemez bir alışkanlıktır. Bu şekilde değerlendirilmesi onun güvenilirliğini artırarak belli standartlarda olduğunu da kanıtlar. Özellikle son zamanlarda, dil modellerini kullanarak çeşitli uygulamalar üretmek oldukça cezbedici ve büyük potansiyele sahip olsa da, şu soruyu göz önünde tutmalıyız: onları nasıl test edip değerlendireceğiz?</p><h3>Değerlendirmedeki Zorluklar</h3><ol><li><strong>Prompt Duyarlılığı:</strong> “Ölçülen durum model ile doğrudan mı ilişkili yoksa prompt’tan kaynaklanan bir durum mudur?” [2] sorusu sorulmalıdır. Çünkü prompt’taki en ufak bir değişim bile cevabın kalitesini oldukça etkilemektedir.</li><li><strong>Yapı Geçerliliği: “</strong>Ortak bir durumu ölçmek isteyen iki araştırmacı, iki farklı prompt kullanarak iki farklı cevap alırsa bu ortak durumda ölçmeye çalıştıkları yapı nedir?” [2] sorusu sorulmalıdır. Üretken Yapay Zeka (YZ) firmalarının şeffaflık raporları hazırlaması kritiktir. Bunun yanında, araştırmacılar modellerin gerçek dünya kullanımı hakkında veri setleri oluşturmalıdır [2]. <strong>Yapı geçerliliği konusunda, ölçmeye çalıştığımız unsurun tam olarak ne olduğu iyi belirlenebilmelidir.</strong> Mesela, insanları değerlendiren sınavlar onların problemleri çözerken ne kadar genelleştirebildiğini ölçmektedir. Fakat dil modelleri anlamlandırmak yerine, <strong>hatırlama</strong> üzerine yetenekli olduğu için genelleştirebilme yeteneğini nasıl ölçebileceğimizi henüz bilmiyoruz.</li><li><strong>Bulaşma: </strong>GPT-4, United States Medical Licensing Examination (USMLE) sınavını gerçekten geçtiği mi, yoksa cevapları sadece hatırlamış mı olduğu bir bulaşma sorunsalıdır. Başka bir örnek, model Eylül 2021 öncesi kodlama sorularına harika cevap verirken, sonrası için başarısı düşmüştür. Modellerin yasal ve medikal konulardaki başarısı için net bir ölçüm yapmak henüz mümkün değildir [2].</li><li><strong>Tekrardan Üretilebilir Olma:</strong> Deterministik olmayan makine öğrenmesi tabanlı bilimdeki önemli bir sorun sonuçları tekrardan üretebiliyor olmaktır. Bulaşma problemi, dil modellerinden önceki tarihteki makine öğrenmesi modellerinde de bulunmaktadır [4]. Test ve eğitim veri setinin birbirinden bağımsız olmadığı ve birbiri içinde ortak örneklere sahip olduğu durumlarda oluşan bu probleme “sızıntı” denilmektedir. Sızıntı problemi, anlam ifade etmeyen aşırı umut verici sonuçlar vererek yanıltıcı olabilmektedir [2].</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHbmdkovTUYsrk58bbth6g.png" /><figcaption>Sızıntı? [5]</figcaption></figure><p>Bu tür modeller, insanların sahip olduğu muhakeme yeteneğine sahip değildir. Dolayısıyla, ChatGPT’nin USMLE üzerindeki başarısı hedef bir sistemin parçalarının nasıl çalıştığı, hata aldığı, oluşturulduğu ve sürdürüldüğünü analiz etmekten daha çok hatırlama yeteneği ölçülmüştür. Bu medikal öğrencilerin nasıl eğitilip, değerlendirildiği hakkındaki yetersizlikleri de göstermektedir. Çünkü ChatGPT’nin başarısı ile görmüş olunacağı üzere, var olan eğitim sistemi devamlı evrimleşen ve değişen tıp alanındaki doğru kabul edilen gerçeklikleri anlamayı ve yorumlamayı gerektiren <strong>kritik düşünme</strong>yi ölçmemektedir [3].</p><h3>Kapalı Kaynak Dil Modelleri</h3><p>Açık kaynak yapay zeka insanlık adına büyük önem arz etmektedir. Çokça kullanılan kapalı kaynak modeller (mesela ChatGPT) bir gün kullanımdan kaldırılırsa bu birçok kişiyi ve araştırmayı olumsuz yönde etkileyecektir. Açık kaynak modellerin varlığı ve sürdürülebilirliği akademi için çok önemlidir.</p><p>Yapay zeka korkusu, “yapay zeka üretme lisansı” gibi belirsiz politikalara yol açabilir. Bu politikalar yüzünden kapalı kaynak teşvik edilerek, açık kaynak ciddi zarar görebilir. Ek olarak, bu yöndeki adımlar dev şirketleri destekleyerek diğer oyuncuların, daha küçük şirketler, sahaya girmesini engelleyerek yapay zekanın tekelleşmesine neden olabilir.</p><p>Bir sonraki açacağımız tarla karesi ne olacaktır?</p><h3>Kaynakça</h3><p>[1] <a href="https://www.chip.com.tr/haber/windows-10da-mayin-tarlasi-oynamanin-yolu_75562.html">https://www.chip.com.tr/haber/windows-10da-mayin-tarlasi-oynamanin-yolu_75562.html</a></p><p>[2] <a href="https://www.cs.princeton.edu/~arvindn/talks/evaluating_llms_minefield/">https://www.cs.princeton.edu/~arvindn/talks/evaluating_llms_minefield/</a></p><p>[3] Mbakwe, A. B., Lourentzou, I., Celi, L. A., Mechanic, O. J., &amp; Dagan, A. (2023). ChatGPT passing USMLE shines a spotlight on the flaws of medical education. <em>PLOS Digital Health</em>, <em>2</em>(2), e0000205.</p><p>[4] <a href="https://reproducible.cs.princeton.edu/">https://reproducible.cs.princeton.edu/</a></p><p>[5] <a href="https://twitter.com/percyliang/status/1619594326585262082?s=20">https://twitter.com/percyliang/status/1619594326585262082?s=20</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad6524931c37" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Self-Supervised Learning: Blending Essence of Biological Intelligence into Machines]]></title>
            <link>https://medium.com/albert-health/self-supervised-learning-blending-essence-of-biological-intelligence-into-machines-1be7a270eb47?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1be7a270eb47</guid>
            <category><![CDATA[image]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[audio]]></category>
            <category><![CDATA[self-supervised-learning]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 06:11:02 GMT</pubDate>
            <atom:updated>2023-08-29T06:11:02.263Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JAcdGYMbWWGqzdyN" /><figcaption>Photo by <a href="https://unsplash.com/@bamin?utm_source=medium&amp;utm_medium=referral">Pierre Bamin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this post, we will go through — so called by Facebook, the dark matter of intelligence, Self-Supervised Learning (SSL) paradigm. Firstly, a quick background will be provided. In the next section, SSL will be deep dived and, in the last section, the commonly used SSL models will be described.</p><h3>1.Background 💭</h3><h4>Energy-Based Model (EBM)</h4><p>An energy-based model (EBM) is a trainable system that, given two inputs, x and y, tells us how incompatible they are with each other [1]. For example, x could be a short video clip and y another proposed video clip. The machine produces a single number which is called an energy. It indicates the incompatibility between x and y. If the energy is low, x and y are deemed compatible; if it is high, they are deemed incompatible.</p><p>Also, there are Siamese networks or joint embedding architecture. It is composed of two identical or almost identical copies of the same network. One network is fed with x and the other with y. The networks produce output vectors that represent x and y and called embeddings. There is also a third module, joining the networks at the head. It computes the energy as the distance between two embedding vectors. So, when the model is shown distorted versions of the same image, the parameters of the networks can easily be adjusted so that their outputs move closer together. This will ensure that the network will produce nearly identical representations or embedding of an object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*BhFEH798JYV31cOMVmatqA.png" /><figcaption>Joint Embedding Architecture. C produces a scalar energy that measures the distance between the representation vectors/embeddings produced by two identical twin networks sharing same parameters w [1]</figcaption></figure><p>However, there is a phenomenon to be aware of that is <strong>collapse</strong>. It is difficult to make sure that the networks produce high energy/different embedding vectors, when x and y are different images. The two networks can ignore their inputs and always produce identical output embeddings, which is called collapse. <em>When collapse occurs, the energy is not higher for non-matching x and y than it is for matching x and y.</em></p><p>To avoid collapse, there are two categories of techniques: <strong>contrastive methods</strong> and <strong>regularization methods</strong>.</p><h4>Contrastive Energy-based SSL</h4><p>The idea of contrastive methods are based on constructing pairs of x and y that are not compatible and adjusting the parameters of the model so that the corresponding output energy is large. Training EBM with a contrastive method consists in simultaneously pushing down on the energy of compatible (x, y) pairs from the training set and pushing up the energy of (x, y) pairs that are incompatible [1].</p><p>In NLP, the method used to train by masking or substituting some input words belongs to the category of contrastive methods. However, they do not use the joint embedding architecture. Instead, they use a predictive architecture in which the model directly produces a prediction for y [1]. Firstly, a complete segment of text y is corrupted by masking some words to produce the observation x. Then, the corrupted input is fed to a large neural network that is trained to reproduce the original text y. An uncorrupted text will be reconstructed as itself —<em> low reconstruction error</em>, while a corrupted text will be reconstructed as an uncorrupted version of itself — <em>large reconstruction error</em>. If reconstruction error is interpreted as an energy, we can say that: low energy is for clean text and higher energy is for corrupted text.</p><p>The general technique of training a model to restore a corrupted version of an input is called denoising auto-encoder. But we can not use this trick for images because it is not feasible to enumerate all possible images. There is no solution to this problem. There are interesting ideas in this direction, but they have not yet led to results that are as good as joint embedding architectures.</p><p>One interesting avenue is <strong>latent-variable predictive architectures</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*ZjhdKqHp40LSgN9EOKu4bQ.png" /><figcaption>A latent-variable predictive architecture. Given an observation x, the model must be able to produce a set of multiple compatible predictions, shown as S-ribbon. As latent variable z varies within a set, the output varies over the set of plausible predictions [1].</figcaption></figure><p>This type of model contain an extra input variable, z. It is called latent because its value is <strong>never</strong> <strong>observed</strong>. As the latent variable varies over a given set, the output prediction varies over the set of plausible predictions compatible with the input x. Latent-variable models can be trained with contrastive methods, like generative adversarial network (GAN). The critic/discriminator is computing energy indicating whether the input y is reasonable. The generator network is trained to produce contrastive samples to which the critic is trained to associate high energy.</p><p>But there is a major issue, contrastive methods are very inefficient to train. In high-dimensional spaces such as images, there are many ways one image can be different from another. Finding a set of contrastive images that cover all the ways they can differ from a given image is a nearly impossible to achieve.</p><h4>Non-contrastive Energy-based SSL</h4><p>This is the hottest topic in SSL and seems very promising. These methods for joint-embedding use various tricks, such as computing virtual target embeddings for groups of similar images or making the two joint embedding architectures slightly different through the architecture or the parameter vector. Examples include Variational Auto-Encoder (VAE) and sparse modeling. SSL for vision is advancing with the models like SEER, SwAV, ConvNet.</p><h3>2.Self-Supervised Learning (SSL) 🎬</h3><p>Labeled data is scarce. Labeled data in a specialized area is even more. With enough labels, a task can be solved very well by using supervised learning that is a bottleneck in terms of building machine learning models without using massive amounts of labeled data. However, good performance usually requires a massive amount of labels which is expensive and laborious. Exploiting that amount of unlabelled data with unsupervised learning is not easy and usually underperforms compared to supervised learning. Empirically, it is impossible to label everything in the world. Producing clean labels is expensive but unlabeled data is being generated all the time. Yet more, there are some tasks that do not have enough labeled data. Furthermore, it facilitates the difficulty of designing effective network architectures for specific tasks.</p><p>Humans do have a <strong>common sense</strong> which refers to our generalized knowledge about the world. For instance, if you are sitting while reading this article, we do not expect from you to float away from the ground.</p><p>Common sense is the essence of biological intelligence in both humans and animals. It helps to learn new skills without requiring massive amounts of teaching for every single task. Simply, humans rely on previously acquired <strong>background knowledge</strong> of how the world works. By this advantage, for instance, once we see a picture of a cat we will be able to recognize cats, even the ones that we have never seen.</p><p>Self-supervised learning (SSL) is one of the most promising ways to build such background knowledge and approximate common sense in intelligent systems [1]. It enables to learn important patterns to recognize and understand the data. Systems that are trained with SSL perform considerably better than supervised manner. SSL aims at learning latent representations from large-scale data by solving designed pretext tasks, rather than using human annotations.</p><p>So basically, by using SSL, we can get labels for free for unlabelled data and train unsupervised dataset in a supervised manner which is achieved by framing a supervised learning task in a special form to predict only a subset of information using the rest. By doing so, all the required information is obtained for both inputs and labels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IoqEqMNDO9_TYHxM6y12Hw.png" /><figcaption>Summary of SSL — LeCun [2]</figcaption></figure><p>SSL obtains supervisory signals that leverage underlying structure from the data. The general technique is to predict any unobserved or hidden part of the input from the any observed or unhidden part of the input. For example, in NLP we can hide a part of the sentence and predict the hidden words from the remaining words. Also, we can predict past or future frames in a video (hidden data) from current ones (observed data).</p><p>Unsupervised learning is ill-defined and refers to no supervision. However, self-supervised refers to using far more feedback signals than unsupervised and reinforcement learning do [1].</p><p>Self-supervised learning allows us to train NLP models such as BERT, RoBERTa, XLM-R etc. These models are trained on large unlabeled text data sets and then for downstream tasks. Basically, they are pretrained phase in which some of the words have been masked or replaced to predict those words. By doing so, this system allows the model to represent the meaning of the text.</p><p>However, it is significantly more difficult to represent uncertainty in the prediction for images than it is for words [3]. Because we do not know how to efficiently represent uncertainty when we predict missing frames in a video or missing patches in an image. However, new SSL models/systems are being developed to overcome this issue.</p><p>SSL frameworks can be categorized into two classes: <strong>predictive</strong> and <strong>contrastive</strong>. Predictive SSL frameworks are auto-encoding, siamese network, and clustering.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mgHASrzYRz1XpzdIGyKJiQ.png" /><figcaption>SSL frameworks. a-c are predictive and d is contrastive SSL [3].</figcaption></figure><h3>Predictive Models</h3><p>Predictive models optimize the similarity or correlations between the representations of two views of the same object, without considering their similarity to that of negative samples in training objectives.</p><h4><strong>Auto-encoding</strong></h4><p>It is based on the use of auto-encoders. A standard auto-encoder learns a compressed latent embedding that represents the input of the encoder and expects to reconstruct the original input from the latent representation, i. e., the decoder output. The dimensionality of the latent representation must be carefully designed, as it determines the representation reliability. When setting a too large latent dimensionality, an auto-encoder risks to learn an identity function, i. e., maps the input directly to the output, and hence becomes useless. There are techniques to prevent auto-encoders from learning an identity function because input data can be partially corrupted by randomly zeroing some input values while trying to recover the original undistorted input.</p><p>Continuous Bag-of Words (CBoW) and Skip-gram are used to learn underlying word representations. CBoW is trained to predict a single word from its context words and conversely, Skip-gram aims to predict the left and right context words. CBoW is better at capturing syntactic relationships and Skip-gram is better at capturing semantic relationships.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LR4aCu2sPYGmbHhed-f_Q.png" /><figcaption>Two architecture of Word2Vec [3]</figcaption></figure><p>Also, auto-regressive models can be used to learn representations by predicting the future on the past context. <em>Auto-regressive Predictive Coding (APC)</em> codes on wave samples by taking into account uni-directional information of a sequence and an additional context network aggregates the resulting representations up to the current time step. So, it is usually like a recurrent neural network (RNN) for modeling the temporal information. The output context vector is used to predict the next audio representation.</p><p><em>Masked Predictive Coding (MPC)</em> trains directly a bidirectional architecture by masking parts of the input signals. Transformer encoders and bidirectional RNNs have been considered as context networks. Further, <em>Non-autoregressive Predictive Coding (NPC)</em> applies a mask on its model input, but it learns representations based on local dependencies of an input sequence, rather than globally.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*48olxC_Ql6OSULFAJes17A.png" /><figcaption>Auto-regressive Predictive Coding (APC) and Masked Predictive Coding (MPC) [3]</figcaption></figure><h4>Siamese Models</h4><p>They have typical two tower architecture in which the towers share same or similar architecture — parameters can be shared or be different. Each tower processes a view of data sample. The encoded representations in the high-dimensional latent space should be close to each other, thus, during training the representations from one tower can be seen as the training target, pseudo-labels, for the other tower.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n0PLRNkwOlXwFbjiM2fX3g.png" /><figcaption>Predictive Models Using Siamese Models [3]</figcaption></figure><h4>Clustering</h4><p>Each category occupy a separate manifold in the representation space. K-means, DeepCluster, Local Aggregation, SwAV etc. can be used for clustering in SSL.</p><h3>Contrastive Models</h3><p>The key idea is to pull the representations of two similar inputs — positive pair — close in the latent space and to push dissimilar ones. Siamese models that employ contrastive learning are SimCLR, MoCo, etc. Some models do not use negative samples, as in BYOL, SimSiam, Barlow Twins.</p><h3>3.SSL in the Wild 🦁</h3><h4>Image-based SSL</h4><p>There are many ideas on this topic. A common workflow is to train a model on one or multiple pretext tasks with unlabelled images and then use one intermediate feature layer of this model to feed a multinomial logistic regression classifier on data. The final classification accuracy quantifies how good the learned representation is.</p><ul><li><strong>Distortion:</strong> A small distortion on an image does not modify its original semantic meaning or geometric forms. Slightly distorted images are considered the same as original. So, the learned features are expected to be invariant to distortion.</li><li><strong>Patches:</strong> The model extracts multiple patches from one image and ask the model to predict the relationship between these patches. <em>Relative position</em> is an important concept to understand the <em>spatial context</em> of objects.</li><li><strong>Colorization: </strong>It can be used as a powerful SSL task by training a model to color a grayscale input image which is precisely mapping this image to a distribution over quantized color value outputs.</li><li><strong>Generative Modeling: </strong>The pretext task is to reconstruct the original input while learning meaningful latent representation. <em>Denoising Autoencoder</em> learns to recover an image from a version that is partially corrupted or has random noise. <em>Context Encoder</em> is trained to fill in a missing piece in the image.</li><li><strong>Bidirectional GANs:</strong> They introduce an additional encoder to learn the mappings from the input to the latent variable z. The discriminator predicts in the joint space of the input data and latent representation.</li><li><strong>Contrastive Learning:</strong> <em>Contrastive Predictive Coding (CPC)</em> is an approach for unsupervised learning from high-dimensional data by translating a generative modeling problem to classification problem. The contrastive loss or InfoNCE is inspired from <em>Noise Contrastive Estimation (NCE). It </em>uses cross-entropy loss to measure how well the model can classify the <em>future</em> representation amongst a set of unrelated negative samples.</li></ul><h4>Audio-based SSL</h4><p>The most of aforementioned SSL methods are transferred into audio domain. Speech2Vec is built based on an RNN encoder-decoder by processing mel-spectrogram of the audio, and Audio2Vec is built of stacks of CNN blocks by processing mel-frequency cepstral coefficients (MFCC). HuBERT, Wav2Vec, CPC models utilizes raw waveform input format. Usually contrastive or InfoNCE loss are employed. For the encoder part, 1D CNN, Transformer, BERT, LSTM, CNN etc. components and combinations are selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*aKcD-ZIWkxZ5VE05qmUi3Q.png" /><figcaption>Wav2Vec Architectures [3]</figcaption></figure><h3>Conclusion</h3><p>In this post, we went through the core idea of SSL and similarity with common sense —background of human knowledge. This idea is implemented via SSL models. SSL paradigm is where a model learns to represent and understand data by generating its own labels/targets (pseudo-labels) from the input data itself, unlike the supervised learning that relies on externally provided labels. There are two main approaches in SSL: predictive models and contrastive models. Predictive models involve training a neural network to predict a part of the input data from another part of the same data and the idea is to create a task where the model to learn meaningful representations from the input. Contrastive models focus on learning representations by contrasting similar and dissimilar examples, so that, similar data points get closer in the representation space while pushing dissimilar data points farther apart.</p><blockquote>For further research papers about self-supervised learning, this awesome Github repo is an awesome start: <a href="https://github.com/jason718/awesome-self-supervised-learning">https://github.com/jason718/awesome-self-supervised-learning</a></blockquote><h3>References</h3><p>[1] <a href="https://ai.meta.com/blog/self-supervised-learning-the-dark-matter-of-intelligence/">https://ai.meta.com/blog/self-supervised-learning-the-dark-matter-of-intelligence/</a></p><p>[2] <a href="https://www.youtube.com/watch?v=7I0Qt7GALVk">https://www.youtube.com/watch?v=7I0Qt7GALVk</a></p><p>[3] Liu, S., Mallol-Ragolta, A., Parada-Cabaleiro, E., Qian, K., Jing, X., Kathan, A., … &amp; Schuller, B. W. (2022). Audio self-supervised learning: A survey. <em>Patterns</em>, <em>3</em>(12).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1be7a270eb47" width="1" height="1" alt=""><hr><p><a href="https://medium.com/albert-health/self-supervised-learning-blending-essence-of-biological-intelligence-into-machines-1be7a270eb47">Self-Supervised Learning: Blending Essence of Biological Intelligence into Machines</a> was originally published in <a href="https://medium.com/albert-health">albert-health</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Çocuk Diş Radyografi Görüntülerinde Instance Segmentation]]></title>
            <link>https://medium.com/@rabiaedayilmaz/%C3%A7ocuk-di%C5%9F-radyografi-g%C3%B6r%C3%BCnt%C3%BClerinde-instance-segmentation-59179064d34?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/59179064d34</guid>
            <category><![CDATA[medical]]></category>
            <category><![CDATA[dentistry]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[instance-segmentation]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Thu, 13 Jul 2023 18:53:52 GMT</pubDate>
            <atom:updated>2023-07-13T18:53:52.022Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*I5P38nCEMMQ_w3M4" /><figcaption>Çocuk Diş Radyografi Veri Setinden Bir Örnek [4]</figcaption></figure><p>Bu yazıda Nature’da 14.06.2023 tarihinde yayınlanan <a href="https://www.nature.com/articles/s41597-023-02237-5"><em>Children’s dental panoramic radiographs dataset for caries segmentation and dental disease detection</em></a> makalesi ve yayınladığı veri setini inceleyeceğiz. Sonrasında ise notebook bölümü mevcuttur. İlk notebook ile veri setini analiz edeceğiz — Exploratory Data Analysis (EDA). İkinci notebook ile Mask R-CNN modelini eğiteceğiz. Üçüncü ve son notebook’taki modeli test edip, sonuçları görselleştirerek gözlemleyeceğiz.</p><h4><strong>İçindekiler</strong></h4><ol><li><strong><em>Giriş — Ağız Sağlığı</em></strong></li><li><strong><em>Makale ve Veri Seti</em></strong></li><li><strong><em>Instance Segmentation ve Mask R-CNN Modeli</em></strong></li><li><strong><em>Notebook—Çocuk Radyografi Diş Görüntüleri</em></strong></li></ol><h3>1.Giriş — Ağız Sağlığı</h3><p>Ağız sağlığı, tüm beden sağlığımıza bir penceredir [1]. Ağzımız solunum ve sindirim sistemlerinin başlangıç noktasıdır ve çoğunlukla zararsız olan bakterilerle dolup taşmaktadır. Günlük diş fırçalama ve diş ipi kullanımı ağız sağlığı için önemli olduğu gibi çürüklere ve diş eti hastalıklarına neden olan bakterileri kontrol altında tutar.</p><p>Diş ile ilgili hastalıklar sadece ağız sağlığını ilgilendirmez. Çeşitli çalışmalara göre periodontitis, diş çürükleri ve diğer diş hastalıkları; koroner kalp hastalıkları, miyokard enfarktüs, felç gibi serebrovasküler hastalıkları, iskemi, hemorajik inme ve iskemik inme gibi durumların riskini önemli ölçüde artırmaktadır [2]. 2019 Küresel Diş Hastalıkları raporuna göre dünya çapında yaklaşık 3.5 milyar insan ağız hastalıklarından muzdarip ve en yaygın hastalık ise kalıcı dişteki çürükler [3]. Diş çürükleri en yaygın kronik hastalıklardandır ve dişin taç ile kök kısmında gelişebilmektedir. Tahmini olarak, 200 milyon insan kalıcı diş çürüğü ve 520 milyon çocuk süt dişi çürüğüne sahiptir [3]. Araştırmalara göre, çocuklarda görülen diş çürüğü vakası her geçen sene artış göstermektedir. Bu yüzden, küçük yaşta doğru önlem ve tedavi diş çürükleri için büyük önem arz etmektedir.</p><h3>2.Makale ve Veri Seti</h3><p>Diş hekimleri pediyatrik vakalarda yetişkinlerden daha karmaşık diş gelişimi ile karşılaştıklarında, manuel olarak analiz ettikleri panoramik diş radyografi görüntülerinden yardım alır. Bu blog yazısında incelenen makaledeki diş çürüklerini segmente etmek ve diş hastalıklarını tespit etme amacını taşıyan veri seti, <strong>ilk genel erişime açılmış çocuk diş radyografi görüntülerini içeren veri seti</strong>dir. 2–13 yaş arasındaki toplamda 106 hastadan derlenen panoramik radyografi görüntüleri EISeg (Efficient Interactive Segmentation)-segmentation annotation- ve LabelMe-image annotation- yazılımları ile işaretlenmiştir.</p><p>Veri setindeki pediyatrik hastaların %71.29&#39;unda çoklu diş hastalıkları gözlemlenmiştir. Bu durum, diş hekimlerinin lezyonu nokta atışı olarak tanımlamasını ve tedavi planı hazırlamasını güçleştirmektedir. Derin öğrenme modellerini kullanmak bu noktada otomatik, işlemde etkili ve kolaylaştırıcı olamasıyla fayda sağlamaktadır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*fK15klPjDXubgBY9ABrAew.png" /><figcaption>Diş Veri Setinin Nasıl Oluşturulup İşlendiğini Anlatan Şekil [4]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*N7JVP737S3Yju4DTXa8_ug.png" /><figcaption>Çocuk Diş Veri Setinin Oluşturulma Adımları[4]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/707/1*wiEWgYIEeUHz7h1RN1uWBw.png" /><figcaption>Çocuk Diş Veri Seti Dağılımı İstatiksel Özellikleri [4]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/705/1*183bXnfkXTokT_CZxlfGaw.png" /><figcaption>Çocuklardaki Diş Hastalıklarının Yaşa Göre Dağılımı [4]</figcaption></figure><p>Veri seti 3 dosya içermektedir: yetişkin diş segmentasyonu, çocuk diş çürükleri segmentasyonu ve pediyatrik diş hastalıkları tespiti. Görüntüler ile birlikte maskeler de sağlanmıştır. Instance segmentation görevi için 2. olan çocuk diş çürükleri segmentasyonu veri setini kullanacağız ve içerisinde pixel etiketleri, segmentasyon ve sınırlayıcı kutuların annotation’larının olduğu <em>.json </em>dosyasını kullanacağız. Ayrıca eğitim için sadece train dosyasındaki görüntüler (70 adet) kullanılmıştır.</p><p>Çalışmada veri seti üzerinde U-Net, R2 U-Net, PSPNet ve DeepLabV3+ modelleri ile semantic segmentation yapılmıştır.</p><blockquote>Veri setine hızlı şekilde ulaşıp, kullanabilmek için Kaggle platformuna eklediğim <a href="https://www.kaggle.com/datasets/truthisneverlinear/childrens-dental-panoramic-radiographs-dataset">bu linkten</a> ulaşabilirsiniz. Ve yeni bir notebook oluşturarak eşlik edebilir veya farklı yaklaşımları test edebilirsiniz.</blockquote><h3>3.Instance Segmentation ve Mask R-CNN Modeli</h3><p>Instance segmentation bir computer vision-bilgisayar görüsü görevidir. Görüntüdeki her bir objeyi tespit ederek, onlar için bir sınırlayıcı kutu-bounding box oluşturup içindeki objedeki pixel’leri segmente ederek sınıflandırma işlemini içeren bir görevdir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*TSEmDpU-rbua7L8bqPY_eQ.png" /><figcaption>Her Bir Sınıf İçerisindeki Objeyi de Ayrı Bir Örnek Olarak Sınıflandırır [5]</figcaption></figure><p>Kısacası instance segmentation görevinin amacı, her bir objeyi tespit ederek pixel-wise olarak segmente etmektir. Bu bağlamda, radyografi veri setimizdeki her bir diş ayrı olarak tespit edilecek ve segmente edilecektir.</p><p>Bu görev için <a href="https://github.com/open-mmlab/mmdetection">MMDetection Toolbox</a> sıklıkla kullanılmaktadır. Annotation bilgisini içeren <em>.json </em>dosyası <a href="https://cocodataset.org/#home">COCO dataset format</a> ile işlenerek hazır hale getirilir.</p><p>Instance segmentation için tercih edilen modeller arasında Mask R-CNN (ICCV’2017), Cascade Mask R-CNN (CVPR’2018), Mask Scoring R-CNN (CVPR’2019), Hybrid Task Cascade (CVPR’2019), YOLACT (ICCV’2019), SOLOv2 (NeurIPS’2020), Mask2Former (ArXiv’2021) vb. yer almaktadır.</p><p>Bu yazımda Mask R-CNN modeli test edilmiştir.</p><h4>Mask R-CNN</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/355/1*PjrRKglMUbNRcFLfvN0wWQ.png" /><figcaption>Mask R-CNN [6]</figcaption></figure><p>Her bir obje için segmentasyon maskesi oluşturan modeldir. Faster R-CNN modeline maske tahmin eden yeni bir dal eklenmesiyle elde edilmiştir. Faster R-CNN her bir aday obje için iki çıktıya sahiptir: sınıf etiketi ve sınırlayıcı kutu-bounding box. İki basamaktan oluşan Faster R-CNN, ilk basamakta aday obje sınırlayıcı kutuları Region Proposal Network (RPN) ile tahmin eder ve ikinci basamakta da Fast R-CNN ile her bir aday sınırlayıcı kutu için RoIPool kullanarak özellikleri/features çıkararak sınıflandırma ve sınırlayıcı kutu regresyon tahmini yapar. Benzer bir şekilde iki basamaklı bir prosedür izleyen Mask R-CNN de birinci basamakta RPN kullanır. İkinci basamakta ise her RoI’de sınıf ve kutu tahmini yapan dala paralel bir binary maske adımı bulunmaktadır. Bu çoğu sistemin aksine bir yöntemdir çünkü genelde sınıflandırma maske tahminine bağlıdır. Loss olarak multi-task loss kullanılmıştır: <em>L = L_cls + L_box + L_mask</em>. L_mask hesaplanırken, her pixel için sigmoid ve binary loss uygulandığı için semantic segmentation’daki gibi (softmax ve multinomial loss) maske tahmininde sınıflar arası rekabet gözlenmez.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/1*MxC7h2HzM1yJBBTKIy0ICA.png" /><figcaption>Eklenen Head Yapısı [6]</figcaption></figure><p>İmplementasyonu ve mimarisini daha yakından incelemek için <a href="https://github.com/matterport/Mask_RCNN">repo</a>’ya göz atabilirsiniz.</p><h3>4.Notebook — Çocuk Radyografi Diş Görüntüleri</h3><p>Bu bölüm notebook’lar üzerinden ilerleyecektir. Sırasıyla linkler üzerinden notebook’lara erişip okuyabilirsiniz.</p><h4><a href="https://www.kaggle.com/code/truthisneverlinear/dental-radiographs-eda-and-visualize">4.1.Dental Radiographs — EDA and Visualize</a></h4><h4><a href="https://www.kaggle.com/code/truthisneverlinear/train-children-dental-radiographs-maskrcnn">4.2.[TRAIN] Children Dental Radiographs — MaskRCNN</a></h4><h4><a href="https://www.kaggle.com/code/truthisneverlinear/infer-children-dental-radiographs">4.3.[INFER] Children Dental Radiographs</a></h4><h4>Sample Result</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/547/1*WG5mtGfgtu93hiHYDqcwkQ.png" /></figure><h3>References</h3><p>[1] <em>Oral health: A window to your overall health</em>. (2021, October 28). Mayo Clinic. <a href="https://www.mayoclinic.org/healthy-lifestyle/adult-health/in-depth/dental/art-20047475">https://www.mayoclinic.org/healthy-lifestyle/adult-health/in-depth/dental/art-20047475</a></p><p>[2] Seitz, M. W. <em>et al</em>. Current knowledge on correlations between highly prevalent dental conditions and chronic diseases: An umbrella review. <em>Prev. chronic disease</em> <strong>16</strong>, E132, <a href="https://doi.org/10.5888/pcd16.180641">https://doi.org/10.5888/pcd16.180641</a> (2019).</p><p>[3] Vos, T. <em>et al</em>. Global burden of 369 diseases and injuries in 204 countries and territories, 1990–2019: a systematic analysis for the global burden of disease study 2019. <em>The Lancet</em> <strong>396</strong>, 1204–1222, <a href="https://doi.org/10.1016/S0140-6736(20)30925-9">https://doi.org/10.1016/S0140-6736(20)30925-9</a> (2020).</p><p>[4] Zhang, Y., Ye, F., Chen, L., Xu, F., Chen, X., Wu, H., Cao, M., Li, Y., Wang, Y., &amp; Huang, X. (2023). Children’s dental panoramic radiographs dataset for caries segmentation and dental disease detection. <em>Scientific Data</em>, <em>10</em>(1). <a href="https://doi.org/10.1038/s41597-023-02237-5">https://doi.org/10.1038/s41597-023-02237-5</a></p><p>[5] Bandyopadhyay, H. (2023, April 24). The Definitive Guide to Instance Segmentation [+V7 tutorial]. <em>V7</em>. <a href="https://www.v7labs.com/blog/instance-segmentation-guide">https://www.v7labs.com/blog/instance-segmentation-guide</a></p><p>[6] He, K., Gkioxari, G., Dollár, P., &amp; Girshick, R. (2017). Mask r-cnn. In <em>Proceedings of the IEEE international conference on computer vision</em> (pp. 2961–2969).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59179064d34" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Transformers in Vision]]></title>
            <link>https://medium.com/@rabiaedayilmaz/transformers-in-vision-899ab1a94a30?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/899ab1a94a30</guid>
            <category><![CDATA[attention]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[transformers]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Tue, 18 Apr 2023 20:55:19 GMT</pubDate>
            <atom:updated>2023-04-18T21:00:52.106Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*STv81dVDqC6xxGgsMsB6Cw.jpeg" /><figcaption>Scene from Bumblebee (2018)</figcaption></figure><p>In this blog, we will delve into the concept of transformers in vision. Starting from the ViT paper, the popular models that are based on ViTs will be reviewed for various tasks.</p><h3>1. Vision Transformers (ViT)</h3><p>Transformers were developed for particularly Natural Language Processing (NLP) tasks, however, this couldn’t stop Dosovitskiy et. al. [1] from coming up with a novel idea: <em>sequences of image patches</em>. Before that paper, transformer architecture was used in conjunction with convolutional networks (CNNs) or used to replace certain components of CNNs while keeping the overall structure [2]. But they demonstrated leveraging the usage of CNNs is not compulsory and that a pure transformer applied directly to sequences of image patches can perform very well on image classification tasks. If it is pre-trained on large amounts of data and transferred to multiple mid-sized or small image recognition benchmarks, such as CIFAR100 and ImageNet, the presented model VisionTransformer (ViT) performs outstanding results while requiring fewer computational sources to train. Following the original ViT paper, new follow-up work is done: DeiT [3], BEiT [4], DINO [5], MAE [6], etc.</p><p>It is the same operation in both fields (NLP and CV): self-attention. It is applied in patch embeddings instead of word embeddings [7].</p><p>Amazing but here is more.</p><p>Transformers are great but especially for vision tasks they have some disadvantages. They lack the inductive biases of CNNs, such as <strong>translation invariance</strong> and a<strong> locally restricted receptive field </strong>[8]. Invariance is when you can recognize an entity in an image, even if its appearance or position varies. Translation, in computer vision, is that each image pixel has been moved by a fixed amount in a particular direction. Moreover, convolution is a linear local operator and we see only neighbor values as indicated by the kernel [9]. On the other hand, the transformer is by design <strong>permutation invariant. </strong>So that, it can not process grid-structure data. Therefore, the goal is to convert a spatial non-sequential signal to a sequence [10].</p><h3>2. How Does It Work?</h3><p>Step by step, it can be summarized as:</p><ol><li>Split an image into patches ✂️</li><li>Flatten the patches 😑</li><li>Produce lower-dimensional linear embeddings from the flattened patches 🥞</li><li>Add positional embeddings ⛩️</li><li>Feed the sequence as an input to a standard transformer encoder 🤖</li><li>Pretrain the model with image labels — fully supervised on a huge dataset 🥷</li><li>Finetune on the downstream dataset for image classification</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_c8SqxPMY_dsApyvDJ8HtA.gif" /><figcaption>After flattening, Image Patches are linearly projected, so they can be fed into a transformer encoder (Jack), and then fed through a simple MLP to classify them [11]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*7NbefNq1df4cWp8sY_KwEg.png" /><figcaption>Famous Encoder Jack from Titanicformer[12]</figcaption></figure><p>To be clear, in ViT there is no decoder. No room for ladies throwing diamonds for nothing in the ocean. After the encoder, there is an extra linear layer — MLP head for the final classification.</p><p>If ViT is trained on datasets that have more than at least 14M images, it can approach or beat state-of-the-art CNNs. Also, it is claimed that it is better to fine-tune at higher resolutions than pre-training. Basically, an image has WxHxC dimensions and N patches denoted as HW/P**2. In the paper [13], the title is “An Image is Worth 16x16 Words” because the image patch [16, 16, 3] is flattened to 16x16x3.</p><p>Transformer encoder performs on patch-level and embeddings learn the order of relationships between patches that contain spatial information. After low-level dimensional linear projection, a trainable positional embedding is added to patch representations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*xMjm3Ta9MDMjpdcgpo6rjQ.png" /><figcaption>ViT representations are not smooth like AlexNet [14].</figcaption></figure><p>Consequently, we have non-local interactions between image patches, for path size P it is maximum PxP.</p><h3>3. More Autobots in Vision</h3><ul><li><strong>DeiT:</strong> scalable and data efficient. Utilizes knowledge distillation technique (teacher-student). Interesting reading on knowledge distillation [15]. Self-distillation [16] is used. Basically, it is using a single trained model with identical architecture but with different seeds. Moreover, there are distillation tokens that are concatenated to the patch embeddings of ViT. The distillation token <strong>comes from a trained teacher CNN backbone</strong>. The distillation allows model to have fewer data and super strong data augmentation, that may cause the ground truth label to be imprecise. It employs data regularization techniques like stochastic depth which is basically dropping out some skip connections.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*lZRnagfPDVm_ria_m85cfw.png" /><figcaption>Loss Function of DeiT [17]</figcaption></figure><ul><li><strong>Pyramid Vision Transformer (PVT):</strong> Spatial Reduction Attention (SRA) is utilized to overcome the quadratic complexity of the attention mechanism in PVTs. It is achieved by a spatial reduction of both keys and values. Similar to Linformer attention [18] idea. <strong>By applying SRA, the spatial dimensions of the features slowly decrease throughout the model. </strong>In PVT-v2, the upgrades: overlapping patch embeddings (good for especially dense tasks), convolutional feedforward networks, and linear-complexity self-atteniton layers.</li><li><strong>Swin Transformer: </strong>The goal is to utilize locality from standard NLP transformers by non-overlapping local/window attentions. This window-to-window communication in the next layer produces a hierarchical representation by progressively merging the windows themselves.</li><li><strong>DINO:</strong> Besides having a cool name, employs self-supervised learning (SSL), so here unsupervised data. Great thing is that you do not need to fine-tune since SSL creates such robust representations. Unlike other SSL models, it used cross-entropy loss. Knowledge distillation is applied. The teacher model is randomly initialized and parameters are updated with an exponential moving average from the student parameters. A temperature softmax is applied to both teacher and student with different temperatures.</li><li><strong>Multiscale Vision Transformers (MViT):</strong> It leverages of the idea of combining multi-scale feature hierarchies with vision transformer models.</li><li><strong>Timeformer:</strong> Video classification. Space-time attention (cool name, right?)</li><li><strong>Segformer:</strong> Semantic segmentation. Contains a hierarchical transformer encoder that outputs multiscale features. Does not need positional encoding.</li><li><strong>UNETR (Unet+Transformer): </strong>Vision transformer for 3D medical image segmentation.</li></ul><p>Scaling is important in terms of deep learning models. For ViT, there are a couple of techniques employ replacing self-attention with independent token and channel mixing methods: MLP-Mixer, XCiT (Cross-Covariance Image Transformers), XCA (Cross-Covariance Attention), Local Patch Interaction, etc.</p><h3><strong>4. Code is the Truth</strong></h3><p>I like reading theory but there is nothing like coding it up.</p><blockquote>“Truth can only be found in one place: the code.” — <strong>Robert C. Martin</strong></blockquote><p>For this task, PyTorch is a good choice and it also is preferred by many researchers as it is flexible, generally used, and Pythonic.</p><pre># REFERENCE: https://github.com/lucidrains/vit-pytorch<br><br># LIBRARIES<br><br>#install library<br>#!pip install einops<br><br># import libraries<br>import torch<br>import torch.nn as nn<br><br>from einops import rearrange, repeat<br>from einops.layers.torch import Rearrange<br><br># HELPER FUNCTION<br>def pair(t):<br>  &quot;&quot;&quot;<br>    Make sure that given size is tuple, else make it tuple of square image<br>  &quot;&quot;&quot;<br>  return t if isinstance(t, tuple) else (t, t)<br><br># BUILDING BLOCKS: CLASSES<br><br>class PreNorm(nn.Module):<br>  &quot;&quot;&quot;<br>    Applies Layer Normalization before given function<br>  &quot;&quot;&quot;<br>  def __init__(self, dim, fn):<br>    super().__init__()<br>    self.norm = nn.LayerNorm(dim)<br>    self.fn = fn<br>  def forward(self, x, **kwargs):<br>    return self.fn(self.norm(x), **kwargs)<br><br>class FeedForward(nn.Module):<br>  &quot;&quot;&quot;<br>    Feedforward part of the encoder transformer for after attention<br>  &quot;&quot;&quot;<br>  def __init__(self, dim, hidden_dim, dropout=0.):<br>    super().__init__()<br>    self.net = nn.Sequential(<br>      nn.Linear(dim, hidden_dim),<br>      nn.GELU(),<br>      nn.Dropout(dropout),<br>      nn.Linear(hidden_dim, dim),<br>    )<br>  def forward(self, x):<br>    return self.net(x)<br><br>class Attention(nn.Module):<br>  &quot;&quot;&quot;<br>    Attention block to implement in transformer<br>  &quot;&quot;&quot;<br>  def __init__(self, dim, heads=8, dim_head=64, dropout=0.):<br>    super().__init__()<br>    inner_dim = dim_head * heads<br>    project_out = not(heads==1 and dim_head==dim)<br>  <br>    self.heads = heads<br>    self.scale = self.dim_head ** -0.5<br><br>    self.attend = nn.Softmax(dim=-1)<br>    self.dropout = nn.Dropout(dropout)<br><br>    self.to_qkv = nn.Linear(dim, inner_dim*3, bias=False)<br><br>    self.to_out = nn.Sequential(<br>      nn.Linear(inner_dim, dim),<br>      nn.Dropout(dropout),<br>    ) if project_out else nn.Identity()<br>  def forward(self, x):<br>    qkv = self.to_qkv(x).chunk(3, dim=-1)<br>    q, k, v = map(lambda t: rearrange(t, &quot;b n (h d) -&gt; b h n d&quot;, h=self.heads), qkv)<br>    <br>    dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale<br><br>    attn = self.attend(dots)<br>    attn = self.dropout(attn)<br><br>    out = torch.matmul(attn, v)<br>    out = rearrange(out, &quot;b h n d -&gt; b n (h d)&quot;)<br><br>    return self.to_out(out)<br><br>class Transformer(nn.Module):<br>  &quot;&quot;&quot;<br>    Encoder transformer<br>  &quot;&quot;&quot;<br>  def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout):<br>    super().__init__()<br>    self.layers = nn.ModuleList([])<br>    for _ in range(depth):<br>      self.layers.append(nn.ModuleList([<br>        PreNorm(dim, Attention(dim, heads, dim_head, dropout)),<br>        PreNorm(dim, FeedForward(dim, mlp_dim, dropout)),<br>    ]))<br>  def forward(self, x):<br>    for attn, ff in self.layers:<br>      x = attn(x) + x<br>      x = ff(x) + x<br>  return x<br><br>class ViT(nn.Module):<br>  &quot;&quot;&quot;<br>    Overall model structure<br>  &quot;&quot;&quot;<br>  def __init__(self, *, image_size, patch_size, num_classes, dim, depth, heads, mlp_dim, pool=&quot;cls&quot;, channels=3, dim_head=64, dropout=0., emb_dropout=0.):<br>    super().__init__()<br>    image_height, image_width = pair(image_size)<br>    patch_height, patch_width = pair(patch_size)<br><br>    assert image_height % patch_height == 0 and image_width % patch_width == 0, &quot;Image dimensions must be divisible by patch size.&quot;<br>    <br>    num_patches = (image_height // patch_height) * (image_width // patch_width)<br>    patch_dim = channels * patch_height * patch_width<br><br>    assert pool in {&quot;cls&quot;, &quot;mean&quot;}, &quot;Pool type must be either cls (cls token) or mean (mean pooling).&quot;<br><br>    self.to_patch_embedding = nn.Sequential(<br>      Rearrange(&quot;b c (h p1) (w p2)&quot; -&gt; &quot;b (h w) (p1 p2 c)&quot;, p1=patch_height, p2=patch_width),<br>      nn.LayerNorm(patch_dim),<br>      nn.Linear(patch_dim, dim),<br>      nn.LayerNorm(dim),<br>    )<br>    self.pos_embedding = nn.Parameter(torch.randn(1, num_patches+1, dim))<br>    self.cls_token = nn.Parameter(torch.randn(1, 1, dim))<br>    self.dropout = nn.Dropout(dropout)<br><br>    self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout)<br><br>    self.pool = pool<br>    self.to_latent = nn.Indetity()<br><br>    self.mlp_head = nn.Sequential(<br>      nn.LayerNorm(dim),<br>      nn.Linear(dim, num_classes),<br>    )<br>  def forward(self, img):<br>    x = self.to_patch_embedding(img)<br>    b, n, _ = x.shape<br><br>    cls_tokens = repeat(self.cls_token, &quot;1 1 d -&gt; b 1 d&quot;, b=b)<br>    x = torch.cat((cls_tokens, x), dim=1)<br>    x += self.pos_embedding[:, :(n+1)]<br>    x = self.dropout(x)<br><br>    x = self.transformer(x)<br><br>    x = x.mean(dim=1) if self.pool == &quot;mean&quot; else x[:, 0]<br><br>    x = self.to_latent(x)<br><br>    return self.mlp_head(x)<br><br><br># TEST<br># sanity check by feeding random tensor<br>def test():<br>    v = ViT(<br>        image_size = 256,<br>        patch_size = 32,<br>        num_classes = 1000,<br>        dim = 1024,<br>        depth = 6,<br>        heads = 16,<br>        mlp_dim = 2048,<br>        dropout = 0.1,<br>        emb_dropout = 0.1<br>    )<br><br>    img = torch.randn(1, 3, 256, 256)<br><br>    preds = v(img)<br>    assert preds.shape == (1, 1000), &#39;correct logits outputted&#39;<br><br><br>test()</pre><h4>REFERENCES</h4><p>[1], [2], [13] Dosovitskiy, A., Beyer, L., Kolesnikov, A. I., Weissenborn, D., Zhai, X., Unterthiner, T., Dehghani, M., Minderer, M., Heigold, G., Gelly, S., Uszkoreit, J., &amp; Houlsby, N. (2020). An Image is Worth 16x16 Words: Transformers for Image Recognition at Scale. arXiv (Cornell University). <a href="https://arxiv.org/pdf/2010.11929">https://arxiv.org/pdf/2010.11929</a></p><p>[3], [17] Touvron, H., Cord, M., Douze, M., Massa, F., Sablayrolles, A., &amp; Jégou, H. (2020). Training data-efficient image transformers &amp; distillation through attention. arXiv (Cornell University). <a href="https://arxiv.org/pdf/2012.12877.pdf">https://arxiv.org/pdf/2012.12877.pdf</a></p><p>[4] Touvron, H., Cord, M., Douze, M., Massa, F., Sablayrolles, A., &amp; Jégou, H. (2020). Training data-efficient image transformers &amp; distillation through attention. arXiv (Cornell University). <a href="https://arxiv.org/pdf/2012.12877.pdf">https://arxiv.org/pdf/2012.12877.pdf</a></p><p>[5] Caron, M., Touvron, H., Misra, I., Jégou, H., Mairal, J., Bojanowski, P., &amp; Joulin, A. (2021). Emerging Properties in Self-Supervised Vision Transformers. HAL (Le Centre Pour La Communication Scientifique Directe). <a href="https://doi.org/10.1109/iccv48922.2021.00951">https://doi.org/10.1109/iccv48922.2021.00951</a></p><p>[6] He, K., Chen, X., Xie, S., Li, Y., Dollar, P., &amp; Girshick, R. (2022). Masked Autoencoders Are Scalable Vision Learners. 2022 IEEE/CVF Conference on Computer Vision and Pattern Recognition (CVPR). <a href="https://doi.org/10.1109/cvpr52688.2022.01553">https://doi.org/10.1109/cvpr52688.2022.01553</a></p><p>[7] Adaloglou, N. (2021, October 21). Transformers in computer vision: ViT architectures, tips, tricks and improvements | AI Summer. AI Summer. <a href="https://theaisummer.com/transformers-computer-vision/">https://theaisummer.com/transformers-computer-vision/</a></p><p>[8], [9], [10] Adaloglou, N. (2021a, January 28). How the Vision Transformer (ViT) works in 10 minutes: an image is worth 16x16 words | AI Summer. AI Summer. <a href="https://theaisummer.com/vision-transformer/">https://theaisummer.com/vision-transformer/</a></p><p>[11] Transformers for Image Recognition at Scale. (2020, December 3). <a href="https://ai.googleblog.com/2020/12/transformers-for-image-recognition-at.html">https://ai.googleblog.com/2020/12/transformers-for-image-recognition-at.html</a></p><p>[12] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., Kaiser, L., &amp; Polosukhin, I. (2017). Attention is All you Need. Neural Information Processing Systems, 30, 5998–6008. <a href="https://arxiv.org/pdf/1706.03762v5">https://arxiv.org/pdf/1706.03762v5</a></p><p>[14] Stanford University CS231n: Deep Learning for Computer Vision. (n.d.). <a href="http://cs231n.stanford.edu/">http://cs231n.stanford.edu/</a></p><p>[15] Hagen, A. (2021, March 8). <em>Three mysteries in deep learning: Ensemble, knowledge distillation, and self-distillation — Microsoft Research</em>. Microsoft Research. <a href="https://www.microsoft.com/en-us/research/blog/three-mysteries-in-deep-learning-ensemble-knowledge-distillation-and-self-distillation/">https://www.microsoft.com/en-us/research/blog/three-mysteries-in-deep-learning-ensemble-knowledge-distillation-and-self-distillation/</a></p><p>[16] Zhang, L. (2019, May 17). Be Your Own Teacher: Improve the Performance of Convolutional Neural Networks via Self Distillation. arXiv.org. <a href="https://arxiv.org/abs/1905.08094">https://arxiv.org/abs/1905.08094</a></p><p>[18] Wang, S., Li, B., Khabsa, M., Fang, H., &amp; Ma, H. (2020). Linformer: Self-Attention with Linear Complexity. arXiv (Cornell University). <a href="https://arxiv.org/pdf/2006.04768.pdf">https://arxiv.org/pdf/2006.04768.pdf</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=899ab1a94a30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ben, ChatGPT (2022)]]></title>
            <link>https://medium.com/@rabiaedayilmaz/ben-chatgpt-2022-1106949f56e1?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/1106949f56e1</guid>
            <category><![CDATA[robots]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[chatgpt]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 14:18:52 GMT</pubDate>
            <atom:updated>2023-01-26T06:42:20.763Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*idOFauWujttzEQK9FJhMVA.jpeg" /><figcaption>Ben, Robot (2004) Filmi [1]</figcaption></figure><blockquote>[Will Smith, kızgın] Sen sadece bir makinesin. Yaşamın bir taklidi. Bir robot senfoni yazabilir mi? Bir robot bir tabloyu güzel bir sanat şaheserine çevirebilir mi?</blockquote><blockquote>[Robot, merakla] Sen yapabilir misin?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*25DLei2rpzJV1yC4cyEGvA.png" /><figcaption>ChatGPT’nin Cevabı</figcaption></figure><p>ChatGPT’nin cevabına göre, ChatGPT, <strong>OpenAI</strong> şirketi tarafından geliştirilen son teknoloji bir dil işleme modelidir. Genel amaçlı gösterimleri öğrenmek için, unsupervised pre-training (etiketler olmadan ön-eğitim) uygulanmıştır. Temel amacı, çok çeşitli doğal dil sentezleme görevleri için (dil çevirisi, soru cevaplama, metin özetleme, diyalog üretme vb.) <strong>insan-<em>benzeri </em>metin</strong> sentezlemektir. Ayrıca, belirli görevler için de (dil modelleme, metin sınıflandırma, named entity recognition gibi) fine-tune edilebilir.</p><p>Bu blog yazımda, ön-hazırlık olarak kelime hazinesi bölümünden sonra makale incelemesi kısmında birlikte biraz uzun bir yolculuğa çıkacağız. ChatGPT’yi daha iyi anlamak için, sırasıyla, GPT, GPT-2 ve GPT-3 makalelerini inceleyeceğiz.</p><p>Sonrasında, diğer gruplar tarafından üretilmiş dev dil modellerinden bahsedeceğiz.</p><p>Onu izleyen bölümde <strong>diyalog ajanı</strong>nın (Google’ın ürettiği Sparrow adlı modele etiksel kaygılarla <strong>chatbot</strong> <strong>yerine</strong> vermiş olduğu terim) gelecek, etiksel boyut, büyük tablo ve gittiği yönden bahsedeceğim.</p><p>Ardından özet ile öğrendiklerimizi toparlayacağız. En sonda ise, basit bir GPT modeli implemente edeceğiz. Bu implementasyon bölümünü hazırlarken, büyük oranda <strong>&lt;3 Andrej Karpathy &lt;3</strong> ‘nin hazırladığı müthiş <a href="https://www.youtube.com/watch?v=kCc8FmEb1nY&amp;t=480s">Let’s build GPT: from scratch, in code, spelled out.</a> videosundan yararlandım. İzlemenizi şiddetle tavsiye etmemin ardından… <strong><em>Nöronlarımızı sıvalayalım!</em></strong></p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — —— —</p><h4><strong>İçindekiler</strong></h4><ol><li><strong><em>Ön-Bilgi Hazinesi 🦜</em></strong></li><li><strong><em>Makale İncelemesi </em></strong>📎</li></ol><p><strong>— 2.1. GPT </strong>🤖</p><p><strong>— 2.2. GPT-2 </strong>🤖🤖</p><p><strong>— 2.3. GPT-3 </strong>🤖🤖🤖</p><p><strong><em>3. Gelecek? </em></strong>⌛</p><p><strong><em>4. Özet </em></strong>📝</p><p><strong><em>5. Sıfırdan GPT İnşaa Edelim </em></strong>🛠️👩‍💻</p><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — —— — —</p><h3>1. Ön-Bilgi Hazinesi 🦜</h3><p>Bu bölümde yazı boyunca kullanacağım bir takım terimler ve olguların açıklaması mevcuttur. Bu bölümü atlayabilir ve ihtiyaç halinde geri dönerek referans alıp, ipin ucundan tutup yeni sekmelere seyahat edebilirsiniz. 🏴‍☠️</p><ul><li><strong>Objective Function:</strong> Modelde belli bir çıktıyı elde edebilmek için minimize veya maksimize edilmesi gereken fonksiyondur.</li><li><strong>Word Embeddings:</strong> Benzer kelimelerin, benzer gösterimlere sahip olmasını sağlayan (yüksek-boyutlu vektörler kullanarak) bir çeşit kelime gösterim şeklidir. Böylelikle kelimeleri, makinenin anlayabileceği vektörlerle çok-boyutlu uzayda ifade etmiş oluruz. Bunun için çeşitli algoritmalar vardır: Embedding Layer, Word2Vec, GloVe vb.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*aKTqbzRUXtTQJkRNUxlMtg.png" /><figcaption>Figüre 0. Embedding Örneği [11]</figcaption></figure><ul><li><strong>Tokenization:</strong> Kütlenin birimine kilogram, uzunluğun birimine metre diyoruz. Peki, dilin birimi nedir? Onu birimlendirmek için paragraflara, cümlelere, kelimelere, hatta harflere bölebiliriz. Bir metni daha küçük alt parçalara bölüp, işlemeye tokenization denilir. Çeşitli tokenization yöntemleri vardır: word tokenization, sentence tokenization, subword tokenization vb.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*diphAQaJ4jhnysVTZxtIpQ.png" /><figcaption>Figür 00. Tokenleştirme Teknikleri [12]</figcaption></figure><ul><li><strong>Pre-training:</strong> Bir modeli önceki çok büyük veri setinde eğitip, verideki genel örüntüleri ve gösterimleri nitelikli bir şekilde çıkarmasına denilir. Bu şekilde, daha sonra hedeflenen problem üzerindeki veride, fine-tuning, pre-training’ten aldığı parametrelerle başlayarak eğitilerek sonuç iyileştirilir.</li><li><strong>Supervised vs Unsupervised vs Semi-Supervised Learning:</strong> Unsupervised’da eitketler olmadan, supervised’da etiketler varken ve semi-supervised’da ise supervised ve unsupervised yöntemleri birlikte kullanılarak (önce etiketsiz veri üzerinde eğitilir ve öğrenilen parametreler ile sonra etiketli veri üzerinde) öğrenim gerçekleştirilir.</li><li><strong>Meta-Learning:</strong> Bir görev yerine, birçok görevden öğrenmeyi öğrenen bir tekniktir. Önceki görevden öğrenilen bilgiyi, yeni görevine de entegre ederek öğrenmeye devam eder. Bu yapısıyla, ensemble learning’e benzetilebilir.</li><li><strong>Ablation Study:</strong> Farklı parçaların veya özelliklerin önemini değerlendirmek için uygulanan, modelden çıkarma (ablation) yoluyla, bir metottur.</li><li><strong>Language Model (LM): </strong>Bir metindeki, cümle veya döküman olsun, kelimelerin olasılıksal dağılımını tahmin etme görevine verilen isimdir. Bu görev ile eğitilen model, eğitim veri setine benzer yeni metin sentezlemekte veya yeni örnek metinlerdeki keliemelere olasılıklar atayarak anlam ve dil bilgisi belirlemede kullanılabilir. Pre-train edilen modeller (mesela self-supervised language modeling objective ile) genel olarak language model, dil modeli, olarak adlandırılır.</li><li><strong>Large Language Model (LLM): </strong>Aşırı derecede büyük veri setlerinde (dolayısıyla büyük boyut ve karmaşıklık) eğitilmiş dil modelleridir.</li><li><strong>Foundation Models: </strong>Etiketsiz metin verisinin bolluğu ve etiketli verinin kıtlığı durumu çok yaygındır. Discriminative language understanding görevleri için ise çok sayıda etiketli veriye ihtiyaç vardır. Bunun yerine bir model pre-train etmek (a — ha, foundation model) ve her bir görev için fine-tune etmek daha elverişlidir.</li><li><strong>Zero-Shot vs One-Shot vs Few-Shot Learning: </strong>Zero-shot learning, modeli zaman ve eforu düşürecek bir şekilde, veriyi etiketlemeden (cumburlop şeklinde) öğrenmektir. One-shot learning, geçmiş veriyi kullanarak sınıflandırma yapar. Yüz tanımlama sistemlerinde kullanılan bir tekniktir. Few-shot learning de, bir küçük set örnek içerir ve bunu yeni görevi öğrenmek için kullanır [32].</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*tc_Laj6K-JCLdylhSUGOMA.png" /><figcaption>Figür 000. Zero-Shot vs One-Shot vs Few-Shot [13]</figcaption></figure><h3>2. Makale İncelemesi📎</h3><p>Bu bölümü okumadan önce, Transformer’lar hakkında temel bilgiye sahip değilseniz, <a href="https://medium.com/@rabiaedayilmaz/attention-i%CC%87htiyac%C4%B1n-olan-tek-%C5%9Fey-adam%C4%B1m-e7e57635f050">bu yazı</a>mı okuyunuz.</p><p>Hatırlatıcı birkaç görsel ile özet geçiyorum.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*vlSR3mYEXDzLeVIUc6KWsA.png" /><figcaption>Figür 0000. Transformer [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*YymXHHQQLsSw9Za9NMWa_Q.png" /><figcaption>Figür 1. Encoder Bloğu [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*x-yp6FP2Vv1VDwgP6oc7sQ.png" /><figcaption>Figür 2. Decoder Bloğu [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*ebp78-9Wo1qjkPROWi3uxg.png" /><figcaption>Figür 3. Kelimeyi [MASK] çevirmek yerine (encoder-only olan BERT gibi), burada sağa doğru kelimeler tahmin edilir. [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*_2vcamyVsogNEP6A-cpLdA.png" /><figcaption>Figür 4. BERT’te Self-Attention kullanılırken, GPT’lerde Masked Self-Attention kullanılır (bir sonraki kelimeyi tahmin için) [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*FS8nWyppa8PN7JtFEIAVuw.png" /><figcaption>Figür 5. Sadece Decoder Bloklardan Oluşan Decoder-Only Model Örneği [8]</figcaption></figure><h4>2.1. GPT🤖</h4><blockquote>Makale: <a href="https://s3-us-west-2.amazonaws.com/openai-assets/research-covers/language-unsupervised/language_understanding_paper.pdf">Improving Language Understanding by Generative Pre-Training</a></blockquote><p>Nitelikli bir şekilde etiketlenmiş veri bulmanın yanı sıra, yeterli miktarda veri bulmak birçok deep learning modelini eğitmek için gerekli olan en önemli ve zor basamaklardan birisidir. Bu yüzden, Yapılan bir önceki araştırmalarda pre-trained word embeddings yetersiz verinin olduğu durumlar için kullanılmıştır ama bazı durumlarda, <em>kelime-seviyesi</em>ndeki bilgi daha karmaşık görevler için yetersiz gelmiştir.</p><p>Bu nedenle, bu makalede geniş bir yelpazedeki görevlerde iyi performans sergileyen (textual entailment, question answering, semantic similarity text classification gibi görevler) <strong>semi-supervised</strong> bir teknik kullanan bir model sunuluyor. Modelin avantajı, az miktardaki etiketlenmiş veri kısıtlamasının üzerinden devasa bir metin korpusunda <strong>unsupervised-generative-pretraining</strong> ve onu takip eden her spesifik görev için <strong>supervised discriminative fine-tuning</strong> ile üstesinden gelmiştir. Pre-training modelleri, tüm görevler için aynı kalmıştır. Fine-tuning için ise, sadece küçük ve belirli bir görev adaptasyonu yeterli olmuştur. Yazıldığı vakitteki 9 dil görevinden 12&#39;sinin state-of-the-art performanslarını büyük oranda iyileştirmiştir [2].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/192/1*gsiB3CNjcTjoxb745LobHg.png" /><figcaption>Figür 6. Bu Makalede Kullanılan Transformer Yapısı — Decoder-Only [5]</figcaption></figure><p>Modelin amacı, küçük adaptasyonlarla birçok göreve transfer edilebilen evrensel gösterimleri (universal representations) öğrenmektir. Bunun için etiketlenmemiş metne sahip olan büyük bir korpusa ve training örnekleri, hedef görevler, için manuel olarak etiketlenmiş birkaç veri seti erişilmiştir. Etiketsiz korpus ve etiketli verinin aynı alandan gelmesi gerekmez.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*6SSsK-nWc04Z2-gQGd8pCA.png" /><figcaption>Figür 7. Her Göreve Özel Fine-tunnig İçin Input Adaptasyonları — Tüm Input Token’lara Çevrilmiş Sonra Pre-trained Modele İşlenmek Üzere Beslenmiş ve Sonrasında Liner+Sofmax Katmanlarına [5].</figcaption></figure><p>İki adımlı eğitim yöntemi kullanılmıştır. Öncelikle, modelin ilk parametrelerini öğrenmesi için etiketsiz veri üzerinde bir dil modeli (language model — LM) objective function kullanılmıştır. Sonrasında ise, belirlenen supervised objective function, bu elde edilen parametrelerde hedef görev için adapte edilmiştir.</p><p>Bir transformer [3] ama daha spesifik olmak gerekirse sadece decoder kısmı kullanılmıştır. (Mesela, BERT modelinde de transformer’ın sadece encoder kısmı kullanılmıştır.) Transformer yapısı, uzun-süreli veriyi kapsayıp, parallel olarak işleyip ve daha stabil oldukları için çeşitli görevlerde RNN ve LSTM’den daha iyi sonuçlar vermektedir [4]. Dahası da, transfer sırasında structured text input’u (mesela düzenli bir csv file içerisindeki yapı gibi) tek bir bitişik token gibi işleyen göreve özel input adaptasyonları kullanılmıştır [2].</p><h4>Unsupervised Pre-training</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*0vY5J7irBsbppmVJxK2tcQ.png" /><figcaption>Figür 8. LM Objective Function —Corpus token seti U = {u1, u2,…, un} ve k context window boyutu ve koşullu olasılık P ve ağdaki parametreler de Θ olmak üzere [5]</figcaption></figure><p>Figür 8&#39;teki formül dil modelinin objective fonksiyonudur. Bu fonksiyonun amacı likelihood’u maksimize etmektir. Performansı optimize etmek için stochastic gradient descent (SGD) kullanılmıştır.</p><p>Deneylerde çok-katmanlı transformer decoder kullanılmıştır. Bu model, multi-headed self-attention işlemini ve ardından position-wise feedforward katmanlarını, input context token’ları üzerine uygulamıştır. Böylelikle, hedef token’lar üzerinde output dağılımı elde edilecektir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*UL120xj8ydXWxRgey0E-Gw.png" /><figcaption>Figür 9. Context vector token’ları — U = {u-k,…, u-1} ve n katman sayısı ve We: token embedding matrix ve Wp: position embedding matrix [5]</figcaption></figure><h4>Supervised Fine-Tuning</h4><p>Figür 8&#39;teki L1 fonksiyonu ile modeli eğittikten sonra, artık parametreler supervised fine-tuning aşaması için hazır hale geldiler.</p><p>Etiketli veri seti C ve veri setindeki dizi halinde input token içeren her bir örnekler x1,…, xm ve etiket y ve hlm son transformer bloğunun aktivasyonu ve Wy linear output katmanı olmak üzere:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*9IUuWfDx0UklHbIAk7g3oQ.png" /><figcaption>Figür 10. Tahmin Edilecek y Etiket Çıktısı Formülü [5]</figcaption></figure><p>Sonuç olarak, bu bize maksimize etmek için şu fonksiyonu verir:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*MtIHsi3C35VulJRQNeCHIw.png" /><figcaption>Figür 11. Maksimize Edilmek İstenen Objective Function [5]</figcaption></figure><p>Modelin, genel bir fonksiyon olma özelliğini geliştirmek için (böylece çeşitli görevlere genellenebilir), L2 objective function yardımcı fonksiyon olarak kullanılmıştır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/235/1*0eZBYU88-mqOC-3obvqjHQ.png" /><figcaption>Figür 12. Modelde Optimize Etmek için Kullanılan Objective Function [5]</figcaption></figure><p>Sonuç olarak, modelde Figür 12&#39;deki L3 objective fonksiyonu kullanılır. Lambda için 0.5 seçilmiştir.</p><h4>Task-Specific Input Transformations</h4><p>Figür 2&#39;de görüldüğü üzere, görevlere özel olarak input dönüşüme uğratılmıştır.</p><h4>Deneyler</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*_udlL0v4-G9pj5PdMOoNXw.png" /><figcaption>Tablo 1. Makaledeki Deneylerde Kullanılan Görevler ve Veri Setleri [5]</figcaption></figure><p>12 katmanlı, içinde masked self-attention heads olan decoder-only bir transformer eğitilmiştir. (768 dimensional states ve 12 attention heads) Position-wise feed-forward networks için 3072 dimensional inner states kullanılmıştır. Tabii ki de, Adam optimizer (max learning rate:2.5e-4) seçilmiştir. Learning schedule kullanılmıştır. Orijinal transformer’ların [3] aksine, sinusoidal kullanmak yerine positional encodings öğrenilmiştir. Yakınsama, convergence, için 3 epoch yeterli olmuştur.</p><h4>Sonuçlar</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*YUtfo0WKKnSEIHeUWcUCtw.png" /><figcaption>Tablo 2. Natural Language Inference Görevi Sonuçları [5]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*Gf1seN9ZQvySL1dRHoe_PA.png" /><figcaption>Tablo 3. Question Answering Görevi Sonuçları [5]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*sa8DNY2PCT-Qf9Fealb2EA.png" /><figcaption>Tablo 4. Semantic Similarity ve Classfication Sonuçları [5]</figcaption></figure><h4>Analiz</h4><ul><li>Pretrained modelden supervised göreve transfer edilen katman sayısı artırıldıkça, hedef görevlerdeki performans artmıştır.</li><li>Unsupervised pretraining’in işe yarayıp yaramadığını anlamak için, fine-tuning yapmadan zero-shot testing yapılmış ve modelin performansının zamanla arttığı ve stabil olduğu gözlemlenmiş.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*YY4cS7u-kW_aTErHG--4rw.png" /><figcaption>Figür 13. Unsupervised Learning Performansı Olumlu Etkiliyor[5]</figcaption></figure><ul><li>Ablation çalışmalarda, L3 kullanmanın, L1&#39;den daha etkili olduğu görülüyor.</li><li>L3&#39;ten büyük veri setleri, küçük veri setlerine göre daha fazla yararlanıyor.</li><li>Pre-training aşamasının önemi vurgulanmış ve dil ile alakalı bilgileri çıkarmasının altı çizilmiş.</li></ul><h4><strong>2.2. GPT-2 </strong>🤖🤖</h4><blockquote>Makale: <a href="https://cdn.openai.com/better-language-models/language_models_are_unsupervised_multitask_learners.pdf">Language Models are Unsupervised Multitask Learners</a></blockquote><h4>İnceleme</h4><p>Selefi GPT ile benzer bir örüntüye sahiptir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*hJ0sd-7WND8C5SDBmmSNSQ.png" /><figcaption>Tablo 5. GPT-2 Mimarisi Hiperparametreleri [6]</figcaption></figure><p>Yine bir objective function ile dil modeli pre-train edilmiştir sma burada fine-tuning işlemi yoktur. Onun yerine zero-shot ile downstream görevleri çözmeyi hedefler. Kısacası, i) çiğ metin üzerinde dil modelini pre-train et, ii) çeşitli görevler üzerinde, metin “prompt”ları ile zero-shot inference (sonuçlandırma) yap.</p><p>Pre-training, Reddit’teki popüler linkleri çekerek oluşturulan custom WebText veri seti ile yapılmış ve dört farklı boyuttaki dil modeli test edilmiştir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*JAhiFyuYZvFEZsMYqIKA8A.png" /><figcaption>Figür 14. WebText Dil Modellerinin Çeşitli Görevler Üzerindeki Zero-Shot Performansı [6]</figcaption></figure><p>Birkaç farklılık dışında GPT-2 model mimarisi, GPT ile eştir. Bu farklılıklara farklı weight initialization, larger vocabulary, daha uzun input dizisi örnek verilebilir. Dil modellerinin boyutlarına rağmen, WebText veri setine underfit etmiştir. Dil modeli ne kadar büyük olursa performansın o kadar arttığı gözlenmiştir, Figür 14. (large language model — LLM)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/949/1*Q93tvZo1sbg9_gf2MOP9jw.png" /><figcaption>Tablo 6. Çeşitli Dil Görevi Üzerindeki Performansı [6]</figcaption></figure><p>Çeşitli dil görevleri üzerinde yapılan deneyler sonucu, Figür 14, her zaman state-of-the-art sonuçlara erişemese de genelde iyi sonuçlar vermiştir. Dil modelleme ve okuma-anlamlandırma görevlerinde, özetleme ve soru cevaplamaya göre daha iyi performans sergilemiştir. Bu başarıları ise, <strong>fine-tuning olmadan ve zero-shot inference </strong>ile<strong> </strong>elde edildiği göz önüne alınırsa, gelecek vaad etmektedir. Yazarlar makalede, dil modelinin büyüklüğü ile performansının doğru orantılı oluşuna dikkat çekmiştir [7].</p><blockquote>“… a language model with sufficient capacity will begin to learn to infer and perform the tasks demonstrated in natural language sequences in order to better predict them, regardless of their method of procurement.” [6]</blockquote><p>Ayrıca, GPT-2&#39;nin kodları açık kaynak halinde <a href="https://github.com/openai/gpt-2">burada </a>bulunabilir. Yine de, bilgisayarınızı eritmek istemiyorsanız, pre-trained modeline <a href="https://huggingface.co/gpt2">buradan </a>ulaşabilirsiniz. İstediğiniz görev için <a href="https://huggingface.co/docs/transformers/v4.14.1/en/training">fine-tune</a> edebilirsiniz.</p><h4>Mimari</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*Jvqa2JiIBQ0pJk6lCGJH-A.png" /><figcaption>Figür 15. GPT-2, her decoder’da 1024 token işleyebilir [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*ghex3x46t1Xqyn1XuLv8oA.png" /><figcaption>Figür 16. Token Embedding’ler (vocab_size, embed_size) boyutuna sahiptir [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*zm_5XElRwkb8e26nyQhWHA.png" /><figcaption>Figür 17. Positional Encoding’ler (context_size, embed_size) boyuta sahiptir. [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*bSVV3DIeNpXRRReLAnGbvQ.png" /><figcaption>Figür 18. Input kelimeler, transformer’a beslenmeden önce işlenir =&gt; token embedding’e positional encoding eklenir. [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*EzgWmTHJLi7api3igIaU2Q.png" /><figcaption>Figür 19. Decoder Katmanları Boyunca Bir Tokenin Serüveni — Token Gulliver Travels :) [8]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*XA3jq6FUPWVHTPQgh2R4_Q.png" /><figcaption>Figür 20. Sonrasında Bu Output Vector, Token Embeddings ile çarpılarak Token Probabilities hesaplanır. En yüksek olasılığa sahip olan kelime seçilir. [8]</figcaption></figure><p>Daha detaylı gösterim ve ilerisi için (GPT-2 içerisinde masked/self-attention nasıl işliyor gibi) bu <a href="https://jalammar.github.io/illustrated-gpt2/">blog yazısı</a>nı okuyunuz.</p><h4>Soluklanıp, Toparlayalım</h4><ul><li><strong>Language model (LM, dil modeli) pre-train etmek harika.</strong> Çünkü pre-train sonrası, representations iyi öğrenilmiş oluyor ve modelin genellenebilir olması artıyor.</li><li><strong>Boyut önemli. </strong>Pre-trained<strong> </strong>LM boyutu arttıkça, öğrenilen representations kalitesi artıyor ve performans da artıyor. (GPT-2 ve GPT arasındaki farktan gördüğümüz üzere)</li><li><strong>Kaynak modeller (foundation models)havalıdır.</strong> Birçok deep learning modeli tek bir görevi çözmeye odaklanır ve eğitilir. Bu yüzden çoğu durumda şunlardan yararlanmakta fayda vardır: i) etiketsiz veri üzerinde self-supervised learning ile büyük bir modeli pre-train etmek, ii) bu modeli çeşitli görevlere uyarlamak. Ayrıca foundation models, computer vision için de kullanılabilir [10].</li></ul><p><strong>2.3. GPT-3 </strong>🤖🤖🤖</p><blockquote>Makale: <a href="https://arxiv.org/pdf/2005.14165.pdf">Language Models are Few-Shot Learners</a></blockquote><p>Bu makalede, CommonCrawl veri seti ile 400B token üzerinde eğitilmiş 175B parametreye sahip çok büyük bir transformer modeli olan GPT-3 tanıtılmıştır. Şaşırtıcı bir şekilde, fine-tuning olmadan zero-shot ve few-shot senaryolarda çok iyi performans sergilemiştir [13].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*wpsdXcIvTwvk-RZK-loWOQ.png" /><figcaption>Figür 21. Parametre Sayısı ile Modelin Boyutunun Artması Performansı Artırıyor [13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*YaTYuJ5MZy4LBQlkCGwZXA.png" /><figcaption>Figür 22. Parametre Sayısı Hepsinin Performansını Artırsa da, En Çok Few-Shot Bundan Faydalanıyor [13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/657/1*ezyqD23fUMaDhLKAefiSbQ.png" /><figcaption>Figür 23. x-shot Learning vs Traditional Fine-Tuning [13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*iZtSAXhcro4AvHP9W7hNyw.png" /><figcaption>Tablo 7. GPT-3&#39;ün Farklı Boyut, Mimari ce Learning Rate Konfigürasyonları [13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*ngImNtlEg70sbCMjI4DtQw.png" /><figcaption>Figür 24. İşlemsel Olarak Maliyet Karşılaştırması — Evet, Fazla[13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*DMZUpeBIhD7ffN-wuzTPvw.png" /><figcaption>Figür 25. GPT-3 Training Curves [13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*OOR1WXu28yuFg8N0sAD9dw.png" /><figcaption>Figür 26. En Çok Önyargıya Sahip Olan Kelimeler. Sol Erkek ve Sağ Kadın [13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*LI1SjY_mK87LSpwbUiQfnw.png" /><figcaption>Figür 27. Irka Göre Duygu Durum. Daha Fazla Siyahilere Negatif Duygu Sergiliyor. [13]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*Gfqm2EcSMiKtOwrutKpFjA.png" /><figcaption>Figür 28. Dini İnanışa Göre En Çok İlişkilendirdiği Kelimeler [13]</figcaption></figure><blockquote>Tek LLM, tabii ki de GPT-3 değil, hatta şu an kullandığımız GPT-3.5 versiyonu. LaMDA [14], Galactica [15], Codex [16], Sparrow [17]… Daha fazla model bulunmakta ve daha fazlasının gelmesi muhtemel.</blockquote><h3>3. Gelecek? ⌛</h3><blockquote>Yaşam sadece geriye doğru anlaşılabilir; fakat ileriye doğru yaşamak zorunludur. ― <strong>Søren Kierkegaard</strong></blockquote><p>Şu anki bilgimiz ile sadece masked self-attention gibi davranabilir ve bir sonraki tokeni tahmin etmeye çalışabiliriz. Yine de, yapay zeka teknolojisinin potansiyelinin apaçık karşımızda duruyor oluşunu göz ardı edemeyiz, edemiyoruz.</p><p>Dikkat edilmesi gereken birkaç husus bulunmakta.</p><p>Mesela, dil modellerinin, ön yargısal, cinsiyetçi, ırkçı, kutuplaştırıcı vb. şekilde metinler üretebilme ihtimaline karşı üstünde iyi kriterlerle belirlenmiş kurallara sahip olması gerekmektedir. Bunun dışında bilgi kirliliğini ve kötü niyetli faaliyetlerde yeni yöntemlerin kilidini açma potansiyeline de sahiptir.</p><p>Diğer yandan, yakın zamanda yeni ve çok daha güçlü bir arama motoru için kullanılacaktır. Bunu Google yapmazsa, başka bir kuruluş yapacaktır [18].</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*c431nriLok3WqVYCw43Ljw.png" /><figcaption>Figür 29. “50 ve 60&#39;ların bilim-kurgularında yapay zeka, hesaplama yapan soğuk ve vulcan gibi makineler olarak tasvir ediliyordu. Şimdilerde ise biraz fazla duygusal yapay zeka çıktı.” — Andrej Karpathy [18]</figcaption></figure><p>Mucitler, uzun zamandan beri <strong>düşünen makineler</strong>i oluşturmayı hayal ediyordu. Bu istek, en az Antik Yunan tarihine uzanacak kadar eskidir. Mitolojik figürler <a href="https://tr.wikipedia.org/wiki/Pygmalion">Pygmalion</a>, <a href="https://tr.wikipedia.org/wiki/Daidalos">Daedalus</a> ve <a href="https://tr.wikipedia.org/wiki/Hephaistos">Hephaestus</a> gibi efsanevi mucitler olarak yorumlanırsa, o zaman <a href="https://en.wikipedia.org/wiki/Galatea_(mythology)">Galatea</a>, <a href="https://tr.wikipedia.org/wiki/Talos">Talos</a> ve <a href="https://www.worldhistory.org/Pandora/">Pandora</a> yapay yaşam olarak düşünülebilir [19].</p><p>Dikkatinizi çekerim ki, düşünen makineler. Hissetmek ve düşünmek çok farklı iki eylemdir. Bu konu hakkında düşünecek olan kişinin öncelikle Platon gibi tartışacağı kelimeleri iyi tanımlayıp, anlaması şarttır.</p><p>Hissetmek, biyolojik bir canlı olmanın parçasıdır ve genellikle hormonlar tarafından kontrol edilir. Bu yüzden, bu konuyla ilgileniyorsanız aramanız gereken şey <a href="https://en.wikipedia.org/wiki/Biorobotics">biorobotics</a> ve <a href="https://arxiv.org/abs/2207.00880">biyolojik robotlar</a>dır: örneğin <a href="https://www.youtube.com/watch?v=w77_yhkXzzo">Xenobots</a>.</p><p>Peki, makineler gerçekten düşünebilir mi? Alan Turing’in ünlü makalesinden,<a href="https://plato.stanford.edu/entries/turing-test/"> Turing testi</a> fikrinin yeşerdiği, alıntı yaparak şimdilik noktalıyorum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/1*23UftWZw3VNrM3LIrRjK0g.png" /><figcaption>Figür 30. “Makineler düşünebilir mi?” sorusu, “Taklit oyununda çok iyi olan hayali dijital bilgisayarlar var mıdır?” ile değiştirilmelidir. — Alan Turing [20]</figcaption></figure><p>Konuya geri dönecek olursak, yapay zeka modellerinin duygulara veya bilince sahip olduğuyla ilgili tartışmalar bulunmuş olsa da, örneğin<a href="https://www.wired.com/story/lamda-artificial-intelligence-sentience/"> LaMDA modelinin duygusal olduğunu söyleyen Google mühendisi</a>, bunlar (en azından) şu anlık için söz konusu değildir. Çünkü bu modeller, sadece belli bir fonksiyonla performansı maksimize ederek tahmin etmeye hizmet eden matematiksel fonksiyonlardan ibarettir. Ne tür bir veriyle eğittiğinize bağlı olarak, tahminleri ve insanların gördüğü çıktılar da ona göre değişecektir.</p><p>Buradaki en büyük tehlike insan kaynaklıdır: i) yapay zekanın bilinçli ve duygulara sahip olduğuna toplulukları ikna ederek onları manipüle edecek kişi veya gruplar ve ii) çeşitli şekillerde teknolojiyi kötüye kullanabilecek insanlar.</p><p>Olumlu getirileri açısından çok büyük bir potansiyel taşıyan bu teknolojinin, <a href="https://en.wikipedia.org/wiki/Industrial_Revolution">sanayi devrimi</a> ve <a href="https://en.wikipedia.org/wiki/Digital_Revolution">dijital devrimi</a>nden sonraki devrim olacağı ön görülüyor.</p><p>Bu tür dil modelleri inovatif ve (henüz?) yeni bir çağ başlangıcı değildir çünkü bunlar bir süredir vardır [24]. <strong>ChatGPT’nin bu kadar dikkat çekme nedeni bir API aracılığıyla herkesin kullanımına açık hale getirilmesidir.</strong></p><p><a href="https://www.youtube.com/watch?v=fHMNYnjuXak">ChatGPT, yapbozdaki sadece küçük parçalardan biri.</a> Bu yazıyı yazarken bile, çeşitli dev firmalar yeni stratejiler belirleyerek milyarca dolar kar yapmanın ve globali net bir şekilde domine etmenin planını oluşturmakta.</p><p>Ek olarak, OpenAI modeli toksik olan veriyi (çocuk cinsel istismarı, hayvanlarla cinsel ilişki, cinayet, intihar, işkence, kendine zarar, ensest vb.) elemek için Kenya, Uganda ve Hindistan gibi ülkelerden insanları saati<strong> en fazla 2$ </strong>olacak şekilde kiralamıştır ve kuruluşlar kendilerini “ethical AI” şirketi olarak tanımlamaktadır [25].</p><p>Bir diğer konu da, daha soyutsal veya somut olsun yükselen bu teknolojik gelişmeler insanlardan daha fazla değer görmektedir. Buna örnek olarak, Amazon çalışanlarının, şirkette robotlara daha iyi davranıldığına dair olan iddiası verilebilir [31]. Merak ettiğim, ileride teknolojik unsurların da insanların uğradığı ön yargısal (ırkçılık, cinsiyetçilik, dini ayrım vb.) sorunlarla karşılaşıp karşılaşmayacağı ve karşılaşırsa bunun nasıl ve kim tarafından olacağıdır.</p><p><a href="https://www.youtube.com/watch?v=-WSQEyT2Mu0&amp;t=388s">Barış Özcan’ın bu videosu</a> ile <a href="https://www.youtube.com/watch?v=cdiD-9MMpb0&amp;t=3800s">Lex Fridman ve Andrej Karpathy’nin podcast’ini</a> buraya ekliyorum.</p><p><strong>Nihayetinde ise… insanları, makineleri olan insanlar yönetecektir.</strong></p><h3><strong><em>4. Özet </em></strong>📝</h3><p>Tebrikler, bir sürü konsept hakkında fikir yürüttük ve buraya kadar geldin!</p><p>Şimdi, bu yazıda neler bahsettiğimizi özetleyelim ve her şeyi toparlayalım.</p><ul><li>ChatGPT sadece sohbet edebildiğiniz uygulamanın ismi. Arkasında GPT-3 modeli kullanılıyor. Aslında topluma açık hale getirildiği için, aldığı geri bildirimlerle birlikte GPT-3.5 olmuş bulunmakta.</li><li>Çoook büyük bir veri seti üzerinde eğitilmiştir.</li><li>GPT, GPT-2 ve GPT-3 olmak üzere versiyonları mevcut. Temelde mimarileri benzese de, en büyük farkları çok daha büyük parametre sayısına sahip olması.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/699/1*s2TokcBZ-kQt8xIMwqC5OA.png" /><figcaption>Figür 31. Parametre Sayısı Karşılaştırması [21]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*HMXKtJCpAoBhvy5VoQf3qA.png" /><figcaption>Figür 32. “GPT3&#39;ün muhteşem performansını geleceğe yansıtmak, yaşam, evren ve her şeyin cevabının sadece 4.398 trilyon parametre olduğunu gösteriyor.” [22]</figcaption></figure><ul><li>GPT, transformer’ların sadece decoder bloklarından oluşan bir modeldir.</li><li>Unsupervised bir şekilde pre-train edilip, spesifik görevler için supervised şeklinde fine-tune edilirler.</li><li>Çeşitli dil görevlerini yerine getirebilmekte: dil çevirisi, özetleme, soru cevaplama vb.</li><li>Harika sonuca sahip olmasına karşın, toplumsal perspektifte ön yargısal ve negatif etkilere sahip olma potansiyeli mecvut.</li><li>Humanity its own worst enemy. [23]</li></ul><h3>5. Sıfırdan GPT İnşaa Edelim 🛠️👩‍💻</h3><p>Bu bölümde Oğuz Atay’ın Tutunamayanlar kitabının .txt haliyle eğitilmiş bir veri seti ile basit bir GPT modeli eğiteceğiz. Tam hali aşağıdaki linkte:</p><p><a href="https://github.com/rabiaedayilmaz/karpathy-youtube-videos/blob/main/lesson7-gpt/gpt_model.ipynb">karpathy-youtube-videos/gpt_model.ipynb at main · rabiaedayilmaz/karpathy-youtube-videos</a></p><p>Bunun için YouTube’daki <a href="https://www.youtube.com/watch?v=kCc8FmEb1nY&amp;t=481s">Andrej Karpathy’nin videosu</a> baz alınmıştır.</p><p>Adım adım kodu inceleyelim. Burada, Google Colab ortamını tercih ettim.</p><p>Veri seti olarak Oğuz Atay’ın Tutunamayanlar kitabını seçtim. Böylelikle modelimiz, bu kitaba benzer şekilde cümleler üretecek. Çakma bir Oğuz Atay, evet.</p><p>Öncelikle gerekli kütüphane ve fonksiyonları çağırıyoruz. İmplementasyonda seçimimiz PyTorch. Sonrasında hiperparametreleri belirliyoruz. Bir tane seed atıyoruz ki, her kod çalıştığında o oturumda aynı sonuç elde edilsin. Sonra da wget komutuyla, Tutunamayanlar kitabının .txt dosya halini indiriyoruz. Ardından indirilen dosyayı okuyup, metni bir değişken içerisine atıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a2a776083733174ace97edcdba8a92a/href">https://medium.com/media/7a2a776083733174ace97edcdba8a92a/href</a></iframe><p>Daha sonra, metindeki eşsiz karakterleri sıralı bir liste halinde chars değişkenine atıyoruz. Bu değişkeni kullandığımız her bir karakter için özel bir alfabe olarak düşünebilirsiniz. Sonrasında özel alfabemizin (:D?) uzunluğunu da vocab_size değişkenine atıyoruz ki, modeli kurarken boyutları ayarlamamızda önemli olacak olan bir parametre.</p><p>Ardından özel alfabemizin her bir karakterini ile dict veri yapıları oluşturuyoruz. Birisi her bir harfin integer karşılığını, diğeri ise her bir interger’ın harf karşılığını bize verecek. Sonra encode ve decode olmak üzere iki lambda fonksiyonu tanımlıyoruz. Encode fonksiyonu, verilen kelimeyi int token’lerden oluşan bir listeye dönüştürür ve decoder fonksiyonu ise, verilen int token listesini kelimelere dönüştürür. Model ile bizim aramızdaki portal gibi düşünülebilir. Daha sonra da veriyi pytorch tensor haline getirdikten sonra, ki efektif bir biçimde pytorch modelimizde işlensin, train ve val olmak üzere iki sete bölüyoruz. En sondaki fonksiyon ise, veriden x(input context) ve y(target) içeren küçük bir batch çağırmak içindir. Verideki diziyi blok blok işleyeceğimizi düşünürsek, en son bloğa kadarki elemanlardan batch_size boyutunda index seçimi yapıyoruz (ix değişkeni). Sonra da, x’ten blok blok batch alıyoruz ve y’den de bir kaydırılmış halinde seçim yaparak target değerleri alıyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43559ec30bc19c791797481e1502f56a/href">https://medium.com/media/43559ec30bc19c791797481e1502f56a/href</a></iframe><p>Ardından loss hesaplamak için bir fonksiyon yazıyoruz. Başından no_grad decorator olma nedeni, bu fonksiyon eğitim için kullanılmayacağından boşuna backward yapıp memory ve cost neden olmasın diye. Bir batch çağrılıp, modele atılıp, loss değeri kaydedilir.</p><p>Daha sonra da, self-attention için bir head implemente ediyoruz. Klasik olarak, nn.Module’den bir sürü özelliği miras alıyoruz. Key, query ve value şekilnde nn.Linear fonksiyonu ile ağımızdaki node’ları oluşturuyoruz. (n_embd, head_size) boyutu ile başlatıyoruz. Bu sınıfa ait olmasa da kullanmak istediğimiz bir değişken var. Dolayısıyla, onu register_buffer ile oluşturuyoruz: tril değişkeni. Kısacası bu bir lower triangular matrix yani matrisiniz kare pastayı sol üst köşeden sağ alt köşeye kesmişsiniz de, üst bölgedekiler hep sıfır iken, alt bölgedekilerin değeri bulunmakta. Kullanım nedeni tokenlerimiz harf harf, bu yüzden cümlede ilerledikçe buna benzer bir şekil oluşmakta.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*SCqxvLevSOiUvVBCJCofyg.png" /><figcaption>Figür 33. Tokenlerin İlerledikçe Lower Triangular Matrix Yapısına Benzemesine Örnek</figcaption></figure><p>PyTorch back-propagation işini bizim için otomatik olarak hallediyor, bu yüzden sadece forward implemente ediyoruz. (Az önceki torch.no_grad decorator nedeni işte tam bu yüzden) Key değerlerini hesaplamak için, veriyi key node’larına atıyoruz. Query için de benzeri bir işlem yapıldıktan sonra, artık attention score’ları hesaplayabiliriz. @ işareti, np.matmul fonksiyonuna tekabül etmektedir yani matrix çarpımı yapmaktadır. Kolaylık olsun diye böyle bir güzellik yapmışlar. Query ve Transpose Key matrisleri (boyutların yeriyle oynanır) çarpılır ve değerlerin boyutunun kareköküne bölünür. Niye bunu yaptık derseniz, attention is all you need:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*dAhOV_F7EkOrFKxmgweW-w.png" /><figcaption>Figür 34. Attention Skor Formülü [26]</figcaption></figure><p>Sonrasında öncesinde oluşturduğumuz lower triangular matrisimizi, T. zamana kadar olan satır ve sütunlarda, eğer 0&#39;a eşitse değer onu -infinity yapıyoruz. Sonra da matrisi softmax’in içine bandırıyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/336/1*kQIkz53KxbXOgLT4hDdGKQ.png" /><figcaption>Figür 35. Softmax Fonksiyonu [27]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*3aHXqtYv7iTGc-DHsKxKjA.png" /><figcaption>Figür 36. e^x Fonksiyonu [28]</figcaption></figure><p>Softmax fonksyionundaki e fonksiyonlarına dikkat ediniz. e^x fonksiyonunun grafiğine göre, Figür 36, x değeri ne kadar eksi sonsuza giderse o kadar sıfıra yaklaşır. Bu yüzden, matrisimizde istenmeyen bölgeyi eksi sonsuz (-infinity) ile doldurduk ki, softmax içine atıldığında sıfır olarak dışarı çıksınlar.</p><p>Ardından dropout işlemi uygulanır, ki bu değeri 0.0 yaptığımız için en başta hiperparametre tanımlarken, bir şey olmayacak. Sonrasında hesaplanan value değeri ile lower triangular matrisimizi çarpıyoruz. Sonrasında oluşan değeri döndürüyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23554764252514cb67130daebf47ec6d/href">https://medium.com/media/23554764252514cb67130daebf47ec6d/href</a></iframe><p>Tabii ki de bu, tek bir attention head idi. Biz ne yapıyorduk, gül demeti gibi paralel olarak bunları multi head attention olarak bağlıyorduk. Bu şekilde oluşan gül demetimizi, daha da güzelleştirmek için yani bir decoder haline getirmek için, gavur ıtırı demeti gibi olan feed forward fonksiyonları ile bütün demet haline getiriyoruz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlvWuD4qAfWjERsKSQnNsQ.jpeg" /><figcaption>Figür 37. Gül (Rose) ve Gavur Itırı (Hardy Geranium) Bahçedelerde Sık Kullanılan İkilidir [29].</figcaption></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77abd161139a42ee1d6b843603d9a732/href">https://medium.com/media/77abd161139a42ee1d6b843603d9a732/href</a></iframe><p>Block sınıfı sayesinde de, multi head attention ve feed forward bir araya getirilmiş oldu. <strong>LayerNorm katmanı burada çok önemli. </strong>Çünkü bu katman olmadan model performansı gerçekten kötü etkileniyor.</p><p>Son olarak da, modelimizi BigramLanguageModel adı altında, yani ardışık iki tokeni göz önüne alarak, oluşturuyoruz. Bu durumda her harften sonra, o harften sonra hangi harfin geleceğini tahmin etmeye çalışacağız.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*NzAfM3NHoHFFduIZGgnc7Q.png" /><figcaption>Figür 38. n-gram Örneği. Ne kadar n, o kadar ardışık köfte yani token[30]</figcaption></figure><p>İlk olarak, birer tane token embedding ve position embedding table oluşturuyoruz. Sonra az önce oluşturduğumuz blokları, gül ve gavur ıtırı demeti, bir dizi halinde diziyoruz. LayerNorm ve Linear fonksiyonlarını da başlatıyoruz.</p><p>Forward propagation kısmında, token embedding tablosundan, index’e göre token embedding alınır. Sonra position embedding tablosundan T zamanı kadar position embedding alınır. Token embedding ile position embedding’i toplayarak, yer bilgisi de içinde bulunan bilgiyi elde ederiz. Oluşan bilgiyi, blokların içerisine atarız. Bloklardan çıkan değere LayerNorm ile çekidüzen verdikten sonra, linear node’lara atarak logits değerlerini elde ederiz. Logits ve targets değişkenlerini yeniden şekillendirip, ikisi arasında boyut sorunu ile karşılaşmadan işlem yapabilmek için, cross entropy fonksiyonu ile loss değerini buluruz.</p><p>En sonda ise, generate kısmında, belirlediğimiz maksimum token sayısına göre, o kadar harften sonra harf tahmin ediyoruz. Birdirbir oyunu gibi.</p><p>Harf dizimizi küme küme, bu durumda blok blok, işliyoruz. Son bloğa kadar olan tüm harfler seçilir. Forward propagation içine atılır, self içine atılınca default olarak oraya gidiyor, ardından da logits ve loss elde edilir. Logits’ten sadece son zaman boyutundaki seçilir ve softmax içine atılarak olasılık değeri hesaplanır. Elde edilen olasılıklardan, multinomial olasılığa göre bir tane seçilir ve çalışmakta olan diziye eklenir. Bu sayede, birdirbir oynayan harflerin tek tek oluşumunu sağlamış oluruz, Figür 39.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/304f72726ab1712d7cdc3d97a0fadd4a/href">https://medium.com/media/304f72726ab1712d7cdc3d97a0fadd4a/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*fStEMUsJm-1TPGp4qgC-KA.jpeg" /><figcaption>Figür 39. Birdirbir Oynayan Bigram Language Model</figcaption></figure><p>Artık en son aşamaya geldik. Burada, yazdığımız her şeyi birleştireceğiz. Önce modeli oluşturuyoruz, ardından GPU’ya atıyoruz. Diğer türlüsü makinenizde yumurta kızartarak, uzun bir süre beklersiniz. Optimizer olarak adam gibi adam olan AdamW kullanıyoruz. Sonrasında belirlediğimiz max iter sayısı kadar, 5000, modeli eğitiyoruz. Yeni bir metin sentezlemek için modele pseudo bir değer atıyoruz. Sonda da, train ve loss eğrilerini çizdiriyoruz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82d2616efc72324d69e8a07056111a35/href">https://medium.com/media/82d2616efc72324d69e8a07056111a35/href</a></iframe><p>Train ve val setlerinin loss’ları:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/1*shQD_l7QiMSgTqLtyILA_A.png" /></figure><p>Üretilen metin:</p><pre>zalada. Geçip onlar, olusunurdu yolarlak. Gerçekkeyenler ve günen<br>biçle bir de şişlerde<br>bıraktık. Oyne orada Talp yengil saderemeklerindikten ön-<br>denik biçirt”iz dedi sözlerin-<br>leri<br>nimle, işmeye neredir middileri olamadığını geçmeneniklerce, ocudur: ‘Hembrizlerdi,<br>  Dedöndüklerimizasını sizdi.<br>  Selim) sıkardı. Oraçalı yaparılantmış için<br>şira kitap teh düşüncelerden yöndüsünüverdiğime güç-<br>lümüzdeceklerinle Adaman için ağmayı mı?” Bir niden kendi ihratti seyğini babaşladı da tanıkkaradaştı bir deren yelinonlarını zoruk iki bulan olduk fonza hayvayım yanıyorumduya bizimli döğtlerden sözendir her harafikmeler.”<br> “MA0 alimeleri, hep bir şeyir<br>yapdılaktı olduğu konuzdu. Türkküyu de-<br>n düzean edkim sizinin şey şekil demekse<br>giyece çerimesiyle<br>bir yoki. Elledi meneler. Türktere kayfada kereşisini içmez yetin azalımkele-<br>ceğini-<br>miz, daha benzemez<br>birlikten olduğu kadanlım.<br>Telli susurduğun rarçık kaybir hükütü Miharlık ona ora-<br>lanma da baskaydık. Öylece, sonra?” dışıntıma dore-<br>de tazan sahtecalar, den kalmazdır. Metinan ölce kurbu uzan evlenmiştiniz ıvarıyorum ve dilence kendiler belki Münetleri, Marplarızarı daskaramadan her kadar kadar gündeyi, Selim çıkışın sankiyesini yetişomuza hayal’ın “Oyunun<br>orna-<br>da, yüz. Belki kaçılna giddiğe için kalim konadık rengclileri yeni etrecekten dumuştuk vermizden boşarları beri sizleririni Ürkekin düşünce, kürkere daiari gelendiğin evilmezlik seyrinde ta-<br>ra detmiştirdiğim bir kimse içindiğinde Antak boynemişde bize değerlik, ortarak kitaplı oldu senin ölrirlikteyince yorulukları, çeşanılıktan de-<br>ğitsim, kalanmış olmanız sın odarlık sigarinmiş meresinde ölmüyanların Bir nasan tehuset bin inan bir sürmek önce-<br>tlerini değil olarak imadeler<br>birlomları elinüzdü:<br>  her şey yaklatrak karşı kal-<br>yum.” Karıda olmuştu oturulmuş kulok kalmamla uğruhatte ildi? Başlagılar şimdilerini<br>   ne beşiştiririm ayrıca, kapıt mükemsim için sariyorum gene yerler tayrigzler? Ve<br>değil yokluğunu yıkanında bir dildikinan, benim hopameler hepfendiğimizz</pre><p>Bir sonuç elde etmiş olsak da, sonuç metin anlamlı olmaktan biraz uzakta.</p><p>Burada veri hakkında birkaç durum söz konusu.</p><ol><li>txt dosyası pek temiz değildi. Sayfa numaraları ve boş satırlar çok vardı.</li><li>Kitabı okumak uzun sürse de, aslında bu çok küçük bir veri seti.</li></ol><p>[Güncelleme: 26.01.2023]: Yaşar Kemal’in yazdığı İnce Memed 1, 2, 3 ve 4 kitapları ile modeli tekrar eğittim. Sonucu buraya iliştiriyorum.</p><pre>nerdi:<br>       &quot;Kafacık, güne öldürürür­<br>nen Ana bem nedi tame-<br>li<br>mış altıvara Akşesi olduklar, delim. Hemur Almı?&quot;<br>      &quot;Boğkacım taşının bir İnce Memede ondan kayıyordu. Sonra kolmaya öfekammak. Bu öylemedin seyreyse, dem, bahçeberini, de, cakan<br>giye aktı.<br>    &quot;Seninden olsun, en geldi edemelerdi.<br>     &quot;Hayanın cevveta getiriyor, harnm, ağlanmdı, harahbe dali, &quot;Kae­<br>remeri geçmez düştü, karamı adam, barasında benden ötekek atmıyordu. Memed?&quot;<br>    &quot;Zürülü, gözyü tikelim..&quot;<br>     Dayram,&quot; dede Memed, Memed:<br>     1Illah açlın.&quot;<br>     Kanerce Arkene köylemede akı­<br>yım<br>konşar gitti. Ali Memedin karşı yarı bütülü çeğikti, erkeli, başamalar, yaran bes<br>dum kendi Alik ben Sulnanda alacam. İnce Memedin alıya görümüyorum. Yüzbe şaşlıyordu. Bit orada mahmıyor, ertasında<br>habboynanın çekte koçune çok müygitçel sana birmu inden vayvarmızlayın sehikten kulmanızlarlayım. İnce<br>mi Memedin üstünde sizmetme gözgetinlere elgenleh de..<br>      &quot;Çocunlanız D güğe germez Torom Eişi etmeri iyi ve.ayrı fıkarmadan<br>bir ben kok. Herke çekin çoca vuzları giderir. Kimse aşlıya germel yerine? Çomeler gözler buldu ortaca, Eşkı Ferhar gözleren oluyorum kabalm. Tüfe ayaklan balt emendi, yer torta birimondan işli,rası Catarn Efal inlende yoldu, şilim edleriye gitmiyor, or­<br>gece M  maharnı karkası altmı olu edeceği dusunu bir da bulamaz bulduros ili işleyirlerinin birrimizen vardaşlar, Hürük korbacı.<br>     Memelid,&quot; dedi. &quot;Aridaki ele eli har oldu.<br>   Bir koy­<br>lara gidenin Meşi bir birliU<br>kal anlıyordu, acak hala Kelas gece Memedin ya­<br>vrum, onu tazığınlı:<br><br>       Konann bışıydan çifdeki. Kisine etin iyi verdi çeki yanı? Yıl etir gincik eli harkane titrdi yatinde aralada sonra da kimşi başımadan gördürdü.<br>     R9<br> enar de­<br>niyordu:<br>    &quot;Dele dedi bilere<br>ıldı, arardam, am areştin aşkıya gir benden köp­<br>ğüm. Yüzbaşı içinin yürüdüğünün iz yap daha valhsın, öfbekelini önleri de...... Ko­<br> yun al, böyle gümler<br>sevince seni belim, Ana dene o at senirden doğların bu oldu kelesindi kırtmıştı, etli:<br>     &quot;Bir kaydı</pre><p>— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —</p><p>Ve böylelikle hem bu bölümün, hem de bu yazımın sonuna gelmiş bulunuyoruz. Hem teşekkürler, hem de tebrikler😇 Katkı ve önerilere her zaman açığım, böylesi daha eğlenceli!</p><p>Bir sonraki yazımda görüşmek üzere.</p><h3>Kaynakça</h3><p>[1] Facundo Verdun. (2017, June 25). <em>I, Robot — Human emotions scene</em> [Video]. YouTube. <a href="https://www.youtube.com/watch?v=siHfHUm3HGE">https://www.youtube.com/watch?v=siHfHUm3HGE</a></p><p>[2]Singh, S. (2021, May 2). <em>Paper Summary #3 — Improving Language Understanding by Generative Pre-Training</em>. Shreyansh Singh. <a href="https://shreyansh26.github.io/post/2021-05-02_language_understanding_generative_pretraining/">https://shreyansh26.github.io/post/2021-05-02_language_understanding_generative_pretraining/</a></p><p>[3] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … &amp; Polosukhin, I. (2017). Attention is all you need. <em>Advances in neural information processing systems</em>, <em>30</em>.</p><p>[4] <em>Why does the transformer do better than RNN and LSTM in long-range context dependencies?</em> (2020, April 7). Artificial Intelligence Stack Exchange. <a href="https://ai.stackexchange.com/questions/20075/why-does-the-transformer-do-better-than-rnn-and-lstm-in-long-range-context-depen">https://ai.stackexchange.com/questions/20075/why-does-the-transformer-do-better-than-rnn-and-lstm-in-long-range-context-depen</a></p><p>[5] Radford, Alec, et al. Improving language understanding by generative pre-training. (2018).</p><p>[6] Radford, Alec, et al. Language Models are Unsupervised Multitask Learners.</p><p>[7] Wolfe, C. R. (2022b, November 21). <em>Language Models: GPT and GPT-2</em>. By Cameron R. Wolfe. <a href="https://cameronrwolfe.substack.com/p/language-models-gpt-and-gpt-2">https://cameronrwolfe.substack.com/p/language-models-gpt-and-gpt-2</a></p><p>[8] <em>Alammar, J (2018). The Illustrated Transformer [Blog post]. Retrieved from </em><a href="https://jalammar.github.io/illustrated-transformer/"><em>https://jalammar.github.io/illustrated-transformer/</em></a></p><p>[9] Brown, T. B., Mann, B., Ryder, N., Subbiah, M., Kaplan, J., Dhariwal, P., Neelakantan, A., Shyam, P., Sastry, G., Askell, A., Agarwal, S., Herbert-Voss, A., Krueger, G., Henighan, T., Child, R., Ramesh, A., Ziegler, D. M., Wu, J., Winter, C., . . . Amodei, D. (2020). Language Models are Few-Shot Learners. <em>ArXiv: Computation and Language</em>. <a href="https://arxiv.org/pdf/2005.14165.pdf">https://arxiv.org/pdf/2005.14165.pdf</a></p><p>[10] Yuan, L., Chen, D., Chen, Y., Codella, N. C. F., Dai, X., Gao, J., Hu, H., Huang, X., Li, B., Li, C., Liu, C., Liu, S., Liu, Z., Lu, Y., Shi, Y., Wang, L., Wang, J., Xiao, B., Xiao, Z., . . . Zhang, P. (2021). Florence: A New Foundation Model for Computer Vision. <em>Cornell University — ArXiv</em>. <a href="https://doi.org/10.48550/arxiv.2111.11432">https://doi.org/10.48550/arxiv.2111.11432</a></p><p>[11] <em>Word embeddings | Text |</em>. (n.d.). TensorFlow. <a href="https://www.tensorflow.org/text/guide/word_embeddings">https://www.tensorflow.org/text/guide/word_embeddings</a></p><p>[12] Tyagi, H. (2021, October 5). <em>The Evolution of Tokenization — Byte Pair Encoding in NLP</em>. freeCodeCamp.org. <a href="https://www.freecodecamp.org/news/evolution-of-tokenization/">https://www.freecodecamp.org/news/evolution-of-tokenization/</a></p><p>[13] <em>Review for NeurIPS paper: Language Models are Few-Shot Learners</em>. (n.d.). <a href="https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Review.html">https://proceedings.neurips.cc/paper/2020/file/1457c0d6bfcb4967418bfb8ac142f64a-Review.html</a></p><p>[14] Thoppilan, R., De Freitas, D., Hall, J., Shazeer, N., Kulshreshtha, A., Cheng, H. T., … &amp; Le, Q. (2022). Lamda: Language models for dialog applications. <em>arXiv preprint arXiv:2201.08239</em>.</p><p>[15] Taylor, R., Kardas, M., Cucurull, G., Scialom, T., Hartshorn, A., Saravia, E., … &amp; Stojnic, R. (2022). Galactica: A large language model for science. <em>arXiv preprint arXiv:2211.09085</em>.</p><p>[16] Chen, M., Tworek, J., Jun, H., Yuan, Q., Pinto, H. P. D. O., Kaplan, J., … &amp; Zaremba, W. (2021). Evaluating large language models trained on code. <em>arXiv preprint arXiv:2107.03374</em>.</p><p>[17] Glaese, A., McAleese, N., Trębacz, M., Aslanides, J., Firoiu, V., Ewalds, T., … &amp; Irving, G. (2022). Improving alignment of dialogue agents via targeted human judgements. <em>arXiv preprint arXiv:2209.14375</em>.</p><p>[18] Lex Fridman. (2022, October 29). <em>Andrej Karpathy: Tesla AI, Self-Driving, Optimus, Aliens, and AGI | Lex Fridman Podcast #333</em> [Video]. YouTube. <a href="https://www.youtube.com/watch?v=cdiD-9MMpb0">https://www.youtube.com/watch?v=cdiD-9MMpb0</a></p><p>[19] Goodfellow, I., Bengio, Y., &amp; Courville, A. (2016). <em>Deep Learning</em>. Amsterdam University Press.</p><p>[20] TURING, A. M. (1950). I. — COMPUTING MACHINERY AND INTELLIGENCE. <em>Mind</em>, <em>LIX</em>(236), 433–460. <a href="https://doi.org/10.1093/mind/lix.236.433">https://doi.org/10.1093/mind/lix.236.433</a></p><p>[21] <em>What Can You Do with the OpenAI GPT-3 Language Model? | Exxact Blog</em>. (n.d.). <a href="https://www.exxactcorp.com/blog/Deep-Learning/what-can-you-do-with-the-openai-gpt-3-language-model">https://www.exxactcorp.com/blog/Deep-Learning/what-can-you-do-with-the-openai-gpt-3-language-model</a></p><p>[22] <em>Geoffrey Hinton on</em>. (2020, June 10). Twitter. <a href="https://twitter.com/geoffreyhinton/status/1270814602931187715">https://twitter.com/geoffreyhinton/status/1270814602931187715</a></p><p>[23] Lander, Harry. (‎1990)‎. Humanity its own worst enemy [‎letter]‎. <em>World health forum 1990 ; 11(‎4)‎ : 431 </em><a href="https://apps.who.int/iris/handle/10665/45653">https://apps.who.int/iris/handle/10665/45653</a></p><p>[24] Ray, T. (2023, January 24). <em>ChatGPT is “not particularly innovative,” and “nothing revolutionary”, says Meta’s chief AI scientist</em>. ZDNET. <a href="https://www.zdnet.com/article/chatgpt-is-not-particularly-innovative-and-nothing-revolutionary-says-metas-chief-ai-scientist/">https://www.zdnet.com/article/chatgpt-is-not-particularly-innovative-and-nothing-revolutionary-says-metas-chief-ai-scientist/</a></p><p>[25] Perrigo, B. (2023, January 18). <em>Exclusive: OpenAI Used Kenyan Workers on Less Than $2 Per Hour to Make ChatGPT Less Toxic</em>. Time. <a href="https://time.com/6247678/openai-chatgpt-kenya-workers/">https://time.com/6247678/openai-chatgpt-kenya-workers/</a></p><p>[26] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … &amp; Polosukhin, I. (2017). Attention is all you need. <em>Advances in neural information processing systems</em>, <em>30</em>.</p><p>[27] Wood, T. (2020, June 25). <em>Softmax Function</em>. DeepAI. <a href="https://deepai.org/machine-learning-glossary-and-terms/softmax-layer">https://deepai.org/machine-learning-glossary-and-terms/softmax-layer</a></p><p>[28] <em>2.1 The Exponential Function</em>. (n.d.). <a href="https://ocw.mit.edu/ans7870/18/18.013a/textbook/HTML/chapter02/section01.html">https://ocw.mit.edu/ans7870/18/18.013a/textbook/HTML/chapter02/section01.html</a></p><p>[29] Rushton, S. (2021, April 8). <em>Great Companion Plants For a Cottage Garden: Geraniums</em>. Susan Rushton. <a href="https://susanrushton.net/2019/09/09/great-companion-plants-for-a-cottage-garden-geraniums/">https://susanrushton.net/2019/09/09/great-companion-plants-for-a-cottage-garden-geraniums/</a></p><p>[30] Mehmood, Arshad. 2019. “Generate Unigrams Bigrams Trigrams Ngrams Etc In Python.” March 19. Accessed 2019–09–26.</p><p>[31] Conway, Z. J. D. B. &amp;. (2023, January 25). Amazon strikes: Workers claim their toilet breaks are timed. <em>BBC News</em>. <a href="https://www.bbc.com/news/business-64384287">https://www.bbc.com/news/business-64384287</a></p><p>[32] Chatterjee, P. (2022, March 23). <em>How do zero-shot, one-shot and few-shot learning differ?</em> Analytics India Magazine. <a href="https://analyticsindiamag.com/how-do-zero-shot-one-shot-and-few-shot-learning-differ/">https://analyticsindiamag.com/how-do-zero-shot-one-shot-and-few-shot-learning-differ/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1106949f56e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BERT’e Sormuşlar…]]></title>
            <link>https://medium.com/@rabiaedayilmaz/berte-sormu%C5%9Flar-83001559d5bf?source=rss-779b7e5cea5------2</link>
            <guid isPermaLink="false">https://medium.com/p/83001559d5bf</guid>
            <category><![CDATA[bert]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Rabia Eda Yılmaz]]></dc:creator>
            <pubDate>Fri, 20 Jan 2023 20:40:45 GMT</pubDate>
            <atom:updated>2023-01-21T10:41:42.791Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*wMGsqmd98IlSC9bg_4GMVA.png" /><figcaption>We All Have Those Days From Reddit [1]</figcaption></figure><blockquote>BERT (Bidirectional Encoder Representations from Transformers) transformer üstüne kurulu ve büyük bir metin korpusu üzerinde pre-trained edilmiş bir modeldir.</blockquote><p>BERT’in duygu analizi, cümle sınıflandırma, soru cevaplama, adlandırılmış varlık tanıma (named entity recognition), metin üretme, metinsel mantık sonucu ve metin benzerliği gibi görevlerde çok daha güçlü olduğu düşünülmektedir.</p><p>Bu blog yazımda, şu sırayı izleyecek şekilde, Google tarafından geliştirilmiş olan BERT hakkındaki notlarımı düzenli bir şekilde paylaşacağım.</p><ol><li><strong><em>Terim Haznesi </em></strong>🦜</li><li><strong><em>Makale İncelemesi</em></strong>📎</li><li><strong><em>Özet </em></strong>📝</li><li><strong><em>Kod</em></strong>👩‍💻</li></ol><h3>1. Terim Haznesi🦜</h3><h4>1.1. Pre-training</h4><p>Pre-training, ön eğitim, modelin daha sonrasında küçük bir veri seti üzerinde fine-tune edilmeden önce büyük bir veri seti üzerinde eğitilmesidir. Amaç, modelin parametrelerini büyük veri setinden öğrenilmiş faydalı feature’lar ile başlatmaktır, ki böylece küçük veri seti üzerinde daha iyi performans gösterebilsin. İki çeşit şekilde pre-training yapılabilir:</p><ul><li><strong>Unsupervised Pre-training:</strong> Büyük veri setinde etiketler olmadan eğitilir. Veriden önemli feature’ları çıkarmayı kendisi öğrenir. Bu yöntem genelde, autoencoding veya generative modeller üzerinde kullanılır.</li><li><strong>Supervised Pre-training:</strong> Büyük veri setinde etiketler kullanılarak eğitilir. Sınıflandırma buna örnek olarak verilebilir.</li></ul><h4>1.2. Downstream Tasks</h4><p>Doğal dil işlemede, downstream görevler belirli bir uygulama veya pre-trained model output’unu input olarak kullanan modellere işaret eder. Bu görevlere örnek olarak: metin sınıflandırma, named entitiy recognition, soru cevaplama, metin özetleme, makine çevirisi, metin sentezleme…</p><p>Görevleri genel olarak üç gruba ayırabiliriz:</p><ul><li><strong>token-level task: </strong>diziyi normal bir şekilde işleyip, her token’ın output’u farklı bir modüle tahmin etmesi için yollanır.</li><li><strong>sentence/document-level task: </strong>diziyi normal bir şekilde işleyip, ardından [CLS] token’ının output gösterimi farklı bir modüle sequence-level tahmini için yollanır.</li><li><strong>text-pair task:</strong> her bir metin çiftini cümle A ve cümle B diye encode ettikten sonra, [CLS] token’ının output gösterimi farklı bir modüle tahmin işlemi için yollanır.</li></ul><h4>1.3. Standard Conditional Models (SCM)</h4><p>Rastgele değişkenler arasında bağımlılık oluşturan istatistiksel bir modeldir. (aka Structural Equation Model — SEM veya Directed Acyclic Graph — DAG)</p><h4>1.4. Self-Supervised and Unsupervised Learning</h4><p>Hem self-supervised hem de unsupervised learning, etiketli veri kullanmaz. Unsupervised, self-supervised learning’in üst kümesidir. Self-supervised ve unsupervised learning, birbiri yerine kullanılabilen terimler olmakla birlikte (ill-defined olarak geçiyor [12]) biraz farklıdır.</p><blockquote>Unsupervised learning is an ill-defined and misleading term that suggests that the learning uses no supervision at all. In fact, self-supervised learning is not unsupervised, as it uses far more feedback signals than standard supervised and reinforcement learning methods do [12].</blockquote><p>Self-supervised learning, SSL veya Facebook Meta AI deyimiyle zekanın kara maddesi, tahmin edici (predictive model) olarak geçer. SSL veri içindeki supervisory sinyalleri<strong>*</strong> alır ve veri içerisindeki yatan yapıdan yararlanır. SSL’de sık kullanılan teknik, input’taki henüz gözlenmemiş veya gizli kısımdaki parçayı tahmin etmektir [12].</p><p><strong>*</strong>Supervised learning’te, her örnek bir input (genelde vector) ve istenen output değeri (<strong>supervisory signal</strong> olarak da adlandırılır) içerir.</p><p>Unsupervised learning, verideki <em>latent</em>, var olan ama aktif olmayan, örüntüleri bulurken; self-supervised learning ise bir unsupervised tipi olmakla birlikte, veride her zaman var olmuş olan ve kullanılan bir takım supervised learning sinyallerini bulur.</p><h3>2. Makale İncelemesi📎</h3><p><a href="https://arxiv.org/abs/1810.04805">BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding</a></p><p>BERT, Bidirectional Encoder Represantations from Transformers, isminden de anlaşılacağı üzere transformer üzerine kurulu ve sadece encoder kısmına sahip olan bir mimaridir. Diğer dil gösterim modellerinin aksine, BERT etiketsiz metinlerden sağ ve solundaki tüm katmanlarla ortaklaşa etkileşime girerek, derin çift-yönlü gösterimler pre-train etmek için tasarlanmıştır. Sonuç olarak, BERT modeli sadece ek bir output katmanı ile fine-tune edilebilir.</p><p>Pre-trained dil modellerini uygulamak için var olan iki strateji vardır: feature-based ve fine-tuning. <strong><em>Feature-based metodu</em></strong>, örnek olarak ELMo, içinde ek feature olarak pre-trained representations olan göreve özel mimariler kullanır.<em> </em><strong><em>Fine-tuning metodu</em></strong> ise, örnek olarak Generative Pre-trained Transfomer (GPT), minimal göreve özel parametreleri tanıtır ve downstream tasks, yani asıl çözülmek istenen problemler, üzerinde tüm pretrained parametreleri fine-tune ederek eğitilir.</p><p>İki metod da, tek-yönlü dil modellerini kullanarak genel dil gösterimlerini (general language representations) öğrenmek için pre-training aşamasında aynı objective function’ı * paylaşmaktadır.</p><blockquote>* Loss Function: tahmin edilen ile gerçek output arasındaki farktır.</blockquote><blockquote>* Cost Function: modelin parametreleri optimize etmek için, modelin parametreleri ve loss function ile oluşturulmuş bir fonksiyondur.</blockquote><blockquote>* Objective Function: Modelde belli bir çıktıyı elde edebilmek için minimize veya maksimize edilmesi gereken fonksiyondur.</blockquote><p>Yazarların düşüncesine göre, var olan teknikler, özellikle fine-tuning metodları için, pre-trained gösterimlerinin gücünü sınırlamaktadır. En büyük sınırlamanın, standart dil modellerinin tek-yönlü olması olduğuna değinilmiş. Çünkü, bu tek-yönlülük pre-training sırasında kullanılabilecek mimari seçiminin sınırlandırmaktadır. Buna örnek olarak, GPT’nin her tokeni sadece önceki tokenlerle etkileşime geçebildiği transformer’ların self-attention katmanlara sahip olan, soldan-sağa bir model kullanması verilmiştir. <em>Cümle-seviyesi</em> görevlerde optimal altı performansa neden olmakla birlikte, <em>token-seviyesi</em> görevlere, soru cevaplama gibi, fine-tuning metodu uygulandığında ise performansını oldukça kötü etkilemektedir.</p><p>Bu makale, BERT modelini sunarak fine-tuning bazlı metodların gelişmesine katkıda bulunmaktadır. BERT, az önce bahsettiğim tek-yönlülük sorununun, <strong>masked language model (MLM)</strong> pretraining kullanarak, kısıtlayıcı etkilerini azaltmaktadır.</p><p>Masked language model, rastgele bir şekilde input’taki bazı tokenleri maskeler ve amaç, sadece cümle bağlamına bakarak orijinal kelimenin id’sini tahmin etmektir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/616/1*iVbg7Bk62RqeuIo9CAUaLg.png" /><figcaption>Chihiro’nun anasıyla babasını bulmaya çalışması gibi, model de maskelenen kelimenin id’sini bulmaya çalışıyor. [2]</figcaption></figure><p>Soldan-sağa dil modeli pretraining işleminin tersine, MLM görevi sola ve sağa representation’ların akışını sağlar. Bu sayede transformer çift-yönlü, bidirectional, olur.</p><p>BERT’te MLM dışında, bir de ortaklaşa metin-çift gösterimlerini (text-pair representations) pretrain eden <strong>next-sentence prediction</strong> görevi kullanılmaktadır.</p><p>Bu makalede, iki önemli çıktı vardır:</p><ul><li>Çift-yönlü pre-training’in dil modelleri için olan önemi ve bunu aktive etmek için masked language models kullanımı</li><li>Göreve özel ve heavy-engineered mimarilere ihtiyaç azalmıştır. BERT, <em>cümle-seviyesi ve token-seviyesi görevlerde</em> ilk state-of-the-art (SOTA) başarısına ulaşan fine-tuning bazlı representation modelidir.</li></ul><h4>2.1. BERT</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*CtwpZO_idN8xLbHymf2oMQ.png" /><figcaption>Figür 1. BERT’in pre-training ve fine-tuning aşamaları [3]</figcaption></figure><p>BERT, iki önemli adıma sahiptir: pre-training ve fine-tuning.</p><p>Pre-training adımında, farklı pre-training görevlerinde etiketsiz veri üzerinde eğitilir.</p><p>Fine-tuning adımında ise, öncelikle BERT pre-training parametreleri ile başlatılır ve sonrasında tüm parametreler, downstream görevlerde, etiketli veri üzerinde fine-tune edilir. Her downstream görevin, aynı pre-training parametrelerle başlatılmış olsa dahi, ayrı bir fine-tune modeli vardır.</p><p>BERT’in ayırt edici özelliklerinden birisi, tek bir mimariye sahip olsa da çeşitli görevler üzerinde kullanılabilmesidir. Pre-trained mimari ile final downstream mimari ile arasındaki fark oldukça küçüktür.</p><h4>2.2. Model Mimarisi</h4><p>BERT modelinin mimarisi, çok katmanlı çift-yönlü transformer encoder bazlıdır.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/139/1*d6RP6VdhBSycfDIO9P_TMA.png" /><figcaption>Transformer Encoder Yapısı [6]</figcaption></figure><p>Katman sayısı L, hidden size H ve self-attention head sayıları A notasyonunu kullanalım. BERT(base) bu durumda, (L=12, H=768, A=12, Total Parametreler=110M) ve BERT(large) bu durumda, (L=24, H=1024, A=16, Total Parametreler=340M) olarak ifade edilebilir.</p><p>GPT ile karşılaştırmak için BERT(base) seçilmiştir, nedeni ise aynı model boyutuna sahip olmalarındandır. Temel fark olarak, BERT Transformer çift-yönlü self-attention kullanırken, GPT sınırlandırılmış self-attention, yani her tokenin sadece solundaki ile etkileşime geçebilen, kullanmaktadır.</p><h4>2.3. Input ve Output Gösterimleri</h4><p>BERT’in birçok downstream görevi gerçekleştirebilmesi için, input gösterimleri açık ve iki şekilde de, bir cümle ile bir çift cümle, tek bir token dizisi içerisinde kullanır. (&lt;Soru, Cevap&gt; gibi)</p><p>Makalede ve bu yazıda, <em>cümle </em>denildiği zaman sadece tamamen bir cümle değil, aynı zamanda bir cümle parçacığı, &lt;span&gt;, da kastedilmektedir. <em>Dizi </em>denildiğinde ise, BERT’e input token dizisi (bir cümle veya bir çift cümle olabilen) anlamına gelmektedir.</p><p>Bu çalışmada, 30k token kütüphanesine sahip WordPiece embeddings kullanılmıştır. Her dizinin ilk tokeni her zaman özel sınıflandırma tokeni (<strong>[CLS]</strong>)’dir. Bu tokene tekabül eden final hidden state ise, sınıflandırmada dizi gösterimlerini toplamak için kullanılmaktadır. Cümle çiftleri, tek bir diziye paketlenmiştir. Cümleler iki yol ile ayırt edilmektedir:</p><ul><li>Onları özel bir token (<strong>[SEP]</strong>) ile ayırırız.</li><li>Her tokene, cümle A’ya mı yoksa cümle B’ye mi ait olduğuna göre, öğrenilmiş bir embedding ekleriz.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*HazlMHs6nb9dftpCoBkauQ.png" /><figcaption>Metni Bir Dizi Token Embeddings’e Dönüştürmek [5]</figcaption></figure><p>Input embedding’ler E, özel final hidden vector [CLS] tokeni C ve i. token için final hidden vector ise Ti şeklinde ifade edilebilir.</p><p>Her bir tokenin input gösterimi alakalı token, segment ve position embeddings toplayarak elde edilir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/893/1*q_iXjkuUBRURkKoKerbdQA.png" /><figcaption>Figür 2. Input Gösterimlerinin Nasıl Toplanarak Elde Edildiği [3]</figcaption></figure><h4>2.4. Pre-training BERT</h4><p>BERT, iki unsupervised görev üzerinde pre-train edilmiştir.</p><p><strong>*Görev 1: Masked Language Model (MLM)</strong></p><p>Standard conditional modeller sadece soldan-sağa veya sağdan-sola eğitilebilirler. Çift-yönlü koşullandırma olsaydı eğer, <em>kendisini</em> görür ve gerçekten öğrenemezdi. Çift-yönlü gösterim elde etmek için, basitçe input tokenlerinden rastgele bazıları maskelenir ve ardından maskelenmiş tokenlar tahmin edilir. Bu işleme MLM denir. Ardından mask token’larına tekabül eden final hidden vectors, output softmax’a beslenir.</p><p>Makaledeki deneylerde, tüm WordPiece embeddings’in %15&#39;i maskelenmiştir. Tüm input, denoising autoencoders’taki gibi yeniden yapılandırmak yerine, sadece maskelenmiş input kelimeleri tahmin etmek için kullanılmıştır. Bu çift-yönlü pre-trained model elde etmeyi sağlasa da, negatif bir yönü bulunmaktadır: [MASK] tokeni fine-tuning aşamasında olmadığı için, pre-training ve fine-tuning arasında uyumsuzluk oluşturulmaktadır. Bu etkiyi azaltmak için, maskelenen kelimeler her zaman [MASK] tokeni ile ifade edilmez. Bunun yerine şu yol izlenir:</p><p>Training data genenator, token pozisyonlarından %15&#39;ini tahmin etmek için rastgele seçer. i. token, Ti, seçildikten sonra, i. token yerine:</p><ul><li>zamanın %80&#39;inde [MASK] tokeni konulur</li><li>%10&#39;unda rastgele bir token konulur</li><li>%10&#39;unda ise değiştirilmez</li></ul><p>Daha sonra da, Ti orijinal tokeni cross-entropy loss ile tahmin etmek için kullanılacak.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*gAT6fJC-5n1cO4l4aG_T0w.png" /><figcaption>Figür 3. Masked Language Modeling (MLM) Örneği [4]</figcaption></figure><p><strong>*Görev 2: Next Sentence Prediction (NSP)</strong></p><p>Birçok önemli downstream görevler, soru cevaplama ve natural language inference gibi, direkt olarak dil modeli tarafından çıkarılamayan <em>iki cümle arasındaki ilişkiye</em> dayanır. Cümleler arasındaki ilişkiyi anlayabilecek bir model eğitmek için, <strong>binarized</strong> next sentence prediction görevi pre-train edilmiştir. Özellikle, her bir pre-training örneği için cümle A ve B’yi seçerken, zamanın %50&#39;si B, A’yı takip eden sonraki cümledir (IsNext olarak etiketlidir); %50&#39;sinde ise corpus’tan rastgele bir cümledir (NotNext olarak etiketlidir).</p><p>Önceki çalışmalarda sadece cümle embedding’leri downstream görevlere yönlendirilirken; BERT tüm parametreleri, end-task model parametrelerini başlatmak için yönlendirir.</p><p>Pre-training verisi olarak BookCorpus (800M) ve English Wikipedia (2.500M) kullanılmıştır.</p><h4>2.5. Fine-tuning BERT</h4><p>Fine-tuning aşaması, transformer içinde self-attention mekanizmasının BERT’e bir sürü downstream görevi yerine getirmesini uygun input ve output’ları değiştirerek sağladığı için, basittir.</p><p>Metin çiftleri içeren uygulamalarda, bidirectional cross-attention uygulamadan önce, genel örüntü bağımsız bir şekilde metin çiftlerini encode etmektir. BERT ise bunun yerine, iki aşamayı birleştirmek için self-attention mekanizmasını kullanır.</p><p>Her görev için, göreve özel input’lar ve output’lar BERT’in içine beslenir ve end-to-end şekilde, uçtan uca, tüm parametreler fine-tune edilir.</p><p>Input’ta, pre-training’ten cümle A ve cümle B şuna benzetilebilir:</p><ul><li>paraphrasing cümle çiftleri</li><li>hypothesis-premise çiftleri (entailment)</li><li>soru cevaplamadaki question-passage çiftleri</li><li>metin sınıflandırmada bozulmuş metin veya sequence tagging</li></ul><p>Output’ta ise, token gösterimleri (sequence tagging ve question answering gibi) token-seviyesi görev için output katmanına beslenirken; [CLS] gösterimleri sınıflandırma için (entailment veya sentiment analysis gibi) output katmanına beslenir.</p><p>Son olarak fine-tuning, pre-training’e göre hesaplama açısından daha ucuzdur.</p><h4>2.6. Sonuçlar</h4><p>GLUE (General Language Understanding Evaluation) içinde birçok görev barındıran bir benchmark (model performansını ölçmek için) veri setidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*HExOWYXKdLVjspqECguPgA.png" /><figcaption>Tablo 1. GLUE Sonuçları [3]</figcaption></figure><p>The Stanford Question Answering Dataset (SQuAD v1.1) 100k tane question-answer çifti içeren bir veri setidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*fjbDtqM6MZhuLg5WSe6UHA.png" /><figcaption>Tablo 2. SQuAD 1.1 Sonuçları [3]</figcaption></figure><p>SQuAD 2.0 veri seti ise, bir tık gelişmişi, kısa cevapların olmadığına emin olan bir veri setidir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*RyADGfhHk-r_5Ko5fEEnKg.png" /><figcaption>Tablo 3. SQuAD 2.0 Sonuçları [3]</figcaption></figure><p>Situations With Adversarial Generations (SWAG) veri seti ise 113k sentence-pair completion içerir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*luNkCMzm1BBb2f08BSxjYA.png" /><figcaption>Tablo 4. SWAG Sonuçları [3]</figcaption></figure><p>Ablation study, farklı parçaların veya özelliklerin önemini değerlendirmek için uygulanan, modelden çıkarma (ablation) yoluyla, bir metottur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*bW_I9X35q83DkGt6GShGow.png" /><figcaption>Tablo 5. No NSP (sadece MLM var) ve left-to-right (LTR) Önemi için Yapılan Ablation Study [3]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*cWqqNfcb2aQm5jfDK8qP7w.png" /><figcaption>Tablo 6. Modelin Boyutunun Etkisi için Yapılan Ablation Study [3]</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*GDDVivaAFKAL1wZ-Uy3NGA.png" /><figcaption>Tablo 7. Named Entity Recognition Görevindeki Model Karşılaştırması [3]</figcaption></figure><p>Kısacası, BERT(base) ve BERT(large)’ın ikisi de, bahsedilen görevlerde çok daha iyi performans göstermiştir. BERT(large), sezgisel uyumluluk sağlayarak, BERT(base)’den daha iyi sonuç vermiştir. NSP ve MLM kaldırmak, modelin performansını ciddi anlamda olumsuz etkilemiştir.</p><h3>3. Özet📝</h3><p>Transformer’lardan çift-yönlü encoder gösterimleri (veya doğadan🍵haliyle Bidirectional Encoder Representations from Transformers) yani BERT, bir sürü dil anlama görevinde kullanılan bir modeldir. Transformer encoder ile aynı mimariye sahiptir. Fazlaca büyüklükte, çiğ (işlenmemiş, dalından yani raw) ve etiketlenmemiş metinsel veri üzerinde, self-supervised learning objective kullanılarak, pre-train edilmiştir. Sonra da downstream görevleri (soru cevaplama, cümle sınıflandırma, named entity recognition vb.) çözmek için fine-tune edilmiştir [5].</p><p>BERT’in süper etkili olma nedenleri şunlardır:</p><ol><li>Devasa boyutta ve çiğ (demek hoşuma gidiyor) metinsel veride self-supervised learning (MLM ve NSP işlemleri buna dahil) kullanılarak pre-train edilmesi</li><li>Bir dizideki her token’ın zengin ve çift-yönlü feature representation’larını çıkartmak</li></ol><p>BERT’in ana konseptleri: i) (Bidirectional) Self-Attention, ii) Transformer Encoders ve iii) Self-Supervised Learning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*4Yy9a7sPXn4xr-PhH1lb3A.png" /><figcaption>Figür 4. Tek-yönlü ve çift-yönlü self-attention Farkı [5]</figcaption></figure><h3>4. Bir BERT, İki BERT, Üç BERT…<strong>🐑</strong></h3><p>Çeşitli BERT modelleri bulunmaktadır. Bunlara örnek olarak:</p><ul><li><strong>ELECTRA</strong>: Pre-training Text Encoders as Discriminators Rather Than Generators [7]</li><li><strong>ALBERT</strong>: A Lite BERT for Self-supervised Learning of Language Representations [8]</li><li><strong>ViLBERT</strong>: Pretraining Task-Agnostic Visiolinguistic Representations for Vision-and-Language Tasks [9]</li><li><strong>RoBERTa</strong>: A Robustly Optimized BERT Pretraining Approach [10]</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6BhblRoEh4rVTIzhPvZWFQ.jpeg" /><figcaption>Figür 5. Çeşitli Dil Modelleri ve İlişkileri [11]</figcaption></figure><h3>5. Code in Action👩‍💻</h3><p>Artık hareket vakti. <em>Başlangıç </em>için linkleri iliştirdim.</p><ul><li><a href="https://huggingface.co/docs/transformers/model_doc/bert">BERT</a></li><li><a href="https://github.com/google-research/bert">GitHub - google-research/bert: TensorFlow code and pre-trained models for BERT</a></li><li><a href="https://github.com/stefan-it/turkish-bert">GitHub - stefan-it/turkish-bert: Turkish BERT/DistilBERT, ELECTRA and ConvBERT models</a></li></ul><blockquote>“The art is in knowing how to ask.” — Dan Brown, Origin</blockquote><h3>Kaynakça</h3><p>[1] <em>We all have those days</em>. (2018, June 4). Reddit. <a href="https://www.reddit.com/r/tumblr/comments/8oga13/we_all_have_those_days/">https://www.reddit.com/r/tumblr/comments/8oga13/we_all_have_those_days/</a></p><p>[2] Ghibli Studio, Hayao Miyazaki (2001). <em>Spirited Away</em>, Movie.</p><p>[3] Devlin, J., Chang, M. W., Lee, K., &amp; Toutanova, K. (2018). Bert: Pre-training of deep bidirectional transformers for language understanding. <em>arXiv preprint arXiv:1810.04805</em>.</p><p>[4] Weyssow, M., Sahraoui, H., &amp; Syriani, E. (2022). Recommending metamodel concepts during modeling activities with pre-trained language models. <em>Software and Systems Modeling</em>, <em>21</em>(3), 1071–1089.</p><p>[5] Wolfe, C. R. (2022, October 10). <em>Language Understanding with BERT</em>. By Cameron R. Wolfe. <a href="https://cameronrwolfe.substack.com/p/language-understanding-with-bert">https://cameronrwolfe.substack.com/p/language-understanding-with-bert</a></p><p>[6] Vaswani, A., Shazeer, N., Parmar, N., Uszkoreit, J., Jones, L., Gomez, A. N., … &amp; Polosukhin, I. (2017). Attention is all you need. <em>Advances in neural information processing systems</em>, <em>30</em>.</p><p>[7] Clark, K., Luong, M. T., Le, Q. V., &amp; Manning, C. D. (2020). Electra: Pre-training text encoders as discriminators rather than generators. <em>arXiv preprint arXiv:2003.10555</em>.</p><p>[8] Lan, Z., Chen, M., Goodman, S., Gimpel, K., Sharma, P., &amp; Soricut, R. (2019). Albert: A lite bert for self-supervised learning of language representations. <em>arXiv preprint arXiv:1909.11942</em>.</p><p>[9] Lu, J., Batra, D., Parikh, D., &amp; Lee, S. (2019). Vilbert: Pretraining task-agnostic visiolinguistic representations for vision-and-language tasks. <em>Advances in neural information processing systems</em>, <em>32</em>.</p><p>[10] Liu, Y., Ott, M., Goyal, N., Du, J., Joshi, M., Chen, D., … &amp; Stoyanov, V. (2019). Roberta: A robustly optimized bert pretraining approach. <em>arXiv preprint arXiv:1907.11692</em>.</p><p>[11] <a href="https://github.com/thunlp/PLMpapers">thunlp. 2019. “Must-read papers on pre-trained language models.” PLMPapers, thunlp on GitHub, November. Accessed 2019–12–01.</a></p><p>[12] <em>Facebook — Meld je aan of registreer je</em>. (n.d.). Facebook. <a href="https://www.facebook.com/unsupportedbrowser">https://www.facebook.com/unsupportedbrowser</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83001559d5bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>