Skip to content

Commit 1e67578

Browse files
committed
Merge branch 'master' into llamacli-tools
2 parents ff18e24 + cf2270e commit 1e67578

File tree

94 files changed

+16030
-12582
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

94 files changed

+16030
-12582
lines changed

.github/workflows/build.yml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -774,7 +774,7 @@ jobs:
774774
env:
775775
OPENBLAS_VERSION: 0.3.23
776776
SDE_VERSION: 9.33.0-2024-01-07
777-
VULKAN_VERSION: 1.3.261.1
777+
VULKAN_VERSION: 1.4.304.1
778778

779779
strategy:
780780
matrix:
@@ -1379,7 +1379,7 @@ jobs:
13791379
id: pack_artifacts
13801380
if: ${{ ( github.event_name == 'push' && github.ref == 'refs/heads/master' ) || github.event.inputs.create_release == 'true' }}
13811381
run: |
1382-
zip -r llama-${{ steps.tag.outputs.name }}-xcframework.zip build-apple/llama.xcframework
1382+
zip --symlinks -r llama-${{ steps.tag.outputs.name }}-xcframework.zip build-apple/llama.xcframework
13831383
13841384
- name: Upload artifacts
13851385
if: ${{ ( github.event_name == 'push' && github.ref == 'refs/heads/master' ) || github.event.inputs.create_release == 'true' }}

CMakeLists.txt

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ else()
2929
set(LLAMA_STANDALONE OFF)
3030
endif()
3131

32+
option(LLAMA_USE_SYSTEM_GGML "Use system libggml" OFF)
33+
3234
if (EMSCRIPTEN)
3335
set(BUILD_SHARED_LIBS_DEFAULT OFF)
3436

@@ -148,7 +150,13 @@ endif()
148150
# 3rd-party
149151
#
150152

151-
if (NOT TARGET ggml)
153+
if (LLAMA_USE_SYSTEM_GGML)
154+
message(STATUS "Using system-provided libggml, skipping ggml build")
155+
find_package(ggml REQUIRED)
156+
add_library(ggml ALIAS ggml::ggml)
157+
endif()
158+
159+
if (NOT TARGET ggml AND NOT LLAMA_USE_SYSTEM_GGML)
152160
add_subdirectory(ggml)
153161
# ... otherwise assume ggml is added by a parent CMakeLists.txt
154162
endif()

Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -836,7 +836,7 @@ ifdef GGML_MUSA
836836
else
837837
MUSA_PATH ?= /opt/musa
838838
endif
839-
MUSA_ARCHITECTURES ?= 21;22
839+
MUSA_ARCHITECTURES ?= 21;22;31
840840

