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

index 04d041018fb7ecb5438d15b21527c340d0e576d5..9bec5bd602fb02018024f198aecd5d5eaa99973b 100644 (file)
@@ -204,10 +204,11 @@ let encoderURL = URL(fileURLWithPath: "encoder.json")
 let bpeURL = URL(fileURLWithPath: "vocab.bpe")
 let tokenizer = try GPT2Tokenizer.load(encoderJSON: encoderURL, mergesTXT: bpeURL)
 
+// Convert our input text to tokens. This will be a list like `[15496, 616, 1438, 318]`
 var tokens = tokenizer.encode(textToEncode)
 
+// Now let's run the model in a loop and pass in the results back at every turn.
 while tokens.count < 20 {
-  // Run the LLM in a loop until we have enough tokens
   print("Current tokens: \(tokens.count), generating more...")
   let nextToken = runLLMInALoop(tokens: tokens)
   tokens.append(nextToken)
@@ -216,30 +217,56 @@ while tokens.count < 20 {
 }
 
 func runLLMInALoop(tokens: [Int32]) -> Int32 {
-  // Convert token IDs to Int32 for Metal Performance Shaders
+  // Without getting into too many details about Metal, there's a strict separation between
+  // GPU and CPU memory, even though they end up sharing the same RAM behind the scenes.
+  // This means we have to create GPU-specific buffers if we want to send data to the GPU.
   let tokensBuf = device.makeBuffer(
     bytes: tokens,
     length: tokens.count * MemoryLayout<Int32>.stride,
     options: [.storageModeShared])!
 
+  // MPSGraphTensorData is Metal Performance Shader's base data structure for tensor manipulation. It's basically
+  // an array of numbers with a data type (int32, float32, etc.) as well as a shape.
   let tokensTensorData = MPSGraphTensorData(
     tokensBuf,
     shape: [NSNumber(value: 1), NSNumber(value: tokens.count)],
     dataType: .int32)
 
-  // The tensor where we will accumulate data in.
+  // The tensor where we will accumulate data in at every step.
   var workingTensorData: MPSGraphTensorData = MPSGraphTensorData(
     device: graphDevice,
     data: Data(),
     shape: [NSNumber(value: tokens.count), NSNumber(value: parsedManifest.config.nEmbd)],
     dataType: .float32)
 
-  // In some cases we need to add residual connections.
+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
+  )
+}
+
+
+
+  // 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() {
-    //print("Processing layer \(i): \(layer.name)")
-
     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
@@ -797,27 +824,6 @@ func geluTanhApprox(_ x: MPSGraphTensor, _ graph: MPSGraph) -> MPSGraphTensor {
   return x.dataType == .float32 ? y32 : graph.cast(y32, to: x.dataType, name: "gelu_cast_out")
 }
 
-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
-  )
-}
-
 func peek(_ td: MPSGraphTensorData, label: String, max: Int = 8) {
   let nda = td.mpsndarray()
   let shape = (0..<nda.numberOfDimensions).map { Int(nda.length(ofDimension: $0)) }