Skip to content

Commit 30dfb49

Browse files
Merge branch 'ggml-org:master' into master
2 parents 55d0db0 + 8ac9f5d commit 30dfb49

31 files changed

+1428
-701
lines changed

.github/workflows/docker.yml

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,13 +36,13 @@ jobs:
3636
matrix:
3737
config:
3838
# Multi-stage build
39-
- { tag: "cpu", dockerfile: ".devops/cpu.Dockerfile", platforms: "linux/amd64,linux/arm64", full: true, light: true, server: true, freediskspace: false}
40-
- { tag: "cuda", dockerfile: ".devops/cuda.Dockerfile", platforms: "linux/amd64", full: true, light: true, server: true, freediskspace: false}
41-
- { tag: "musa", dockerfile: ".devops/musa.Dockerfile", platforms: "linux/amd64", full: true, light: true, server: true, freediskspace: true}
42-
- { tag: "intel", dockerfile: ".devops/intel.Dockerfile", platforms: "linux/amd64", full: true, light: true, server: true, freediskspace: false}
43-
- { tag: "vulkan", dockerfile: ".devops/vulkan.Dockerfile", platforms: "linux/amd64", full: true, light: true, server: true, freediskspace: false}
39+
- { tag: "cpu", dockerfile: ".devops/cpu.Dockerfile", platforms: "linux/amd64,linux/arm64", full: true, light: true, server: true, free_disk_space: false }
40+
- { tag: "cuda", dockerfile: ".devops/cuda.Dockerfile", platforms: "linux/amd64", full: true, light: true, server: true, free_disk_space: false }
41+
- { tag: "musa", dockerfile: ".devops/musa.Dockerfile", platforms: "linux/amd64", full: true, light: true, server: true, free_disk_space: true }
42+
- { tag: "intel", dockerfile: ".devops/intel.Dockerfile", platforms: "linux/amd64", full: true, light: true, server: true, free_disk_space: false }
43+
- { tag: "vulkan", dockerfile: ".devops/vulkan.Dockerfile", platforms: "linux/amd64", full: true, light: true, server: true, free_disk_space: false }
4444
# Note: the rocm images are failing due to a compiler error and are disabled until this is fixed to allow the workflow to complete
45-
#- {tag: "rocm", dockerfile: ".devops/rocm.Dockerfile", platforms: "linux/amd64,linux/arm64", full: true, light: true, server: true, freediskspace: true }
45+
#- {tag: "rocm", dockerfile: ".devops/rocm.Dockerfile", platforms: "linux/amd64,linux/arm64", full: true, light: true, server: true, free_disk_space: true }
4646
steps:
4747
- name: Check out the repo
4848
uses: actions/checkout@v4

build-xcframework.sh

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,11 @@ COMMON_CMAKE_ARGS=(
4141
-DGGML_OPENMP=${GGML_OPENMP}
4242
)
4343

