Skip to content

Commit f2b7b28

Browse files
committed
Metal support for Swift
1 parent 6a31a3b commit f2b7b28

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

Package.swift

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,23 +4,27 @@ import PackageDescription
44

55
let package = Package(
66
name: "llama",
7+
platforms: [.macOS(.v11)],
78
products: [
89
.library(name: "llama", targets: ["llama"]),
910
],
1011
targets: [
1112
.target(
1213
name: "llama",
1314
path: ".",
14-
exclude: ["ggml-metal.metal"],
1515
sources: [
1616
"ggml.c",
1717
"llama.cpp",
1818
"ggml-alloc.c",
19-
"k_quants.c"
19+
"k_quants.c",
20+
"ggml-metal.m",
2021
],
2122
publicHeadersPath: "spm-headers",
2223
cSettings: [
2324
.unsafeFlags(["-Wno-shorten-64-to-32"]),
25+
.unsafeFlags(["-fno-objc-arc"]),
26+
.define("GGML_SWIFT"),
27+
.define("GGML_USE_METAL"),
2428
.define("GGML_USE_K_QUANTS"),
2529
.define("GGML_USE_ACCELERATE")
2630
],

ggml-metal.m

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -140,12 +140,22 @@ @implementation GGMLMetalClass
140140

141141
ctx->d_queue = dispatch_queue_create("llama.cpp", DISPATCH_QUEUE_CONCURRENT);
142142

143-
#if 0
144-
// compile from source string and show compile log
143+
MTLCompileOptions* options = [MTLCompileOptions new];
144+
options.preprocessorMacros = @{ @"QK_K" : @(64) };
145+
146+
#ifdef GGML_SWIFT
147+
// load the default.metallib file
145148
{
146149
NSError * error = nil;
147150

148-
ctx->library = [ctx->device newLibraryWithSource:msl_library_source options:nil error:&error];
151+
NSBundle * bundle = [NSBundle bundleForClass:[GGMLMetalClass class]];
152+
NSString * llamaBundlePath = [bundle pathForResource:@"llama_llama" ofType:@"bundle"];
153+
NSBundle * llamaBundle = [NSBundle bundleWithPath:llamaBundlePath];
154+
NSString * libPath = [llamaBundle pathForResource:@"default" ofType:@"metallib"];
155+
156+
// Load the metallib file into a Metal library
157+
ctx->library = [ctx->device newLibraryWithFile:libPath error:&error];
158+
149159
if (error) {
150160
metal_printf("%s: error: %s\n", __func__, [[error description] UTF8String]);
151161
return NULL;
@@ -170,8 +180,6 @@ @implementation GGMLMetalClass
170180
}
171181

172182
#ifdef GGML_QKK_64
173-
MTLCompileOptions* options = [MTLCompileOptions new];
174-
options.preprocessorMacros = @{ @"QK_K" : @(64) };
175183
ctx->library = [ctx->device newLibraryWithSource:src options:options error:&error];
176184
#else
177185
ctx->library = [ctx->device newLibraryWithSource:src options:nil error:&error];

0 commit comments

Comments
 (0)