彼はしばらくスタンフォード大学の教授で、後にテスラのAI部門の責任者となり、OpenAIで働き、そして、私の見解では、今日利用可能な最高のAI教育ビデオのいくつかも制作している。 最新のプロジェクトは、 しかし、それは私が芸術作品としてしか表現できないものだ。 microGPT microGPT は GPT で書かれた完全な実装です。 そしてこれは巧妙に圧縮されたコードではなく、逆に、コードは清潔で、よく構造化され、徹底的にコメントされています。それは外部の深層学習ライブラリの使用を避けることさえします。 only about 200 lines of Python code 実際には、プロジェクト全体には完全なリポジトリさえありません - それは単に、プロジェクトとして公開されます。 . single GitHub Gist https://gist.github.com/karpathy/8627fe009c40f57531cb18360106ce95?embedable=true この記事では、この素晴らしいコードの一部がどのように機能するかを説明しようと思います。 . anyone with basic Python knowledge can understand 名前から始めよう . GPT GPT 賛成 このアーキテクチャは、ほとんどの現代の大型言語モデルの基礎を形成します ChatGPT自体は、その名称にこの略称を含んでおり、ほとんどの主要な代替案は現在、同じ基本的なアイデアに基づいて構築されています。 Generative Pretrained Transformer GPTモデル予測 テキストの前の言葉に基づく。 the next word (or token) This is essentially what all language models do. They generate responses by predicting one word at a time. First, they predict the next word, then they add that word to the text and predict the next one again, and so on. 一見すると、これは単純に聞こえるかもしれませんが、より慎重に考えると、次の単語を正しく予測するには一定のレベルが必要です。 . understanding of the text and its meaning ニューラルネットワークでは、この「思考」プロセスは、 . very large mathematical function 入力単語は数字に変換され、次に次の単語を計算するこの関数に供給されます. 原則として、どんなルールシステムも、そのような関数を使用して数学的に表すことができます. したがって、問題は言語の構造をキャプチャする正しい関数を見つけることです. この機能は、私たちが呼ぶ「The . model 問題は、この機能が 現代の言語モデルには数十億のパラメータが含まれているため、それらを記述する数学的公式には数十億の構成要素が含まれる可能性がある。 extremely complex 幸いなことに、スマートなワークアウトがあります。 正確な公式を私たち自身で書く代わりに、私たちはAを定義します。 for the formula, a structure with many adjustable parameters. これらのパラメータは、モデルがうまく機能するまで自動的に調節することができます。 “template” 私たちが解決したい問題の種類に応じて、いくつかのテンプレートがあります: Convolutional networks are commonly used for image processing. Convolutional networks are commonly used for image processing. MLPs(multi-layer perceptrons)は、一般的な機能のアプローチに使用される。 トランスフォーマーは、ChatGPTのような言語モデルに使用されます。 など これらのテンプレートは、パラメータが適切に調整されると、複雑なルールに近づくことができる巨大な数学構造を表します。 残りの質問は、 あるいは、すなわち: How do we adjust these parameters? How do we “program” a neural network? 神経ネットワークのパラメータを手動で調整することは明らかに不可能であり、特に数百万、あるいは数十億のパラメータを含むモデルに取り組んでいる場合です。 幸いにも、データを使用して自動的にこれを行う方法があります。このプロセスは私たちが呼ぶものです。 , and the method that makes it possible is called . training gradient descent 大きなデータセットと大きな数学式(当社のモデル)がある場合、データセット内の各例のモデルのエラーを計算できます。 トランスフォーマーの場合、プロセスは大体こんな感じです。 Words are represented as points in a high-dimensional vector space, where words with similar meanings appear closer to each other. 各単語は、この空間の点に対応します。 モデルは入力として単語の順序を受け取り、次の単語を予測しようとします。単語がベクトルとして表されるので、予測された単語が正しい単語からどのくらい離れているかを計算できます。 そして、今度は魔法がやってくる。 gradient descent を使用して、このエラーを減らすために公式のパラメータがどのように変化するかを計算できます。 If we have enough data, a sufficiently large network, and we train it for long enough, the formula gradually adapts to the patterns in the dataset and produces increasingly accurate predictions. しかし、この「魔法」は正確にどのように機能するのでしょうか? グラディエントダウンは実際により良いパラメータを見つける方法がありますか? エラーは高次元空間における関数として、それぞれの次元がモデルの1つのパラメータに対応することを想像できます。 多くの次元で考えることは人間にとってほぼ不可能なので、代わりに、もっと単純な類似を想像することができます:丘と谷の風景。 In this analogy: 風景の各点は、モデルパラメータの特定の組み合わせを表しています。 その時点での風景の高さは、モデルのエラーを表しています。 At the beginning of training, the parameters are initialized randomly. This is like being placed somewhere randomly on the hillside. 私たちの目標は、エラーを最小限に抑えること、つまり景観の最も低い点を見つけることです。 困難なのは、私たちは風景がどう見えるか分からないということです. まるで、盲目的に覆われた山を下りようとしているかのようなものです. それでは、私たちは何ができるでしょうか? そこで降りてくるのがグレード。 数学には、いわゆる , 特定の点での関数の傾斜を記述する。 derivative これは非常に役に立ちます. Derivative は私たちに言う。 . which direction the landscape slopes downward アルゴリズムは単に以下のことを行います。 風景の傾斜を測る。 エラーが減る方向に小さな一歩を踏み出します。 繰り返し ステップごとに、モデルは、エラーの風景の低い点に達するまで徐々に下りて行きます。 これが、基本的に降り注がれることです。 残る質問は、このような複雑な機能の傾斜をどのように計算するかである。 私はここで完全な数学的な詳細に進むつもりはない、なぜなら、カルパティーにはすでに を説明する。 素晴らしい動画 私たちの目的のために、次のことを知るだけで十分です。 それぞれの数学的操作には、その地元の階段を計算することを可能にする相応のルールがあります。さらに、連鎖ルールと呼ばれるルールがあり、これらの地元の階段を組み合わせて、合成機能全体の階段を計算することができます。 重要なアイデアは、我々は運用チェーンを通じて後方に移動し、途中でグレディエントを収集することである。 すべての主要な深層学習フレームワークがこのメカニズムを実装しています。 例えば: TensorFlow は GradientTape と呼ばれるシステムを使用し、テープレコーダーのような操作を記録し、後でグラディエントを計算することができます。 attaches gradient information directly to tensors. Each tensor remembers how it was created, which allows gradients to be computed automatically. This system is called . PyTorch autograd Karpathyの実装は、同じ基本的なアイデアに従います。 # Let there be Autograd to recursively apply the chain rule through a computation graph class Value: __slots__ = ('data', 'grad', '_children', '_local_grads') # Python optimization for memory usage def __init__(self, data, children=(), local_grads=()): self.data = data # scalar value of this node calculated during forward pass self.grad = 0 # derivative of the loss w.r.t. this node, calculated in backward pass self._children = children # children of this node in the computation graph self._local_grads = local_grads # local derivative of this node w.r.t. its children def __add__(self, other): other = other if isinstance(other, Value) else Value(other) return Value(self.data + other.data, (self, other), (1, 1)) def __mul__(self, other): other = other if isinstance(other, Value) else Value(other) return Value(self.data * other.data, (self, other), (other.data, self.data)) def __pow__(self, other): return Value(self.data**other, (self,), (other * self.data**(other-1),)) def log(self): return Value(math.log(self.data), (self,), (1/self.data,)) def exp(self): return Value(math.exp(self.data), (self,), (math.exp(self.data),)) def relu(self): return Value(max(0, self.data), (self,), (float(self.data > 0),)) def __neg__(self): return self * -1 def __radd__(self, other): return self + other def __sub__(self, other): return self + (-other) def __rsub__(self, other): return other + (-self) def __rmul__(self, other): return self * other def __truediv__(self, other): return self * other**-1 def __rtruediv__(self, other): return other * self**-1 def backward(self): topo = [] visited = set() def build_topo(v): if v not in visited: visited.add(v) for child in v._children: build_topo(child) topo.append(v) build_topo(self) self.grad = 1 for v in reversed(topo): for child, local_grad in zip(v._children, v._local_grads): child.grad += local_grad * v.grad In Karpathy’s code, the entire gradient computation logic is implemented in the クラスとは、ただ単に . Value 40 lines long This class is essentially a wrapper around numerical values. Besides storing the data itself, it also stores: 子どもの(子どもの)から見たもの。 後ろ向きに必要とされる地元の階段。 コードを見ると、標準オペレーターが再定義されていることがわかります。 加えて __mul__ そして他者。 つまり、数学的な操作を行うたびに、 プログラムは結果を計算するだけでなく、どの値がそれを生成し、どのようにグレディエントが拡散されるべきかを記録します。 Value Finally, the method performs the backpropagation process. It walks backward through the chain of operations and computes the total gradient with respect to the error. backward() それが基本的に、アイデア全体です。 トレーニングのもう一つの重要なコンポーネントは、モデルのパラメータを更新するために計算されたグライデントを使用するグライデントダウン自体です。 言い換えれば、これは傾斜情報を使用して実際に丘を下りるコードの一部です。 # Adam optimizer update: update the model parameters based on the corresponding gradients lr_t = learning_rate * (1 - step / num_steps) # linear learning rate decay for i, p in enumerate(params): m[i] = beta1 * m[i] + (1 - beta1) * p.grad v[i] = beta2 * v[i] + (1 - beta2) * p.grad ** 2 m_hat = m[i] / (1 - beta1 ** (step + 1)) v_hat = v[i] / (1 - beta2 ** (step + 1)) p.data -= lr_t * m_hat / (v_hat ** 0.5 + eps_adam) p.grad = 0 In Karpathy’s implementation, this is done with the 深層学習における最も広く使用されている最適化アルゴリズムの1つです。 Adam optimizer アダムは基本的なグレディントダウンよりも少し複雑です。固定サイズのステップを取る代わりに、以前のグレディントの歴史に基づいてステップサイズをダイナミックに調整します。 . faster and more stable 前述のグレディエント計算と最適化ステップは、コードの一部として深い学習枠組みと呼べるものを形成します。 言語モデル、イメージジェネレータ、ロボットコントローラ、自動運転車を駆動するかに関わらず、あらゆるニューラルネットワークは、本質的に同じ原則を用いて訓練されています。 これらのコードのいくつかの行は、現代のAIの背後にあるコアアイデアをキャプチャします。 大型フレームワーク: Large Frameworks Like: TensorFlowについて ピーターチ JAX GPU、TPU、および分散クラスターで実行できる高度に最適化された実装を提供し、多くの追加トリックと最適化を含みます。 しかし、すべてを基本的なものに切り落とすと、その根底にある原理は、この小さなPythonの実装で私たちが見るものとまったく同じです。 コードの深層学習フレームワーク部分を見た今では、実際のニューラルネットワーク、すなわちGPTモデル自体に移行することができます。 前述したように、GPTの目的は、それ以前のトークンに基づいて次のトークンを予測することです。 This definition is slightly simplified, because the input does not actually consist of words, but of tokens. トークンは単語に非常に似ていますが、同じではありません。事前定義された辞書に依存する代わりに、システムはトレーニングデータから統計的に辞書を学びます。 したがって、トレーニングは、それぞれの単語がすでにそれに割り当てられた数を持っている固有の単語リストから始まらないのであり、代わりに、この「辞書」は、プレプロセス中にデータ自体から生じます。 このアプローチは、ハンガリー語などのアグルチナティブ言語に特に有用であり、単一の単語は、補足や文法の終わりによって多くの異なる形を持つことができます。 十分なトレーニングデータがあれば、言語モデルは、自然や人工のいずれかの言語を学ぶことができます。 実際、トークンはテキストを表す必要もありません。 parts of images オーディオ Fragments of Audio センサー読み方 ほぼあらゆる種類のデータ このため、トランスフォーマーモデルは言語処理に限らず、画像生成、スピーチ処理、ロボット、その他の多くのタスクにも使用できます。 Karpathyのモデルは意図的に非常に小さいので、この場合、トークンは単語ではなく文字です。 したがって、モデルの目的は、完全な文や答えを生成することではなく、単に現実的に見える名前を生成することです。 トレーニングデータセットは、大規模な名前リストで構成され、トレーニング後、モデルが統計的に例に似た新しい名前を生成することを期待します。 これは、ChatGPTのような完全な言語モデルとは明らかに遠いが、実際には、違いはほとんどがスケールである。 このモデルを何百万回も拡大し、文字の代わりにトークンを使用し、インターネットから収集された膨大なデータセットでトレーニングすれば、現代の大きな言語モデルに非常に似ているものが生まれるでしょう。 これらの大きなモデルは通常、2つの段階で訓練されます: Pretraining – training on massive internet datasets to learn general language patterns. Fine-tuning - ヒューマン生成会話を使用して反応を改善するためのさらなるトレーニング。 このプロセスには膨大な計算資源と膨大な量の高品質のデータが必要であり、しばしば数百万ドルの計算費がかかります。 私たちのほとんどがそのようなリソースにアクセスできないので、私たちは名前を生成するために決めなければなりません。 # Let there be a Dataset `docs`: list[str] of documents (e.g. a list of names) if not os.path.exists('input.txt'): import urllib.request names_url = 'https://raw.githubusercontent.com/karpathy/makemore/988aa59/names.txt' urllib.request.urlretrieve(names_url, 'input.txt') docs = [line.strip() for line in open('input.txt') if line.strip()] random.shuffle(docs) print(f"num docs: {len(docs)}") # Let there be a Tokenizer to translate strings to sequences of integers ("tokens") and back uchars = sorted(set(''.join(docs))) # unique characters in the dataset become token ids 0..n-1 BOS = len(uchars) # token id for a special Beginning of Sequence (BOS) token vocab_size = len(uchars) + 1 # total number of unique tokens, +1 is for BOS print(f"vocab size: {vocab_size}") コードの始まりには、名前のデータセットをロードし、辞書を構築する責任のあるセクションがあります。 この場合、辞書は単にデータセットに表示される文字のリストで構成されます。 Each character is assigned a numerical identifier, allowing the text to be converted into numbers that the neural network can process. Next comes one of the most important concepts in deep learning: . embeddings アイデアはシンプルですが、強力です。 原始トークンIDで作業する代わりに、私たちは各トークンを一つのトークンにマッピングします。 これらのベクターは、ニューラルネットワークが実際に処理するものです。 point in a high-dimensional vector space 実際、あらゆるニューラルネットワークは、 . maps vectors from one high-dimensional space into another 例えば: 神経ネットワークを犬や猫に分類するように訓練すると、ネットワークは画像を二次元空間にマッピングし、一つの次元は「犬性」、もう一つの次元は「猫性」に対応します。 Midjourneyのような画像ジェネレーターを想像すると、それはランダムな騒音を高次元の空間にマッピングし、各点はプロンプトに条件付けられた画像を表します。 仕事に関係なく、ネットワークは常に実行しています。 . vector-to-vector transformation using a large mathematical function GPTについても同様です。 The dimensionality of the vector space is defined in the code by the constant この実施の目的は、 . n_embd 16 これは、それぞれのトークン(この場合、それぞれの文字)がAとして表されることを意味します。 . 16-dimensional vector Mathematically, this mapping is simply a . matrix multiplication このコードでは、この変換を担当するマトリックスを , which stands for . wte word/token embedding However, knowing which characters appear in a word is not enough. Their also matters. position たとえば、文字列の意味は、文字列を変更する場合に変化します。 位置情報を組み込むには、モデルは , implemented using another matrix called . positional embeddings wpe コードは、トークンとその位置を16次元ベクターにマッピングし、その後単に . adds the two vectors together 結果は、両方をコードする単一のベクターです。 the identity of the token its position within the sequence Earlier, we mentioned that these vector representations must be meaningful, because later the model will compute errors based on distances between vectors. Ideally: should be close to the correct vector Almost correct predictions should be far away from it Very wrong predictions This raises an interesting question: How do we design a good embedding space? 答えは驚くほどシンプルです: We don’t. Instead, we initialize the embedding matrices ( and ) with random numbers and allow gradient descent to learn the correct representation during training. wte wpe If we have enough data, the optimization process will gradually adjust the matrices until they represent useful relationships. これは驚くほど強力な新興資産につながる可能性があります。 例えば、有名な embedding model, vector arithmetic can capture semantic relationships. A classic example is: word2vec king − man + woman ≈ queen Here we can already see that the embedding space begins to represent a kind of , where relationships between concepts appear as geometric relationships between vectors. コンセプト間の関係は、ベクター間の地理的関係として現れる。 simplified model of the world Now that we have seen how vectors are created, we can finally look at the neural network itself, the component that transforms these vectors into new vectors representing the next token. In other words, the network maps vectors from the token embedding space back into the same space, but shifted by one token. For each token, it predicts which token should follow next. By repeatedly applying this process, the model can generate an entire sequence of text — or in this case, a name. The architecture used for this is called the . Transformer The Transformer was introduced in 2017 by researchers at Google in the famous paper: “Attention Is All You Need.” The original architecture was designed for . It consisted of two main parts: machine translation an encoder デコード The encoder processed the input sentence, while the decoder generated the translated output sentence. For generative models like GPT, however, we only need : the . half of the original architecture decoder stack This is why GPT models are often described as . decoder-only transformers The decoder receives the input tokens and repeatedly processes them through a stack of identical layers. Each layer contains two main components: Self-attention feed forward neural network(MLP)とは これらの層は、大きなモデルで何度も繰り返されます. In diagrams, you often see this represented as つまり、ブロックは複数回積み重ねられているということです。 ×N One of the key innovations of the Transformer architecture is that it processes the . entire sequence at once Older language models, especially recurrent neural networks (RNNs), processed text one word at a time, sequentially passing information along the sequence. Transformers work differently. They can look at all tokens simultaneously, allowing the model to learn relationships between any parts of the text. このメカニズムは呼ばれる。 , which is why the original paper was titled . attention 注意はあなたが必要とするすべて 注意メカニズムは、どのように計算するか 順番では relevant each token is to every other token For each token vector, the model computes a set of weights describing how much attention it should pay to the other tokens. It then combines the information from those tokens accordingly. The resulting vector therefore represents not only the token itself, but also . its meaning in the context of the entire sequence This may sound complicated, but the intuition is straightforward. 例えば、言語モデルを問うとします。 “What is the capital of France?” If we only looked at the word , we couldn't determine the answer. but attention allows the model to connect the word. 答えを決められなかったが、注意がモデルに単語を接続することを可能にした。 同 . “capital” “capital” “France” The resulting representation captures the meaning of the phrase , making it possible for the model to produce the correct answer: . “capital of France” Paris One way to think about transformers is to imagine them as a kind of . soft database 明確な事実を格納する代わりに、モデルはベクトル空間の表現に知識を格納するので、神経ネットワークは正確なルールを記憶するのではなく、接近的な機能を提供するので、これまで見たことのない質問によく答えることができます。 Returning to our earlier embedding example: If the training data contains information about kings and women, the model may still be able to answer questions about queens, because the relationships between these concepts are captured in the vector space. このデータベースの類似性に従えば、次のように言えます。 acts like an , helping the model locate relevant information. Attention index MLPレイヤーには、知識そのものが含まれています。 この精神モデルは直感に役立ちますが、文字通り正しくありません。 In a real transformer like the one used in ChatGPT, these attention + MLP blocks are repeated many times. Knowledge is not stored in a single location but is distributed across layers. Additionally, each layer includes a residual connection, which mixes the original input vectors with the newly computed vectors. This allows information to flow through the network more effectively and stabilizes training. ベクトルがレイヤーを通過するにつれて、新しい抽象と意味が現れることがあります. By the time the final layer produces its output, the model has combined information from many different levels of representation. ベクトルがレイヤーを通過するにつれて、新しい抽象と意味が現れることがあります。 The full process is far too complex to follow step by step with human intuition. Yet despite this complexity, the system works remarkably well in practice. Now that we have a rough intuition about the transformer architecture, let’s look at one of its most important components in more detail: . attention # 1) Multi-head Attention block x_residual = x x = rmsnorm(x) q = linear(x, state_dict[f'layer{li}.attn_wq']) k = linear(x, state_dict[f'layer{li}.attn_wk']) v = linear(x, state_dict[f'layer{li}.attn_wv']) keys[li].append(k) values[li].append(v) x_attn = [] for h in range(n_head): hs = h * head_dim q_h = q[hs:hs+head_dim] k_h = [ki[hs:hs+head_dim] for ki in keys[li]] v_h = [vi[hs:hs+head_dim] for vi in values[li]] attn_logits = [sum(q_h[j] * k_h[t][j] for j in range(head_dim)) / head_dim**0.5 for t in range(len(k_h))] attn_weights = softmax(attn_logits) head_out = [sum(attn_weights[t] * v_h[t][j] for t in range(len(v_h))) for j in range(head_dim)] x_attn.extend(head_out) x = linear(x_attn, state_dict[f'layer{li}.attn_wo']) x = [a + b for a, b in zip(x, x_residual)] In Karpathy’s implementation, attention is calculated using three matrices called: Q (Query) K (Key) V (Value) These matrices perform vector projections. In other words, each token vector is mapped into three different vector spaces. 私たちが計算するすべてのトークンに対して: クエリー ベクター a key vector 価値ベクター Once we have these vectors, we compare the query vector of one token with the key vectors of all tokens in the sequence. Mathematically, this is done using a dot product. The dot product gives a score that represents how strongly two vectors are related. This produces a set of numbers that represent . how relevant each token is to the current token However, these raw scores are not yet probabilities. To convert them into a probability distribution, we apply the , which transforms the scores into values between 0 and 1 that sum to 1. この値を 0 から 1 までの値に変換します。 softmax function これらの値は、各トークンがどれだけの注意を払うべきかを表します。 Finally, the model combines the value vectors using these attention weights, producing a new vector that contains information gathered from the entire context. Scaled dot-product attentionの公式は以下のようになります。 注意(Q、K、V) = softmax(QKT / √dk) V Here: computes the similarity between queries and keys QKᵀ is a scaling factor that stabilizes training √dₖ softmax はスコアを注意の確率に変換します。 Vは、これらの確率に従って結合される情報を提供します。 結果は、反映する各トークンのための新しい表示です。 . its meaning in the context of the entire sequence At this point, it is worth mentioning an important concept: . context length As we discussed earlier, transformers process the entire sequence at once. This is necessary because attention requires comparing . every token with every other token That means the computational cost grows with the number of tokens. quadratically コンテキストの長さを2倍にすると、計算量は約4倍になります。 This is one of the main limitations of transformer models. Unlike some other architectures, transformers do not have a separate memory system. They can only “see” the tokens that fit within their context window. Everything outside that window is effectively invisible to the model. だからこそ、文脈の長さは現代言語モデルの重要な属性である。 多くの現代のAIシステムでは、この制限は、外部メモリメカニズムを追加することによって解決されます。 A common approach is to use a . vector database Instead of storing knowledge directly in the model, information can be stored externally as vector embeddings. When the model receives a question, the system can: Convert the question into a vector. Search the vector database for related information. Insert the retrieved information into the model’s context. This means the model sees both: 質問 and the relevant knowledge retrieved from the database 両方ともコンテキストウィンドウに表示されるため、モデルはその情報に基づいて回答を生成することができます。 このテクニックは、 and is widely used in modern AI systems and agent frameworks. Retrieval-Augmented Generation (RAG) この設定では、言語モデルの主な役割は知識を保存することではなく、その文脈で利用可能な情報に基づいて一貫した回答を生成することです。 But as we can see, this requires space in the context window, which is why context length remains so important. Karpathy の実装に戻ると、モデルは , which is an improved form of the basic attention mechanism. multi-head attention Q、K、Vマトリックスの単一セットを使用して注意を計算する代わりに、モデルは複数の注意頭を使用します。 この実施には、4つの頭があります。 それぞれの頭部は、トークン間の異なる種類の関係に焦点を当てることを学びます. たとえば、一つの頭部は文法関係に焦点を当てることができ、もう一つの頭部は、より長い範囲の依存性を捉えることができます。 Using multiple heads improves the quality of the representation. 計算コストをほぼ同じように維持するには、それぞれのヘッドの次元性が削減されます。 Earlier, we mapped vectors from a . 16-dimensional space to another 16-dimensional space 4つの注意の頭で、それぞれの頭部は代わりに、 . The results from the heads are then combined back into a single vector. 4-dimensional space それぞれのヘッドは低次元ベクターで動作しますが、組み合わせた結果は単一の注意ヘッドを使用するよりもより表現的で正確です。 注目メカニズムをカバーした今、トランスフォーマーブロックの2番目の主要なコンポーネントに移行しましょう。 あるいは . MLP feed-forward neural network コードでは、MLPブロックはこんな感じです。 # 2) MLP block x_residual = x x = rmsnorm(x) x = linear(x, state_dict[f'layer{li}.mlp_fc1']) x = [xi.relu() for xi in x] x = linear(x, state_dict[f'layer{li}.mlp_fc2']) x = [a + b for a, b in zip(x, x_residual)] MLPはA . If we look at the structure of the weight matrices, we can interpret the rows of the matrix as . classic neural network architecture neurons A neuron is a simple computational unit that: multiplies each input by a weight, 結果をまとめ、 Then it applies a nonlinear activation function to produce the output. This model was originally inspired by biological neurons in the human brain. In that sense, neural networks were historically motivated by attempts to mimic how the brain might process information. However, modern AI systems have moved quite far from this original analogy. In the MLP component, we can still loosely recognize something that resembles neurons. But when we look at mechanisms like 脳にインスピレーションを与えた解釈を維持することは、より困難になります。 attention このため、現代のAIシステムを単に考えるのがよくあります。 , rather than literal models of the brain. trainable mathematical functions コード内のMLPブロックは、3つの主要なステップで構成されています。 a (matrix multiplication), linear transformation 非線形活性化関数(ReLU) another . linear transformation This may look simple, but structures like this have an extremely powerful mathematical property. They are known as . universal approximators universal approximators これは、一定の条件下で、十分に大きなMLPが近づくことができることを意味します。 to an arbitrary degree of accuracy. any mathematical function 原則として、一つの巨大なMLPはほぼ何でも学ぶことができます。 However, that would not be very efficient in practice. That is why transformer architectures combine multiple mechanisms, including attention and stacked layers, to distribute the computation more effectively. ネットワークの出力は単一のトークンではなく、 . probability distribution over all possible tokens 言い換えれば、辞書の各トークンに対して、モデルは、次の順序に表示される可能性を生成します。 During generation, the algorithm then samples from this probability distribution. This means that tokens with higher probability are more likely to be chosen, but there is still an element of randomness. このランダム性は、いわゆるパラメータによって制御されます。 . temperature THE パラメータは、モデルの出力がどれほど決定的か、あるいは創造的かを決定します。 temperature - the model strongly favors the most probable tokens, producing more predictable and accurate responses. Low temperature 高温 - 確率分布がより平らになり、より頻繁にトークンを選択する可能性が低くなり、より多様かつ創造的な出力が生じます。 For example: モデルが文書を分析し、事実上の質問に答えることを望む場合は、低い温度が一般的に好まれる。 モデルがクリエイティブなテキストを生成するか、新しいアイデアを探求することを望むなら、より高い温度がより興味深い結果を生み出すことができます。 これは、この素晴らしいコードについて、そしてGPTモデルについて一般的に説明したいことだ。 私の目標は、2つのことのバランスをとることでした:できるだけ多くの有用な洞察を含む一方で、議論を1つの記事の範囲内で維持することでした。 説明の一部を少し不明確に見つけた読者、または詳細をより深く探求したい人は、私は強くお勧めします。 彼の そして、 そこでは、ここで議論された概念を完全に理解するために必要なすべてを説明する優れた資料を見つけることができます。 Andrej Karpathy’s personal website YouTube channel his blog I hope this article was useful to many readers. If nothing else, perhaps it serves as an invitation to explore the fascinating world of AI.