]> khamidou — GitHub mirrors - gpt2.git/commitdiff
wip main
authorKarim Hamidou <khamidou@gmail.com>
Thu, 21 Aug 2025 21:06:56 +0000 (14:06 -0700)
committerKarim Hamidou <khamidou@gmail.com>
Thu, 21 Aug 2025 21:06:56 +0000 (14:06 -0700)
main.swift

index 9bec5bd602fb02018024f198aecd5d5eaa99973b..6174f39786c8bdb0358ab69eee572ad4f062aea4 100644 (file)
 //
 // Let's jump into the actual code now.
 
-
 // ### The actual code
 import Foundation
 import Metal
@@ -239,34 +238,36 @@ func runLLMInALoop(tokens: [Int32]) -> Int32 {
     shape: [NSNumber(value: tokens.count), NSNumber(value: parsedManifest.config.nEmbd)],
     dataType: .float32)
 
-func loadWeights(
-  from manifest: Manifest,
-  at index: Int,
-  using weightsData: Data
-) -> MPSGraphTensorData {
-  guard manifest.tensors.indices.contains(index) else {
-    fatalError("Index out of bounds for tensors array")
-  }
+  // A utility function to create a tensor based on the data in the manifest.
+  // Don't come at me for defining a function within a function, this is just to make it clearer to the reader.
+  func loadWeights(from manifest: Manifest, at index: Int, using weightsData: Data) -> MPSGraphTensorData {
+    guard manifest.tensors.indices.contains(index) else {
+      fatalError("Index out of bounds for tensors array")
+    }
 
-  let tensorInfo = manifest.tensors[index]
-  let data = weightsData.subdata(
-    in: tensorInfo.byteOffset..<(tensorInfo.byteOffset + tensorInfo.nBytes))
-
-  return MPSGraphTensorData(
-    device: graphDevice,
-    data: data,
-    shape: tensorInfo.shape.map { NSNumber(value: $0) },
-    dataType: .float32
-  )
-}
+    let tensorInfo = manifest.tensors[index]
+    let data = weightsData.subdata(
+      in: tensorInfo.byteOffset..<(tensorInfo.byteOffset + tensorInfo.nBytes))
 
+    return MPSGraphTensorData(
+      device: graphDevice,
+      data: data,
+      shape: tensorInfo.shape.map { NSNumber(value: $0) },
 
+      // Note that we always use Float32s in this file. Float16s are faster but there's some operations that
+      // don't work on them, so for simplicity we use Float32s.
+      dataType: .float32
+    )
+  }
 
   // A transformer block includes a residual step – that means that we have to sometimes add the unaltered input
   // of the block back into the computed result. To do that we have to save the input to the block in this tensor.
   var residualTensorData: MPSGraphTensorData? = nil
 
   for (i, layer) in parsedManifest.tensors.enumerated() {
+    // ### Encoding the data
+    // The very first step of GPT-2 is to take the tokens and map them to vectors. These vectors represent
+    // the words in the context as well as the position of each word in the sentence.
     if layer.name == "transformer.wte.weight" {
       // Let's pass our input data to the embedding layer:
       // Create a tensor data object for the WTE weights