44+
XCODE_VERSION=$(xcodebuild -version 2>/dev/null | head -n1 | awk '{ print $2 }')
45+
MAJOR_VERSION=$(echo $XCODE_VERSION | cut -d. -f1)
46+
MINOR_VERSION=$(echo $XCODE_VERSION | cut -d. -f2)
47+
echo "Detected Xcode version: $XCODE_VERSION"
48+
4449
check_required_tool() {
4550
local tool=$1
4651
local install_message=$2
@@ -325,21 +330,28 @@ combine_static_libraries() {
325330

326331
# Platform-specific post-processing for device builds
327332
if [[ "$is_simulator" == "false" ]]; then
328-
if command -v vtool &>/dev/null; then
333+
if command -v xcrun vtool &>/dev/null; then
329334
case "$platform" in
330335
"ios")
331336
echo "Marking binary as a framework binary for iOS..."
332-
vtool -set-build-version ios ${IOS_MIN_OS_VERSION} ${IOS_MIN_OS_VERSION} -replace \
337+
xcrun vtool -set-build-version ios ${IOS_MIN_OS_VERSION} ${IOS_MIN_OS_VERSION} -replace \
333338
-output "${base_dir}/${output_lib}" "${base_dir}/${output_lib}"
334339
;;
335340
"visionos")
336341
echo "Marking binary as a framework binary for visionOS..."
337-
vtool -set-build-version xros ${VISIONOS_MIN_OS_VERSION} ${VISIONOS_MIN_OS_VERSION} -replace \
342+
if [[ "$MAJOR_VERSION" -gt 16 ]] || [[ "$MAJOR_VERSION" -eq 16 && "$MINOR_VERSION" -gt 2 ]]; then
343+
echo "Xcode version greater than 16.2, using visionOS."
344+
VISION_OS_BUILD_VERSION="visionos"
345+
else
346+
echo "Xcode version less than or equal to 16.2, using xros."
347+
VISION_OS_BUILD_VERSION="xros"
348+
fi
349+
xcrun vtool -set-build-version ${VISION_OS_BUILD_VERSION} ${VISIONOS_MIN_OS_VERSION} ${VISIONOS_MIN_OS_VERSION} -replace \
338350
-output "${base_dir}/${output_lib}" "${base_dir}/${output_lib}"
339351
;;
340352
"tvos")
341353
echo "Marking binary as a framework binary for tvOS..."
342-
vtool -set-build-version tvos ${TVOS_MIN_OS_VERSION} ${TVOS_MIN_OS_VERSION} -replace \
354+
xcrun vtool -set-build-version tvos ${TVOS_MIN_OS_VERSION} ${TVOS_MIN_OS_VERSION} -replace \
343355
-output "${base_dir}/${output_lib}" "${base_dir}/${output_lib}"
344356
;;
345357
esac

convert_hf_to_gguf.py

Lines changed: 49 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@ class Model:
6565
model_name: str | None
6666
metadata_override: Path | None
6767
dir_model_card: Path
68+
remote_hf_model_id: str | None
6869

6970
# subclasses should define this!
7071
model_arch: gguf.MODEL_ARCH
@@ -73,7 +74,7 @@ def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, fname_out: Path,
7374
use_temp_file: bool = False, eager: bool = False,
7475
metadata_override: Path | None = None, model_name: str | None = None,
7576
split_max_tensors: int = 0, split_max_size: int = 0, dry_run: bool = False,
76-
small_first_shard: bool = False, hparams: dict[str, Any] | None = None):
77+
small_first_shard: bool = False, hparams: dict[str, Any] | None = None, remote_hf_model_id: str | None = None):
7778
if type(self) is Model:
7879
raise TypeError(f"{type(self).__name__!r} should not be directly instantiated")
7980

@@ -83,11 +84,24 @@ def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, fname_out: Path,
8384
self.is_big_endian = is_big_endian
8485
self.endianess = gguf.GGUFEndian.BIG if is_big_endian else gguf.GGUFEndian.LITTLE
8586
self.use_temp_file = use_temp_file
86-
self.lazy = not eager
87-
self.part_names = Model.get_model_part_names(self.dir_model, "model", ".safetensors")
88-
self.is_safetensors = len(self.part_names) > 0
89-
if not self.is_safetensors:
90-
self.part_names = Model.get_model_part_names(self.dir_model, "pytorch_model", ".bin")
87+
self.lazy = not eager or (remote_hf_model_id is not None)
88+
self.remote_hf_model_id = remote_hf_model_id
89+
if remote_hf_model_id is not None:
90+
self.is_safetensors = True
91+
92+
def get_remote_tensors() -> Iterator[tuple[str, Tensor]]:
93+
logger.info(f"Using remote model with HuggingFace id: {remote_hf_model_id}")
94+
remote_tensors = gguf.utility.SafetensorRemote.get_list_tensors_hf_model(remote_hf_model_id)
95+
self.tensor_names = set(name for name in remote_tensors.keys())
96+
for name, remote_tensor in gguf.utility.SafetensorRemote.get_list_tensors_hf_model(remote_hf_model_id).items():
97+
yield (name, LazyTorchTensor.from_remote_tensor(remote_tensor))
98+
99+
self.get_tensors = get_remote_tensors
100+
else:
101+
self.part_names = Model.get_model_part_names(self.dir_model, "model", ".safetensors")
102+
self.is_safetensors = len(self.part_names) > 0
103+
if not self.is_safetensors:
104+
self.part_names = Model.get_model_part_names(self.dir_model, "pytorch_model", ".bin")
91105
self.hparams = Model.load_hparams(self.dir_model) if hparams is None else hparams
92106
self.block_count = self.find_hparam(["n_layers", "num_hidden_layers", "n_layer", "num_layers"])
93107
self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
@@ -393,6 +407,10 @@ def prepare_metadata(self, vocab_only: bool):
393407