841841
MK_CPPFLAGS += -DGGML_USE_MUSA -DGGML_USE_CUDA
842842
MK_LDFLAGS += -L$(MUSA_PATH)/lib -Wl,-rpath=$(MUSA_PATH)/lib

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,7 @@ Instructions for adding support for new models: [HOWTO-add-model.md](docs/develo
172172
- [eva](https://github.com/ylsdamxssjxxdd/eva) (MIT)
173173
- [iohub/collama](https://github.com/iohub/coLLaMA) (Apache-2.0)
174174
- [janhq/jan](https://github.com/janhq/jan) (AGPL)
175+
- [johnbean393/Sidekick](https://github.com/johnbean393/Sidekick) (MIT)
175176
- [KanTV](https://github.com/zhouwg/kantv?tab=readme-ov-file) (Apache-2.0)
176177
- [KodiBot](https://github.com/firatkiral/kodibot) (GPL)
177178
- [llama.vim](https://github.com/ggml-org/llama.vim) (MIT)

cmake/common.cmake

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
include("ggml/cmake/common.cmake")
2+
13
function(llama_add_compile_flags)
24
if (LLAMA_FATAL_WARNINGS)
35
if (CMAKE_CXX_COMPILER_ID MATCHES "GNU" OR CMAKE_CXX_COMPILER_ID MATCHES "Clang")

common/arg.cpp

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -764,7 +764,11 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
764764
).set_env("LLAMA_ARG_CTX_SIZE"));
765765
add_opt(common_arg(
766766
{"-n", "--predict", "--n-predict"}, "N",
767-
string_format("number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)", params.n_predict),
767+
string_format(
768+
ex == LLAMA_EXAMPLE_MAIN || ex == LLAMA_EXAMPLE_INFILL
769+
? "number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)"
770+
: "number of tokens to predict (default: %d, -1 = infinity)",
771+
params.n_predict),
768772
[](common_params & params, int value) {
769773
params.n_predict = value;
770774
}
@@ -849,6 +853,20 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
849853
}
850854
}
851855
).set_excludes({LLAMA_EXAMPLE_SERVER}));
856+
add_opt(common_arg(
857+
{"-sysf", "--system-prompt-file"}, "FNAME",
858+
"a file containing the system prompt (default: none)",
859+
[](common_params & params, const std::string & value) {
860+
std::ifstream file(value);
861+
if (!file) {
862+
throw std::runtime_error(string_format("error: failed to open file '%s'\n", value.c_str()));
863+
}
864+
std::copy(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>(), back_inserter(params.system_prompt));
865+
if (!params.system_prompt.empty() && params.system_prompt.back() == '\n') {
866+
params.system_prompt.pop_back();
867+
}
868+
}
869+
).set_examples({LLAMA_EXAMPLE_MAIN}));
852870
add_opt(common_arg(
853871
{"--in-file"}, "FNAME",
854872
"an input file (repeat to specify multiple files)",
@@ -1871,7 +1889,7 @@ common_params_context common_params_parser_init(common_params & params, llama_ex
18711889
[](common_params & params, const std::string & value) {
18721890
params.out_file = value;
18731891
}
1874-
).set_examples({LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_CVECTOR_GENERATOR, LLAMA_EXAMPLE_EXPORT_LORA}));
1892+
).set_examples({LLAMA_EXAMPLE_IMATRIX, LLAMA_EXAMPLE_CVECTOR_GENERATOR, LLAMA_EXAMPLE_EXPORT_LORA, LLAMA_EXAMPLE_TTS}));
18751893
add_opt(common_arg(
18761894
{"-ofreq", "--output-frequency"}, "N",
18771895
string_format("output the imatrix every N iterations (default: %d)", params.n_out_freq),

common/common.cpp

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -956,8 +956,8 @@ struct common_init_result common_init_from_params(common_params & params) {
956956
return iparams;
957957
}
958958

959-
if (params.ctx_shift && !llama_kv_cache_can_shift(lctx)) {
960-
LOG_WRN("%s: KV cache shifting is not supported for this model, disabling KV cache shifting\n", __func__);
959+
if (params.ctx_shift && !llama_kv_self_can_shift(lctx)) {
960+
LOG_WRN("%s: KV cache shifting is not supported for this context, disabling KV cache shifting\n", __func__);
961961
params.ctx_shift = false;
962962
}
963963

@@ -1034,6 +1034,8 @@ struct common_init_result common_init_from_params(common_params & params) {
10341034
if (params.warmup) {
10351035
LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
10361036

1037+
llama_set_warmup(lctx, true);
1038+
10371039
std::vector<llama_token> tmp;
10381040
llama_token bos = llama_vocab_bos(vocab);
10391041
llama_token eos = llama_vocab_eos(vocab);
@@ -1061,9 +1063,10 @@ struct common_init_result common_init_from_params(common_params & params) {
10611063
if (llama_model_has_decoder(model)) {
10621064
llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch)));
10631065
}
1064-
llama_kv_cache_clear(lctx);
1066+
llama_kv_self_clear(lctx);
10651067
llama_synchronize(lctx);
10661068
llama_perf_context_reset(lctx);
1069+
llama_set_warmup(lctx, false);
10671070
}
10681071

10691072
iparams.model.reset(model);

common/speculative.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ llama_tokens common_speculative_gen_draft(
173173
result.reserve(params.n_draft);
174174

175175
if (reuse_n == 0) {
176-
llama_kv_cache_clear(ctx);
176+
llama_kv_self_clear(ctx);
177177

178178
prompt.clear();
179179
} else {
@@ -192,14 +192,14 @@ llama_tokens common_speculative_gen_draft(
192192
}
193193

194194
if (reuse_i > 0) {
195-
llama_kv_cache_seq_rm (ctx, 0, 0, reuse_i);
196-
llama_kv_cache_seq_add(ctx, 0, reuse_i, -1, -reuse_i);
195+
llama_kv_self_seq_rm (ctx, 0, 0, reuse_i);
196+
llama_kv_self_seq_add(ctx, 0, reuse_i, -1, -reuse_i);
197197

198198
prompt.erase(prompt.begin(), prompt.begin() + reuse_i);
199199
}
200200

201201
if (reuse_n < (int) prompt.size()) {
202-
llama_kv_cache_seq_rm (ctx, 0, reuse_n, -1);
202+
llama_kv_self_seq_rm (ctx, 0, reuse_n, -1);
203203

204204
prompt.erase(prompt.begin() + reuse_n, prompt.end());
205205
}

convert_hf_to_gguf.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -861,6 +861,9 @@ def _create_vocab_sentencepiece(self):
861861
for token_id, token_data in added_tokens_decoder.items():
862862
token_id = int(token_id)
863863
token: str = token_data["content"]
864+
if token_id >= vocab_size:
865+
logger.warning(f'ignore token {token_id}: id is out of range, max={vocab_size - 1}')
866+
continue
864867
if toktypes[token_id] != SentencePieceTokenTypes.UNUSED:
865868
if tokens[token_id] != token.encode("utf-8"):
866869
logger.warning(f'replacing token {token_id}: {tokens[token_id].decode("utf-8")!r} -> {token!r}')
@@ -3322,6 +3325,83 @@ def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iter
33223325
return [(self.map_tensor_name(name), data_torch)]
33233326

33243327

3328+
@Model.register("Gemma3ForCausalLM", "Gemma3ForConditionalGeneration")
3329+
class Gemma3Model(Model):
3330+
model_arch = gguf.MODEL_ARCH.GEMMA3
3331+
has_vision: bool = False
3332+
3333+
# we need to merge the text_config into the root level of hparams
3334+
def __init__(self, *args, **kwargs):
3335+
hparams = Model.load_hparams(kwargs["dir_model"])
3336+
if "text_config" in hparams:
3337+
hparams = {**hparams, **hparams["text_config"]}
3338+
kwargs["hparams"] = hparams
3339+
super().__init__(*args, **kwargs)
3340+
if "vision_config" in hparams:
3341+
logger.info("Has vision encoder, but it will be ignored")
3342+
self.has_vision = True
3343+
3344+
def write(self):
3345+
super().write()
3346+
if self.has_vision:
3347+
logger.info("NOTE: this script only convert the language model to GGUF")
3348+
logger.info(" for the vision model, please use gemma3_convert_encoder_to_gguf.py")
3349+
3350+
def set_vocab(self):
3351+
self._set_vocab_sentencepiece()
3352+
3353+
self.gguf_writer.add_add_space_prefix(False)
3354+
3355+
def set_gguf_parameters(self):
3356+
hparams = self.hparams
3357+
block_count = hparams["num_hidden_layers"]
3358+
3359+
# some default values are not specified in the hparams
3360+
self.gguf_writer.add_context_length(hparams.get("max_position_embeddings", 131072))
3361+
self.gguf_writer.add_embedding_length(hparams["hidden_size"])
3362+
self.gguf_writer.add_block_count(block_count)
3363+
self.gguf_writer.add_feed_forward_length(hparams["intermediate_size"])
3364+
self.gguf_writer.add_head_count(hparams.get("num_attention_heads", 8))
3365+
self.gguf_writer.add_layer_norm_rms_eps(self.hparams.get("rms_norm_eps", 1e-6))
3366+
self.gguf_writer.add_key_length(hparams.get("head_dim", 256))
3367+
self.gguf_writer.add_value_length(hparams.get("head_dim", 256))
3368+
self.gguf_writer.add_file_type(self.ftype)
3369+
self.gguf_writer.add_rope_freq_base(hparams.get("rope_theta", 1_000_000.0)) # for global layers
3370+
# both attn_logit_softcapping and final_logit_softcapping are removed in Gemma3
3371+
assert hparams.get("attn_logit_softcapping") is None
3372+
assert hparams.get("final_logit_softcapping") is None
3373+
self.gguf_writer.add_sliding_window(hparams["sliding_window"])
3374+
self.gguf_writer.add_head_count_kv(hparams.get("num_key_value_heads", 4))
3375+
if hparams.get("rope_scaling") is not None:
3376+
assert hparams["rope_scaling"]["rope_type"] == "linear"
3377+
# important: this rope_scaling is only applied for global layers, and not used by 1B model
3378+
self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.LINEAR)
3379+
self.gguf_writer.add_rope_scaling_factor(hparams["rope_scaling"]["factor"])
3380+
3381+
def modify_tensors(self, data_torch: Tensor, name: str, bid: int | None) -> Iterable[tuple[str, Tensor]]:
3382+
del bid # unused
3383+
3384+
if name.startswith("language_model."):
3385+
name = name.replace("language_model.", "")
3386+
elif name.startswith("multi_modal_projector.") or name.startswith("vision_tower.") \
3387+
or name.startswith("multimodal_projector.") or name.startswith("vision_model."): # this is for old HF model, should be removed later
3388+
# ignore vision tensors
3389+
return []
3390+
3391+
# remove OOV (out-of-vocabulary) rows in token_embd
3392+
if "embed_tokens.weight" in name:
3393+
vocab = self._create_vocab_sentencepiece()
3394+
tokens = vocab[0]
3395+
data_torch = data_torch[:len(tokens)]
3396+
3397+
# ref code in Gemma3RMSNorm
3398+
# output = output * (1.0 + self.weight.float())
3399+
if name.endswith("norm.weight"):
3400+
data_torch = data_torch + 1
3401+
3402+
return [(self.map_tensor_name(name), data_torch)]
3403+
3404+
33253405
@Model.register("Starcoder2ForCausalLM")
33263406
class StarCoder2Model(Model):
33273407
model_arch = gguf.MODEL_ARCH.STARCODER2

docs/build.md

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -197,28 +197,52 @@ The following compilation options are also available to tweak performance:
197197

198198
## MUSA
199199

200-
This provides GPU acceleration using the MUSA cores of your Moore Threads MTT GPU. Make sure to have the MUSA SDK installed. You can download it from here: [MUSA SDK](https://developer.mthreads.com/sdk/download/musa).
200+
This provides GPU acceleration using a Moore Threads GPU. Make sure to have the [MUSA SDK](https://developer.mthreads.com/musa/musa-sdk) installed.
201201

202-
- Using `CMake`:
202+
#### Download directly from Moore Threads
203203

204-
```bash
205-
cmake -B build -DGGML_MUSA=ON
206-
cmake --build build --config Release
207-
```
204+
You may find the official downloads here: [Moore Threads developer site](https://developer.mthreads.com/sdk/download/musa).
208205

209-
For static build:
206+
### Compilation
210207

211-
```bash
208+
```bash
209+
cmake -B build -DGGML_MUSA=ON
210+
cmake --build build --config Release
211+
```
212+
213+
#### Override Compute Capability Specifications
214+
215+
By default, all supported compute capabilities are enabled. To customize this behavior, you can specify the `MUSA_ARCHITECTURES` option in the CMake command:
216+
217+
```bash
218+
cmake -B build -DGGML_MUSA=ON -DMUSA_ARCHITECTURES="21"
219+
```
220+
221+
This configuration enables only compute capability `2.1` (MTT S80) during compilation, which can help reduce compilation time.
222+
223+
#### Compilation options
224+
225+
Most of the compilation options available for CUDA should also be available for MUSA, though they haven't been thoroughly tested yet.
226+
227+
- For static builds, add `-DBUILD_SHARED_LIBS=OFF` and `-DCMAKE_POSITION_INDEPENDENT_CODE=ON`:
228+
```
212229
cmake -B build -DGGML_MUSA=ON \
213230
-DBUILD_SHARED_LIBS=OFF -DCMAKE_POSITION_INDEPENDENT_CODE=ON
214231
cmake --build build --config Release
215232
```
216233

217-
The environment variable [`MUSA_VISIBLE_DEVICES`](https://docs.mthreads.com/musa-sdk/musa-sdk-doc-online/programming_guide/Z%E9%99%84%E5%BD%95/) can be used to specify which GPU(s) will be used.
234+
### Runtime MUSA environmental variables
218235

219-
The environment variable `GGML_CUDA_ENABLE_UNIFIED_MEMORY=1` can be used to enable unified memory in Linux. This allows swapping to system RAM instead of crashing when the GPU VRAM is exhausted.
236+
You may set the [musa environmental variables](https://docs.mthreads.com/musa-sdk/musa-sdk-doc-online/programming_guide/Z%E9%99%84%E5%BD%95/) at runtime.
220237

221-
Most of the compilation options available for CUDA should also be available for MUSA, though they haven't been thoroughly tested yet.
238+
```bash
239+
# Use `MUSA_VISIBLE_DEVICES` to hide the first compute device.
240+
MUSA_VISIBLE_DEVICES="-0" ./build/bin/llama-server --model /srv/models/llama.gguf
241+
```
242+
243+
### Unified Memory
244+
245+
The environment variable `GGML_CUDA_ENABLE_UNIFIED_MEMORY=1` can be used to enable unified memory in Linux. This allows swapping to system RAM instead of crashing when the GPU VRAM is exhausted.
222246

223247
## HIP
224248

0 commit comments

Comments
 (0)