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)
}
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
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)) }