394408
self.metadata = gguf.Metadata.load(self.metadata_override, self.dir_model_card, self.model_name, total_params)
395409

410+
# If we are using HF model id, set the metadata name to the model id
411+
if self.remote_hf_model_id:
412+
self.metadata.name = self.remote_hf_model_id
413+
396414
# Fallback to model directory name if metadata name is still missing
397415
if self.metadata.name is None:
398416
self.metadata.name = self.dir_model.name
@@ -1788,10 +1806,6 @@ def set_gguf_parameters(self):
17881806
self.gguf_writer.add_expert_feed_forward_length(self.hparams["intermediate_size_moe"])
17891807

17901808
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None):
1791-
name = name.replace("language_model.", "")
1792-
name = name.replace("feed_forward.", "mlp.") # a bit hacky for now
1793-
name = name.replace(".router.weight", ".gate.weight") # a bit hacky for now
1794-
17951809
# split the gate_up into gate and up
17961810
if "gate_up_proj" in name:
17971811
name_up = name.replace("gate_up_proj", "up_proj.weight")
@@ -5403,6 +5417,14 @@ def from_safetensors_slice(cls, st_slice: Any) -> Tensor:
54035417
lazy = cls(meta=cls.meta_with_dtype_and_shape(dtype, shape), args=(st_slice,), func=lambda s: s[:])
54045418
return cast(torch.Tensor, lazy)
54055419

5420+
@classmethod
5421+
def from_remote_tensor(cls, remote_tensor: gguf.utility.RemoteTensor):
5422+
dtype = cls._dtype_str_map[remote_tensor.dtype]
5423+
shape = remote_tensor.shape
5424+
meta = cls.meta_with_dtype_and_shape(dtype, shape)
5425+
lazy = cls(meta=meta, args=(remote_tensor,), func=lambda r: torch.frombuffer(r.data(), dtype=dtype).reshape(shape))
5426+
return cast(torch.Tensor, lazy)
5427+
54065428
@classmethod
54075429
def __torch_function__(cls, func, types, args=(), kwargs=None):
54085430
del types # unused
@@ -5480,6 +5502,10 @@ def parse_args() -> argparse.Namespace:
54805502
"--print-supported-models", action="store_true",
54815503
help="Print the supported models"
54825504
)
5505+
parser.add_argument(
5506+
"--remote", action="store_true",
5507+
help="(Experimental) Read safetensors file remotely without downloading to disk. Config and tokenizer files will still be downloaded. To use this feature, you need to specify Hugging Face model repo name instead of a local directory. For example: 'HuggingFaceTB/SmolLM2-1.7B-Instruct'. Note: To access gated repo, set HF_TOKEN environment variable to your Hugging Face token.",
5508+
)
54835509

54845510
args = parser.parse_args()
54855511
if not args.print_supported_models and args.model is None:
@@ -5520,6 +5546,14 @@ def main() -> None:
55205546

55215547
dir_model = args.model
55225548

