Transformer Modelle

RNNs erlauben uns den Kontext vor oder nach der aktuellen Position zu verwenden.

Information über weite Entfernungen wird trotzdem vergessen.

Encoder-Decoder hat eine fixe Memory Größe zwischen den Modulen.

State Vektor ist der Flaschenhals um Lange Sequenzen zu speichern.

Wir würden am liebsten immer Zugriff auf den ganzen Input beim Decoden haben.

Wie können wir das bei einer Variablen Sequenz Länge erreichen?

Attention Mechanismus

Idee: Mehr Fokus auf dem relevantesten Wort / Token des Inputs

Attention ist eine gewichtete Summe aller Input Tokens.

Für jedes Input Token $i$ berechnen wir zwei Vektoren:

  • Einen Key $k_i$
  • Einen Value $v_i$

Zu jedem Decoding Schritt $j$ berechnen wir einen Query Vektor $q_j$

Das Produkt $q_j \cdot k_i$ bestimmt wie relevant das Token $i$ für das Decoding an Position $j$ ist.

$q$ und $k$ müssen die gleiche Dimension $n$ haben.

Mit Softmax skalieren wir diese Gewichte:

\[ \tilde w_j = \operatorname{softmax}(\frac{\sum_i q_j \cdot k_i}{\sqrt{n}}) \]

Zum Schluss berechnen wir die gewichtete Summe aller Values.

\[ \sum_i \tilde w_j \cdot v_i \]

Die $v_i$ sind word / token embeddings.

Relevantere Embeddings $v_i$ haben einen größeren Anteil am Ergebnis.

Das softmax von $q_j \cdot k_i$ liefert uns einen differenzierbaren Lookup

Mit Attention kann jedes Input Token zu jedem Decoding Schritt als Teil des Inputs erreicht werden, ohne über die Zeit an Relevanz zu verlieren.

Die Punkt Produkte der Attention skalieren quadratisch ($O(n^2)$) mit der Sequenz Länge.

Rechenzeit limitiert, wie lang unsere Input Sequenz, bzw. die generierte Output Sequenz sein können.

(es gibt einige Tricks um das praktisch effizienter zu machen)

Wenn wir die initialen Embeddings für die Input Token ($k_i$, $v_i$) berechnen, sollten wir dem Algorithmus einen Weg mitgeben, die Position des Tokens zu wissen.

Andernfalls erhalten wir nur ein (kompliziertes) Bag-of-Words Modell.

Positional Encoding

Idee: Füge dem Embedding einen Teil hinzu, mitdem wir die Position bestimmen können.

Das Positional Encoding der Länge $d$ an Position $p$ ist:

\[ \begin{bmatrix} \sin(\frac{p}{10000^{\frac{2 \cdot 0}{d}}}) \\[3mm] \cos(\frac{p}{10000^{\frac{2 \cdot 0}{d}}}) \\[3mm] \sin(\frac{p}{10000^{\frac{2 \cdot 1}{d}}}) \\[3mm] \cos(\frac{p}{10000^{\frac{2 \cdot 1}{d}}}) \\[3mm] \vdots \\[3mm] \sin(\frac{p}{10000^{\frac{d}{d}}}) \\[3mm] \cos(\frac{p}{10000^{\frac{d}{d}}}) \\[3mm] \end{bmatrix} \]

Wir erhalten ein Wellenmuster mit ansteigenden Wellenlängen.


https://commons.wikimedia.org/wiki/File:Positional_encoding.png

  • Kleine Indizes unterscheiden die lokale Position.
  • Große Indizes unterscheiden die globale Position.

Anstelle eines statischen Positional Encodings kann man auch ein gelerntes Encoding verwenden.

Transformer Architektur


https://commons.wikimedia.org/wiki/File:The-Transformer-model-architecture.png

Transformer sind eine sehr generische und mächtige Architektur.

Wenn wir nicht genug Daten haben können wir sehr viel Overfitting erwarten.

Aktuelle Large Language Models (LLMs), wie GPT-4 - basieren auf Transformern (nur Decoder), trainiert auf riesigen Mengen Text Daten aus dem Internet.

