Andrej Karpathy no anaran'ny olona maro ao amin'ny tontolo AI. Izy dia mpampianatra tao amin'ny Stanford nandritra ny fotoana ela, taorian'izay dia lasa lohan'ny fizarana AI tao amin'ny Tesla, niasa tao amin'ny OpenAI, ary, araka ny hevitro, izy ihany koa dia mamokatra ny sasany amin'ireo lahatsary fampianarana AI tsara indrindra azo jerena amin'izao fotoana izao. Ny tetikasa farany dia Na izany aza, izany dia zavatra izay tsy azoko atao afa-tsy hoe asa zavakanto. microGPT microGPT dia fampiharana GPT feno voasoratra ao amin'ny Ary izany dia tsy misy fehezan-dalàna malaza na tsy misy fehezan-dalàna. Ankoatra izany, ny fehezan-dalàna dia madio, tsara rafitra, ary tanteraka ny fanehoan-kevitra. Na izany aza dia manakana ny fampiasana biby fianarana avo lenta ivelany. amin'ny teny hafa, tsy ahitana ny tambajotra neuronal ihany, fa koa ny rafitra kely indrindra ilaina amin'ny fampiofanana sy ny fandefasana azy. only about 200 lines of Python code Raha ny marina, ny tetikasa manontolo dia tsy manana trano fitehirizana tanteraka - fotsiny dia navoaka ho toy ny . single GitHub Gist https://gist.github.com/karpathy/8627fe009c40f57531cb18360106ce95?embedable=true Ao amin'ity lahatsoratra ity, dia miezaka ny manazava ny fomba fiasa ity karazana code mahafinaritra ity amin'ny fomba izay . anyone with basic Python knowledge can understand Andeha isika hanomboka amin'ny anarana . GPT Ny GPT dia miantso Ity rafitra ity dia mamorona fototry ny ankamaroan'ny modely fiteny lehibe maoderina. ChatGPT ihany no ahitana ity fanamarihana ity ao amin'ny anarany, ary ny ankamaroan'ny safidy lehibe amin'izao fotoana izao dia miorina amin'ny hevitra mitovy amin'izany. Generative Pretrained Transformer Ny modely GPT dia manambara mifototra amin'ny teny mialoha ao amin'ny lahatsoratra iray. the next word (or token) Amin'ny ankapobeny, izany no ataon'ny modely rehetra amin'ny fiteny. dia mamokatra valiny amin'ny alàlan'ny fanambaran'ny teny iray amin'ny fotoana iray. Voalohany, manambara ny teny manaraka izy ireo, dia manampy izany teny izany amin'ny lahatsoratra ary manambara indray ny teny manaraka, ary toy izany koa. Amin'ny voalohany, dia mety ho tsotra izany. fa raha mieritreritra bebe kokoa isika, ny fanambaran'ny teny manaraka amin'ny fomba marina dia mitaky avo lenta. . understanding of the text and its meaning Ao amin'ny tambajotra neuronaly, ity dingana "fantatra" ity dia ampiharina ho toy ny . very large mathematical function Ny teny fidirana dia miova amin'ny isan-karazany ary voatery ho amin'ity endri-javatra ity, izay manombana ny teny manaraka. Amin'ny fitsipika, ny rafitra fitsipika rehetra dia azo aseho amin'ny fomba matetika amin'ny fampiasana asa toy izany. Ity asa ity dia antsoina hoe . model Ny olana dia ny fahafahana manao io asa io Ny modely fiteny maoderina dia ahitana lavitrisa parameters, izay midika fa ny vahaolana matematika mamaritra azy ireo dia mety manana lavitrisa components. extremely complex Soa ihany fa misy fifanarahana malaza. Fa raha tsy manoratra ny fehezan-dalàna marina isika, dia mamaritra ny ho an'ny famolavolana, rafitra miaraka amin'ny parametra maro azo ampiharina. Ireo parametra ireo dia azo ampiharina avy hatrany mandra-pahatongan'ny modely tsara. “template” Misy modely maromaro toy izany, miankina amin'ny karazana olana tiantsika hamaha: Ny tambajotra convolutional dia ampiasaina matetika amin'ny fanodinana sary Ny MLP (multi-layer perceptrons) dia ampiasaina amin'ny fampidirana ny asa ankapobeny. Ny transformers dia ampiasaina amin'ny modely fiteny toy ny ChatGPT Ary ny Ireo templates ireo dia maneho rafitra matematika goavana izay afaka manodidina fitsipika sarotra rehefa voafaritra tsara ny parameters. Ny fanontaniana sisa dia: Na, amin'ny teny hafa dia: How do we adjust these parameters? How do we “program” a neural network? Manually adjusting the parameters of a neural network would obviously be impossible, especially when we are dealing with models that contain millions or even billions of parameters. Soa ihany fa misy fomba hanaovana izany, amin'ny fampiasana ny angon-drakitra. Ity dingana ity dia antsoina hoe ary ny fomba izay mahatonga izany dia antsoina hoe . training gradient descent Raha manana dataset lehibe sy endrika matematika lehibe (ny modely), dia azontsika atao ny mandinika ny fahadisoan'ny modely ho an'ny ohatra tsirairay ao amin'ny dataset. Amin'ny tranga transformers, ny dingana dia miasa toy izao manodidina. Ny teny dia aseho toy ny vato ao amin'ny sehatry ny vektor avo lenta, izay teny amin'ny dikany mitovy dia hita akaiky kokoa amin'ny hafa. Ny modely dia mahazo andian-dahatsoratra ny teny ho toy ny fidirana ary miezaka manambara ny teny manaraka. Satria ny teny dia aseho amin'ny vektor, dia azontsika atao ny mahatakatra izay lavitra ny teny voalaza avy amin'ny marina. Ary ankehitriny dia tonga ny fahagagana. Amin'ny fampiasana ny fivoaran'ny gradient, azontsika atao ny manombana ny fomba fiovana ny parameter amin'ny formula mba hampihenana io fahadisoana io. Raha manana angon-drakitra ampy isika, tambajotra lehibe ampy, ary mandritra ny fotoana mahazatra isika, dia mifanaraka amin'ny endrika ao amin'ny angon-drakitra ny vahaolana ary mamokatra famaritana marina kokoa. Fa ahoana no tena miasa ity "magic" ity? Ahoana no mahatonga ny fivoaran'ny gradient hahita fepetra tsara kokoa? Afaka mijery ny fahadisoana toy ny endri-javatra ao amin'ny efitrano avo lenta, izay mifanaraka amin'ny singa iray amin'ny endrika tsirairay. Ny fikarohana amin'ny lafiny maro dia tsy azo atao ho an'ny olombelona, noho izany dia azontsika atao ny mieritreritra ny ankamaroan'ny ankamaroan'ny ankamaroan'ny ankamaroan'ny ankamaroan'ny ankamaroan'ny ankamaroan'ny ankamaroan'ny ankamaroan'ny olona. Amin'ny ankapobeny izany: Ny dingana tsirairay eo amin'ny sehatra dia maneho ny fiaraha-miombon'ny endrika manokana. Ny habetsahan'ny tany amin'izany fotoana izany dia maneho ny fahadisoan'ny modely. Ao amin'ny fanombohan'ny fampiofanana, ny parameters dia voasokafana amin'ny fomba am-bava. Izany dia toy ny toerana misy azy ireo amin'ny fomba am-bava eo amin'ny tendrombohitra. Ny tanjona dia ny hampihenana ny fahadisoana, izay midika fa mahita ny toerana ambany indrindra ao amin'ny sehatra. Ny fahasamihafana dia ny hoe tsy fantatsika hoe ahoana ny toeran'ny tany. Tahaka ny hoe miezaka mandeha eny ambanin'ny tendrombohitra na amin'ny haizina mafy isika. Izany no mahatonga ny fivoaran'ny gradient. Ao amin'ny matematika, misy hevitra antsoina hoe , izay mamaritra ny fihenan'ny fonosana amin'ny toerana voafaritra. derivative Izany dia tena mahasoa eto. Ny derivative milaza amintsika . which direction the landscape slopes downward So the algorithm simply does the following: Ataovy azo antoka ny fihenan'ny toetr'andro. Take a small step in the direction where the error decreases. Miverena ny Amin'ny dingana tsikelikely, ny modely dia mandeha lavitra hatrany mandra-pahatongan'ny lanjany ambany ao amin'ny sehatry ny fahadisoana. Izany no tena zava-nitranga amin'ny fivoaran'ny gradient. Ny fanontaniana sisa dia: Ahoana no ahafantarantsika ny fihenan'ny asa sarotra toy izany? Tsy handeha any amin'ny antsipirihany matematika tanteraka eto aho, satria Karpathy efa manana Ny fanazavana izany. Tsara ny lahatsary Ho an'ny tanjona, ampy ny mahafantatra ny manaraka. Na izany aza, misy fitsipika antsoina hoe fitsipika an-tserasera, izay mamela antsika hampifandray ireo fitsipika an-tserasera ireo mba handrefesana ny fitsipika an-tserasera manontolo. Ny hevitra fototra dia ny mandeha mivantana amin'ny alalan'ny orinasa, manangona gradients eo amin'ny lalana. Ny rafitra fampianarana lehibe rehetra dia mampihatra io rafitra io. For example: Ny TensorFlow dia mampiasa rafitra antsoina hoe GradientTape, izay manoratra hetsika toy ny fitaovana fisoratana anarana mba hahafantarana ny gradients avy eo. 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 Ny fampiharana an'i Karpathy dia mifanaraka amin'ny hevitra fototra mitovy. Aoka isika hijery ny fomba. # 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 Ny fampianarana, izay momba ny . Value 40 lines long Ity kilasy ity dia fototra manodidina ny isa. Ankoatra ny fitehirizana ny angon-drakitra, dia mitahiry ihany koa: Fa inona no fanantenan'ny zanany? ary ny gradients ao an-toerana ilaina ho an'ny backpropagation. Raha mijery ny fehezan-dalàna isika dia afaka mahita fa voafaritra indray ny mpampiasa matetika: __add__ Ary ny and others. Izany dia midika fa isaky ny manao asa matematika amin'ny Ny fandaharam-potoana dia tsy mamaritra fotsiny ny vokatra, fa manoratra ihany koa ireo lanjany nateraky azy sy ny fomba tokony hampitomboana ny gradient. Value Farany, ny method performs the backpropagation process. It walks backward through the chain of operations and computes the total gradient with respect to the error. backward() Ary izany no fototra ny hevitra manontolo. Ny ampahany manan-danja hafa amin'ny fampiofanana dia ny fivoaran'ny gradient, izay mampiasa ny gradients nomerika mba hanatsarana ny parameter ny modely. Amin'ny teny hafa, ity no ampahany amin'ny code izay tena mandeha amin'ny tendrombohitra amin'ny fampiasana ny fampahalalana momba ny tendrombohitra. # 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 Ao amin'ny fampiharana Karpathy, izany dia atao amin'ny , izay iray amin'ireo algorithm optimization ampiasaina indrindra amin'ny fampianarana lalina. Adam optimizer Adam is slightly more sophisticated than basic gradient descent. Instead of taking fixed-size steps, it adapts the step size dynamically based on the history of previous gradients. This makes the training process both . faster and more stable The gradient computation described earlier and the optimization step together form what we could call the deep learning framework part of the code. Ny tambajotra neuronal tsirairay - na mampiasa modely fiteny, generator sary, robot fanaraha-maso, na fiara tsy mitondra fiara - dia nianatra amin'ny fampiasana ny fitsipika mitovy. Ireo andininy vitsivitsy amin'ny code ireo dia mahazo ny hevitra fototra ao ambadiky ny AI maoderina. Ny rafitra lehibe toy ny: Ny fifamoivoizana PyTorch Ny X manome fampiharana avo lenta izay afaka mihazakazaka amin'ny GPUs, TPUs, ary clusters nomerika, ary ahitana fitaovana fanampiny maro sy ny fanatsarana. Fa raha manala ny zava-drehetra amin'ny fototra isika, ny fitsipika fototra dia mitovy amin'izay hitantsika amin'ity fametrahana Python kely ity. Now that we have seen the deep learning framework part of the code, we can move on to the actual neural network, in other words, the GPT model itself. Araka ny voalaza etsy ambony, ny tanjona amin'ny GPT dia ny mandinika ny token manaraka mifototra amin'ny token izay tonga talohan'izany. Ity famaritana ity dia tsotra kely, satria ny entana dia tsy ahitana teny, fa token. Token dia mitovy amin'ny teny, fa tsy mitovy izy ireo. Fa tsy miankina amin'ny vokatra voafaritra, ny rafitra dia mianatra vokatra avy amin'ny angon-drakitra fampiofanana. So training does not begin with a fixed list of words where each word already has a number assigned to it. Instead, this “dictionary” emerges from the data itself during preprocessing. Ity fomba ity dia mahasoa indrindra amin'ny fiteny agglutinative, toy ny Hungarian, izay teny iray dia afaka manana endrika maro samihafa noho ny famantarana sy ny famaranana. Amin'ny angon-drakitra fampiofanana ampy, ny modely fiteny dia afaka mianatra fiteny rehetra, na voajanahary na voajanahary. Raha ny marina, ny token dia tsy voatery mampiseho ny lahatsoratra. Afaka mampiseho: Ny ampahany amin'ny sary Ny ampahany amin'ny audio Ny famakiana ny sensor Raha ny marina, ny karazana angon-drakitra rehetra Noho izany, ny modely transformers dia tsy voafetra amin'ny fanodinana fiteny. Azo ampiasaina koa amin'ny famokarana sary, fanodinana feo, robotika, ary asa maro hafa. Ny modely Karpathy dia tena kely, ka amin'ity tranga ity, ny token dia tsy teny fa soratra. The model’s goal is therefore not to generate full sentences or answers, but simply to produce realistic-looking names. Ny dataset fampiofanana dia ahitana lisitra lehibe amin'ny anarana, ary aorian'ny fampiofanana, manantena isika fa ny modely dia hiteraka anarana vaovao izay mitovy amin'ny ohatra. This is obviously far from a full-scale language model like ChatGPT. But in reality, the difference is mostly one of scale. Raha mampitombo ity modely ity an-tapitrisany isika, mampiasa token-teny fa tsy an-tsoratra, ary mampiofana azy amin'ny angon-drakitra goavana avy amin'ny aterineto, dia ho tonga amin'ny zavatra mitovy amin'ny modely fiteny lehibe maoderina. Ireo modely lehibe ireo dia matetika voaomana amin'ny dingana roa: Pre-training - fampiofanana amin'ny angon-drakitra lehibe amin'ny aterineto mba hianatra ny fiteny ankapobeny. Fine-tuning - fampiofanana fanampiny amin'ny fampiasana fifanakalozan-kevitra nateraky ny olombelona mba hanatsarana ny valiny. Ny dingana dia mitaky loharanom-pahalalana goavana sy habetsaky ny angon-drakitra avo lenta, matetika mandany vola an-tapitrisany amin'ny solosaina. Satria ny ankamaroan'ny antsika dia tsy manana fidirana amin'ireo loharano ireo, dia tsy maintsy manaiky ny famokarana anarana isika. # 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}") Ao amin'ny fanombohan'ny code, dia hitantsika ny fizarana tompon'andraikitra amin'ny famoahana ny dataset ny anarana sy ny famoronana ny vokatra. Amin'ity tranga ity, ny vokatra dia ahitana fotsiny ny lisitry ny soratra izay hita ao amin'ny dataset. Ny marika tsirairay dia nomena ID nomerika, izay mamela ny lahatsoratra hiverina ho an'ny isa izay afaka mandrindra ny tambajotra neuronal. Ireto manaraka ireto no iray amin'ireo hevitra manan-danja indrindra ao amin'ny fampianarana lalina: . embeddings The idea is simple but powerful. Ankoatra ny miasa amin'ny token ID, dia mametraka ny token tsirairay amin'ny token iray isika. Ireo vektor ireo dia izay tena miasa amin'ny tambajotra neuronal. point in a high-dimensional vector space Raha ny marina, ny tambajotra neuronal rehetra dia azo heverina ho asa izay . maps vectors from one high-dimensional space into another Ohatra ny Raha manara-maso ny tambajotran'ny neuron izahay mba hanara-maso ny sary ho toy ny alika na saka, ny tambajotran'ny sary dia mapping ny sary fampisehoana ho any amin'ny habakabaka roa-dimensiona, izay iray mifanaraka amin'ny "dogness" ary ny hafa amin'ny "catness". Raha mieritreritra ny famokarana sary toy ny Midjourney isika, dia mapping feo mahazatra ho any amin'ny toerana avo-dimensiona izay ny tsirairay dia maneho sary voajanahary eo amin'ny fangatahana. Na inona na inona ny asa, ny tambajotra dia manatanteraka . vector-to-vector transformation using a large mathematical function The same is true for GPT. Ny fahasamihafana amin'ny sehatra vektor dia voafaritra ao amin'ny code amin'ny Izay voatendry amin'ity fampiharana ity . n_embd 16 Izany dia midika fa ny token tsirairay (ao amin'ity tranga ity, ny singa tsirairay) dia aseho toy ny . 16-dimensional vector Mathematically, this mapping is simply a . matrix multiplication Ao amin'ny code, ny matrice tompon'andraikitra amin'io fanovana io dia antsoina hoe , which stands for . wte word/token embedding Na izany aza, ny mahafantatra izay karazana hita ao amin'ny teny iray dia tsy ampy. Fa ny zava-dehibe. position Ohatra, ny dikany amin'ny andininy dia miova raha manova ny soratra. To incorporate positional information, the model uses , ampiasaina amin'ny alalan'ny matrix iray hafa antsoina hoe . positional embeddings wpe The code maps both the token and its position into 16-dimensional vectors, and then simply . adds the two vectors together Ny vokatra dia vektor tokana izay manoratra ny roa: 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: Ny fanehoan-kevitra dia tokony ho akaiky amin'ny vektor marina. should be far away from it Very wrong predictions This raises an interesting question: How do we design a good embedding space? The answer is surprisingly simple: We don’t. Instead, we initialize the embedding matrices ( and ) miaraka amin'ny isan-karazany ary mamela ny fivoahana gradient mba hianatra ny fampisehoana marina mandritra ny fampiofanana. wte wpe If we have enough data, the optimization process will gradually adjust the matrices until they represent useful relationships. This can lead to surprisingly powerful emergent properties. For example, in the famous amin'ny fametrahana modely, ny aritmetika vektor dia afaka mahazo fifandraisana semantika. Ny ohatra mahazatra dia: 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 Ny Transformer dia navoakan'ny mpikaroka ao amin'ny Google tamin'ny taona 2017 tao amin'ny lahatsoratra malaza: “Attention Is All You Need.” Ny fanorenana voalohany dia natao ho Noforonina tamin'ny ampahany roa lehibe: machine translation Ny encoder a decoder Ny encoder dia mandrindra ny andininy fidirana, raha ny decoder dia niteraka ny andininy avy amin'ny teny. For generative models like GPT, however, we only need Ny . 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 A feed-forward neural network (MLP) Ireo sehatra ireo dia mifarana matetika amin'ny modely lehibe. Ao amin'ny diagram, matetika ianao mahita izany toy ny Izany dia midika fa ny blôka dia voafafa isan-kerinandro. ×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. This mechanism is called , which is why the original paper was titled . attention Attention Is All You Need The attention mechanism calculates how in the sequence. 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. Noho izany, ny vektor vokatr'izany dia manolotra tsy ny token ihany, fa koa . its meaning in the context of the entire sequence Mety ho sarotra izany, fa ny intuition dia tsotra. Suppose we ask a language model: “What is the capital of France?” If we only looked at the word , we could not determine the answer. But attention allows the model to connect the word with . “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 Fa tsy mitahiry ny zava-misy mazava, ny modely mitahiry ny fahalalana ao amin'ny vektor space representation.Satria ny tambajotra neuronal mihoatra ny asa fa tsy mahatsiaro ny fitsipika marina, izy ireo matetika afaka mamaly fanontaniana tsy mbola hitany teo aloha. 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. If we follow this database analogy, we might say: Ny fahatsiarovana dia miasa toy ny indices, manampy ny modely hamantatra ny fampahalalana manan-danja. The contain the knowledge itself. MLP layers This mental model is useful for intuition, but it is not literally correct. In a real transformer like the one used in ChatGPT, these attention + MLP blocks are repeated many times. Ny fahalalana dia tsy voatahiry ao amin'ny toerana iray, fa alefa amin'ny sehatra maro. Ankoatra izany, tsirairay dia ahitana fifandraisana sisa, izay mampifangaro ny vektor voalohany amin'ny vektor novolavolaina vaovao. Izany dia mamela ny fampahalalana hiditra amin'ny tambajotra amin'ny fomba mahomby kokoa ary mametraka ny fampiofanana. Rehefa mivezivezy ny vektor amin'ny loharano, dia mety hitranga ny fanazavana vaovao sy ny dikany. Amin'ny fotoana izay ny loharano farany dia mamokatra ny vokatra, ny modely dia nanangona vaovao avy amin'ny ambaratonga samihafa amin'ny fampisehoana. 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: Ny faniriana K (Key) Ny lanjany dia These matrices perform vector projections. In other words, each token vector is mapped into three different vector spaces. Ho an'ny tsirairay dia mifanaraka amin'ny: a query vector a key vector Ny vektor dia Once we have these vectors, we compare the query vector of one token with the key vectors of all tokens in the sequence. Matetika, izany dia atao amin'ny fampiasana vokatra vitsivitsy. Ny vokatra vitsivitsy dia manome valiny izay maneho ny fahasamihafana amin'ny vektor roa mifandray. Izany dia mahatonga ny isan'ny isan-karazany izay maneho . 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. softmax function These values represent how much attention each token should receive. Farany, ny modely dia mampifandray ny vektoran'ny lanjany amin'ny fampiasana ireo vatom-pifantoka ireo, mamokatra vektor vaovao izay ahitana fampahalalana avy amin'ny kontekst manontolo. The formula for scaled dot-product attention looks like this: Attention(Q, K, V) = softmax(QKᵀ / √dₖ) V Here: computes the similarity between queries and keys QKᵀ is a scaling factor that stabilizes training √dₖ converts the scores into attention probabilities softmax provides the information that is combined according to those probabilities V The result is a new representation for each token that reflects . its meaning in the context of the entire sequence At this point, it is worth mentioning an important concept: . context length Araka ny efa nolazainay teo aloha, ny transformers dia mandrindra ny andian-dahatsoratra manontolo amin'ny fotoana iray. . every token with every other token That means the computational cost grows Araka ny isan'ny token. quadratically Raha mihoatra ny roa heny ny habetsaky ny toe-javatra, ny habetsaky ny solosaina dia mitombo manodidina ny efatra. 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. Izany no antony mahatonga ny faharetan'ny kontekst dia toetra manan-danja amin'ny modely fiteny maoderina. In many modern AI systems, this limitation is addressed by adding an external memory mechanism. A common approach is to use a . vector database Ankoatra ny fametrahana ny fahalalana mivantana ao amin'ny modely, ny fampahalalana dia azo voatahiry ivelany ho toy ny vektor embeddings. When the model receives a question, the system can: Miverina amin'ny vektor ny fanontaniana. Search the vector database for related information. Ampidiro ny fampahalalana hita ao amin'ny kontekst ny modely. Izany dia midika fa ny modely dia mahita ny roa: Ny fanontaniana ary ny fahalalana manan-danja azo avy amin'ny database Because both appear in the context window, the model can generate an answer based on that information. Ity teknika ity dia fantatra amin'ny ary ampiasaina be dia be amin'ny rafitra AI maoderina sy agent. Retrieval-Augmented Generation (RAG) In this setup, the language model’s main role is not to store knowledge, but to generate coherent answers based on the information available in its context. But as we can see, this requires space in the context window, which is why context length remains so important. Returning to Karpathy’s implementation, the model uses , izay endrika fanatsarana ny rafitra fototra. multi-head attention Instead of computing attention using a single set of Q, K, and V matrices, the model uses multiple attention heads. In this implementation, there are four heads. Each head learns to focus on different kinds of relationships between tokens. For example, one head might focus on grammatical relationships, while another might capture longer-range dependencies. Ny fampiasana loha maromaro dia manatsara ny kalitaon'ny fampisehoana. Mba hitazonana ny vidin'ny fandaniana dia mitovy amin'ny mitovy, ny fahasamihafana amin'ny lohany tsirairay dia farafaharatsiny. Nandritra izany fotoana izany, dia nandefa vektor avy amin'ny a . 16-dimensional space to another 16-dimensional space Miaraka amin'ny lohany efatra, ny lohany tsirairay dia miasa amin'ny . The results from the heads are then combined back into a single vector. 4-dimensional space Na dia miasa amin'ny vektor ambany-dimensiona aza ny lohany tsirairay, ny vokatra mifandraika dia mahazatra kokoa sy marina kokoa noho ny fampiasana lohany iray. Amin'izao fotoana izao izay efa nanararaotra ny rafitra fisainana, aoka isika handeha amin'ny singa faharoa lehibe amin'ny tranom-pifamoivoizana: ny , or . MLP feed-forward neural network In the code, the MLP block looks something like this: # 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)] An MLP is 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: Mitombo amin'ny lanjany ny fidirana tsirairay, sums the results, Avy eo dia mampiasa ny fampiharana tsy ara-barotra ho an'ny famokarana ny vokatra. Ity modely ity dia nihevitra voalohany tamin'ny neurons ara-biolojika ao amin'ny atidoha olombelona. amin'izany fomba izany, ny tambajotra neuronal dia niantsoana teo amin'ny tantara amin'ny fanandramana ny fomba ahafahan'ny atidoha mandrindra fampahalalana. 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 , it becomes much harder to maintain the brain-inspired interpretation. attention Because of this, it is often better to think of modern AI systems simply as Fa tsy ny endriky ny atidoha. trainable mathematical functions Ny blôka MLP ao amin'ny code dia ahitana dingana telo lehibe: a (matrix multiplication), linear transformation Ny fonosam-pifamoivoizana tsy ara-dalàna (ReLU) dia Amin'ny alalan'ny endrika linear iray hafa. This may look simple, but structures like this have an extremely powerful mathematical property. Fantatra amin'ny maha . universal approximators universal approximators This means that, under certain conditions, a sufficiently large MLP can approximate to an arbitrary degree of accuracy. any mathematical function In principle, a single enormous MLP could learn almost anything. Izany no antony mahatonga ny famolavolana ny famolavolana mampifandray rafitra maro, anisan'izany ny fifantohana sy ny habetsaky ny habetsaky ny, mba hizara ny solosaina amin'ny fomba mahomby kokoa. The output of the network is not a single token, but a . probability distribution over all possible tokens In other words, for each token in the vocabulary, the model outputs the probability that it should appear next in the sequence. Nandritra ny famoronana, ny algorithm dia avy amin'io famoronana mety. Izany dia midika fa ny token amin'ny mety ho avo kokoa dia mety ho voafidy, fa mbola misy ny singa amin'ny fahafahana. This randomness is controlled by a parameter called . temperature The Ny parameter dia mamaritra ny fomba deterministika na famoronana ny vokatra amin'ny modely. temperature Ny hafanana ambany - ny modely dia mankafy ny token azo antoka indrindra, mamokatra valiny azo antoka sy marina kokoa. - the probability distribution becomes flatter, allowing less likely tokens to be selected more often, resulting in more diverse or creative outputs. High temperature Ohatra ny If we want the model to analyze a document and answer factual questions, a is usually preferable. low temperature If we want the model to generate creative text or explore new ideas, a can produce more interesting results. higher temperature This is roughly what I wanted to explain about this beautiful piece of code, and about GPT models in general. Amin'ny ankamaroan'ny toerana, ny fanazavana dia tsy maintsy mbola lavitra loatra. Ny tanjoko dia ny hahita fitoviana eo amin'ny zavatra roa: ahitana ny fahalalana mahasoa araka izay azo atao, raha mbola mitazona ny adihevitra ao anatin'ny sehatry ny lahatsoratra tokana. Ho an'ireo mpamaky izay nahita ny ampahany amin'ny fanazavana kely tsy mazava, na izay te-hikaroka bebe kokoa ny antsipirihany, manoro hevitra mafy aho Ary ny Ary . There, you will find excellent material explaining everything needed to fully understand the concepts discussed here. Ny tranonkala manokana an'i Andrej Karpathy YouTube channel Ny bilaoginy Manantena aho fa ity lahatsoratra ity dia mahasoa ho an'ny mpamaky maro. Raha tsy izany, angamba dia miantso anao hanadihady ny tontolo mahatalanjona amin'ny AI.