5549+
if args.remote:
5550+
from huggingface_hub import snapshot_download
5551+
local_dir = snapshot_download(
5552+
repo_id=str(dir_model),
5553+
allow_patterns=["LICENSE", "*.json", "*.md", "*.txt", "tokenizer.model"])
5554+
dir_model = Path(local_dir)
5555+
logger.info(f"Downloaded config and tokenizer to {local_dir}")
5556+
55235557
if not dir_model.is_dir():
55245558
logger.error(f'Error: {args.model} is not a directory')
55255559
sys.exit(1)
@@ -5541,6 +5575,9 @@ def main() -> None:
55415575

55425576
if args.outfile is not None:
55435577
fname_out = args.outfile
5578+
elif args.remote:
5579+
# if remote, use the model ID as the output file name
5580+
fname_out = Path("./" + str(args.model).replace("/", "-") + "-{ftype}.gguf")
55445581
else:
55455582
fname_out = dir_model
55465583

@@ -5564,7 +5601,8 @@ def main() -> None:
55645601
metadata_override=args.metadata, model_name=args.model_name,
55655602
split_max_tensors=args.split_max_tensors,
55665603
split_max_size=split_str_to_n_bytes(args.split_max_size), dry_run=args.dry_run,
5567-
small_first_shard=args.no_tensor_first_split)
5604+
small_first_shard=args.no_tensor_first_split,
5605+
remote_hf_model_id=str(args.model) if args.remote else None)
55685606

55695607
if args.vocab_only:
55705608
logger.info("Exporting model vocab...")