Ein kleines bis mittelgroßes, vortrainiertes LLM kann auch auf regulären Rechnern heruntergeladen und ausgeführt werden.


          %pip install --upgrade torch torchvision torchaudio
          %pip install transformers einops accelerate xformers

          from transformers import AutoTokenizer, AutoModelForCausalLM

          model_name = "togethercomputer/RedPajama-INCITE-7B-Instruct"
          tokenizer = AutoTokenizer.from_pretrained(model_name)
          model = AutoModelForCausalLM.from_pretrained(model_name)
          model = model.to('cuda')
        

LLMs sind darauf trainiert, die bedingten Wahrscheinlichkeiten des nächsten Token vorherzusagen:


          import numpy as np

          inputs = tokenizer("Bananas are yellow and apples are", return_tensors="pt").to(model.device)
          generation_output = model.generate(**inputs, return_dict_in_generate=True, output_scores=True, max_new_tokens=1)

          def softmax(x):
              e = np.exp(x.cpu())
              return e / e.sum()

          probs = softmax(generation_output.scores[0][0])
          top_10 = np.argsort(-probs)[:10]

          for token_id in top_10:
              token = tokenizer.decode(token_id)
              print(f"{repr(token)}: {probs[token_id]*100}")
        

LLMs zeigen eine beeindruckende Fähigkeit zur Generalisierung auf neue Aufgaben.


          prompt = """Classify the text into neutral, negative or positive.
          Text: Even though the acting was terrific, the whole movie could not stand up to our expectations.
          Sentiment:"""

          inputs = tokenizer(prompt, return_tensors='pt').to(model.device)

          outputs = model.generate(
              **inputs, max_new_tokens=3, num_beams=5, return_dict_in_generate=True
          )

          output_str = tokenizer.decode(outputs.sequences[0,:])
          print(output_str)
        

LLMs lassen sich einsetzen um Information aus unstrukturiertem Input zu ziehen.


          prompt = """
          Context:
          BEIJING, Sept 15 (Reuters) - China's factory output and retail sales grew at a faster pace in August, but tumbling investment in the crisis-hit property sector threatens to undercut a flurry of support steps that are showing signs of stabilising parts of the wobbly economy.
          Chinese policymakers are facing a daunting task in trying to revive growth following a brief post-COVID bounce in the wake of persistent weakness in the crucial property industry, a faltering currency and weak global demand for its manufactured goods.
          Industrial output rose 4.5% in August from a year earlier, data released on Friday by the National Bureau of Statistics (NBS) showed, accelerating from the 3.7% pace in July and beating expectations for a 3.9% increase in a Reuters poll of analysts. The growth marked the quickest pace since April.
          Retail sales, a gauge of consumption, also increased at a faster 4.6% pace in August aided by the summer travel season, and was the quickest growth since May. That compared with a 2.5% increase in July, and an expected 3% rise.
          The upbeat data suggest that a flurry of recent measures to shore up a faltering economy are starting to bear fruit.
          Yet, a durable recovery is far from assured, analysts say, especially as confidence remains low in the embattled property sector and continues to be a major drag on growth.
          "Despite signs of stabilisation in manufacturing and related investment, the deteriorating property investment will continue to pressure economic growth," said Gary Ng, Natixis Asia Pacific senior economist.
          The markets, however, showed relief at some of the better-than-expected indicators.
          The Chinese yuan touched two-week highs against the dollar, while the blue-chip CSI 300 Index (.CSI300) was up 0.2% and Hong Kong's Hang Seng Index (.HSI) climbed 1% in early morning trade.
          Further aiding sentiment, separate commodities data showed China's primary aluminium output hit a record-monthly high in August while oil refinery throughput also rose to a record.

          Question:
          How does the Chinese yuan perform? (good/bad/neutral)

          Answer:"""
        

          prompt = """
          Create a JSON representation of the article, containing the following keys: 'source', 'country', 'tags', 'category'.

          Article:
          BEIJING, Sept 15 (Reuters) - China's factory output and retail sales grew at a faster pace in August, but tumbling investment in the crisis-hit property sector threatens to undercut a flurry of support steps that are showing signs of stabilising parts of the wobbly economy.
          Chinese policymakers are facing a daunting task in trying to revive growth following a brief post-COVID bounce in the wake of persistent weakness in the crucial property industry, a faltering currency and weak global demand for its manufactured goods.
          Industrial output rose 4.5% in August from a year earlier, data released on Friday by the National Bureau of Statistics (NBS) showed, accelerating from the 3.7% pace in July and beating expectations for a 3.9% increase in a Reuters poll of analysts. The growth marked the quickest pace since April.
          Retail sales, a gauge of consumption, also increased at a faster 4.6% pace in August aided by the summer travel season, and was the quickest growth since May. That compared with a 2.5% increase in July, and an expected 3% rise.
          The upbeat data suggest that a flurry of recent measures to shore up a faltering economy are starting to bear fruit.
          Yet, a durable recovery is far from assured, analysts say, especially as confidence remains low in the embattled property sector and continues to be a major drag on growth.
          "Despite signs of stabilisation in manufacturing and related investment, the deteriorating property investment will continue to pressure economic growth," said Gary Ng, Natixis Asia Pacific senior economist.
          The markets, however, showed relief at some of the better-than-expected indicators.
          The Chinese yuan touched two-week highs against the dollar, while the blue-chip CSI 300 Index (.CSI300) was up 0.2% and Hong Kong's Hang Seng Index (.HSI) climbed 1% in early morning trade.
          Further aiding sentiment, separate commodities data showed China's primary aluminium output hit a record-monthly high in August while oil refinery throughput also rose to a record.

          JSON:"""
        

