-
Notifications
You must be signed in to change notification settings - Fork 2
/
build.rs
312 lines (285 loc) · 11.1 KB
/
build.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
// Build script and bindings generation modified from https://github.com/rustformers/llama-rs
use std::{collections::HashSet, env, path::PathBuf};
const GGML_SOURCE_DIR: &str = "ggml-src";
const GGML_HEADER: &str = "ggml.h";
fn generate_bindings() {
let ggml_header_path = PathBuf::from(GGML_SOURCE_DIR).join(GGML_HEADER);
let librs_path = PathBuf::from("src").join("lib.rs");
let mut bbuilder = bindgen::Builder::default()
.derive_copy(true)
.derive_debug(true)
.derive_partialeq(true)
.derive_partialord(true)
.derive_eq(true)
.derive_ord(true)
.derive_hash(true)
.impl_debug(true)
.merge_extern_blocks(true)
.enable_function_attribute_detection()
.sort_semantically(true)
.header(ggml_header_path.to_string_lossy())
// Suppress some warnings
.raw_line("#![allow(non_upper_case_globals)]")
.raw_line("#![allow(non_camel_case_types)]")
.raw_line("#![allow(non_snake_case)]")
.raw_line("#![allow(unused)]")
.raw_line("pub const GGMLSYS_VERSION: Option<&str> = option_env!(\"CARGO_PKG_VERSION\");")
// Do not generate code for ggml's includes (stdlib)
.allowlist_file(ggml_header_path.to_string_lossy());
if cfg!(feature = "use_cmake") {
if cfg!(feature = "cublas") || cfg!(feature = "hipblas") {
let hfn = PathBuf::from(GGML_SOURCE_DIR).join("ggml-cuda.h");
let hfn = hfn.to_string_lossy();
bbuilder = bbuilder.header(hfn.clone()).allowlist_file(hfn);
}
if cfg!(feature = "clblast") {
let hfn = PathBuf::from(GGML_SOURCE_DIR).join("ggml-opencl.h");
let hfn = hfn.to_string_lossy();
bbuilder = bbuilder.header(hfn.clone()).allowlist_file(hfn);
}
if cfg!(feature = "metal") {
let hfn = PathBuf::from(GGML_SOURCE_DIR).join("ggml-metal.h");
let hfn = hfn.to_string_lossy();
bbuilder = bbuilder.header(hfn.clone()).allowlist_file(hfn);
}
if cfg!(feature = "llamacpp_api") {
let hfn = PathBuf::from(GGML_SOURCE_DIR).join("llama.h");
let hfn = hfn.to_string_lossy();
bbuilder = bbuilder
.header(hfn.clone())
.allowlist_file(hfn)
.clang_args(["-x", "c++", "-std=c++11"]);
}
}
let bindings = bbuilder.generate().expect("Unable to generate bindings");
bindings
.write_to_file(librs_path)
.expect("Couldn't write bindings");
}
fn main() {
// By default, this crate will attempt to compile ggml with the features of your host system if
// the host and target are the same. If they are not, it will turn off auto-feature-detection,
// and you will need to manually specify target features through target-features.
println!("cargo:rerun-if-changed=ggml-src");
// If running on docs.rs, the filesystem is readonly so we can't actually generate
// anything. This package should have been fetched with the bindings already generated
// so we just exit here.
if env::var("DOCS_RS").is_ok() {
return;
}
if cfg!(not(feature = "use_cmake")) {
return build_simple();
}
build_cmake();
}
fn build_cmake() {
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
generate_bindings();
// This silliness is necessary to get the cc crate to discover and
// spit out the necessary stuff to link with C++ (and CUDA if enabled).
let mut build = cc::Build::new();
build.cpp(true).file("dummy/dummy.c");
if cfg!(feature = "cublas") {
build.cuda(true);
} else if cfg!(feature = "hipblas") {
println!("cargo:rerun-if-changed=ROCM_PATH");
build.cpp(true);
}
build.compile("dummy");
let rocm_path = if cfg!(feature = "hipblas") {
Some(PathBuf::from(
env::var("ROCM_PATH").unwrap_or_else(|_| String::from("/opt/rocm")),
))
} else {
None
};
let mut cmbuild = cmake::Config::new("ggml-src");
cmbuild.build_target("ggml_static");
if cfg!(feature = "no_k_quants") {
cmbuild.define("LLAMA_K_QUANTS", "OFF");
}
if cfg!(feature = "cublas") {
cmbuild.define("LLAMA_CUBLAS", "ON");
} else if cfg!(feature = "hipblas") {
let rocm_path = rocm_path.as_ref().expect("Impossible: rocm_path not set!");
let rocm_llvm_path = rocm_path.join("llvm").join("bin");
cmbuild.define("LLAMA_HIPBLAS", "ON");
cmbuild.define("CMAKE_PREFIX_PATH", rocm_path);
cmbuild.define("CMAKE_C_COMPILER", rocm_llvm_path.join("clang"));
cmbuild.define("CMAKE_CXX_COMPILER", rocm_llvm_path.join("clang++"));
} else if cfg!(feature = "clblast") {
cmbuild.define("LLAMA_CLBLAST", "ON");
} else if cfg!(feature = "openblas") {
cmbuild.define("LLAMA_BLAS", "ON");
cmbuild.define("LLAMA_BLAS_VENDOR", "OpenBLAS");
}
if target_os == "macos" {
cmbuild.define(
"LLAMA_ACCELERATE",
if cfg!(feature = "no_accelerate") {
"OFF"
} else {
"ON"
},
);
cmbuild.define(
"LLAMA_METAL",
if cfg!(feature = "metal") { "ON" } else { "OFF" },
);
}
let dst = cmbuild.build();
if cfg!(feature = "cublas") {
println!("cargo:rustc-link-lib=cublas");
} else if cfg!(feature = "hipblas") {
let rocm_path = rocm_path.as_ref().expect("Impossible: rocm_path not set!");
println!(
"cargo:rustc-link-search={}",
rocm_path.join("lib").to_string_lossy()
);
println!("cargo:rustc-link-lib=hipblas");
println!("cargo:rustc-link-lib=amdhip64");
println!("cargo:rustc-link-lib=rocblas");
let mut build = cc::Build::new();
build.cpp(true).file("dummy/dummy.c").object(
PathBuf::from(env::var("OUT_DIR").expect("OUT_DIR not set!"))
.join("build")
.join("CMakeFiles")
.join("ggml-rocm.dir")
.join("ggml-cuda.cu.o"),
);
build.compile("dummy");
} else if cfg!(feature = "clblast") {
println!("cargo:rustc-link-lib=clblast");
println!(
"cargo:rustc-link-lib={}OpenCL",
if target_os == "macos" {
"framework="
} else {
""
}
);
} else if cfg!(feature = "openblas") {
println!("cargo:rustc-link-lib=openblas");
}
if target_os == "macos" {
if cfg!(not(feature = "no_accelerate")) {
println!("cargo:rustc-link-lib=framework=Accelerate");
}
if cfg!(feature = "metal") {
println!("cargo:rustc-link-lib=framework=Foundation");
println!("cargo:rustc-link-lib=framework=Metal");
println!("cargo:rustc-link-lib=framework=MetalKit");
println!("cargo:rustc-link-lib=framework=MetalPerformanceShaders");
}
}
println!("cargo:rustc-link-search=native={}/build", dst.display());
println!("cargo:rustc-link-lib=static=ggml_static");
}
fn build_simple() {
if cfg!(feature = "cublas") || cfg!(feature = "clblast") || cfg!(feature = "hipblas") {
panic!("Must build with feature use_cmake when enabling BLAS!");
}
generate_bindings();
let mut builder = cc::Build::new();
let build = builder
.files([
PathBuf::from(GGML_SOURCE_DIR).join("ggml.c"),
PathBuf::from(GGML_SOURCE_DIR).join("ggml-alloc.c"),
PathBuf::from(GGML_SOURCE_DIR).join("ggml-backend.c"),
#[cfg(not(feature = "no_k_quants"))]
PathBuf::from(GGML_SOURCE_DIR).join("ggml-quants.c"),
])
.include(PathBuf::from(GGML_SOURCE_DIR))
.include("include");
#[cfg(not(feature = "no_k_quants"))]
build.define("GGML_USE_K_QUANTS", None);
// This is a very basic heuristic for applying compile flags.
// Feel free to update this to fit your operating system.
let target_arch = env::var("CARGO_CFG_TARGET_ARCH").unwrap();
let target_os = env::var("CARGO_CFG_TARGET_OS").unwrap();
let is_release = env::var("PROFILE").unwrap() == "release";
let compiler = build.get_compiler();
match target_arch.as_str() {
"x86" | "x86_64" => {
let features = x86::Features::get();
if compiler.is_like_clang() || compiler.is_like_gnu() {
build.flag("-pthread");
features.iter().for_each(|feat| {
build.flag(&format!("-m{feat}"));
});
} else if compiler.is_like_msvc() {
if features.contains("avx2") {
build.flag("/arch:AVX2");
} else if features.contains("avx") {
build.flag("/arch:AVX");
}
}
}
"aarch64" => {
if compiler.is_like_clang() || compiler.is_like_gnu() {
if std::env::var("HOST") == std::env::var("TARGET") {
build.flag("-mcpu=native");
} else if &target_os == "macos" {
build.flag("-mcpu=apple-m1");
build.flag("-mfpu=neon");
}
build.flag("-pthread");
}
}
_ => (),
}
if &target_os == "macos" {
build.define("GGML_USE_ACCELERATE", None);
println!("cargo:rustc-link-lib=framework=Accelerate");
}
if is_release {
build.define("NDEBUG", None);
}
build.warnings(false);
build.compile(GGML_SOURCE_DIR);
}
fn get_supported_target_features() -> HashSet<String> {
env::var("CARGO_CFG_TARGET_FEATURE")
.unwrap()
.split(',')
.filter(|s| x86::RELEVANT_FLAGS.contains(s))
.map(ToString::to_string)
.collect::<HashSet<_>>()
}
mod x86 {
use super::HashSet;
pub const RELEVANT_FLAGS: &[&str] = &["fma", "avx", "avx2", "f16c", "sse3"];
pub struct Features(HashSet<String>);
impl std::ops::Deref for Features {
type Target = HashSet<String>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Features {
pub fn get() -> Self {
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
if std::env::var("HOST") == std::env::var("TARGET") {
return Self::get_host();
}
Self(super::get_supported_target_features())
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
pub fn get_host() -> Self {
Self(
[
std::is_x86_feature_detected!("fma"),
std::is_x86_feature_detected!("avx"),
std::is_x86_feature_detected!("avx2"),
std::is_x86_feature_detected!("f16c"),
std::is_x86_feature_detected!("sse3"),
]
.into_iter()
.enumerate()
.filter(|(_, exists)| *exists)
.map(|(idx, _)| RELEVANT_FLAGS[idx].to_string())
.collect::<HashSet<_>>(),
)
}
}
}