examples/llava/CMakeLists.txt

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
# llava (legacy)
2+
13
add_library(llava OBJECT
24
llava.cpp
35
llava.h
@@ -22,12 +24,41 @@ if (BUILD_SHARED_LIBS)
2224
install(TARGETS llava_shared LIBRARY)
2325
endif()
2426

27+
# mtmd
28+
29+
add_library(mtmd OBJECT
30+
mtmd.cpp
31+
mtmd.h
32+
clip.cpp
33+
clip.h
34+
clip-impl.h
35+
)
36+
37+
target_link_libraries(mtmd PRIVATE ggml llama ${CMAKE_THREAD_LIBS_INIT})
38+
39+
target_include_directories(mtmd PUBLIC .)
40+
target_include_directories(mtmd PRIVATE ../..)
41+
target_include_directories(mtmd PRIVATE ../../common) # for stb_image.h
42+
43+
target_compile_features(mtmd PRIVATE cxx_std_17)
44+
45+
add_library(mtmd_static STATIC $<TARGET_OBJECTS:mtmd>)
46+
if (BUILD_SHARED_LIBS)
47+
set_target_properties(mtmd PROPERTIES POSITION_INDEPENDENT_CODE ON)
48+
target_compile_definitions(mtmd PRIVATE LLAMA_SHARED LLAMA_BUILD)
49+
add_library(mtmd_shared SHARED $<TARGET_OBJECTS:mtmd>)
50+
target_link_libraries(mtmd_shared PRIVATE ggml llama ${CMAKE_THREAD_LIBS_INIT})
51+
install(TARGETS mtmd_shared LIBRARY)
52+
endif()
53+
2554
if (NOT MSVC)
2655
target_compile_options(llava PRIVATE -Wno-cast-qual) # stb_image.h
56+
target_compile_options(mtmd PRIVATE -Wno-cast-qual) # stb_image.h
2757
endif()
2858

2959
if(TARGET BUILD_INFO)
3060
add_dependencies(llava BUILD_INFO)
61+
add_dependencies(mtmd BUILD_INFO)
3162
endif()
3263

3364
set(TARGET llama-llava-cli)
@@ -55,7 +86,7 @@ set(TARGET llama-gemma3-cli)
5586
add_executable(${TARGET} gemma3-cli.cpp)
5687
set_target_properties(${TARGET} PROPERTIES OUTPUT_NAME llama-gemma3-cli)
5788
install(TARGETS ${TARGET} RUNTIME)
58-
target_link_libraries(${TARGET} PRIVATE common llava ${CMAKE_THREAD_LIBS_INIT})
89+
target_link_libraries(${TARGET} PRIVATE common mtmd ${CMAKE_THREAD_LIBS_INIT})
5990
target_compile_features(${TARGET} PRIVATE cxx_std_17)
6091

6192
set(TARGET llama-llava-clip-quantize-cli)

examples/llava/clip-impl.h

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,15 @@
11
#include "ggml.h"
22
#include "gguf.h"
33

4+
#include "clip.h"
5+
46
#include <climits>
57
#include <cstdarg>
68
#include <string>
79
#include <map>
810
#include <sstream>
911
#include <vector>
12+
#include <memory>
1013

1114
// Internal header for clip.cpp
1215

@@ -120,6 +123,23 @@ static projector_type clip_projector_type_from_string(const std::string & str) {
120123
return PROJECTOR_TYPE_UNKNOWN;
121124
}
122125

126+
// RGB uint8 image
127+
struct clip_image_u8 {
128+
int nx;
129+
int ny;
130+
131+
std::vector<uint8_t> buf;
132+
};
133+
134+
// RGB float32 image (NHWC)
135+
// Memory layout: RGBRGBRGB...
136+
struct clip_image_f32 {
137+
int nx;
138+
int ny;
139+
140+
std::vector<float> buf;
141+
};
142+
123143
//
124144
// logging
125145
//
@@ -178,6 +198,28 @@ static void clip_log_internal(enum ggml_log_level level, const char * format, ..
178198
#define LOG_DBG(...) LOG_TMPL(GGML_LOG_LEVEL_DEBUG, __VA_ARGS__)
179199
#define LOG_CNT(...) LOG_TMPL(GGML_LOG_LEVEL_CONT, __VA_ARGS__)
180200

201+
//
202+
// cpp wrappers
203+
//
204+
205+
struct clip_image_u8_deleter {
206+
void operator()(clip_image_u8 * val) { clip_image_u8_free(val); }
207+
};
208+
209+
struct clip_image_f32_deleter {
210+
void operator()(clip_image_f32 * val) { clip_image_f32_free(val); }
211+
};
212+
213+
struct clip_image_f32_batch_deleter {
214+
void operator()(clip_image_f32_batch * val) { clip_image_f32_batch_free(val); }
215+
};
216+
217+
typedef std::unique_ptr<clip_image_u8, clip_image_u8_deleter> clip_image_u8_ptr;
218+
typedef std::unique_ptr<clip_image_f32, clip_image_f32_deleter> clip_image_f32_ptr;
219+
typedef std::unique_ptr<clip_image_f32_batch, clip_image_f32_batch_deleter> clip_image_f32_batch_ptr;
220+
221+
// TODO @ngxson : we're currently having a naming clash between struct clip_image_size and function clip_image_size()
222+
181223
//
182224
// common utils
183225
//
@@ -214,6 +256,20 @@ static void string_replace_all(std::string & s, const std::string & search, cons
214256
s = std::move(builder);
215257
}
216258

259+
// split string by a `std::string delim` instead of `char delim`
260+
static std::vector<std::string> string_split_str(std::string s, const std::string & delimiter) {
261+
std::vector<std::string> tokens;
262+
size_t pos = 0;
263+
std::string token;
264+
while ((pos = s.find(delimiter)) != std::string::npos) {
265+
token = s.substr(0, pos);
266+
tokens.push_back(token);
267+
s.erase(0, pos + delimiter.length());
268+
}
269+
tokens.push_back(s);
270+
return tokens;
271+
}
272+
217273
//
218274
// gguf utils
219275
//
@@ -271,3 +327,9 @@ static std::string gguf_kv_to_str(const struct gguf_context * ctx_gguf, int i) {
271327
return gguf_data_to_str(type, gguf_get_val_data(ctx_gguf, i), 0);
272328
}
273329
}
330+
331+
//
332+
// API used internally with mtmd
333+
//
334+
335+
projector_type clip_get_projector_type(const struct clip_ctx * ctx);

0 commit comments

Comments
 (0)