Wenn wir strukturierten Output wollen, können wir die generierten Wahrscheinlichkeiten so anpassen, dass wir eine korrekte Output Struktur forcieren.

Die bisherigen Beispiele waren alle "zero-shot" prompting.

Es kann oft hilfreich sein, dem LLM Beispiele mitzugeben, um die Performance zu steigern ("few-shot" prompting)


          prompt = """
          This is awesome! - 9/10
          This is bad! - 3/10
          This was the most horrific show - 1/10
          Wow that movie was rad! - 10/10
          The movie was quite okay - 6/10
          Unimaginative plot but good performance! -"""
        

Question Answering funktioniert am besten, wenn das LLM Zugriff auf eine Referenz hat, welche die Antwort enthält.


          prompt = """
          Context:
          In the time of King Frederick William I (1688), shortly after the Thirty Years' War and a century before today's Brandenburg Gate was constructed, Berlin was a small walled city within a star fort with several named gates: Spandauer Tor, St. Georgen Tor, Stralower Tor, Cöpenicker Tor, Neues Tor, and Leipziger Tor (see map). Relative peace, a policy of religious tolerance, and status as capital of the Kingdom of Prussia facilitated the growth of the city. With the construction of Dorotheenstadt around 1670 and its inclusion in Berlin's city fortifications, a first gate was built on the site, consisting of a breach through the raised wall and a drawbridge over the dug moat.
          The Berlin Customs Wall with its eighteen gates, around 1855. The Brandenburger Thor (Brandenburg Gate) is on the left.
          With the construction of the Berlin Customs Wall (German: Akzisemauer) in 1734, which enclosed the old fortified city and many of its then suburbs, a predecessor of today's Brandenburg Gate was built by the Court Architect Philipp Gerlach as a city gate on the road to Brandenburg an der Havel. The gate system consisted of two Baroque pylons decorated with pilasters and trophies, to which the gate wings were attached. In addition to the ornamental gate, there were simple passages for pedestrians in the wall, which were decorated with ornamental vases at this point.[3]
          The current gate was commissioned by Frederick William II of Prussia to represent peace and was originally named the Peace Gate (German: Friedenstor).[4] It was designed by Carl Gotthard Langhans, the Court Superintendent of Buildings, and built between 1788 and 1791, replacing the earlier simple guardhouses which flanked the original gate in the Customs Wall. The gate consists of twelve Doric columns, six to each side, forming five passageways. Citizens were originally allowed to use only the outermost two on each side. Its design is based on the Propylaea, the gateway to the Acropolis in Athens, and is consistent with Berlin's history of architectural classicism (first Baroque, and then neo-Palladian). The gate was the first element of a "new Athens on the river Spree" by Langhans.[5] Atop the gate is a sculpture by Johann Gottfried Schadow of a quadriga—a chariot drawn by four horses—driven by Victoria, the Roman goddess of victory.

          Question:
          Who designed the Brandenburg Gate?

          Answer:"""
          

Wie können wir eine solche Referenz bereitstellen?

Idee 1: Nutze Websuche und einen Crawler.

    Ansatz

  • Verwende eine Suchmaschine um nach der Antwort zu suchen.
    • Optional: Wir können das LLM nutzen, um die Suchanfrage zu formulieren.
  • Wir crawlen die ersten $n$ Suchergebnisse
  • Diese Seiten nutzen wir als Kontext für die ursprüngliche Query.

Idee 2: Nutze Embeddings für eine semantische Ähnlichkeitssuche.

Word / Token / Text Embeddings von semantisch ähnlichem Input haben eine kleine Cosine Distance.

Wir können Text Embeddings nutzen um passende Text Referenzen zu finden.

    Ansatz

  • Erstelle eine Knowledge Database aus Text Fragmenten.
  • Berechne Embeddings für jedes Fragment.
  • Berechne Embedding für den Query String.
  • Suche $k$ Text Fragmente mit den ähnlichsten Embeddings.
  • Verwende diese als Referenzen, um die Antwort zu generieren.

Problem: Mit einer großen Knowledge Database müssen wir viele Cosine Distanzen berechnen.

Wir suchen die $k$ Nearest Neighbors (KNN) eines gegebenen Vektor.

Allgemein braucht das $O(n)$ Zeitschritte.

Eine Verbesserung ist, eine approximierte Nearest Neighbor (ANN) Suche zu machen.

Idee: Es ist okay, wenn wir manchmal einen dichteren Nachbarn verpassen.

Ein ANN Algorithmus: Hierarchical Navigable Small World Graphs


https://arxiv.org/abs/1603.09320

Vektor Datenbanken implementieren ANN Suche:

Für alle Input Daten, für die wir ein sinnvolles Embedding berechnen können, können wir so eine semantische Suche implementieren.

  • Texts
  • Images
  • Audio
  • DNA fragments
  • ...

LLMs zeigen oft eine beeindruckende zero oder few shot performance.

Sobald wir ein paar hundert Beispiele haben, können wir ein LLM auch fine tunen.

(so wie wir es auch bei CNNs gemacht haben)

Ein kleines LLM, welches auf den Use Case finegetuned wurde kann besser als ein großes unmodifiziertes funktionieren.

Das kann relevant sein, da Inferenz für LLMs ins Geld gehen kann.

Manche LLMs, wie ChatGPT, sind "instruction-tuned".

Der Fine Tuning Datensatz besteht aus Instructions Chats, damit das LLM besser wird, Anweisungen zu folgen.

Transformer sind nicht auf Sequenzdaten beschränkt.

Ein Transformer nimmt die Welt als Bag of Vektors wahr.

Transformer können auch auf Bildern funktionieren.

Idee: Teile das Bild in kleine Patches auf.

Jeder Patch erhält ein Positional Encoding und ist Flattened (oder mit einem CNN Preprocessed).


https://commons.wikimedia.org/wiki/File:Vision_Transformer.gif

Bild und Textdaten können sogar zu einem Input für einen Transformer vereint werden.
Solange wir Vektoren $v$ und $k$ der gleichen Länge für alle Arten von Input Daten verwenden.

Sehr große "foundational models" bieten ein neues Paradigma für die Entwicklung von Machine Learning Anwendungen:

  • Entwickle ein MVP Nutzer Interface.
  • Prompte ein Foundation Model um eine Aufgabe zu automatisieren.
  • Verbessere das Produkt und sammle Daten.
  • Fine Tune das Model um die Performance zu verbessern / Kosten zu reduzieren.