Compare commits

..
14 Commits
Author SHA1 Message Date
Aleksander Grygier 6d8a8886fa ui: draw markdown tables with row rules instead of a cell grid (#33195)
A table in a chat column drew a rule around every cell, a band behind the
header and a frame around its scroll wrapper. The lines did the separating
twice over, so the table read heavier than the prose around it.

A hairline under each row carries the structure on its own now: no cell grid,
no header band, no frame, and the outer columns line up with the text above
and below. GFM column alignment arrives as an align attribute, which an
authored text-align beats, so the three values are restated and a
right-aligned column keeps its figures under its header. Numbers take tabular
figures, code in a cell stays one token, and a table of six or more columns
keeps a width a word sits on and scrolls in its wrapper.

The Tables story covers it: alignment, code and links in cells, a list and a
line break in a cell, escaped pipes and an empty cell, and a table wider than
the column.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-27 17:20:19 +01:00
Pedro Cuenca 4c7344447c [Inkling 2] Support nvfp4 pass-through (#33062) 2026-11-27 15:44:37 +01:00
fox5611 3ab385146c CUDA: fix ADD_ID launch for more than 65535 tokens (#33162)
The grid's y dimension came directly from the token count, so ADD_ID
launches with more than 65535 tokens failed with "invalid configuration
argument". NVIDIA and HIP are equally affected, since gridDim.y is
capped at 65535 on both.

Clamp the grid and stride over ne2 in the kernel, matching convert.cu
and pad.cu. Add a test case at 70000 tokens; the existing cases top out
at 129.

Assisted-by: Claude Opus 5
2026-11-27 15:32:42 +01:00
Ruben Ortlam d67b7a99d8 vulkan: handle empty conv3d kernel, fixes validation error (#33106) 2026-11-27 15:31:18 +01:00
Jeff Bolz 3b103f75e9 vulkan: further optimize coopmat2 GDN (#32860)
* vulkan: further optimize coopmat2 GDN

Refactor split+store callbacks so hi and lo portions are all stored together.
This should help allow the stores to be vectorized.

Interleave the state store callbacks with the gram_pmat work. The compiler
doesn't seem to let these things overlap without manual effort like this. I
suspect this is because the compiler doesn't have smart enough alias analyssis
to know what can/can't conflict.

Similarly, split the invert function into separate calculation/store calls,
so the inverse work can interleave better with the MMAs.

Move "solved" from sh_dh to sh_sh - reusing sh_dh needed a barrier but sh_sh
doesn't.

* interact properly with new replay code
2026-11-27 15:26:19 +01:00
Aaron Teo 4346838ad8 ggml-zdnn: make zTensor memory usage visible for fitting (#31849)
* ggml-zdnn: make memory usage visible for fitting

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

* ggml-zdnn: switch to a flag check for ztensor buffer storage

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

* ggml-zdnn: fix rebase conflicts

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>

---------

Signed-off-by: Aaron Teo <aaron.teo1@ibm.com>
2026-11-27 15:22:50 +01:00
NoahandJohannes Gäßler 0020197457 CUDA: cache the device type at init (#33142)
* CUDA: cache the device type at init

ggml_backend_cuda_device_get_type called cudaGetDeviceProperties on every
call, which takes ~0.7-1 ms with the CUDA 12 runtime. With tensor
overrides on multiple GPUs the scheduler queries the device type for every
split input, so this ran dozens of times per token.

Store the device type in ggml_cuda_device_info at init. It is derived from
prop.integrated, not from the integrated flag, which is forced off (#15034).

Ref #33132

* Apply suggestion from @JohannesGaessler

---------

Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
2026-11-27 15:18:23 +01:00
a386950136 ggml: support quant scales for fp8 and nvfp4 (#28898)
* ggml: add tensor scaling (per-tensor, per-channel, per-expert, per-expert-per-channel) support

* add meta backend scale split

* add optional activation scales to mul_mat and mul_mat_id tensors

* handle bitnet scales too, disable in backends

* Don't treat single expert as per-channel-per-expert

* Temp workaround for moe-cache with scaled data-types

* Also apply scales in CPU backend 's tiled mul_mat

* Handle strided views on scales

* Make *scale tensors use existing GGML_OP_MUL buffer probe

* Make scale tensors required for ggml_type with needs_scale=true

* Make needs_scale=true for FP8

* Use ggml_need_scale in code-base

* Transform companion FP8 scales

* Add comment explaining intended use of activation scales

* Fix pre-existing view-handling failure in meta backend

eae135bd4 exposed an issue with single-ton dimension ambiguitiy + views
in meta backend, see https://github.com/ggml-org/llama.cpp/actions/runs/39765669007/job/119780422102

* Enforce scale side-cars for scaled data-types during conversion

* tq quants also need scales

* llama: use map for scale tensors instead of manual handling

Assisted-by: Codex

* Fix conversion edge-case for FP8 block-scales

* Revert "tq quants also need scales"

This reverts commit 5920e55b01.

* Disable dedicated kernels also for kleidiai in requant test

We want to test requant errors so we should be using the same kernels
to avoid a cofounder

* Add separate tests for scaled and unscaled DSV2

* Also remove IQ from needs_scale related tests/behvaior

* Wire activation scales and disallow broadcasting over K

* Adjust build_* in lfm3.cpp

* Avoid internal includes in test-llama-arch for moe scales

see https://github.com/ggml-org/llama.cpp/pull/27512#discussion_r4410518158

* djust build_* in limite.c
pp as well

* Adjust build_* for mistral 4

* More build_*_ffn changes

* fp8 : fix integration after rebase

* Another round of model scale map fixes

* Only read scales for valid experts

* handle input scales through cache similar to weight scales

* check supports_op in cache slots

* use is_scalar/is_vector functions

* fix Windows CI cleanup failure

* exclude BLOOM, JAIS and REFACT from sm_tensor due to Alibi not handled in TP correctly yet

* increase error threshold for hunyuan and maincoder context shifting

* adapt CUDA fusion code to scale change

* fix MoE cache too small error

* increase error threshold for hrm_text

* replace missing model matmul cases

* clean up unused CUDA code

* more missed matmuls

* handle per-tensor (scalar) scales in moe cache

* place scales with their weights

* increase error threshold for moe scales check

* restore CUDA cublaslt scale path

* convert model matmuls, handle weight views, add tests

* fix comments and error style

* cuda: use global scale functions

* fix kleidiai

* cuda: honour f32 prec in cublaslt call

* update Metal fusion count

* fix gemma4 scale issue

* don't remove trivial scale if required

* adapt new models changes

* adapt conversion qwen4exp changes and tests

* improve error message when scale unsupported

* address feedback

* adapt new models

* metal : apply the weight scale of MUL_MAT and MUL_MAT_ID

* ggml : avoid `ggml_type_traits` ABI change + TODOs

* metal : drop the comments of the weight scale epilogue

* undo moe-cache-specific changes

* tests : update the Metal fusion baseline

* handle scale in repack and kleidiai, fix scale buffer placement in loader

* llama : fix weight scale lookup, validate MUL_MAT_ID scales

- only look up a weight scale for .weight tensors (k_scale/v_scale
  tensors were checked against the weight scale and failed to load)
- check MUL_MAT_ID weight scale shapes at load time instead of asserting
- llama-quantize: error out on nvfp4/f8_e4m3 targets (no scale computed)
- llama-quant: NULL -> nullptr

* clean up unnecessary tests

---------

Co-authored-by: Oliver Simons <osimons@nvidia.com>
Co-authored-by: Pascal <admin@serveurperso.com>
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2026-11-27 14:51:55 +01:00
AWA 15fcfc7357 convert : preserve pooler for BertForSequenceClassification (#33122)
* convert : preserve pooler for BertForSequenceClassification

Signed-off-by: bc15575202581 <bc15575202581@gmail.com>

* convert : address review feedback for BertForSequenceClassification

Signed-off-by: bc15575202581 <bc15575202581@gmail.com>

* convert : use setdefault for classifier_activation

---------

Signed-off-by: bc15575202581 <bc15575202581@gmail.com>
2026-11-27 12:37:10 +01:00
Lucius 7b74cb92d6 graph : read recurrent states in place instead of copying (#28841) (#30139)
* graph : read recurrent states in place instead of copying (#28841)

This is a graph only change that speeds up token output in the majority of cases and backends by removing state copy steps.
Where possible, kernels now read recurrent states directly from the cache instead of a copy from ggml_get_rows.
A change to RWKV6/7 makes it read its old state before overwriting.
A graph-reuse check condition is added to keep track of whether states are read in place.

Assisted-by: Claude Opus 5.5 + Sol 6.1

* graph : keep recurrent-state graph the same shape, both when read in place or for movement

Vulkan and Metal failed under GGML_SCHED_NO_REALLOC. The readers now always read the states from cache.
Graph shape is mainmtained throughout.

Assisted by: Opus 5.5

* Prevent any throughput regressions from caching clashing with speculative decoding rollback snapshots. Fix WebGPU CI error by skipping the fusion step when input states overlap with the cache it writes to.

* Refactor comment on rollback snapshots in llama-graph

Simplified comment.

* tests : add regression test for after memory clear

* graph : check rs_in_place when reusing the hybrid iswa rel input

* graph : document build_rs rules, read src0 directly in get_rs_in_place

* graph : expose the rs snapshot rule once via get_rs_snapshots

* graph : drop the repeated snapshot rule from the build_rs comment

* graph : clarify the build_rs snapshot comment
2026-11-27 12:15:29 +01:00
anujj 2a8bf0f593 cuda : fix NVFP4 MMQ y_scale over-read in the stream-k fixup (#33136) 2026-11-27 15:18:10 +05:30
Aman Gupta e7ec6361dc moe-cache : support experts selected on another backend (#33133)
When the experts are selected on another backend than the cache, e.g. the loop passes of inkling2_loop with a layer split, the lookup reads a copy of the ids made by the scheduler, which has no source to read the shape from. Take the experts per token from build_lookup instead.

Fixes #33101
2026-11-27 11:32:07 +02:00
Sigbjørn Skjæret 69812f63c2 llama : remove unused llm_tensor enums (#33179) 2026-11-27 10:18:09 +01:00
Georgi Gerganov f351f415d6 metal : check all fused nodes for concurrency (#33175)
* metal : check all fused nodes for concurrency

The concurrency check for a fused group only examined the last node, so
intermediate outputs (e.g. the TOPK_MOE ids/weights) and the group's
sources (e.g. the router logits) were ignored. This allowed the fused
top-k kernel to run concurrently with the router matmul that writes its
input, producing nondeterministic expert routing.

Check every node of the fused group instead.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)

* tests : update the Metal fusion baseline for bailingmoe3

PR #33081 enables the SSM_CONV + SILU fusion in bailingmoe3. Record the
new SSM_CONV+UNARY count in the Metal baseline.

Assisted-by: dsh:llama.cpp/ggml-org/DeepSeek-V4.1-Flash-1017-GGUF (Mac Studio, M5 Ultra, 256GB)
2026-11-27 11:10:50 +02:00
240 changed files with 3592 additions and 2583 deletions
+88 -13
View File
@@ -333,13 +333,13 @@ class ModelBase:
return scale.numel() <= 1 and abs(float(scale.float().sum()) - 1.0) < 1e-6
def _write_scale_tensor(self, scale_name: str, scale: Tensor):
if not self._scale_is_trivial(scale):
if not scale_name.endswith(".input_scale") or not self._scale_is_trivial(scale):
scale_f32 = scale.float().numpy().flatten()
logger.info(f" + {scale_name} (per-tensor scale, shape [{scale_f32.size}])")
self.gguf_writer.add_tensor(scale_name, scale_f32)
def _write_scales_tensor(self, scale_name: str, scales: list[float]):
if not np.allclose(scales, 1.0, atol=1e-6):
if not scale_name.endswith(".input_scale") or not np.allclose(scales, 1.0, atol=1e-6):
scale_vals = np.array(scales, dtype=np.float32)
logger.info(f" + {scale_name} (per-expert scale, shape [{len(scales)}])")
self.gguf_writer.add_tensor(scale_name, scale_vals)
@@ -689,14 +689,34 @@ class ModelBase:
new_name = self.tensor_map.get_name(name, try_suffixes=(".weight",))
return (new_name,) if new_name is not None else ()
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
# Return scales in mapped weight order, or None to dequantize.
# A new weight transform must also provide scale handling.
if type(self).modify_tensors is ModelBase.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
return (scale,)
return None
def _prepare_fp8_e4m3_tensors(self):
if not self._preserve_fp8:
return
quant_config = self.hparams.get("quantization_config") or {}
fp8_configs = [
group["weights"] for group in (quant_config.get("config_groups") or {}).values()
if isinstance(group, dict) and group.get("weights", {}).get("type") == "float"
and group.get("weights", {}).get("num_bits") == 8
]
unsupported_layout = quant_config.get("weight_block_size") is not None or any(
config.get("strategy") not in (None, "tensor", "channel")
or config.get("block_structure") is not None or config.get("group_size") is not None
for config in fp8_configs
)
scale_tensors: dict[str, list[tuple[int, float]] | np.ndarray] = {}
input_scale_tensors: dict[str, list[tuple[int, float]] | np.ndarray] = {}
consumed: list[str] = []
candidates: dict[str, tuple[str, Tensor, tuple[str, ...], torch.Size]] = {}
channel_scales: dict[str, tuple[Tensor, ...]] = {}
weight_dtypes: dict[str, torch.dtype] = {}
scaled_weights: set[str] = set()
expert_pattern = re.compile(r"(\.[^.]*experts)\.(\d+)\.")
@@ -729,8 +749,19 @@ class ModelBase:
continue
scale = self.model_tensors[scale_name]()
if prod(scale.shape) != 1:
continue
# Accept per-tensor or per-output-channel scale layouts.
scale_size = prod(scale.shape)
is_channel_scale = 1 <= scale.ndim <= weight.ndim and scale.shape[0] == weight.shape[0] and all(size == 1 for size in scale.shape[1:])
if unsupported_layout or (scale_size != 1 and not is_channel_scale):
if quant_config.get("quant_method") in ("modelopt", "modelopt_mixed") and scale_name.endswith("_scale_inv"):
continue
if self._is_nvfp4_compressed_tensors(quant_config.get("quant_method"), quant_config.get("format"), quant_config.get("config_groups") or {}):
continue
raise ValueError(
f"FP8 weight {weight_name!r} has an unsupported block/group scale "
f"(scale shape {list(scale.shape)}, weight shape {list(weight.shape)}); "
f"only per-tensor or per-output-channel scales are supported. "
f"Re-run with --fp8-as-q8 to dequantize instead.")
merged_name = expert_pattern.sub(r"\1.", weight_name)
new_names = self._map_fp8_weight_names(merged_name)
@@ -743,6 +774,12 @@ class ModelBase:
if any(new_name.endswith("_norm.weight") or self.tensor_force_quant(weight_name, new_name, bid, weight.ndim) != gguf.GGMLQuantizationType.F8_E4M3 for new_name in new_names):
self._fp8_e4m3_preserved.discard(weight_name)
continue
if scale_size != 1:
transformed = self._transform_fp8_scale(weight_name, scale.reshape(-1, 1)) if weight.ndim == 2 else None
if transformed is None or len(transformed) != len(new_names):
self._fp8_e4m3_preserved.discard(weight_name)
continue
channel_scales[weight_name] = transformed
candidates[weight_name] = (scale_name, scale, new_names, weight.shape)
expert_groups: dict[str, list[str]] = {}
@@ -758,8 +795,13 @@ class ModelBase:
continue
if dtypes == {torch.float8_e4m3fn} and not any(name in scaled_weights for name in names):
continue
scale_sizes: dict[str, set[int]] = {}
for name in names:
if name in candidates:
proj = name.rsplit(".", 2)[1]
scale_sizes.setdefault(proj, set()).add(prod(candidates[name][1].shape))
# The converter merges expert projections together.
if not all(name in candidates for name in names):
if not all(name in candidates for name in names) or any(len(sizes) > 1 for sizes in scale_sizes.values()):
for name in names:
candidates.pop(name, None)
self._fp8_e4m3_preserved.discard(name)
@@ -769,6 +811,7 @@ class ModelBase:
for weight_name, (scale_name, scale, new_names, shape) in candidates.items():
scale = LazyTorchTensor.to_eager(scale).float().flatten()
output_scales = tuple(LazyTorchTensor.to_eager(s).float().flatten() for s in channel_scales.get(weight_name, (scale,) * len(new_names)))
weight_prefix = weight_name.removesuffix(".weight")
# Transformers fine-grained FP8 uses activation_scale while ModelOpt uses input_scale.
@@ -792,25 +835,25 @@ class ModelBase:
expert_match = expert_pattern.search(weight_name)
if expert_match:
expert_id = int(expert_match.group(2))
for new_name in new_names:
for new_name, target_scale in zip(new_names, output_scales):
target_name = new_name.replace(".weight", ".scale")
entries = scale_tensors.setdefault(target_name, [])
assert isinstance(entries, list)
cast(list[tuple[int, float]], entries).append((expert_id, float(scale[0])))
cast(list, entries).append((expert_id, target_scale.numpy().astype(np.float32)))
if input_scale is not None:
target_name = new_name.replace(".weight", ".input_scale")
entries = input_scale_tensors.setdefault(target_name, [])
assert isinstance(entries, list)
cast(list[tuple[int, float]], entries).append((expert_id, float(input_scale[0])))
else:
for new_name in new_names:
for new_name, target_scale in zip(new_names, output_scales):
mapped = self.tensor_map.get_type_and_name(new_name, try_suffixes=(".weight",)) if len(shape) == 3 else None
is_packed_expert = mapped is not None and mapped[0] in (
gguf.MODEL_TENSOR.FFN_GATE_EXP, gguf.MODEL_TENSOR.FFN_UP_EXP, gguf.MODEL_TENSOR.FFN_DOWN_EXP,
)
# Packed expert weights need one scale value per expert.
n_scales = shape[0] if is_packed_expert else 1
scale_tensors[new_name.replace(".weight", ".scale")] = np.repeat(scale.numpy(), n_scales)
scale_tensors[new_name.replace(".weight", ".scale")] = np.repeat(target_scale.numpy(), n_scales)
if input_scale is not None:
input_scale_tensors[new_name.replace(".weight", ".input_scale")] = np.repeat(input_scale.numpy(), n_scales)
@@ -820,11 +863,15 @@ class ModelBase:
for name, values in chain(scale_tensors.items(), input_scale_tensors.items()):
if isinstance(values, list):
values.sort(key=lambda item: item[0])
scale = np.array([item[1] for item in values], dtype=np.float32)
arrays = [np.asarray(item[1], dtype=np.float32).reshape(-1) for item in values]
if all(a.size == 1 for a in arrays):
scale = np.array([a[0] for a in arrays], dtype=np.float32)
else:
scale = np.stack(arrays, axis=0)
else:
scale = values.astype(np.float32)
if not np.allclose(scale, 1.0, atol=1e-6):
logger.info(f" + {name} (FP8 scale, shape [{scale.size}])")
if not name.endswith(".input_scale") or not np.allclose(scale, 1.0, atol=1e-6):
logger.info(f" + {name} (FP8 scale, shape {list(scale.shape)})")
self.gguf_writer.add_tensor(name, scale)
@classmethod
@@ -1359,6 +1406,8 @@ class ModelBase:
scale2_name = name.replace(".weight", ".weight_scale_2")
input_scale_name = name.replace(".weight", ".input_scale")
if scale_name not in self.model_tensors:
if self.model_tensors[name]().dtype == torch.uint8:
raise ValueError(f"Cannot convert NVFP4 weight {name!r}: source block scale {scale_name!r} is missing")
continue
weight = self.model_tensors[name]()
scale = self.model_tensors[scale_name]()
@@ -1369,9 +1418,11 @@ class ModelBase:
if weight.ndim != 2 or scale.shape[0] != weight.shape[0] or scale.shape[1] * 8 != weight.shape[1]:
raise ValueError(f"NVFP4 weight {name!r} has incompatible shapes: weight {list(weight.shape)}, scale {list(scale.shape)}")
if scale2_name not in self.model_tensors:
raise ValueError(f"Cannot convert NVFP4 weight {name!r}: source weight scale is missing ({scale2_name!r})")
weight = LazyTorchTensor.to_eager(weight)
scale = LazyTorchTensor.to_eager(scale)
scale2 = LazyTorchTensor.to_eager(self.model_tensors.get(scale2_name, lambda: torch.tensor(1.0))())
scale2 = LazyTorchTensor.to_eager(self.model_tensors[scale2_name]())
input_scale = LazyTorchTensor.to_eager(self.model_tensors.get(input_scale_name, lambda: torch.tensor(1.0))())
# Mark tensors for removal from model_tensors (already written to gguf)
@@ -1450,7 +1501,19 @@ class ModelBase:
self._has_ple |= is_ple
return is_ple if self.ple_only else not is_ple
def _has_fp8_source_scale(self, name: str) -> bool:
scale_names = (name + "_scale", name + "_scale_inv", name.removesuffix("weight") + "qscale_weight")
return any(scale_name in self.model_tensors for scale_name in scale_names)
def prepare_tensors(self):
for name, load in self.model_tensors.items():
if not name.endswith(".weight"):
continue
if load().dtype not in (torch.float8_e4m3fn, torch.float8_e5m2):
continue
if not self._has_fp8_source_scale(name):
raise ValueError(f"Cannot convert FP8 weight {name!r}: source weight scale is missing")
# detect NVFP4 quantization (ModelOpt and Compressed-tensors formats)
quantization_config = self.hparams.get("quantization_config") or {}
quant_algo = quantization_config.get("quant_algo")
@@ -1666,6 +1729,18 @@ class ModelBase:
if any(qkv_buffers):
raise ValueError("QKV fusion did not consume all buffered tensors")
tensor_names = {name for shard in self.gguf_writer.tensors for name in shard}
for shard in self.gguf_writer.tensors:
for name, tensor in shard.items():
# a PLE-only file holds just the table, its scale stays in the backbone
if self.ple_only and self._include_ple_tensor(name):
continue
# Keep in sync with needs_scale in ggml.c.
if tensor.dtype in (gguf.GGMLQuantizationType.F8_E4M3, gguf.GGMLQuantizationType.NVFP4):
scale_name = name.removesuffix(".weight") + ".scale"
if scale_name not in tensor_names:
raise ValueError(f"Cannot export {name!r} as {tensor.dtype.name}: required scale tensor {scale_name!r} is missing (implicit unit scales are not supported)")
def set_type(self):
self.gguf_writer.add_type(gguf.GGUFType.MODEL)
+25 -1
View File
@@ -14,7 +14,7 @@ if TYPE_CHECKING:
from .base import ModelBase, SentencePieceTokenTypes, TextModel, gguf, jinja_str_or_json, logger
@ModelBase.register("BertModel", "BertForMaskedLM", "CamembertModel", "BertForSequenceClassification")
@ModelBase.register("BertModel", "BertForMaskedLM", "CamembertModel")
@ModelBase.example("BAAI/bge-small-en-v1.5", "dangvantuan/sentence-camembert-base")
class BertModel(TextModel):
model_arch = gguf.MODEL_ARCH.BERT
@@ -241,6 +241,30 @@ class BertModel(TextModel):
special_vocab.add_to_gguf(self.gguf_writer)
@ModelBase.register("BertForSequenceClassification")
@ModelBase.example("cross-encoder/ms-marco-MiniLM-L-12-v2")
class BertForSequenceClassification(BertModel):
model_arch = gguf.MODEL_ARCH.BERT
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.cls_out_labels is None:
self.cls_out_labels = self.hparams.get("id2label")
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
name, gen = item
name = name.replace("pooler.dense", "classifier.dense")
return super().filter_tensors((name, gen))
def set_gguf_parameters(self):
if "classifier.dense.weight" in self.model_tensors:
self.hparams.setdefault("classifier_activation", "tanh")
super().set_gguf_parameters()
@ModelBase.register("DistilBertModel", "DistilBertForMaskedLM", "DistilBertForSequenceClassification")
@ModelBase.example("distilbert/distilbert-base-uncased")
class DistilBertModel(BertModel):
+67 -11
View File
@@ -65,6 +65,26 @@ def _dequant_expert_chunk(weight: Callable[[], Tensor], scale: Callable[[], Tens
return values
def _repack_nvfp4_rows(packed: np.ndarray, scales: np.ndarray, name: str, expert: int) -> np.ndarray:
if np.any(scales & 0x80) or np.any(scales == 0x7F):
raise ValueError(f"Inkling2: {name}_scale expert {expert}: NVFP4 block scales must be finite and nonnegative")
n_rows = packed.shape[0]
n_blocks = scales.shape[1]
nibbles = np.stack([packed & 0x0F, packed >> 4], axis=-1).reshape(n_rows, n_blocks, 16)
qs = (nibbles[:, :, :8] | (nibbles[:, :, 8:] << 4)).astype(np.uint8)
n_super = n_blocks // 4
blocks = np.concatenate([scales.reshape(n_rows, n_super, 4), qs.reshape(n_rows, n_super, 32)], axis=-1)
return blocks.reshape(n_rows, n_super * 36)
def _repack_nvfp4_expert(weight: Callable[[], Tensor], scale: Callable[[], Tensor], name: str, expert: int, w13: bool) -> np.ndarray:
packed = LazyTorchTensor.to_eager(weight().view(torch.uint8)[expert]).numpy()
scales = LazyTorchTensor.to_eager(scale().view(torch.uint8)[expert]).numpy()
if not w13:
return _repack_nvfp4_rows(packed, scales, name, expert)
return np.concatenate([_repack_nvfp4_rows(packed[half::2], scales[half::2], name, expert) for half in (0, 1)])
def _is_inkling2(dir_model: Path) -> bool:
if not (dir_model / "config.json").is_file():
return False
@@ -84,9 +104,11 @@ def _load_inkling2_hparams(dir_model: Path):
class Inkling2Model(TextModel):
model_arch = gguf.MODEL_ARCH.INKLING2
def __init__(self, dir_model: Path, *args, **kwargs):
def __init__(self, dir_model: Path, ftype: gguf.LlamaFileType, *args, **kwargs):
self._expert_quant: dict[str, dict] = {}
self._packed_experts: dict[str, gguf.LazyChunkedTensor] = {}
self._native_experts: dict[str, tuple[gguf.LazyChunkedTensor, np.ndarray]] = {}
self._preserve_nvfp4 = ftype == gguf.LlamaFileType.GUESSED
quant_path = dir_model / "hf_quant_config.json"
if quant_path.is_file():
with open(quant_path, encoding="utf-8") as f:
@@ -99,7 +121,7 @@ class Inkling2Model(TextModel):
if name in self._expert_quant:
raise ValueError(f"Inkling2: duplicate hf_quant_config.json scheme for {name}")
self._expert_quant[name] = group
super().__init__(dir_model, *args, **kwargs)
super().__init__(dir_model, ftype, *args, **kwargs)
logger.warning("Inkling2: converting the text backbone only; vision and MTP tensors are skipped")
hp = self.hparams
for name, default in (("q_bias", False), ("o_bias", False), ("n_shared_experts", 0), ("use_value_norm_no_gamma", True), ("attn_res_normalize_values", True), ("scoring_func", "sigmoid")):
@@ -165,15 +187,38 @@ class Inkling2Model(TextModel):
t = gen()
if t.dtype != torch.float32 or tuple(t.shape) != expected:
raise ValueError(f"Inkling2: {companion}: expected F32 {expected}, got {t.dtype} {tuple(t.shape)}")
chunks: list[Callable[[], np.ndarray]] = []
for expert in range(experts):
for half in range(2 if w13 else 1):
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
# The same packed row slice selects the weight and its scale groups.
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
preserve_nvfp4 = nvfp4 and self._preserve_nvfp4
if preserve_nvfp4 and cols % 64 != 0:
logger.warning("Inkling2: %s: %d columns are not a multiple of 64; dequantizing NVFP4", name, cols)
preserve_nvfp4 = False
chunks: list[Callable[[], np.ndarray]]
if preserve_nvfp4:
assert amax is not None and denominator is not None
a = LazyTorchTensor.to_eager(amax()).numpy().astype(np.float32)
d = LazyTorchTensor.to_eager(denominator()).numpy().astype(np.float32)
if not np.isfinite(a).all() or (a < 0).any():
raise ValueError(f"Inkling2: {name}_amax: expected finite nonnegative values")
if not np.isfinite(d).all() or (d <= 0).any():
raise ValueError(f"Inkling2: {name}_outer_scale_denominator: expected finite positive value")
with np.errstate(over="ignore", invalid="ignore"):
outer_scale = a / d
if not np.isfinite(outer_scale).all():
raise ValueError(f"Inkling2: {name}: non-finite outer scale")
chunks = [partial(_repack_nvfp4_expert, weight, scale, name, expert, w13) for expert in range(experts)]
byte_shape = (experts, rows, cols // 64 * 36)
self._native_experts[name] = (gguf.LazyChunkedTensor(chunks, byte_shape, np.uint8), outer_scale)
else:
chunks = []
for expert in range(experts):
for half in range(2 if w13 else 1):
for start in range(0, rows // 2 if w13 else rows, _EXPERT_CHUNK_ROWS):
stop = min(start + _EXPERT_CHUNK_ROWS, rows // 2 if w13 else rows)
# The same packed row slice selects the weight and its scale groups.
row_slice = slice(2 * start + half, 2 * stop + half, 2) if w13 else slice(start, stop)
chunks.append(partial(_dequant_expert_chunk, weight, scale, amax, denominator, name, expert, row_slice))
self._packed_experts[name] = gguf.LazyChunkedTensor(chunks, shape, np.float32)
if not nvfp4 and self._fp8_as_q8:
self._fp8_dequantized.add(name)
self.model_tensors[name] = lambda shape=shape: torch.empty(shape, dtype=torch.float32, device="meta")
for companion in required:
del self.model_tensors[companion]
@@ -181,6 +226,7 @@ class Inkling2Model(TextModel):
t = gen()
if not t.dtype.is_floating_point or t.element_size() == 1 or name.endswith(("_weight_scale", "_weight_amax", "_weight_outer_scale_denominator")):
raise ValueError(f"Inkling2: unexpected packed tensor or orphan companion {name}")
self._is_nvfp4 = bool(self._native_experts)
@classmethod
def filter_tensors(cls, item: tuple[str, Callable[[], Tensor]]) -> tuple[str, Callable[[], Tensor]] | None:
@@ -254,6 +300,16 @@ class Inkling2Model(TextModel):
if name.endswith(".o_proj.gate_proj.weight"):
yield self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid), data_torch
return
if name in self._native_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
new_name = self.map_tensor_name(target, try_suffixes=()) + ".weight"
packed, scale = self._native_experts[name]
shape = gguf.quant_shape_from_byte_shape(packed.shape, gguf.GGMLQuantizationType.NVFP4)
shape_str = f"{{{', '.join(str(n) for n in reversed(shape))}}}"
logger.info(f"{new_name}, NVFP4 --> NVFP4, shape = {shape_str}")
self.gguf_writer.add_tensor(new_name, cast("np.ndarray", packed), raw_dtype=gguf.GGMLQuantizationType.NVFP4)
self._write_scales_tensor(new_name.removesuffix(".weight") + ".scale", scale.tolist())
return
if name in self._packed_experts:
target = name.replace(".w13_weight", ".gate_up_proj").replace(".w2_weight", ".down_proj")
yield self.map_tensor_name(target, try_suffixes=()) + ".weight", cast("Tensor", self._packed_experts[name])
+12
View File
@@ -181,6 +181,18 @@ class LlamaModel(TextModel):
.swapaxes(1, 2)
.reshape(weights.shape))
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
if type(self).modify_tensors is not LlamaModel.modify_tensors:
return None
if self.undo_permute:
n_head = self.find_hparam(["n_heads", "num_attention_heads"])
n_kv_head = self.find_hparam(["n_kv_heads", "num_key_value_heads"])
if name.endswith("q_proj.weight"):
scale = self.permute(scale, n_head, n_head)
elif name.endswith("k_proj.weight"):
scale = self.permute(scale, n_head, n_kv_head)
return (scale,)
def _repack_nvfp4(self, name: str, weight: Tensor, scale: Tensor, scale2: Tensor, input_scale: Tensor):
# Mirror the BF16 Q/K RoPE permutation site in modify_tensors; the NVFP4 path bypasses it.
if self.undo_permute:
+49 -27
View File
@@ -58,6 +58,11 @@ class QwenModel(TextModel):
class Qwen2Model(TextModel):
model_arch = gguf.MODEL_ARCH.QWEN2
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
if type(self).modify_tensors is Qwen2Model.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
return (scale,)
return None
def set_vocab(self):
# HuggingFaceBio/Carbon-14B: Qwen3 with the HybridDNATokenizer (Qwen3 BPE plus DNA 6-mers)
if self._is_hybriddna():
@@ -92,6 +97,11 @@ class Qwen2MoeModel(TextModel):
)
return super()._map_fp8_weight_names(name)
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
if type(self).modify_tensors is Qwen2MoeModel.modify_tensors and len(self._map_fp8_weight_names(name)) == 1:
return (scale,)
return None
def set_gguf_parameters(self):
super().set_gguf_parameters()
if (moe_intermediate_size := self.hparams.get("moe_intermediate_size")) is not None:
@@ -395,13 +405,50 @@ class Qwen3NextModel(_QwenMtpMixin, Qwen2MoeModel):
def _map_fp8_weight_names(self, name: str) -> tuple[str, ...]:
if name.endswith(".linear_attn.in_proj_qkvz.weight"):
bid = next(int(part) for part in self.map_tensor_name(name).split(".") if part.isdecimal())
# Both split projections keep the original per-tensor scales.
return (
self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_QKV, bid),
self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid),
)
return super()._map_fp8_weight_names(name)
def _transform_fp8_scale(self, name: str, scale: Tensor) -> tuple[Tensor, ...] | None:
if type(self).modify_tensors is not Qwen3NextModel.modify_tensors:
return None
if name.endswith(".linear_attn.in_proj_qkvz.weight"):
return self._split_qkvz(scale)
if len(self._map_fp8_weight_names(name)) == 1:
return (scale,)
return None
def _split_qkvz(self, data_torch: Tensor) -> tuple[Tensor, Tensor]:
# original order: [q, k, v, z] * head_count
# corrected order: [q * head_count, k * head_count, v * head_count, z * head_count]
head_k_dim = self.hparams["linear_key_head_dim"]
head_v_dim = self.hparams["linear_value_head_dim"]
num_v_heads = self.hparams["linear_num_value_heads"]
num_k_heads = self.hparams["linear_num_key_heads"]
hidden_size = data_torch.shape[1]
split_arg_list_qkvz = [
head_k_dim, # q partition
head_k_dim, # k partition
(num_v_heads // num_k_heads * head_v_dim), # v partition
(num_v_heads // num_k_heads * head_v_dim), # z partition
]
# view as (n_embd, head_count, [q+k+v+z])
data_torch = data_torch.permute(1, 0).contiguous()
data_torch = data_torch.view(-1, num_k_heads, sum(split_arg_list_qkvz))
# split into q, k, v, z
q, k, v, z = torch.split(data_torch, split_arg_list_qkvz, dim=-1)
# flatten dim + head_count
q = q.contiguous().view(hidden_size, -1)
k = k.contiguous().view(hidden_size, -1)
v = v.contiguous().view(hidden_size, -1)
z = z.contiguous().view(hidden_size, -1)
# stack back
qkv = torch.cat([q, k, v], dim=-1).permute(1, 0).contiguous()
z = z.permute(1, 0).contiguous()
return qkv, z
def set_gguf_parameters(self):
super().set_gguf_parameters()
self.gguf_writer.add_ssm_conv_kernel(self.hparams["linear_conv_kernel_dim"])
@@ -432,32 +479,7 @@ class Qwen3NextModel(_QwenMtpMixin, Qwen2MoeModel):
data_torch = data_torch + 1
if "in_proj_qkvz.weight" in name:
# original order: [q, k, v, z] * head_count
# corrected order: [q * head_count, k * head_count, v * head_count, z * head_count]
head_k_dim = self.hparams["linear_key_head_dim"]
head_v_dim = self.hparams["linear_value_head_dim"]
num_v_heads = self.hparams["linear_num_value_heads"]
num_k_heads = self.hparams["linear_num_key_heads"]
hidden_size = self.hparams["hidden_size"]
split_arg_list_qkvz = [
head_k_dim, # q partition
head_k_dim, # k partition
(num_v_heads // num_k_heads * head_v_dim), # v partition
(num_v_heads // num_k_heads * head_v_dim), # z partition
]
# view as (n_embd, head_count, [q+k+v+z])
data_torch = data_torch.permute(1, 0).contiguous()
data_torch = data_torch.view(-1, num_k_heads, sum(split_arg_list_qkvz))
# split into q, k, v, z
q, k, v, z = torch.split(data_torch, split_arg_list_qkvz, dim=-1)
# flatten dim + head_count
q = q.contiguous().view(hidden_size, -1)
k = k.contiguous().view(hidden_size, -1)
v = v.contiguous().view(hidden_size, -1)
z = z.contiguous().view(hidden_size, -1)
# stack back
qkv = torch.cat([q, k, v], dim=-1).permute(1, 0).contiguous()
z = z.permute(1, 0).contiguous()
qkv, z = self._split_qkvz(data_torch)
yield (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_QKV, bid, ".weight"), qkv)
yield (self.format_tensor_name(gguf.MODEL_TENSOR.ATTN_GATE, bid, ".weight"), z)
else:
+6
View File
@@ -54,6 +54,12 @@ class Qwen4ExpTextModel(_Qwen35MRopeMixin, _LinearAttentionVReorderBase):
self._ple_scale = float(scale[0])
super().dequant_model()
def _has_fp8_source_scale(self, name: str) -> bool:
if ".ngram_embedding.shard_" in name:
prefix = name.split(".ngram_embedding.shard_")[0]
return prefix + ".ngram_embedding.weight_scale" in self.model_tensors or self._ple_scale is not None
return super()._has_fp8_source_scale(name)
@classmethod
def filter_tensors(cls, item):
name, gen = item
+25 -1
View File
@@ -607,6 +607,7 @@ extern "C" {
GGML_API size_t ggml_element_size(const struct ggml_tensor * tensor);
GGML_API bool ggml_is_quantized(enum ggml_type type);
GGML_API bool ggml_needs_scale(enum ggml_type type);
// TODO: temporary until model loading of ggml examples is refactored
GGML_API enum ggml_type ggml_ftype_to_ggml_type(enum ggml_ftype ftype);
@@ -1322,6 +1323,16 @@ extern "C" {
struct ggml_tensor * a,
struct ggml_tensor * b);
// scale_weight is F32, either a scalar or one value per output channel.
// scale_activations is an optional F32 scalar for activation quantization.
// Divide activations by the scale before quantization, then multiply the matmul result by the scale.
GGML_API struct ggml_tensor * ggml_mul_mat_ext(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
struct ggml_tensor * scale_weight,
struct ggml_tensor * scale_activations);
// change the hint of a matrix multiplication
GGML_API void ggml_mul_mat_set_hint(
struct ggml_tensor * a,
@@ -1335,6 +1346,16 @@ extern "C" {
struct ggml_tensor * b,
struct ggml_tensor * ids);
// scale_weight: [1], [n_as] or [n_out, n_as], selected by ids
// scale_activations: [1] or [n_as], selected by ids
GGML_API struct ggml_tensor * ggml_mul_mat_id_ext(
struct ggml_context * ctx,
struct ggml_tensor * as,
struct ggml_tensor * b,
struct ggml_tensor * ids,
struct ggml_tensor * scale_weight,
struct ggml_tensor * scale_activations);
// A: m columns, n rows,
// B: p columns, n rows,
// result is m columns, p rows
@@ -2813,12 +2834,14 @@ extern "C" {
typedef void (*ggml_to_float_t) (const void * GGML_RESTRICT x, float * GGML_RESTRICT y, int64_t k);
typedef void (*ggml_from_float_t)(const float * GGML_RESTRICT x, void * GGML_RESTRICT y, int64_t k);
// TODO: deprecate struct definition from the public API, replace with functions [TAG_GGML_AVOID_PUBLIC_STRUCTS]
struct ggml_type_traits {
const char * type_name;
int64_t blck_size;
int64_t blck_size_interleave; // interleave elements in blocks
size_t type_size;
bool is_quantized;
bool is_quantized; // whether it's a block-quantized data-type
//bool needs_scale; // add this flag in the next update [TAG_GGML_VERSION_MAJOR_UPDATE]
ggml_to_float_t to_float;
ggml_from_float_t from_float_ref;
};
@@ -2840,6 +2863,7 @@ extern "C" {
// threadpool params
// Use ggml_threadpool_params_default() or ggml_threadpool_params_init() to populate the defaults
// TODO: deprecate struct definition from the public API, replace with functions [TAG_GGML_AVOID_PUBLIC_STRUCTS]
struct ggml_threadpool_params {
bool cpumask[GGML_MAX_N_THREADS]; // mask of cpu cores (all-zeros means use default affinity settings)
int n_threads; // number of threads
+4 -3
View File
@@ -704,11 +704,9 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
};
auto handle_view = [&](const std::vector<ggml_backend_meta_split_state> & src_ss) -> ggml_backend_meta_split_state {
if (ggml_is_contiguous(tensor) && ggml_is_contiguous(tensor->src[0])) {
return handle_reshape(src_ss);
}
const int axis = src_ss[0].axis;
{
// Keep the split axis when strides match; reshape is ambiguous across singleton dimensions.
bool all_strides_the_same = true;
for (int dim = 0; dim < GGML_MAX_DIMS; dim++) {
if (tensor->ne[dim] == 1 && tensor->src[0]->ne[dim] == 1) {
@@ -723,6 +721,9 @@ static struct ggml_backend_meta_split_state ggml_backend_meta_get_split_state(
return src_ss[0];
}
}
if (ggml_is_contiguous(tensor) && ggml_is_contiguous(tensor->src[0])) {
return handle_reshape(src_ss);
}
if (!ggml_is_permuted(tensor) && !ggml_is_permuted(tensor->src[0]) && axis >= 0 && axis < GGML_MAX_DIMS-1) {
for (int dim = 0; dim < GGML_MAX_DIMS-1; dim++) {
if (tensor->nb[dim+1] == tensor->src[0]->nb[axis+1]) {
+4
View File
@@ -398,6 +398,10 @@ static bool ggml_backend_blas_device_supports_op(ggml_backend_dev_t dev, const s
const struct ggml_tensor * src0 = op->src[0];
const struct ggml_tensor * src1 = op->src[1];
if (ggml_get_src_scale(op, 0)) {
return false;
}
switch (op->op) {
case GGML_OP_NONE:
case GGML_OP_RESHAPE:
+4
View File
@@ -2405,6 +2405,10 @@ static enum ggml_status ggml_backend_cann_graph_compute(ggml_backend_t backend,
* otherwise false.
*/
static bool ggml_backend_cann_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_get_src_scale(op, 0)) {
return false;
}
switch (op->op) {
case GGML_OP_UNARY:
switch (ggml_get_unary_op(op)) {
+93 -2
View File
@@ -1306,6 +1306,38 @@ static void ggml_cpu_bf16_to_vec_dot_type(const ggml_bf16_t * x, void * y, int64
}
}
// apply the weight scale (src[2]) carried by ggml_mul_mat_ext, broadcast over dst
static void ggml_compute_forward_mul_mat_scale(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
const struct ggml_tensor * scale = dst->src[2];
if (!scale) {
return;
}
const int ith = params->ith;
const int nth = params->nth;
const int64_t ne0 = dst->ne[0], ne1 = dst->ne[1], ne2 = dst->ne[2], ne3 = dst->ne[3];
const size_t nb1 = dst->nb[1], nb2 = dst->nb[2], nb3 = dst->nb[3];
ggml_barrier(params->threadpool);
const char * sd = (const char *) scale->data;
const int64_t sne0 = scale->ne[0], sne1 = scale->ne[1], sne2 = scale->ne[2], sne3 = scale->ne[3];
const int64_t nr = ne1 * ne2 * ne3;
for (int64_t ir = ith; ir < nr; ir += nth) {
const int64_t i1 = ir % ne1;
const int64_t i2 = (ir / ne1) % ne2;
const int64_t i3 = ir / (ne1 * ne2);
float * dp = (float *) ((char *) dst->data + i1*nb1 + i2*nb2 + i3*nb3);
const size_t so = (i1 % sne1)*scale->nb[1] + (i2 % sne2)*scale->nb[2] + (i3 % sne3)*scale->nb[3];
for (int64_t i0 = 0; i0 < ne0; i0++) {
dp[i0] *= *(const float *) (sd + (i0 % sne0)*scale->nb[0] + so);
}
}
}
void ggml_compute_forward_mul_mat(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
@@ -1321,6 +1353,7 @@ void ggml_compute_forward_mul_mat(
// If tiled is supported, it will execute the full op here and we return
if (ggml_compute_forward_mul_mat_tiled(params, dst)) {
ggml_compute_forward_mul_mat_scale(params, dst);
return;
}
@@ -1377,6 +1410,7 @@ void ggml_compute_forward_mul_mat(
src1->type,
dst->type))
goto UseGgmlGemm1;
ggml_compute_forward_mul_mat_scale(params, dst);
return;
}
UseGgmlGemm1:;
@@ -1457,6 +1491,7 @@ UseGgmlGemm1:;
vec_dot_type,
dst->type))
goto UseGgmlGemm2;
ggml_compute_forward_mul_mat_scale(params, dst);
return;
}
UseGgmlGemm2:;
@@ -1524,6 +1559,8 @@ UseGgmlGemm2:;
current_chunk = atomic_fetch_add_explicit(&params->threadpool->current_chunk, 1, memory_order_relaxed);
}
ggml_compute_forward_mul_mat_scale(params, dst);
}
// ggml_compute_forward_mul_mat_id
@@ -1606,6 +1643,53 @@ static void * incr_ptr_aligned(void ** p, size_t size, size_t align) {
return ptr;
}
// apply the weight scale (src[3]) carried by ggml_mul_mat_id_ext: per-tensor [1],
// per-expert [n_expert] or per-channel-per-expert [n_out, n_expert], indexed via ids
static void ggml_compute_forward_mul_mat_id_scale(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
const struct ggml_tensor * scale = dst->src[3];
if (!scale) {
return;
}
const struct ggml_tensor * ids = dst->src[2];
const int ith = params->ith;
const int nth = params->nth;
const int64_t ne0 = dst->ne[0], ne1 = dst->ne[1], ne2 = dst->ne[2];
const int64_t ne02 = dst->src[0]->ne[2];
const size_t nb1 = dst->nb[1], nb2 = dst->nb[2];
ggml_barrier(params->threadpool);
const char * sd = (const char *) scale->data;
const bool per_ch_exp = scale->ne[0] == ne0 && scale->ne[1] == ne02;
const bool per_expert = ggml_nelements(scale) == ne02;
const int64_t nr = ne1 * ne2;
for (int64_t ir = ith; ir < nr; ir += nth) {
const int64_t i1 = ir % ne1;
const int64_t i2 = ir / ne1;
const int32_t expert = *(const int32_t *) ((const char *) ids->data + i1*ids->nb[0] + i2*ids->nb[1]);
if (expert < 0) {
continue;
}
float * dp = (float *) ((char *) dst->data + i1*nb1 + i2*nb2);
if (per_ch_exp) {
const char * sp = sd + expert*scale->nb[1];
for (int64_t i0 = 0; i0 < ne0; i0++) {
dp[i0] *= *(const float *) (sp + i0*scale->nb[0]);
}
} else {
const float s = *(const float *) (sd + (per_expert ? expert*scale->nb[0] : 0));
for (int64_t i0 = 0; i0 < ne0; i0++) {
dp[i0] *= s;
}
}
}
}
static void ggml_compute_forward_mul_mat_id(
const struct ggml_compute_params * params,
struct ggml_tensor * dst) {
@@ -1800,6 +1884,8 @@ static void ggml_compute_forward_mul_mat_id(
current_chunk = atomic_fetch_add_explicit(current_chunk_ctr, 1, memory_order_relaxed);
}
}
ggml_compute_forward_mul_mat_id_scale(params, dst);
}
/////////////////////////////////
@@ -1813,6 +1899,11 @@ static void ggml_compute_forward(struct ggml_compute_params * params, struct ggm
// extra_buffer op?
if (ggml_cpu_extra_compute_forward(params, tensor)) {
if (tensor->op == GGML_OP_MUL_MAT) {
ggml_compute_forward_mul_mat_scale(params, tensor);
} else if (tensor->op == GGML_OP_MUL_MAT_ID) {
ggml_compute_forward_mul_mat_id_scale(params, tensor);
}
return;
}
@@ -2930,7 +3021,7 @@ struct ggml_cplan ggml_graph_plan(
case GGML_OP_ADD:
case GGML_OP_ADD_ID:
{
if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3) {
if (ggml_is_quantized(node->src[0]->type) || ggml_needs_scale(node->src[0]->type)) {
cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
}
} break;
@@ -2978,7 +3069,7 @@ struct ggml_cplan ggml_graph_plan(
} break;
case GGML_OP_OUT_PROD:
{
if (ggml_is_quantized(node->src[0]->type) || node->src[0]->type == GGML_TYPE_F8_E4M3 ||
if (ggml_is_quantized(node->src[0]->type) || ggml_needs_scale(node->src[0]->type) ||
node->src[0]->type == GGML_TYPE_F16) {
cur = ggml_type_size(GGML_TYPE_F32) * node->src[0]->ne[0] * n_tasks;
}
+2 -2
View File
@@ -615,7 +615,7 @@ static void ggml_compute_forward_add_q_f32(
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
GGML_ASSERT(ggml_is_quantized(src0->type) || src0->type == GGML_TYPE_F8_E4M3);
GGML_ASSERT(ggml_is_quantized(src0->type) || ggml_needs_scale(src0->type));
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT(ne00 % ggml_blck_size(type) == 0);
@@ -965,7 +965,7 @@ static void ggml_compute_forward_add1_q_f32(
GGML_ASSERT(nb1 <= nb2);
GGML_ASSERT(nb2 <= nb3);
GGML_ASSERT(ggml_is_quantized(src0->type) || src0->type == GGML_TYPE_F8_E4M3);
GGML_ASSERT(ggml_is_quantized(src0->type) || ggml_needs_scale(src0->type));
GGML_ASSERT(dst->type == src0->type);
GGML_ASSERT(src1->type == GGML_TYPE_F32);
+14 -12
View File
@@ -2,26 +2,28 @@
static __global__ void add_id_kernel(
const float * src0, const float * src1, const int32_t * src2, float * dst,
int64_t ne0, int64_t ne1,
int64_t ne0, int64_t ne1, int64_t ne2,
size_t nb01, size_t nb02,
size_t nb11,
size_t nb21
) {
const int64_t i1 = blockIdx.x;
const int64_t i2 = blockIdx.y;
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
// gridDim.y is capped at 65535, blocks stride over larger ne2
for (int64_t i2 = blockIdx.y; i2 < ne2; i2 += gridDim.y) {
const int i11 = *(const int32_t *) ((const char *) src2 + i1*sizeof(int32_t) + i2*nb21);
const size_t nb1 = ne0 * sizeof(float);
const size_t nb2 = ne1 * nb1;
const size_t nb1 = ne0 * sizeof(float);
const size_t nb2 = ne1 * nb1;
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
float * dst_row = (float *)((char *)dst + i1*nb1 + i2*nb2);
const float * src0_row = (const float *)((const char *)src0 + i1*nb01 + i2*nb02);
const float * src1_row = (const float *)((const char *)src1 + i11*nb11);
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
dst_row[i0] = src0_row[i0] + src1_row[i0];
for (int64_t i0 = threadIdx.x; i0 < ne0; i0 += blockDim.x) {
dst_row[i0] = src0_row[i0] + src1_row[i0];
}
}
}
@@ -47,10 +49,10 @@ void ggml_cuda_op_add_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
float * dst_d = (float *)dst->data;
int threads = std::min((int)ne00, 768); // cols
dim3 blocks(ne01, ne02); // n_experts_used, n_tokens
dim3 blocks(ne01, std::min(ne02, (int64_t)65535)); // n_experts_used, n_tokens
add_id_kernel<<<blocks, threads, 0, ctx.stream()>>>(
src0_d, src1_d, src2_d, dst_d,
ne0, ne1,
ne0, ne1, ne2,
nb01, nb02,
nb11,
nb21
+1
View File
@@ -1309,6 +1309,7 @@ struct ggml_cuda_device_info {
size_t smpb; // max. shared memory per block
size_t smpbo; // max. shared memory per block (with opt-in)
bool integrated; // Device is integrated as opposed to discrete
enum ggml_backend_dev_type type; // GPU or IGPU, from cudaDeviceProp::integrated
bool vmm; // virtual memory support
size_t vmm_granularity; // granularity of virtual memory
size_t total_vram;
+64 -453
View File
@@ -22,22 +22,24 @@
#include <cstring>
#include <initializer_list>
// the weight scale forms that the fused gate/up/GLU kernels apply: per-tensor or per-expert, NVFP4 (mmvq/mmq) or F8 (mmvf)
static bool ggml_cuda_mm_weight_scale_fusable(const ggml_tensor * mm) {
const ggml_tensor * s = ggml_get_src_scale(mm, 0);
return s && s->type == GGML_TYPE_F32 && ggml_is_contiguous(s) &&
ggml_nelements(s) == (mm->op == GGML_OP_MUL_MAT_ID ? mm->src[0]->ne[2] : 1) &&
(mm->src[0]->type == GGML_TYPE_NVFP4 || mm->src[0]->type == GGML_TYPE_F8_E4M3);
}
static bool ggml_cuda_should_fuse_mul_mat(const ggml_tensor * ffn_up,
const ggml_tensor * ffn_gate,
const ggml_tensor * glu,
const ggml_tensor * ffn_up_bias = nullptr,
const ggml_tensor * ffn_gate_bias = nullptr,
const ggml_tensor * ffn_up_scale = nullptr,
const ggml_tensor * ffn_gate_scale = nullptr) {
const ggml_tensor * ffn_gate_bias = nullptr) {
const bool has_bias = ffn_up_bias != nullptr || ffn_gate_bias != nullptr;
const bool has_scale = ffn_up_scale != nullptr || ffn_gate_scale != nullptr;
if (has_bias && (!ffn_up_bias || !ffn_gate_bias)) {
return false;
}
if (has_scale && (!ffn_up_scale || !ffn_gate_scale)) {
return false;
}
const bool is_mul_mat = ffn_up->op == GGML_OP_MUL_MAT && ffn_gate->op == GGML_OP_MUL_MAT && glu->op == GGML_OP_GLU;
const bool is_mul_mat_id = ffn_up->op == GGML_OP_MUL_MAT_ID && ffn_gate->op == GGML_OP_MUL_MAT_ID && glu->op == GGML_OP_GLU;
@@ -48,40 +50,33 @@ static bool ggml_cuda_should_fuse_mul_mat(const ggml_tensor * ffn_up,
return false;
}
if (ggml_get_src_scale(ffn_up, 0) || ggml_get_src_scale(ffn_gate, 0)) {
if (!ggml_cuda_mm_weight_scale_fusable(ffn_up) || !ggml_cuda_mm_weight_scale_fusable(ffn_gate)) {
return false;
}
}
const ggml_op expected_bias_op = is_mul_mat ? GGML_OP_ADD : GGML_OP_ADD_ID;
const ggml_tensor * ffn_up_bias_src = has_scale ? ffn_up_scale : ffn_up;
const ggml_tensor * ffn_gate_bias_src = has_scale ? ffn_gate_scale : ffn_gate;
const ggml_tensor * ffn_up_out = has_bias ? ffn_up_bias : ffn_up_bias_src;
const ggml_tensor * ffn_gate_out = has_bias ? ffn_gate_bias : ffn_gate_bias_src;
const ggml_tensor * ffn_up_out = has_bias ? ffn_up_bias : ffn_up;
const ggml_tensor * ffn_gate_out = has_bias ? ffn_gate_bias : ffn_gate;
if (glu->src[0] != ffn_gate_out || glu->src[1] != ffn_up_out) {
return false;
}
if (has_scale) {
if (ffn_up_scale->op != GGML_OP_MUL || ffn_gate_scale->op != GGML_OP_MUL) {
return false;
}
const bool up_has_mm = ffn_up_scale->src[0] == ffn_up || ffn_up_scale->src[1] == ffn_up;
const bool gate_has_mm = ffn_gate_scale->src[0] == ffn_gate || ffn_gate_scale->src[1] == ffn_gate;
if (!up_has_mm || !gate_has_mm) {
return false;
}
}
if (has_bias) {
if (ffn_up_bias->op != expected_bias_op || ffn_gate_bias->op != expected_bias_op) {
return false;
}
if (expected_bias_op == GGML_OP_ADD) {
const bool up_has_mul = ffn_up_bias->src[0] == ffn_up_bias_src || ffn_up_bias->src[1] == ffn_up_bias_src;
const bool gate_has_mul = ffn_gate_bias->src[0] == ffn_gate_bias_src || ffn_gate_bias->src[1] == ffn_gate_bias_src;
const bool up_has_mul = ffn_up_bias->src[0] == ffn_up || ffn_up_bias->src[1] == ffn_up;
const bool gate_has_mul = ffn_gate_bias->src[0] == ffn_gate || ffn_gate_bias->src[1] == ffn_gate;
if (!up_has_mul || !gate_has_mul) {
return false;
}
} else { // GGML_OP_ADD_ID
if (ffn_up_bias->src[0] != ffn_up_bias_src || ffn_gate_bias->src[0] != ffn_gate_bias_src) {
if (ffn_up_bias->src[0] != ffn_up || ffn_gate_bias->src[0] != ffn_gate) {
return false;
}
if (ffn_up_bias->src[2] != ffn_up->src[2] || ffn_gate_bias->src[2] != ffn_gate->src[2]) {
@@ -153,7 +148,7 @@ static bool ggml_cuda_should_fuse_mul_mat_vec_f(const ggml_tensor * tensor, cons
return use_mul_mat_vec_f;
}
static bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor) {
bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor) {
ggml_tensor * src0 = tensor->src[0];
ggml_tensor * src1 = tensor->src[1];
const ggml_tensor * dst = tensor;
@@ -215,6 +210,7 @@ static bool ggml_cuda_match_shared_expert(const ggml_cgraph * graph, int routed_
if (!is_pair(gate, up, routed_idx) || !is_pair(shared_gate, shared_up, shared_idx) ||
!ggml_cuda_should_fuse_mul_mat(up, gate, routed) ||
!ggml_cuda_should_fuse_mul_mat(shared_up, shared_gate, shared) ||
ggml_get_src_scale(up, 0) || ggml_get_src_scale(shared_up, 0) ||
!up->src[0]->buffer ||
!ggml_is_quantized(up->src[0]->type)) {
return false;
@@ -239,50 +235,8 @@ static bool ggml_cuda_match_shared_expert(const ggml_cgraph * graph, int routed_
return true;
}
// The weight scale that scale_node (MUL) applies to the output of mm_node (MUL_MAT), or nullptr.
// Shared by ggml_cuda_try_fuse and graph_optimize so that both accept the same patterns.
static const ggml_tensor * ggml_cuda_get_mul_mat_scale(const ggml_tensor * scale_node, const ggml_tensor * mm_node) {
const bool scale_lhs_mm = scale_node->src[0] == mm_node;
const bool scale_rhs_mm = scale_node->src[1] == mm_node;
if (!scale_lhs_mm && !scale_rhs_mm) {
return nullptr;
}
const ggml_tensor * scale = scale_lhs_mm ? scale_node->src[1] : scale_node->src[0];
if ((mm_node->src[0]->type != GGML_TYPE_NVFP4 && mm_node->src[0]->type != GGML_TYPE_F8_E4M3) || scale_node->type != GGML_TYPE_F32 ||
scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || ggml_nelements(scale) != 1 ||
!ggml_are_same_shape(scale_node, mm_node)) {
return nullptr;
}
return scale;
}
// The same for MUL_MAT_ID with one scale per expert: RESHAPE, REPEAT and GET_ROWS (by the ids) of the scales, then the MUL.
static const ggml_tensor * ggml_cuda_get_mul_mat_id_scale(const ggml_tensor * reshape, const ggml_tensor * repeat, const ggml_tensor * getrows,
const ggml_tensor * scale_node, const ggml_tensor * mm_node) {
if (repeat->src[0] != reshape || getrows->src[0] != repeat || getrows->src[1] != mm_node->src[2]) {
return nullptr;
}
if (!((scale_node->src[0] == mm_node && scale_node->src[1] == getrows) ||
(scale_node->src[0] == getrows && scale_node->src[1] == mm_node))) {
return nullptr;
}
const ggml_tensor * scale = reshape->src[0];
if ((mm_node->src[0]->type != GGML_TYPE_NVFP4 && mm_node->src[0]->type != GGML_TYPE_F8_E4M3) || scale_node->type != GGML_TYPE_F32 ||
scale->type != GGML_TYPE_F32 || !ggml_is_contiguous(scale) || ggml_nelements(scale) != mm_node->src[0]->ne[2] ||
!ggml_are_same_shape(scale_node, mm_node)) {
return nullptr;
}
return scale;
}
// Buffer- and batch-size independent, so graph_optimize produces the same graph topology for every ubatch size (see #29986).
// up_scale/gate_scale: the MUL nodes that apply the NVFP4 weight scales (per tensor or per expert) between the MUL_MATs and the GLU.
static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu, const int device,
const ggml_tensor * up_scale = nullptr, const ggml_tensor * gate_scale = nullptr) {
static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu, const int device) {
const ggml_tensor * x_up = up->src[0];
const ggml_tensor * y = up->src[1];
@@ -296,7 +250,7 @@ static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggm
return false;
}
if (!ggml_cuda_should_fuse_mul_mat(up, gate, glu, nullptr, nullptr, up_scale, gate_scale)) {
if (!ggml_cuda_should_fuse_mul_mat(up, gate, glu)) {
return false;
}
@@ -314,8 +268,7 @@ static bool ggml_cuda_mul_mat_q_fusion_matches(const ggml_tensor * up, const ggm
return turing_mma_available(ggml_cuda_info().devices[device].cc);
}
static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu,
const ggml_tensor * up_scale = nullptr, const ggml_tensor * gate_scale = nullptr) {
static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_tensor * gate, const ggml_tensor * glu) {
// A hinted matmul can be fused, but its unfused path may be faster (e.g. FWHT for GGML_HINT_SRC0_IS_HADAMARD).
if (ggml_get_op_params_i32(up, 1) != GGML_HINT_NONE || ggml_get_op_params_i32(gate, 1) != GGML_HINT_NONE) {
return false;
@@ -327,7 +280,7 @@ static bool ggml_cuda_should_fuse_mul_mat_q(const ggml_tensor * up, const ggml_t
ggml_nbytes(x) != ggml_backend_buffer_get_alloc_size(x->buffer, x) && x->view_src;
};
const int device = ggml_cuda_get_device();
if (!ggml_cuda_mul_mat_q_fusion_matches(up, gate, glu, device, up_scale, gate_scale) || bad_padding_clear(up->src[0]) || bad_padding_clear(gate->src[0])) {
if (!ggml_cuda_mul_mat_q_fusion_matches(up, gate, glu, device) || bad_padding_clear(up->src[0]) || bad_padding_clear(gate->src[0])) {
return false;
}
@@ -1997,6 +1950,9 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
ggml_tensor * node = cgraph->nodes[i];
// a scaled matmul only takes part in the gate/up/GLU fusion, which passes its weight scale on
const bool scaled_mm = (node->op == GGML_OP_MUL_MAT || node->op == GGML_OP_MUL_MAT_ID) && ggml_get_src_scale(node, 0);
if (node->op == GGML_OP_MUL_MAT_ID && cuda_ctx->stream_context().concurrent_events.empty() &&
ggml_cuda_match_shared_expert(cgraph, i, i + 3) &&
ggml_cuda_should_fuse_mul_mat_vec_q(cgraph->nodes[i + 2]->src[1])) {
@@ -2245,220 +2201,10 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
return bias_node->src[1];
};
// gate + glu + up, with optional scale/bias on both lanes.
// gate + glu + up, with optional bias on both lanes.
for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) {
const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID;
if (op == GGML_OP_MUL_MAT) {
for (const bool with_bias : { false, true }) {
const int gate_idx = i;
const int gate_scale_idx = i + 1;
const int gate_bias_idx = with_bias ? i + 2 : -1;
const int up_idx = with_bias ? i + 3 : i + 2;
const int up_scale_idx = up_idx + 1;
const int up_bias_idx = with_bias ? up_idx + 2 : -1;
const int glu_idx = with_bias ? up_idx + 3 : up_idx + 2;
const int out_nodes[] = { glu_idx };
ggml_op ops[7];
if (with_bias) {
ops[0] = op;
ops[1] = GGML_OP_MUL;
ops[2] = bias_op;
ops[3] = op;
ops[4] = GGML_OP_MUL;
ops[5] = bias_op;
ops[6] = GGML_OP_GLU;
} else {
ops[0] = op;
ops[1] = GGML_OP_MUL;
ops[2] = op;
ops[3] = GGML_OP_MUL;
ops[4] = GGML_OP_GLU;
}
const int n_ops = with_bias ? 7 : 5;
if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) ||
!ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) {
continue;
}
ggml_tensor * gate_n = cgraph->nodes[gate_idx];
ggml_tensor * gate_scale_n = cgraph->nodes[gate_scale_idx];
ggml_tensor * gate_out_n = with_bias ? cgraph->nodes[gate_bias_idx] : gate_scale_n;
ggml_tensor * up_n = cgraph->nodes[up_idx];
ggml_tensor * up_scale_n = cgraph->nodes[up_scale_idx];
ggml_tensor * up_out_n = with_bias ? cgraph->nodes[up_bias_idx] : up_scale_n;
const ggml_tensor * glu = cgraph->nodes[glu_idx];
if (!ggml_cuda_should_fuse_mul_mat(up_n, gate_n, glu,
with_bias ? up_out_n : nullptr, with_bias ? gate_out_n : nullptr, up_scale_n, gate_scale_n)) {
continue;
}
const ggml_tensor * gate_scale = ggml_cuda_get_mul_mat_scale(gate_scale_n, gate_n);
const ggml_tensor * up_scale = ggml_cuda_get_mul_mat_scale(up_scale_n, up_n);
if (!gate_scale || !up_scale) {
continue;
}
const ggml_tensor * up_bias = with_bias ? get_bias_tensor(up_out_n, up_scale_n, bias_op) : nullptr;
const ggml_tensor * gate_bias = with_bias ? get_bias_tensor(gate_out_n, gate_scale_n, bias_op) : nullptr;
if (with_bias && (!ggml_are_same_shape(gate_out_n->src[0], gate_out_n->src[1]) ||
!ggml_are_same_shape(up_out_n->src[0], up_out_n->src[1]))) {
continue;
}
const ggml_tensor * src0 = up_n->src[0];
const ggml_tensor * src1 = up_n->src[1];
const ggml_tensor * ids = up_n->src[2];
ggml_cuda_mm_fusion_args_host fusion_data{};
fusion_data.gate = gate_n->src[0];
fusion_data.x_bias = up_bias;
fusion_data.gate_bias = gate_bias;
fusion_data.x_scale = up_scale;
fusion_data.gate_scale = gate_scale;
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) {
ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data);
fused_mul_mat_vec = true;
fused_node_count = n_ops;
break;
}
if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) {
ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data);
fused_mul_mat_vec = true;
fused_node_count = n_ops;
break;
}
if (!with_bias && ggml_cuda_should_fuse_mul_mat_q(up_n, gate_n, glu, up_scale_n, gate_scale_n)) {
fusion_data.prec_src1 = ggml_prec_get_src(up_n, 1);
ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data);
fused_mul_mat_vec = true;
fused_node_count = n_ops;
break;
}
}
if (fused_mul_mat_vec) {
break;
}
} else {
for (const bool with_bias : { false, true }) {
const int gate_idx = i;
const int gate_scale_idx = i + 4;
const int gate_bias_idx = with_bias ? i + 5 : -1;
const int up_idx = with_bias ? i + 6 : i + 5;
const int up_scale_idx = up_idx + 4;
const int up_bias_idx = with_bias ? up_idx + 5 : -1;
const int glu_idx = with_bias ? up_idx + 6 : up_idx + 5;
const int out_nodes[] = { glu_idx };
ggml_op ops[13];
if (with_bias) {
ops[0] = op;
ops[1] = GGML_OP_RESHAPE;
ops[2] = GGML_OP_REPEAT;
ops[3] = GGML_OP_GET_ROWS;
ops[4] = GGML_OP_MUL;
ops[5] = bias_op;
ops[6] = op;
ops[7] = GGML_OP_RESHAPE;
ops[8] = GGML_OP_REPEAT;
ops[9] = GGML_OP_GET_ROWS;
ops[10] = GGML_OP_MUL;
ops[11] = bias_op;
ops[12] = GGML_OP_GLU;
} else {
ops[0] = op;
ops[1] = GGML_OP_RESHAPE;
ops[2] = GGML_OP_REPEAT;
ops[3] = GGML_OP_GET_ROWS;
ops[4] = GGML_OP_MUL;
ops[5] = op;
ops[6] = GGML_OP_RESHAPE;
ops[7] = GGML_OP_REPEAT;
ops[8] = GGML_OP_GET_ROWS;
ops[9] = GGML_OP_MUL;
ops[10] = GGML_OP_GLU;
}
const int n_ops = with_bias ? 13 : 11;
if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) ||
!ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) {
continue;
}
ggml_tensor * gate_n = cgraph->nodes[gate_idx];
ggml_tensor * gate_scale_n = cgraph->nodes[gate_scale_idx];
ggml_tensor * gate_out_n = with_bias ? cgraph->nodes[gate_bias_idx] : gate_scale_n;
ggml_tensor * up_n = cgraph->nodes[up_idx];
ggml_tensor * up_scale_n = cgraph->nodes[up_scale_idx];
ggml_tensor * up_out_n = with_bias ? cgraph->nodes[up_bias_idx] : up_scale_n;
const ggml_tensor * glu = cgraph->nodes[glu_idx];
if (!ggml_cuda_should_fuse_mul_mat(up_n, gate_n, glu,
with_bias ? up_out_n : nullptr, with_bias ? gate_out_n : nullptr, up_scale_n, gate_scale_n)) {
continue;
}
const ggml_tensor * gate_scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[gate_idx + 1], cgraph->nodes[gate_idx + 2],
cgraph->nodes[gate_idx + 3], gate_scale_n, gate_n);
const ggml_tensor * up_scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[up_idx + 1], cgraph->nodes[up_idx + 2],
cgraph->nodes[up_idx + 3], up_scale_n, up_n);
if (!gate_scale || !up_scale) {
continue;
}
const ggml_tensor * up_bias = with_bias ? get_bias_tensor(up_out_n, up_scale_n, bias_op) : nullptr;
const ggml_tensor * gate_bias = with_bias ? get_bias_tensor(gate_out_n, gate_scale_n, bias_op) : nullptr;
const ggml_tensor * src0 = up_n->src[0];
const ggml_tensor * src1 = up_n->src[1];
const ggml_tensor * ids = up_n->src[2];
ggml_cuda_mm_fusion_args_host fusion_data{};
fusion_data.gate = gate_n->src[0];
fusion_data.x_bias = up_bias;
fusion_data.gate_bias = gate_bias;
fusion_data.x_scale = up_scale;
fusion_data.gate_scale = gate_scale;
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) {
ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data);
fused_mul_mat_vec = true;
fused_node_count = n_ops;
break;
}
if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) {
ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data);
fused_mul_mat_vec = true;
fused_node_count = n_ops;
break;
}
if (!with_bias && ggml_cuda_should_fuse_mul_mat_q(up_n, gate_n, glu, up_scale_n, gate_scale_n)) {
fusion_data.prec_src1 = ggml_prec_get_src(up_n, 1);
ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, cgraph->nodes[glu_idx], &fusion_data);
fused_mul_mat_vec = true;
fused_node_count = n_ops;
break;
}
}
if (fused_mul_mat_vec) {
break;
}
}
if (ggml_cuda_can_fuse(cgraph, i, { op, bias_op, op, bias_op, GGML_OP_GLU }, {})) {
ggml_tensor * glu = cgraph->nodes[i + 4];
ggml_tensor * gate_bias_n = glu->src[0];
@@ -2493,15 +2239,17 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
const ggml_tensor * src0 = up_n->src[0];
const ggml_tensor * src1 = up_n->src[1];
const ggml_tensor * ids = up_n->src[2];
const ggml_tensor * ids = op == GGML_OP_MUL_MAT_ID ? up_n->src[2] : nullptr;
if (ggml_cuda_should_fuse_mul_mat_vec_f(up_n, gate_n)) {
ggml_cuda_mm_fusion_args_host fusion_data{};
fusion_data.gate = gate_n->src[0];
fusion_data.x_bias = up_bias_tensor;
fusion_data.gate_bias = gate_bias_tensor;
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
fusion_data.gate = gate_n->src[0];
fusion_data.x_bias = up_bias_tensor;
fusion_data.gate_bias = gate_bias_tensor;
fusion_data.x_scale = ggml_get_src_scale(up_n, 0);
fusion_data.gate_scale = ggml_get_src_scale(gate_n, 0);
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
fused_mul_mat_vec = true;
@@ -2511,11 +2259,13 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
if (ggml_cuda_should_fuse_mul_mat_vec_q(up_n)) {
ggml_cuda_mm_fusion_args_host fusion_data{};
fusion_data.gate = gate_n->src[0];
fusion_data.x_bias = up_bias_tensor;
fusion_data.gate_bias = gate_bias_tensor;
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
fusion_data.gate = gate_n->src[0];
fusion_data.x_bias = up_bias_tensor;
fusion_data.gate_bias = gate_bias_tensor;
fusion_data.x_scale = ggml_get_src_scale(up_n, 0);
fusion_data.gate_scale = ggml_get_src_scale(gate_n, 0);
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
fused_mul_mat_vec = true;
@@ -2536,13 +2286,15 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
const ggml_tensor * src0 = up->src[0];
const ggml_tensor * src1 = up->src[1];
const ggml_tensor * ids = up->src[2];
const ggml_tensor * ids = op == GGML_OP_MUL_MAT_ID ? up->src[2] : nullptr;
if (ggml_cuda_should_fuse_mul_mat_vec_f(up, gate)) {
ggml_cuda_mm_fusion_args_host fusion_data{};
fusion_data.gate = gate->src[0];
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
fusion_data.gate = gate->src[0];
fusion_data.x_scale = ggml_get_src_scale(up, 0);
fusion_data.gate_scale = ggml_get_src_scale(gate, 0);
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
fused_mul_mat_vec = true;
@@ -2552,9 +2304,11 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
if (ggml_cuda_should_fuse_mul_mat_vec_q(up)) {
ggml_cuda_mm_fusion_args_host fusion_data{};
fusion_data.gate = gate->src[0];
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
fusion_data.gate = gate->src[0];
fusion_data.x_scale = ggml_get_src_scale(up, 0);
fusion_data.gate_scale = ggml_get_src_scale(gate, 0);
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
fused_mul_mat_vec = true;
@@ -2564,10 +2318,12 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
if (ggml_cuda_should_fuse_mul_mat_q(up, gate, glu)) {
ggml_cuda_mm_fusion_args_host fusion_data{};
fusion_data.gate = gate->src[0];
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
fusion_data.prec_src1 = ggml_prec_get_src(up, 1);
fusion_data.gate = gate->src[0];
fusion_data.x_scale = ggml_get_src_scale(up, 0);
fusion_data.gate_scale = ggml_get_src_scale(gate, 0);
fusion_data.glu_op = ggml_get_glu_op(glu);
fusion_data.glu_limit = ggml_get_op_params_f32(glu, 3);
fusion_data.prec_src1 = ggml_prec_get_src(up, 1);
ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, glu, &fusion_data);
fused_mul_mat_vec = true;
@@ -2581,126 +2337,8 @@ int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgrap
return fused_node_count - 1;
}
fused_mul_mat_vec = false;
fused_node_count = 0;
// mul_mat + scale + optional bias
for (ggml_op op : { GGML_OP_MUL_MAT, GGML_OP_MUL_MAT_ID }) {
const ggml_op bias_op = op == GGML_OP_MUL_MAT ? GGML_OP_ADD : GGML_OP_ADD_ID;
for (const bool with_bias : { false, true }) {
const int n_ops = op == GGML_OP_MUL_MAT ? (with_bias ? 3 : 2) : (with_bias ? 6 : 5);
const int out_nodes[] = { i + n_ops - 1 };
ggml_op ops[6];
if (op == GGML_OP_MUL_MAT) {
if (with_bias) {
ops[0] = op;
ops[1] = GGML_OP_MUL;
ops[2] = bias_op;
} else {
ops[0] = op;
ops[1] = GGML_OP_MUL;
}
} else {
if (with_bias) {
ops[0] = op;
ops[1] = GGML_OP_RESHAPE;
ops[2] = GGML_OP_REPEAT;
ops[3] = GGML_OP_GET_ROWS;
ops[4] = GGML_OP_MUL;
ops[5] = bias_op;
} else {
ops[0] = op;
ops[1] = GGML_OP_RESHAPE;
ops[2] = GGML_OP_REPEAT;
ops[3] = GGML_OP_GET_ROWS;
ops[4] = GGML_OP_MUL;
}
}
if (!ggml_can_fuse_subgraph(cgraph, i, n_ops, ops, out_nodes, 1) ||
!ggml_cuda_check_fusion_memory_ranges(cgraph, i, n_ops, out_nodes, 1)) {
continue;
}
ggml_tensor * mm_node = cgraph->nodes[i];
ggml_tensor * scale_node = op == GGML_OP_MUL_MAT ? cgraph->nodes[i + 1] : cgraph->nodes[i + 4];
ggml_tensor * out_node = with_bias ? cgraph->nodes[i + n_ops - 1] : scale_node;
const ggml_tensor * scale = nullptr;
if (op == GGML_OP_MUL_MAT) {
scale = ggml_cuda_get_mul_mat_scale(scale_node, mm_node);
} else {
scale = ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 3], scale_node, mm_node);
}
if (!scale) {
continue;
}
const ggml_tensor * bias = with_bias ? get_bias_tensor(out_node, scale_node, bias_op) : nullptr;
if (with_bias && !bias) {
continue;
}
if (with_bias && bias_op == GGML_OP_ADD && !ggml_are_same_shape(out_node->src[0], out_node->src[1])) {
continue;
}
if (with_bias && bias_op == GGML_OP_ADD_ID && out_node->src[2] != mm_node->src[2]) {
continue;
}
const ggml_tensor * src0 = mm_node->src[0];
const ggml_tensor * src1 = mm_node->src[1];
const ggml_tensor * ids = mm_node->src[2];
ggml_cuda_mm_fusion_args_host fusion_data{};
fusion_data.x_bias = bias;
fusion_data.x_scale = scale;
if (ggml_cuda_should_fuse_mul_mat_vec_f(mm_node)) {
ggml_cuda_mul_mat_vec_f(*cuda_ctx, src0, src1, ids, out_node, &fusion_data);
fused_mul_mat_vec = true;
fused_node_count = n_ops;
break;
}
if (op == GGML_OP_MUL_MAT && !with_bias && src0->type == GGML_TYPE_F8_E4M3 &&
ggml_get_op_params_i32(mm_node, 3) != GGML_PREC_F32 &&
ggml_cuda_mul_mat_fp8(*cuda_ctx, src0, src1, scale_node, scale)) {
return 1;
}
if (!with_bias && src0->type == GGML_TYPE_NVFP4 && (src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16) &&
mm_node->type == GGML_TYPE_F32) {
const int cc = ggml_cuda_info().devices[cuda_ctx->device].cc;
const bool is_id = op == GGML_OP_MUL_MAT_ID;
const int64_t ncols = is_id ? src1->ne[2] : src1->ne[1];
const bool use_mmvq = is_id ? ncols <= get_mmvq_mmid_max_batch(src0->type, cc) :
ggml_cuda_should_use_mmvq(src0->type, cc, ncols);
const bool bad_padding_clear = ggml_backend_buffer_get_usage(src0->buffer) == GGML_BACKEND_BUFFER_USAGE_COMPUTE &&
ggml_nbytes(src0) != ggml_backend_buffer_get_alloc_size(src0->buffer, src0) &&
src0->view_src;
if (!use_mmvq && !bad_padding_clear &&
ggml_cuda_should_use_mmq(src0->type, cc, ncols, /*n_experts =*/ is_id ? src0->ne[2] : 0)) {
fusion_data.prec_src1 = ggml_prec_get_src(mm_node, 1);
ggml_cuda_mul_mat_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data);
return n_ops - 1;
}
}
if (ggml_cuda_should_fuse_mul_mat_vec_q(mm_node)) {
ggml_cuda_mul_mat_vec_q(*cuda_ctx, src0, src1, ids, out_node, &fusion_data);
fused_mul_mat_vec = true;
fused_node_count = n_ops;
break;
}
}
if (fused_mul_mat_vec) {
break;
}
}
if (fused_mul_mat_vec) {
return fused_node_count - 1;
if (scaled_mm) {
return 0;
}
// mul_mat + add
@@ -2882,33 +2520,6 @@ void ggml_cuda_fusion_add_alloc_deps(ggml_backend_cuda_context * cuda_ctx, ggml_
continue;
}
}
// Same with the NVFP4 scales: MUL_MAT(gate), MUL(gate scale), MUL_MAT(up), MUL(up scale), GLU.
if (i + 4 < cgraph->n_nodes && cgraph->nodes[i + 4]->op == GGML_OP_GLU) {
ggml_tensor * glu = cgraph->nodes[i + 4];
ggml_tensor * gate_scale = cgraph->nodes[i + 1];
ggml_tensor * up_scale = cgraph->nodes[i + 3];
if (glu->src[0] == gate_scale && glu->src[1] == up_scale &&
ggml_cuda_mul_mat_q_fusion_matches(cgraph->nodes[i + 2], cgraph->nodes[i], glu, cuda_ctx->device, up_scale, gate_scale) &&
ggml_cuda_get_mul_mat_scale(gate_scale, cgraph->nodes[i]) && ggml_cuda_get_mul_mat_scale(up_scale, cgraph->nodes[i + 2])) {
add_alloc_deps(i, i + 4);
i += 4;
continue;
}
}
// Same with per-expert NVFP4 scales: MUL_MAT_ID, RESHAPE, REPEAT, GET_ROWS, MUL for gate and for up, GLU.
if (i + 10 < cgraph->n_nodes && cgraph->nodes[i + 10]->op == GGML_OP_GLU) {
ggml_tensor * glu = cgraph->nodes[i + 10];
ggml_tensor * gate_scale = cgraph->nodes[i + 4];
ggml_tensor * up_scale = cgraph->nodes[i + 9];
if (glu->src[0] == gate_scale && glu->src[1] == up_scale &&
ggml_cuda_mul_mat_q_fusion_matches(cgraph->nodes[i + 5], cgraph->nodes[i], glu, cuda_ctx->device, up_scale, gate_scale) &&
ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 1], cgraph->nodes[i + 2], cgraph->nodes[i + 3], gate_scale, cgraph->nodes[i]) &&
ggml_cuda_get_mul_mat_id_scale(cgraph->nodes[i + 6], cgraph->nodes[i + 7], cgraph->nodes[i + 8], up_scale, cgraph->nodes[i + 5])) {
add_alloc_deps(i, i + 10);
i += 10;
continue;
}
}
ggml_cuda_moe_weighted_reduction_match match;
if (ggml_cuda_match_moe_weighted_reduction(cgraph, i, match)) {
+3
View File
@@ -3,6 +3,9 @@
#include "common.cuh"
#include "ggml-backend-impl.h"
// whether a mat-vec node can use the fused MMVQ path
bool ggml_cuda_should_fuse_mul_mat_vec_q(const ggml_tensor * tensor);
// try and fuse nodes starting at node i and return the number of nodes to skip
int ggml_cuda_try_fuse(ggml_backend_cuda_context * cuda_ctx, ggml_cgraph * cgraph, int i);
+139 -35
View File
@@ -404,6 +404,7 @@ static ggml_cuda_device_info ggml_cuda_init() {
info.default_tensor_split[id] = total_vram;
total_vram += device_vram;
info.devices[id].integrated = false; // Temporarily disabled due to issues with corrupted output (e.g. #15034)
info.devices[id].type = prop.integrated ? GGML_BACKEND_DEVICE_TYPE_IGPU : GGML_BACKEND_DEVICE_TYPE_GPU;
info.devices[id].nsm = prop.multiProcessorCount;
info.devices[id].smpb = prop.sharedMemPerBlock;
info.devices[id].warp_size = prop.warpSize;
@@ -2123,7 +2124,7 @@ static void ggml_cuda_mul_mat_cublas(ggml_backend_cuda_context & ctx, const ggml
const int cc = ggml_cuda_info().devices[ctx.device].cc;
const ggml_prec prec = ggml_prec_get_acc(dst);
ggml_type compute_type = src0->type;
if (ggml_is_quantized(compute_type) || compute_type == GGML_TYPE_F8_E4M3) {
if (ggml_is_quantized(compute_type) || ggml_needs_scale(compute_type)) {
compute_type = fast_fp16_hardware_available(cc) ? GGML_TYPE_F16 : GGML_TYPE_F32;
if (ggml_cuda_info().devices[ctx.device].prefer_fp32_acc) {
compute_type = GGML_TYPE_BF16;
@@ -2203,11 +2204,22 @@ static void ggml_cuda_mul_mat_cublas(ggml_backend_cuda_context & ctx, const ggml
}
}
static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
// returns true if a scaled matmul applied its weight scale in-kernel (mmvq/mmq epilogue or cuBLASLt fp8 fold),
// so the caller can skip the separate ggml_cuda_op_mul_mat_scale pass
static bool ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
GGML_TENSOR_BINARY_OP_LOCALS
if (ggml_cuda_op_mul_mat_use_fwht(dst) && ggml_cuda_op_fwht(ctx, src1, dst)) {
return;
return false;
}
// mmvq and mmq can fold the weight scale (src[2]) into their epilogue for NVFP4 per-tensor scales
const bool scale_fold = ggml_get_src_scale(dst, 0) != NULL &&
src0->type == GGML_TYPE_NVFP4 && ggml_nelements(ggml_get_src_scale(dst, 0)) == 1;
ggml_cuda_mm_fusion_args_host fusion = {};
if (scale_fold) {
fusion.x_scale = ggml_get_src_scale(dst, 0);
fusion.prec_src1 = ggml_prec_get_src(dst, 1);
}
// If src0 is a temporary compute buffer it may have some padding that needs to be cleared for mul_mat_vec_q or mul_mat_q.
@@ -2218,7 +2230,7 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor
// MMVQ, MMQ and MMVF (BF16 and FP8 weights) also read a BF16 src1, MMF only an F32 src1
if (bad_padding_clear || (src1->type != GGML_TYPE_F32 && src1->type != GGML_TYPE_BF16) || dst->type != GGML_TYPE_F32) {
ggml_cuda_mul_mat_cublas(ctx, src0, src1, dst);
return;
return false;
}
const int cc = ggml_cuda_info().devices[ctx.device].cc;
@@ -2228,7 +2240,7 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor
// The custom vector kernel can be used over batched cuBLAS GEMM.
// But this is only faster for GPUs without tensor cores or with a thin src0 matrix (particularly KQV in attention)
ggml_cuda_mul_mat_vec_f(ctx, src0, src1, nullptr, dst);
return;
return false;
}
// A transposed vector can still use MMVF (i.e. ne01 == 1)
if (ne01 == 1 && ne11 > MMVF_MAX_BATCH_SIZE && ne2 == 1 && ne3 == 1
@@ -2242,30 +2254,36 @@ static void ggml_cuda_mul_mat(ggml_backend_cuda_context & ctx, const ggml_tensor
dst_vec.nb[2] = dst_vec.nb[1];
dst_vec.nb[3] = dst_vec.nb[1];
ggml_cuda_mul_mat_vec_f(ctx, src1, src0, nullptr, &dst_vec);
return;
return false;
}
if (src1->type == GGML_TYPE_F32 && ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, ne11, /*mul_mat_id =*/ false)) {
ggml_cuda_mul_mat_f(ctx, src0, src1, nullptr, dst);
return;
return false;
}
// from a per-type number of src1 columns up to 24, few-row MMQ is faster than MMVQ and MMQ
const bool use_mmq_few = ggml_cuda_should_use_mmq_few(src0, src1, nullptr, cc);
if (!use_mmq_few && ggml_cuda_should_use_mmvq(src0->type, cc, ne11)) {
ggml_cuda_mul_mat_vec_q(ctx, src0, src1, nullptr, dst);
return;
const bool fold = scale_fold && ggml_cuda_should_fuse_mul_mat_vec_q(dst);
ggml_cuda_mul_mat_vec_q(ctx, src0, src1, nullptr, dst, fold ? &fusion : nullptr);
return fold;
}
if (use_mmq_few) {
ggml_cuda_mul_mat_q_few(ctx, src0, src1, nullptr, dst);
return;
return false;
}
if (ggml_cuda_should_use_mmq(src0->type, cc, ne11, /*n_experts =*/ 0)) {
ggml_cuda_mul_mat_q(ctx, src0, src1, nullptr, dst);
return;
ggml_cuda_mul_mat_q(ctx, src0, src1, nullptr, dst, scale_fold ? &fusion : nullptr);
return scale_fold;
}
if (src0->type == GGML_TYPE_F8_E4M3 && ggml_cuda_mul_mat_fp8(ctx, src0, src1, dst)) {
return;
if (src0->type == GGML_TYPE_F8_E4M3 && ggml_prec_get_acc(dst) != GGML_PREC_F32) {
const ggml_tensor * w_scale = ggml_get_src_scale(dst, 0);
const ggml_tensor * weight_scale = w_scale && ggml_nelements(w_scale) == 1 ? w_scale : nullptr;
if (ggml_cuda_mul_mat_fp8(ctx, src0, src1, dst, weight_scale)) {
return weight_scale != nullptr;
}
}
ggml_cuda_mul_mat_cublas(ctx, src0, src1, dst);
return false;
}
// returns true when ggml_cuda_mul_mat_id takes the fallback path that requires stream synchronization
@@ -2304,7 +2322,8 @@ static bool ggml_cuda_mul_mat_id_needs_sync(const ggml_tensor * dst, const int c
return true;
}
static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
// returns true if a scaled matmul applied its weight scale in-kernel (mmvq/mmq epilogue fold)
static bool ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const ggml_tensor * src0 = dst->src[0];
const ggml_tensor * src1 = dst->src[1];
const ggml_tensor * ids = dst->src[2];
@@ -2317,6 +2336,16 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *
const int cc = ggml_cuda_info().devices[ggml_cuda_get_device()].cc;
const int warp_size = ggml_cuda_info().devices[ggml_cuda_get_device()].warp_size;
// mmvq and mmq can fold the per-expert weight scale (src[3]) into their epilogue for NVFP4
const bool scale_fold = ggml_get_src_scale(dst, 0) != NULL &&
src0->type == GGML_TYPE_NVFP4 && ggml_nelements(ggml_get_src_scale(dst, 0)) == src0->ne[2] &&
ggml_is_contiguous(ggml_get_src_scale(dst, 0));
ggml_cuda_mm_fusion_args_host fusion = {};
if (scale_fold) {
fusion.x_scale = ggml_get_src_scale(dst, 0);
fusion.prec_src1 = ggml_prec_get_src(dst, 1);
}
// [TAG_MUL_MAT_ID_CUDA_GRAPHS]
if ((src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_BF16) && dst->type == GGML_TYPE_F32) {
// up to 24 tokens few-row MMQ is faster than MMQ, on DGX Spark also faster than MMVQ
@@ -2327,28 +2356,29 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *
if (ggml_is_quantized(src0->type)) {
const int mmvq_mmid_max = get_mmvq_mmid_max_batch(src0->type, cc);
if (ne2 <= mmvq_mmid_max) {
ggml_cuda_mul_mat_vec_q(ctx, src0, src1, ids, dst);
return;
const bool fold = scale_fold && ggml_cuda_should_fuse_mul_mat_vec_q(dst);
ggml_cuda_mul_mat_vec_q(ctx, src0, src1, ids, dst, fold ? &fusion : nullptr);
return fold;
}
} else if (ggml_cuda_should_use_mmvf(src0, src1->type, cc, warp_size, ne2, /*mul_mat_id =*/ true)) {
ggml_cuda_mul_mat_vec_f(ctx, src0, src1, ids, dst);
return;
return false;
}
}
if (use_mmq_few) {
ggml_cuda_mul_mat_q_few(ctx, src0, src1, ids, dst);
return;
return false;
}
if (ggml_cuda_should_use_mmq(src0->type, cc, ne12, /*n_experts=*/ne02)) {
ggml_cuda_mul_mat_q(ctx, src0, src1, ids, dst);
return;
ggml_cuda_mul_mat_q(ctx, src0, src1, ids, dst, scale_fold ? &fusion : nullptr);
return scale_fold;
}
if (src1->type == GGML_TYPE_F32 && ggml_cuda_should_use_mmf(src0->type, cc, warp_size, src0->ne, src0->nb, src1->ne[2], /*mul_mat_id=*/true)) {
ggml_cuda_mul_mat_f(ctx, src0, src1, ids, dst);
return;
return false;
}
}
@@ -2360,7 +2390,7 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *
GGML_ASSERT(nb2 % nb1 == 0);
const ggml_type type_src1_sorted = (src0->type == GGML_TYPE_F16 && !fast_fp16_hardware_available(cc))
|| ggml_is_quantized(src0->type) || src0->type == GGML_TYPE_F8_E4M3 ? GGML_TYPE_F32 : src0->type;
|| ggml_is_quantized(src0->type) || ggml_needs_scale(src0->type) ? GGML_TYPE_F32 : src0->type;
const ggml_type type_dst_sorted = GGML_TYPE_F32;
const size_t ts_src1_sorted = ggml_type_size(type_src1_sorted);
const size_t ts_dst_sorted = ggml_type_size(type_dst_sorted);
@@ -2469,6 +2499,79 @@ static void ggml_cuda_mul_mat_id(ggml_backend_cuda_context & ctx, ggml_tensor *
ne0, ne0*ts_dst_sorted, ne_get_rows*ne0*ts_dst_sorted, ne_get_rows*ne0*ts_dst_sorted,
ne_get_rows, 1, 1, sizeof(int32_t), ne_get_rows*sizeof(int32_t), ne_get_rows*sizeof(int32_t),
nb1, nb2, nb3, stream);
return false;
}
// epilogue for a scaled MUL_MAT/MUL_MAT_ID (weight scale in src[2] dense / src[3] id)
#define CUDA_MUL_MAT_SCALE_BLOCK_SIZE 256
static __global__ void mul_mat_scale_dense(float * dst, const float * scale,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ne3,
int64_t sne0, int64_t sne1, int64_t sne2, int64_t sne3,
size_t snb0, size_t snb1, size_t snb2, size_t snb3) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= ne0*ne1*ne2*ne3) {
return;
}
const int64_t i0 = i % ne0;
const int64_t i1 = (i / ne0) % ne1;
const int64_t i2 = (i / (ne0*ne1)) % ne2;
const int64_t i3 = i / (ne0*ne1*ne2);
const size_t si = (i0 % sne0)*snb0 + (i1 % sne1)*snb1 + (i2 % sne2)*snb2 + (i3 % sne3)*snb3;
dst[i] *= *(const float *) ((const char *) scale + si);
}
// strides are in bytes; channel_stride is zero for per-expert scalar scales
static __global__ void mul_mat_scale_id(float * dst, const float * scale, const int32_t * ids,
int64_t ne0, int64_t ne1, int64_t ne2, int64_t ids_s0, int64_t ids_s1,
size_t channel_stride, size_t expert_stride) {
const int64_t i = (int64_t) blockIdx.x * blockDim.x + threadIdx.x;
if (i >= ne0*ne1*ne2) {
return;
}
const int64_t i0 = i % ne0;
const int64_t i1 = (i / ne0) % ne1;
const int64_t i2 = i / (ne0*ne1);
const int64_t expert = ids[i1*ids_s0 + i2*ids_s1];
if (expert < 0) {
return;
}
dst[i] *= *(const float *) ((const char *) scale + i0*channel_stride + expert*expert_stride);
}
static void ggml_cuda_op_mul_mat_scale(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
const bool is_id = dst->op == GGML_OP_MUL_MAT_ID;
const ggml_tensor * scale = ggml_get_src_scale(dst, 0);
GGML_ASSERT(scale != NULL && scale->type == GGML_TYPE_F32);
GGML_ASSERT(ggml_is_contiguous(dst));
float * dst_d = (float *) dst->data;
const float * scale_d = (const float *) scale->data;
cudaStream_t stream = ctx.stream();
const int64_t ne0 = dst->ne[0], ne1 = dst->ne[1], ne2 = dst->ne[2], ne3 = dst->ne[3];
// per-expert scale is indexed through ids (scalar [n_expert] or 2D per-channel [n_out, n_expert]);
// per-tensor / dense scale is a plain broadcast
const bool per_channel_expert = is_id && scale->ne[0] == ne0 && scale->ne[1] == dst->src[0]->ne[2];
const bool per_expert = is_id && (ggml_nelements(scale) == dst->src[0]->ne[2] || per_channel_expert);
if (per_expert) {
const ggml_tensor * ids = dst->src[2];
const int64_t total = ne0*ne1*ne2;
const int64_t blocks = (total + CUDA_MUL_MAT_SCALE_BLOCK_SIZE - 1) / CUDA_MUL_MAT_SCALE_BLOCK_SIZE;
mul_mat_scale_id<<<blocks, CUDA_MUL_MAT_SCALE_BLOCK_SIZE, 0, stream>>>(
dst_d, scale_d, (const int32_t *) ids->data, ne0, ne1, ne2,
ids->nb[0]/sizeof(int32_t), ids->nb[1]/sizeof(int32_t),
per_channel_expert ? scale->nb[0] : 0, per_channel_expert ? scale->nb[1] : scale->nb[0]);
} else {
const int64_t total = ne0*ne1*ne2*ne3;
const int64_t blocks = (total + CUDA_MUL_MAT_SCALE_BLOCK_SIZE - 1) / CUDA_MUL_MAT_SCALE_BLOCK_SIZE;
mul_mat_scale_dense<<<blocks, CUDA_MUL_MAT_SCALE_BLOCK_SIZE, 0, stream>>>(
dst_d, scale_d, ne0, ne1, ne2, ne3,
scale->ne[0], scale->ne[1], scale->ne[2], scale->ne[3],
scale->nb[0], scale->nb[1], scale->nb[2], scale->nb[3]);
}
CUDA_CHECK(cudaGetLastError());
}
static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct ggml_tensor * dst) {
@@ -2662,12 +2765,18 @@ static bool ggml_cuda_compute_forward(ggml_backend_cuda_context & ctx, struct gg
case GGML_OP_RMS_NORM_BACK:
ggml_cuda_op_rms_norm_back(ctx, dst);
break;
case GGML_OP_MUL_MAT:
ggml_cuda_mul_mat(ctx, dst->src[0], dst->src[1], dst);
break;
case GGML_OP_MUL_MAT_ID:
ggml_cuda_mul_mat_id(ctx, dst);
break;
case GGML_OP_MUL_MAT: {
const bool scale_folded = ggml_cuda_mul_mat(ctx, dst->src[0], dst->src[1], dst);
if (ggml_get_src_scale(dst, 0) != NULL && !scale_folded) {
ggml_cuda_op_mul_mat_scale(ctx, dst);
}
} break;
case GGML_OP_MUL_MAT_ID: {
const bool scale_folded = ggml_cuda_mul_mat_id(ctx, dst);
if (ggml_get_src_scale(dst, 0) != NULL && !scale_folded) {
ggml_cuda_op_mul_mat_scale(ctx, dst);
}
} break;
case GGML_OP_OUT_PROD:
ggml_cuda_out_prod(ctx, dst);
break;
@@ -3988,12 +4097,7 @@ static void ggml_backend_cuda_device_get_memory(ggml_backend_dev_t dev, size_t *
static enum ggml_backend_dev_type ggml_backend_cuda_device_get_type(ggml_backend_dev_t dev) {
ggml_backend_cuda_device_context * ctx = (ggml_backend_cuda_device_context *) dev->context;
cudaDeviceProp prop;
CUDA_CHECK(cudaGetDeviceProperties(&prop, ggml_cuda_get_physical_device(ctx->device)));
return prop.integrated
? GGML_BACKEND_DEVICE_TYPE_IGPU
: GGML_BACKEND_DEVICE_TYPE_GPU;
return ggml_cuda_info().devices[ctx->device].type;
}
static void ggml_backend_cuda_device_get_props(ggml_backend_dev_t dev, ggml_backend_dev_props * props) {
+4 -4
View File
@@ -169,7 +169,7 @@ void ggml_cuda_mul_mat_q(
GGML_ASSERT(!ids || ids->type == GGML_TYPE_I32); // Optional, used for batched GGML_MUL_MAT_ID.
// Fused gate/up/GLU: src0 is the up weight, dst the GLU output.
// Fused scale (no gate): dst is the MUL that applies the weight scale to the MUL_MAT.
// Fused scale (no gate): dst is the MUL_MAT whose attached weight scale is applied.
const ggml_tensor * gate = fusion ? fusion->gate : nullptr;
ggml_cuda_mm_fusion_args_device fusion_device = {};
if (fusion) {
@@ -236,7 +236,7 @@ void ggml_cuda_mul_mat_q(
const bool fallback = ggml_cuda_mmq_needs_fallback(ne01);
// With fusion dst is the GLU output or the scale node, not a MUL_MAT; the src1 precision requested by the fused MUL_MATs is in the fusion args.
// With fusion dst can be the GLU output, not a MUL_MAT; the src1 precision requested by the fused MUL_MATs is in the fusion args.
const ggml_prec prec_src1 = ggml_cuda_mmq_get_prec_src1(src0->type, fusion ? fusion->prec_src1 : ggml_prec_get_src(dst, 1), cc);
const bool use_native_fp4 = prec_src1 == GGML_PREC_Q4;
@@ -272,7 +272,7 @@ void ggml_cuda_mul_mat_q(
ggml_cuda_pool_alloc<char> src1_q8_1(ctx.pool(), nbytes_src1_q8_1);
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool());
if (src0->type == GGML_TYPE_NVFP4 && use_native_fp4) {
src1_scale.alloc(ne13*ne12*ne11);
src1_scale.alloc(ne13*ne12*ne11 + J_best-1); // Needs to be padded for unconditional memory access.
}
{
@@ -342,7 +342,7 @@ void ggml_cuda_mul_mat_q(
ggml_cuda_pool_alloc<char> src1_q8_1(ctx.pool(), nbytes_src1_q8_1);
ggml_cuda_pool_alloc<float> src1_scale(ctx.pool());
if (src0->type == GGML_TYPE_NVFP4 && use_native_fp4) {
src1_scale.alloc(ne12*n_expert_used);
src1_scale.alloc(ne12*n_expert_used + J_best-1); // Needs to be padded for unconditional memory access.
}
const int64_t ne11_flat = ne12*n_expert_used;
+2 -2
View File
@@ -467,7 +467,7 @@ template <ggml_type type, int J, bool fallback, ggml_prec prec_src1> static __de
const ggml_glu_op glu_op, const float glu_limit, const float * __restrict__ x_scale, const float * __restrict__ gate_scale) {
GGML_UNUSED_VARS(glu_op, glu_limit, gate_scale);
// NVFP4 weight scale of a fused MUL (per tensor, or of the expert of this tile), 1 without.
// NVFP4 weight scale (per tensor, or of the expert of this tile), 1 without.
const float scale = type == GGML_TYPE_NVFP4 && x_scale ? *x_scale : 1.0f;
constexpr int warp_size = ggml_cuda_get_physical_warp_size();
@@ -528,7 +528,7 @@ static __device__ __forceinline__ void ggml_cuda_mmq_write_back_mma(
const bool y_scale_used = type == GGML_TYPE_NVFP4 && y_scale != nullptr;
// NVFP4: load the weight scales once, 1 without scales. Without fusion x_scale is the scale of a fused MUL.
// NVFP4: load the weight scales once, 1 without scales. Without fusion x_scale is the weight scale attached to the MUL_MAT.
constexpr bool fused_nvfp4 = has_fusion && type == GGML_TYPE_NVFP4;
const float scale_up = type == GGML_TYPE_NVFP4 && x_scale ? *x_scale : 1.0f;
const float scale_gate = fused_nvfp4 && gate_scale ? *gate_scale : 1.0f;
+4
View File
@@ -868,6 +868,10 @@ static bool et_ggml_is_row_contiguous(const ggml_tensor * t) {
static bool ggml_backend_et_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
GGML_UNUSED(dev);
if (ggml_get_src_scale(op, 0)) {
return false;
}
bool supported = false;
switch (op->op) {
case GGML_OP_CUMSUM:
+4
View File
@@ -3233,6 +3233,10 @@ static bool ggml_backend_hexagon_device_supports_op(ggml_backend_dev_t dev, cons
return false;
}
if (ggml_get_src_scale(op, 0)) {
return false;
}
bool supp = false;
if (ggml_op_is_empty(op->op) || ggml_is_empty(op)) {
supp = true;
+10
View File
@@ -104,6 +104,16 @@ static inline bool ggml_impl_is_view(const struct ggml_tensor * t) {
return t->view_src != NULL;
}
// scale of src[i] set by ggml_mul_mat_ext / ggml_mul_mat_id_ext
static inline const struct ggml_tensor * ggml_get_src_scale(const struct ggml_tensor * op, int i) {
GGML_ASSERT(i == 0 || i == 1);
switch (op->op) {
case GGML_OP_MUL_MAT: return op->src[2 + i];
case GGML_OP_MUL_MAT_ID: return op->src[3 + i];
default: return NULL;
}
}
static inline float ggml_compute_softplus_f32(float input) {
return (input > 20.0f) ? input : log1pf(expf(input));
}
+11
View File
@@ -97,6 +97,17 @@ ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cpy(ggml_metal_l
return res;
}
ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mat_scale(ggml_metal_library_t lib) {
const char * name = "kernel_mul_mat_scale";
ggml_metal_pipeline_with_params res = ggml_metal_library_get_pipeline(lib, name);
if (!res.pipeline) {
res = ggml_metal_library_compile_pipeline(lib, name, name, nullptr);
}
return res;
}
ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_1d(ggml_metal_library_t lib, const ggml_tensor * op, ggml_op_pool op_pool) {
GGML_ASSERT(ggml_is_contiguous(op->src[0]));
GGML_ASSERT(op->src[0]->type == GGML_TYPE_F32 && op->src[0]->type == op->type);
+1
View File
@@ -109,6 +109,7 @@ struct ggml_metal_pipeline_with_params ggml_metal_library_compile_pipeline(ggml_
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_base (ggml_metal_library_t lib, enum ggml_op op);
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_cpy (ggml_metal_library_t lib, enum ggml_type tsrc, enum ggml_type tdst);
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_mul_mat_scale (ggml_metal_library_t lib);
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_1d (ggml_metal_library_t lib, const struct ggml_tensor * op, enum ggml_op_pool op_pool);
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_pool_2d (ggml_metal_library_t lib, const struct ggml_tensor * op, enum ggml_op_pool op_pool);
struct ggml_metal_pipeline_with_params ggml_metal_library_get_pipeline_get_rows (ggml_metal_library_t lib, enum ggml_type tsrc);
@@ -4,6 +4,7 @@
#include "ggml-metal-device.h"
#include "ggml-backend-impl.h"
#include "ggml-impl.h"
#include <algorithm>
#include <cstddef>
@@ -792,6 +793,10 @@ static bool ggml_metal_fusion_check_mul_mat_add(
const ggml_tensor * mm = nodes[0];
const ggml_tensor * add = nodes[1];
if (ggml_get_src_scale(mm, 0) != nullptr) {
return false;
}
if (ggml_metal_mul_mat_add_operand(mm, add) == nullptr ||
!ggml_metal_op_mul_mat_may_use_mma(mm)) {
return false;
+13
View File
@@ -290,6 +290,19 @@ typedef struct {
size_t nb21;
} ggml_metal_kargs_add_id;
typedef struct {
int64_t ne0;
int64_t ne2;
uint64_t nb1;
uint64_t nb2;
uint64_t nb3;
uint64_t s_nb0;
uint64_t s_nb1;
uint64_t ids_nb0;
uint64_t ids_nb1;
int32_t use_ids;
} ggml_metal_kargs_mul_mat_scale;
typedef struct {
int32_t ne00;
int32_t ne01;
+61 -2
View File
@@ -236,8 +236,13 @@ static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) {
int n_fuse = 1;
const ggml_metal_fusion * fusion = ctx->can_fuse(idx, GGML_METAL_FUSION_FULL, &n_fuse);
if (fusion) {
// fused kernels write to the last node of the group, not necessarily to the first node's dst
is_concurrent = ggml_mem_ranges_check(ctx->mem_ranges, ctx->node(idx + n_fuse - 1));
// every node of the group contributes sources and destinations, check all of them
for (int j = 0; j < n_fuse; ++j) {
if (!ggml_mem_ranges_check(ctx->mem_ranges, ctx->node(idx + j))) {
is_concurrent = false;
break;
}
}
}
}
@@ -383,10 +388,12 @@ static int ggml_metal_op_encode_impl(ggml_metal_op_t ctx, int idx) {
case GGML_OP_MUL_MAT:
{
n_fuse = ggml_metal_op_mul_mat(ctx, idx);
ggml_metal_op_mul_mat_scale(ctx, idx);
} break;
case GGML_OP_MUL_MAT_ID:
{
n_fuse = ggml_metal_op_mul_mat_id(ctx, idx);
ggml_metal_op_mul_mat_scale(ctx, idx);
} break;
case GGML_OP_GET_ROWS:
{
@@ -3218,6 +3225,58 @@ int ggml_metal_op_add_id(ggml_metal_op_t ctx, int idx) {
return 1;
}
int ggml_metal_op_mul_mat_scale(ggml_metal_op_t ctx, int idx) {
ggml_tensor * op = ctx->node(idx);
const ggml_tensor * scale = ggml_get_src_scale(op, 0);
if (scale == nullptr) {
return 1;
}
ggml_metal_library_t lib = ctx->lib;
ggml_metal_encoder_t enc = ctx->enc;
GGML_ASSERT(scale->type == GGML_TYPE_F32);
GGML_ASSERT(op->type == GGML_TYPE_F32);
GGML_ASSERT(ggml_is_contiguous_rows(op));
const ggml_tensor * src0 = op->src[0];
const ggml_tensor * ids = op->op == GGML_OP_MUL_MAT_ID ? op->src[2] : nullptr;
const bool per_channel_expert = ids && scale->ne[0] == op->ne[0] && scale->ne[1] == src0->ne[2];
const bool per_expert = ids && (ggml_nelements(scale) == src0->ne[2] || per_channel_expert);
const bool per_channel = per_expert ? per_channel_expert : scale->ne[0] == op->ne[0] && ggml_nelements(scale) > 1;
ggml_metal_kargs_mul_mat_scale args = {
/*.ne0 =*/ op->ne[0],
/*.ne2 =*/ op->ne[2],
/*.nb1 =*/ op->nb[1],
/*.nb2 =*/ op->nb[2],
/*.nb3 =*/ op->nb[3],
/*.s_nb0 =*/ per_channel ? scale->nb[0] : 0,
/*.s_nb1 =*/ per_expert ? (per_channel_expert ? scale->nb[1] : scale->nb[0]) : 0,
/*.ids_nb0 =*/ per_expert ? ids->nb[0] : 0,
/*.ids_nb1 =*/ per_expert ? ids->nb[1] : 0,
/*.use_ids =*/ per_expert,
};
ggml_metal_op_concurrency_reset(ctx);
auto pipeline = ggml_metal_library_get_pipeline_mul_mat_scale(lib);
ggml_metal_encoder_set_pipeline(enc, pipeline);
ggml_metal_encoder_set_bytes (enc, &args, sizeof(args), 0);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(scale), 1);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(per_expert ? ids : scale), 2);
ggml_metal_encoder_set_buffer (enc, ggml_metal_get_buffer_id(op), 3);
const int nth = std::min<int64_t>(ggml_metal_pipeline_max_theads_per_threadgroup(pipeline), op->ne[0]);
ggml_metal_encoder_dispatch_threadgroups(enc, op->ne[1], op->ne[2]*op->ne[3], 1, nth, 1, 1);
return 1;
}
bool ggml_metal_op_flash_attn_ext_use_vec(const ggml_tensor * op) {
assert(op->op == GGML_OP_FLASH_ATTN_EXT);
+1
View File
@@ -83,6 +83,7 @@ int ggml_metal_op_pool_2d (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_fwht (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat_id (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_mul_mat_scale (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_add_id (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_flash_attn_ext (ggml_metal_op_t ctx, int idx);
int ggml_metal_op_bin (ggml_metal_op_t ctx, int idx);
@@ -205,6 +205,35 @@ kernel void kernel_add_id(
}
}
kernel void kernel_mul_mat_scale(
constant ggml_metal_kargs_mul_mat_scale & args,
device const char * scale,
device const char * ids,
device char * dst,
uint3 tgpig[[threadgroup_position_in_grid]],
ushort3 tpitg[[thread_position_in_threadgroup]],
ushort3 ntg[[threads_per_threadgroup]]) {
const int i1 = tgpig.x;
const int i2 = tgpig.y % args.ne2;
const int i3 = tgpig.y / args.ne2;
device const char * s = scale;
if (args.use_ids) {
const int32_t expert = *((device const int32_t *) (ids + i1*args.ids_nb0 + i2*args.ids_nb1));
if (expert < 0) {
return;
}
s += expert*args.s_nb1;
}
device float * dst_row = (device float *) (dst + i1*args.nb1 + i2*args.nb2 + i3*args.nb3);
for (int i0 = tpitg.x; i0 < args.ne0; i0 += ntg.x) {
dst_row[i0] *= *((device const float *) (s + i0*args.s_nb0));
}
}
template<typename T>
kernel void kernel_repeat(
constant ggml_metal_kargs_repeat & args,
+4
View File
@@ -12746,6 +12746,10 @@ static bool ggml_opencl_supports_op(ggml_backend_dev_t dev, const struct ggml_te
return false;
}
if (ggml_get_src_scale(op, 0)) {
return false;
}
switch (op->op) {
case GGML_OP_NONE:
return true;
+4
View File
@@ -2409,6 +2409,10 @@ struct supports_op_tally {
} // namespace
static bool ggml_backend_openvino_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_get_src_scale(op, 0)) {
return false;
}
auto res = ggml_backend_openvino_device_supports_op_impl(dev, op);
const bool supported = res.is_supported;
if (!supported) {
+4
View File
@@ -7344,6 +7344,10 @@ static ggml_backend_buffer_t ggml_backend_sycl_device_buffer_from_host_ptr(ggml_
}
static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
if (ggml_get_src_scale(op, 0)) {
return false;
}
ggml_backend_sycl_device_context *sycl_ctx =
(ggml_backend_sycl_device_context *)dev->context;
int device = sycl_ctx->device;
+11
View File
@@ -13261,6 +13261,13 @@ void ggml_vk_conv_3d(ggml_backend_vk_context * ctx, vk_context & subctx, const g
GGML_ASSERT(src1->type == GGML_TYPE_F32);
GGML_ASSERT(dst->type == GGML_TYPE_F32);
if (ggml_is_empty(src0)) {
const vk_subbuffer dst_buf = ggml_vk_tensor_subbuffer(ctx, dst, true);
const size_t size = ggml_nbytes(dst);
subctx->s->buffer->buf.fillBuffer(dst_buf.buffer->buffer, dst_buf.offset + dst_buf.size - size, size, 0);
return;
}
GGML_TENSOR_BINARY_OP_LOCALS
GGML_ASSERT(nb00 == sizeof(float) || nb00 == sizeof(ggml_fp16_t));
GGML_ASSERT(nb10 == sizeof(float));
@@ -16728,6 +16735,10 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
ggml_backend_vk_device_context * ctx = (ggml_backend_vk_device_context *)dev->context;
const vk_device& device = ggml_vk_get_device(ctx->device);
if (ggml_get_src_scale(op, 0)) {
return false;
}
const bool uses_bda = (op->op == GGML_OP_IM2COL || op->op == GGML_OP_IM2COL_3D) &&
device->shader_int64 && device->buffer_device_address;
@@ -36,7 +36,7 @@ shared OPD sh_kqh[2 * C * LDP], sh_kql[2 * C * LDP];
shared OPD sh_sh[V * LDP], sh_sl[V * LDP]; // state mirror [V x D] row-major (D padded)
shared OPD sh_ph[C * C], sh_pl[C * C];
shared OPD sh_ih[C * C], sh_il[C * C];
shared OPD sh_dh[C * LDV], sh_dl[C * LDV]; // delta / solved [C x V] row-major (V padded)
shared OPD sh_dh[C * LDV], sh_dl[C * LDV]; // delta [C x V] row-major (V padded)
shared float sh_lower[C * (C - 1) / 2]; // packed strictly-lower Gram entries
shared float sh_prefix[C], sh_ep[C], sh_beta[C], sh_carry[C];
@@ -70,9 +70,15 @@ float StoreGramPmat(const in uint32_t r, const in uint32_t c, const in float ele
return elem;
}
float SplitRowS(const in uint32_t r, const in uint32_t c, const in float elem) {
const uint i = r * LDP + c;
split(elem, sh_sh[i], sh_sl[i]);
// The bf16 hi and lo parts go to the state mirror in separate callbacks, so
// that a thread's stores of neighboring elements are adjacent and vectorize.
float StoreHi(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t c0) {
sh_sh[r * LDP + c0 + c] = OPD(elem);
return elem;
}
float StoreLo(const in uint32_t r, const in uint32_t c, const in float elem, const in uint32_t c0) {
sh_sl[r * LDP + c0 + c] = OPD(elem - float(OPD(elem)));
return elem;
}
@@ -92,13 +98,8 @@ float StoreDeltaV(const in uint32_t r, const in uint32_t c, const in float ks, c
return ks;
}
float StoreSolved(const in uint32_t r, const in uint32_t c, const in float elem) {
const uint i = c * LDV + r;
split(elem, sh_dh[i], sh_dl[i]);
// The state mirror is no longer needed after KS/QS.
const uint j = r * LDP + c;
split(sh_carry[c] * elem, sh_sh[j], sh_sl[j]);
return elem;
float ScaleCarry(const in uint32_t r, const in uint32_t c, const in float elem) {
return sh_carry[c] * elem;
}
float StoreOut(const in uint32_t r, const in uint32_t c, const in float elem,
@@ -146,8 +147,9 @@ void stage_inputs(const in float q[NQK], const in float k[NQK]) {
}
}
// [K; Q] * K^T computes Gram and P in one 32-row matrix.
void gram_pmat() {
// [K; Q] * K^T computes Gram and P in one 32-row matrix. Each state block's
// hi/lo split for the S*K^T/S*Q^T products runs interleaved with these MMAs.
void gram_pmat(in coopmat<float, WG, V, KT, MACC> state[D / KT]) {
coopmat<float, WG, KQ_ROWS, C, MACC> x = coopmat<float, WG, KQ_ROWS, C, MACC>(0.0);
[[unroll]] for (uint kk = 0; kk < D; kk += KT) {
coopmat<OPD, WG, KQ_ROWS, KT, MUA> ah, al;
@@ -157,17 +159,20 @@ void gram_pmat() {
coopMatLoad(bh, sh_kqh, kk, LDP, COL);
coopMatLoad(bl, sh_kql, kk, LDP, COL);
PRODUCT(x, ah, al, bh, bl);
coopMatPerElementNV(state[kk / KT], state[kk / KT], StoreHi, kk);
coopMatPerElementNV(state[kk / KT], state[kk / KT], StoreLo, kk);
}
coopMatPerElementNV(x, x, StoreGramPmat);
}
void invert() {
// The elimination steps only write registers; store_inverse() runs after the
// S*K^T/S*Q^T products, so the compiler can overlap the steps with them.
void invert(out float x[C / (2 * NSUB)]) {
const uint col = gl_SubgroupInvocationID % C;
// Each half-subgroup covers all columns of its assigned rows.
const uint section = gl_SubgroupInvocationID / C;
const uint row_base = (gl_SubgroupID * 2u + section) * (C / (2 * NSUB));
// Keep the diagonal zero so pivots at or above the row do nothing.
float x[C / (2 * NSUB)];
[[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) {
const uint row = row_base + j;
x[j] = col < row ? -sh_lower[row * (row - 1) / 2 + col] : 0.0;
@@ -179,6 +184,11 @@ void invert() {
x[j] -= xp * lower;
}
}
}
void store_inverse(const in float x[C / (2 * NSUB)]) {
const uint col = gl_SubgroupInvocationID % C;
const uint row_base = (gl_SubgroupID * 2u + gl_SubgroupInvocationID / C) * (C / (2 * NSUB));
[[unroll]] for (uint j = 0; j < C / (2 * NSUB); ++j) {
const uint row = row_base + j;
split(col == row ? 1.0 : x[j], sh_ih[row * C + col], sh_il[row * C + col]);
@@ -195,17 +205,25 @@ float replay_update(const in uint32_t r, const in uint32_t c, const in float s,
return s + data_pk[k_off + c] * (beta * (data_pv[v_off + r] - dot));
}
void replay(inout coopmat<float, WG, V, D, MACC> state, uint seq_id, uint head_id, uint iq1, uint v0) {
// The products of the state blocks with their slices of k are summed per
// element first, so one row reduction gives the dot product over all of D.
void replay(inout coopmat<float, WG, V, KT, MACC> state[D / KT], uint seq_id, uint head_id, uint iq1, uint v0) {
const uint n_rep = replay_count(seq_id);
[[dont_unroll]] for (uint t = 0; t < n_rep; ++t) {
uint k_off, v_off;
float decay, beta;
replay_inputs(seq_id, head_id, iq1, t, k_off, v_off, decay, beta);
state *= decay;
coopmat<float, WG, V, D, MACC> dot;
coopMatPerElementNV(dot, state, replay_product, k_off);
coopmat<float, WG, V, KT, MACC> dot = coopmat<float, WG, V, KT, MACC>(0.0);
[[unroll]] for (uint b = 0; b < D / KT; ++b) {
state[b] *= decay;
coopmat<float, WG, V, KT, MACC> prod;
coopMatPerElementNV(prod, state[b], replay_product, k_off + b * KT);
dot += prod;
}
coopMatReduceNV(dot, dot, gl_CooperativeMatrixReduceRowNV, replay_sum);
coopMatPerElementNV(state, state, replay_update, dot, k_off, v_off + v0, beta);
[[unroll]] for (uint b = 0; b < D / KT; ++b) {
coopMatPerElementNV(state[b], state[b], replay_update, dot, k_off + b * KT, v_off + v0, beta);
}
}
}
#endif
@@ -224,8 +242,11 @@ void main() {
const uint out_base = (seq_id * p.n_tokens * p.H + head_id) * D + v0;
// Transposing the state-side products gives them V=32 rows with C=16 columns.
coopmat<float, WG, V, D, MACC> state;
coopMatLoad(state, data_state, state_base, D, ROW);
// It is kept as one [V x KT] block per K-tile.
coopmat<float, WG, V, KT, MACC> state[D / KT];
[[unroll]] for (uint t = 0; t < D / KT; ++t) {
coopMatLoad(state[t], data_state, state_base + t * KT, D, ROW);
}
#ifdef GDN_REPLAY
replay(state, seq_id, head_id, iq1, v0);
@@ -267,11 +288,10 @@ void main() {
// Current inputs are in shared memory; keep the next chunk in registers.
prefetch(t0 + C, q_base, k_base, gb_base, qreg, kreg, greg, breg);
gram_pmat();
barrier();
invert();
coopMatPerElementNV(state, state, SplitRowS);
gram_pmat(state);
barrier();
float inv[C / (2 * NSUB)];
invert(inv);
coopmat<float, WG, V, C, MACC> ks = coopmat<float, WG, V, C, MACC>(0.0), base_r = coopmat<float, WG, V, C, MACC>(0.0);
[[unroll]] for (uint kk = 0; kk < D; kk += KT) {
@@ -286,6 +306,7 @@ void main() {
PRODUCT(ks, ah, al, kh, kl);
PRODUCT(base_r, ah, al, qh, ql);
}
store_inverse(inv);
coopMatPerElementNV(base_r, base_r, ApplyExpPrefix);
coopMatPerElementNV(ks, ks, StoreDeltaV, vmat);
barrier();
@@ -300,15 +321,21 @@ void main() {
coopMatLoad(il, sh_il, 0, C, COL);
PRODUCT(solved, rh, rl, ih, il);
}
barrier();
coopMatPerElementNV(solved, solved, StoreSolved);
// The state mirror is no longer needed after KS/QS. Unlike the delta
// buffer, it needs no barrier before solved is stored there.
coopmat<float, WG, V, C, MACC> carry_solved;
coopMatPerElementNV(carry_solved, solved, ScaleCarry);
coopMatPerElementNV(carry_solved, carry_solved, StoreHi, 0u);
coopMatPerElementNV(carry_solved, carry_solved, StoreLo, 0u);
coopMatPerElementNV(solved, solved, StoreHi, uint(C));
coopMatPerElementNV(solved, solved, StoreLo, uint(C));
barrier();
{
coopmat<OPD, WG, V, C, MUA> xh, xl;
coopmat<OPD, WG, C, C, MUB> ph, pl;
coopMatLoad(xh, sh_dh, 0, LDV, COL);
coopMatLoad(xl, sh_dl, 0, LDV, COL);
coopMatLoad(xh, sh_sh, C, LDP, ROW);
coopMatLoad(xl, sh_sl, C, LDP, ROW);
coopMatLoad(ph, sh_ph, 0, C, COL);
coopMatLoad(pl, sh_pl, 0, C, COL);
PRODUCT(base_r, xh, xl, ph, pl);
@@ -316,14 +343,18 @@ void main() {
coopMatPerElementNV(base_r, base_r, StoreOut, out_base + t0 * (p.H * D), valid);
coopmat<OPD, WG, V, C, MUA> xh, xl;
coopmat<OPD, WG, C, D, MUB> kh, kl;
coopMatLoad(xh, sh_sh, 0, LDP, ROW);
coopMatLoad(xl, sh_sl, 0, LDP, ROW);
coopMatLoad(kh, sh_kqh, 0, LDP, ROW);
coopMatLoad(kl, sh_kql, 0, LDP, ROW);
state *= sh_ep[valid - 1];
PRODUCT(state, xh, xl, kh, kl);
[[unroll]] for (uint t = 0; t < D / KT; ++t) {
coopmat<OPD, WG, C, KT, MUB> kh, kl;
coopMatLoad(kh, sh_kqh, t * KT, LDP, ROW);
coopMatLoad(kl, sh_kql, t * KT, LDP, ROW);
state[t] *= sh_ep[valid - 1];
PRODUCT(state[t], xh, xl, kh, kl);
}
}
coopMatStore(state, data_dst, p.s_off + state_base, D, ROW);
[[unroll]] for (uint t = 0; t < D / KT; ++t) {
coopMatStore(state[t], data_dst, p.s_off + state_base + t * KT, D, ROW);
}
}
+15 -2
View File
@@ -3593,7 +3593,10 @@ static bool ggml_webgpu_can_fuse_rms_norm_mul(const struct ggml_cgraph * cgraph,
return true;
}
static bool ggml_webgpu_can_fuse_gdn_cache(const struct ggml_cgraph * cgraph, int node_idx, int & num_encoded_ops) {
static bool ggml_webgpu_can_fuse_gdn_cache(const webgpu_global_context & global_ctx,
const struct ggml_cgraph * cgraph,
int node_idx,
int & num_encoded_ops) {
const ggml_tensor * gdn = cgraph->nodes[node_idx];
// the kernel skips the snapshot tail, so the gdn output must not be a graph output
@@ -3649,6 +3652,12 @@ static bool ggml_webgpu_can_fuse_gdn_cache(const struct ggml_cgraph * cgraph, in
return false;
}
// the input state can be read straight from the cache the kernel writes to; webgpu rejects a
// writable binding that overlaps another binding of the same dispatch
if (ggml_webgpu_tensor_binding_overlap(global_ctx, gdn->src[5], cpy_dst)) {
return false;
}
num_encoded_ops = cpy_idx - node_idx + 1;
return true;
@@ -3797,7 +3806,7 @@ static std::optional<webgpu_encoded_op> ggml_webgpu_encode(webgpu_context ctx,
case GGML_OP_GATED_DELTA_NET:
if (ggml_webgpu_gated_delta_net_n_storage_buffers(node, true) <=
ctx->global_ctx->capabilities.limits.maxStorageBuffersPerShaderStage &&
ggml_webgpu_can_fuse_gdn_cache(cgraph, node_idx, num_encoded_ops)) {
ggml_webgpu_can_fuse_gdn_cache(ctx->global_ctx, cgraph, node_idx, num_encoded_ops)) {
ggml_tensor * dst_fuse = cgraph->nodes[node_idx + num_encoded_ops - 1]->src[1];
return ggml_webgpu_gated_delta_net(ctx, src0, src1, src2, node->src[3], node->src[4], node->src[5],
node, dst_fuse);
@@ -5003,6 +5012,10 @@ static bool ggml_backend_webgpu_device_supports_op(ggml_backend_dev_t dev, const
ggml_tensor * src1 = op->src[1];
ggml_tensor * src2 = op->src[2];
if (ggml_get_src_scale(op, 0)) {
return false;
}
// on smaller devices (or CI), tensors may be larger than the max storage buffer size
if (ggml_nbytes(op) > ctx->webgpu_global_ctx->capabilities.limits.maxStorageBufferBindingSize ||
(src0 != nullptr &&
+3 -1
View File
@@ -17,7 +17,8 @@
#include <utility>
#include <vector>
#define GGML_ZDNN_NAME "zDNN"
#define GGML_ZDNN_NAME "zDNN"
#define GGML_ZDNN_ZTENSOR_ALIGN 4096
#define ZDNN_CHECK(stmt) \
do { \
@@ -47,6 +48,7 @@ struct ggml_backend_zdnn_buffer {
zdnn_tensor_desc pre_tfm_desc;
zdnn_tensor_desc tfm_desc;
zdnn_ztensor ztensor;
bool ztensor_in_buffer = false; // the ztensor uses the ggml buffer memory and is freed with it
std::vector<float> scales; // per-row scales for quantized weights
std::vector<float> channel_scales; // per-input-channel scales for quantized weights, applied to the inputs
+25 -3
View File
@@ -100,6 +100,10 @@ static bool ggml_zdnn_is_tensor_own(const ggml_tensor * tensor) {
}
static bool ggml_zdnn_supports_op(const ggml_backend_zdnn_device_context * ctx_dev, const ggml_tensor * op) {
if (ggml_get_src_scale(op, 0)) {
return false;
}
switch (op->op) {
case GGML_OP_NONE:
case GGML_OP_RESHAPE:
@@ -266,7 +270,9 @@ static void ggml_backend_zdnn_buffer_free_buffer(ggml_backend_buffer_t buffer) {
// Free any extra buffer allocated for the tensor. E.g., bias for GGML_OP_MUL_MAT
if (buf->extra != nullptr) free(buf->extra->data);
if (buf->ztensor.buffer_size > 0) ZDNN_CHECK(zdnn_free_ztensor_buffer(&buf->ztensor));
if (buf->ztensor.buffer_size > 0 && !buf->ztensor_in_buffer) {
ZDNN_CHECK(zdnn_free_ztensor_buffer(&buf->ztensor));
}
}
if (ctx->owned) {
@@ -423,7 +429,7 @@ static void ggml_backend_zdnn_buffer_reset(ggml_backend_buffer_t buffer) {
free(buf->extra->data);
}
if (buf->ztensor.buffer_size > 0) {
if (buf->ztensor.buffer_size > 0 && !buf->ztensor_in_buffer) {
ZDNN_CHECK(zdnn_free_ztensor_buffer(&buf->ztensor));
}
}
@@ -505,6 +511,22 @@ static size_t ggml_backend_zdnn_buffer_type_get_alignment(ggml_backend_buffer_ty
GGML_UNUSED(buft);
}
static size_t ggml_backend_zdnn_buffer_type_get_alloc_size(ggml_backend_buffer_type_t buft, const ggml_tensor * tensor) {
// views share the ztensor of their source, empty tensors have none, and the rest cannot grow
if (tensor->view_src != nullptr || ggml_is_empty(tensor) || !ggml_zdnn_ztensor_in_alloc(tensor)) {
return ggml_nbytes(tensor);
}
zdnn_tensor_desc pre_tfm_desc;
zdnn_tensor_desc tfm_desc;
ggml_zdnn_init_tensor_desc(pre_tfm_desc, tfm_desc, tensor);
// room for the ztensor after the tensor data, at the next 4K boundary
return ggml_nbytes(tensor) + GGML_ZDNN_ZTENSOR_ALIGN - 1 + zdnn_getsize_ztensor(&tfm_desc);
GGML_UNUSED(buft);
}
static bool ggml_backend_zdnn_buffer_type_is_host(ggml_backend_buffer_type_t buft) {
return true;
@@ -519,7 +541,7 @@ ggml_backend_buffer_type_t ggml_backend_zdnn_buffer_type(void) {
/* .alloc_buffer_n = */ NULL,
/* .get_alignment = */ ggml_backend_zdnn_buffer_type_get_alignment,
/* .get_max_size = */ NULL,
/* .get_alloc_size = */ NULL, // defaults to ggml_nbytes
/* .get_alloc_size = */ ggml_backend_zdnn_buffer_type_get_alloc_size, // used with autofitting
/* .get_alloc_size_n = */ NULL,
/* .is_host = */ ggml_backend_zdnn_buffer_type_is_host,
},
+38 -15
View File
@@ -1,4 +1,5 @@
#include "ggml.h"
#include "ggml-backend-impl.h"
#include "utils.hpp"
#include <algorithm>
@@ -158,7 +159,14 @@ void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
}
}
void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) {
// ggml allows a larger allocation only for these tensors, the others keep a ztensor allocated by zDNN
bool ggml_zdnn_ztensor_in_alloc(const ggml_tensor * tensor) {
return ggml_op_is_empty(tensor->op) || ggml_is_quantized(tensor->type) || ggml_op_alloc_size_may_expand(tensor->op);
}
void ggml_zdnn_init_tensor_desc(zdnn_tensor_desc & pre_tfm_desc,
zdnn_tensor_desc & tfm_desc,
const ggml_tensor * tensor) {
if (ggml_is_quantized(tensor->type)) {
GGML_ASSERT(ggml_is_matrix(tensor));
@@ -171,26 +179,19 @@ void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
zdnn_init_pre_transformed_desc(
ZDNN_3DS,
INT8,
&buffer->pre_tfm_desc,
&pre_tfm_desc,
n_groups, gs, tensor->ne[1]
);
buffer->scales.resize(n_groups * tensor->ne[1]);
} else {
zdnn_init_pre_transformed_desc(
ZDNN_2D,
INT8,
&buffer->pre_tfm_desc,
&pre_tfm_desc,
tensor->ne[0], tensor->ne[1]
);
buffer->scales.resize(tensor->ne[1]);
}
buffer->channel_scales.resize(tensor->ne[0]);
ZDNN_CHECK(zdnn_generate_quantized_transformed_desc(&buffer->pre_tfm_desc, QUANTIZED_WEIGHTS_INT8, &buffer->tfm_desc));
ZDNN_CHECK(zdnn_init_quantized_ztensor_with_malloc(&buffer->pre_tfm_desc, &buffer->tfm_desc, 1.0f, 0.0f, &buffer->ztensor));
ZDNN_CHECK(zdnn_generate_quantized_transformed_desc(&pre_tfm_desc, QUANTIZED_WEIGHTS_INT8, &tfm_desc));
return;
}
@@ -200,7 +201,7 @@ void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
zdnn_init_pre_transformed_desc(
ZDNN_2D,
ggml_zdnn_type_mapping(tensor->type),
&buffer->pre_tfm_desc,
&pre_tfm_desc,
tensor->ne[1], tensor->ne[0]
);
} break;
@@ -214,7 +215,7 @@ void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
zdnn_init_pre_transformed_desc(
ZDNN_NHWC,
ggml_zdnn_type_mapping(tensor->type),
&buffer->pre_tfm_desc,
&pre_tfm_desc,
tensor->ne[3], tensor->ne[2], tensor->ne[1], tensor->ne[0]
);
@@ -224,6 +225,28 @@ void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor
} break;
}
ZDNN_CHECK(zdnn_generate_transformed_desc(&buffer->pre_tfm_desc, &buffer->tfm_desc));
ZDNN_CHECK(zdnn_init_ztensor_with_malloc(&buffer->pre_tfm_desc, &buffer->tfm_desc, &buffer->ztensor));
ZDNN_CHECK(zdnn_generate_transformed_desc(&pre_tfm_desc, &tfm_desc));
}
void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor) {
ggml_zdnn_init_tensor_desc(buffer->pre_tfm_desc, buffer->tfm_desc, tensor);
if (ggml_is_quantized(tensor->type)) {
const bool stacked = buffer->pre_tfm_desc.layout == ZDNN_3DS;
buffer->scales.resize((stacked ? buffer->pre_tfm_desc.dim3 : 1) * tensor->ne[1]);
buffer->channel_scales.resize(tensor->ne[0]);
zdnn_init_quantized_ztensor(&buffer->pre_tfm_desc, &buffer->tfm_desc, 1.0f, 0.0f, &buffer->ztensor);
} else if (ggml_zdnn_ztensor_in_alloc(tensor)) {
zdnn_init_ztensor(&buffer->pre_tfm_desc, &buffer->tfm_desc, &buffer->ztensor);
} else {
ZDNN_CHECK(zdnn_init_ztensor_with_malloc(&buffer->pre_tfm_desc, &buffer->tfm_desc, &buffer->ztensor));
return;
}
// the ztensor uses the memory after the tensor data, see ggml_backend_zdnn_buffer_type_get_alloc_size
buffer->ztensor.buffer = (void *)GGML_PAD((uintptr_t)tensor->data + ggml_nbytes(tensor), GGML_ZDNN_ZTENSOR_ALIGN);
buffer->ztensor.buffer_size = zdnn_getsize_ztensor(&buffer->tfm_desc);
buffer->ztensor_in_buffer = true;
}
+6
View File
@@ -20,6 +20,12 @@ void ggml_zdnn_load_tensor_q(ggml_backend_zdnn_buffer * buffer, const ggml_tenso
void ggml_zdnn_load_weights(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor);
bool ggml_zdnn_ztensor_in_alloc(const ggml_tensor * tensor);
void ggml_zdnn_init_tensor_desc(zdnn_tensor_desc & pre_tfm_desc,
zdnn_tensor_desc & tfm_desc,
const ggml_tensor * tensor);
void ggml_zdnn_init_tensor(ggml_backend_zdnn_buffer * buffer, const ggml_tensor * tensor);
#endif // GGML_ZDNN_UTILITIES_HPP
+4
View File
@@ -698,6 +698,10 @@ static bool ggml_zendnn_adaptive_fallback_enabled() {
}
static bool ggml_backend_zendnn_device_supports_op(ggml_backend_dev_t dev, const struct ggml_tensor * op) {
if (ggml_get_src_scale(op, 0)) {
return false;
}
switch (op->op) {
case GGML_OP_NONE:
case GGML_OP_RESHAPE:
+86
View File
@@ -1376,6 +1376,18 @@ bool ggml_is_quantized(enum ggml_type type) {
return type_traits[type].is_quantized;
}
bool ggml_needs_scale(enum ggml_type type) {
assert(type >= 0);
assert(type < GGML_TYPE_COUNT);
switch (type) {
case GGML_TYPE_NVFP4:
case GGML_TYPE_F8_E4M3:
return true;
default:
return false;
}
}
const char * ggml_op_name(enum ggml_op op) {
return GGML_OP_NAME[op];
}
@@ -3386,8 +3398,31 @@ struct ggml_tensor * ggml_mul_mat(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b) {
if (ggml_needs_scale(a->type)) {
GGML_LOG_ERROR("%s: tensor type %s requires a weight scale; use ggml_mul_mat_ext instead\n",
__func__, ggml_type_name(a->type));
GGML_ABORT("fatal error");
}
return ggml_mul_mat_ext(ctx, a, b, NULL, NULL);
}
struct ggml_tensor * ggml_mul_mat_ext(
struct ggml_context * ctx,
struct ggml_tensor * a,
struct ggml_tensor * b,
struct ggml_tensor * scale_weight,
struct ggml_tensor * scale_activations) {
GGML_ASSERT(ggml_can_mul_mat(a, b));
GGML_ASSERT(!ggml_is_transposed(a));
GGML_ASSERT(!ggml_needs_scale(a->type) || scale_weight != NULL);
if (ggml_needs_scale(b->type)) {
GGML_LOG_ERROR("%s: scaled tensor type %s currently cannot be used as the activation tensor\n",
__func__, ggml_type_name(b->type));
GGML_ABORT("fatal error");
}
GGML_ASSERT(scale_weight == NULL || scale_weight->type == GGML_TYPE_F32);
GGML_ASSERT(scale_activations == NULL || scale_activations->type == GGML_TYPE_F32);
const int64_t ne[4] = { a->ne[1], b->ne[1], b->ne[2], b->ne[3] };
struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, 4, ne);
@@ -3396,6 +3431,16 @@ struct ggml_tensor * ggml_mul_mat(
result->src[0] = a;
result->src[1] = b;
if (scale_weight) {
GGML_ASSERT(ggml_is_scalar(scale_weight) || (ggml_is_vector(scale_weight) && scale_weight->ne[0] == a->ne[1]));
result->src[2] = scale_weight;
}
if (scale_activations) {
GGML_ASSERT(ggml_is_scalar(scale_activations));
result->src[3] = scale_activations;
}
return result;
}
@@ -3430,8 +3475,32 @@ struct ggml_tensor * ggml_mul_mat_id(
struct ggml_tensor * as,
struct ggml_tensor * b,
struct ggml_tensor * ids) {
if (ggml_needs_scale(as->type)) {
GGML_LOG_ERROR("%s: tensor type %s requires a weight scale; use ggml_mul_mat_id_ext instead\n",
__func__, ggml_type_name(as->type));
GGML_ABORT("fatal error");
}
return ggml_mul_mat_id_ext(ctx, as, b, ids, NULL, NULL);
}
struct ggml_tensor * ggml_mul_mat_id_ext(
struct ggml_context * ctx,
struct ggml_tensor * as,
struct ggml_tensor * b,
struct ggml_tensor * ids,
struct ggml_tensor * scale_weight,
struct ggml_tensor * scale_activations) {
GGML_ASSERT(!ggml_is_transposed(as));
GGML_ASSERT(ids->type == GGML_TYPE_I32);
if (ggml_needs_scale(b->type)) {
GGML_LOG_ERROR("%s: scaled tensor type %s currently cannot be used as the activation tensor\n",
__func__, ggml_type_name(b->type));
GGML_ABORT("fatal error");
}
GGML_ASSERT(!ggml_needs_scale(as->type) || scale_weight != NULL);
GGML_ASSERT(scale_weight == NULL || scale_weight->type == GGML_TYPE_F32);
GGML_ASSERT(scale_activations == NULL || scale_activations->type == GGML_TYPE_F32);
GGML_ASSERT(as->ne[3] == 1); // as is 3d (one matrix per expert)
GGML_ASSERT(b->ne[3] == 1); // b is 3d
@@ -3448,6 +3517,23 @@ struct ggml_tensor * ggml_mul_mat_id(
result->src[1] = b;
result->src[2] = ids;
if (scale_weight) {
struct ggml_tensor * s = scale_weight;
const bool per_tensor = ggml_is_scalar(s);
const bool per_expert = ggml_is_vector(s) && s->ne[0] == as->ne[2];
const bool per_ch_exp = s->ne[0] == as->ne[1] && s->ne[1] == as->ne[2] && s->ne[2] == 1 && s->ne[3] == 1;
GGML_ASSERT(per_tensor || per_expert || per_ch_exp);
result->src[3] = s;
}
if (scale_activations) {
const struct ggml_tensor * s = scale_activations;
const bool per_tensor = ggml_is_scalar(s);
const bool per_expert = ggml_is_vector(s) && s->ne[0] == as->ne[2];
GGML_ASSERT(per_tensor || per_expert);
result->src[4] = scale_activations;
}
return result;
}
+3
View File
@@ -1583,6 +1583,9 @@ bool llm_arch_supports_sm_tensor(const llm_arch & arch) {
case LLM_ARCH_ZAYA1:
case LLM_ARCH_GROK:
case LLM_ARCH_MPT:
case LLM_ARCH_BLOOM: // ALiBi
case LLM_ARCH_JAIS: // ALiBi
case LLM_ARCH_REFACT: // ALiBi
case LLM_ARCH_PLAMO2:
case LLM_ARCH_MINICPM3:
case LLM_ARCH_GEMMA3N:
-2
View File
@@ -674,8 +674,6 @@ enum llm_tensor {
LLM_TENSOR_LAYER_OUT_NORM,
LLM_TENSOR_LAYER_OUT_SCALE,
LLM_TENSOR_ATTN_VRES_LAMBDA,
LLM_TENSOR_POST_ATTN_NORM,
LLM_TENSOR_POST_MLP_NORM,
LLM_TENSOR_PER_LAYER_TOKEN_EMBD, // gemma3n
LLM_TENSOR_PER_LAYER_MODEL_PROJ, // gemma3n
LLM_TENSOR_PER_LAYER_INP_GATE, // gemma3n
+1
View File
@@ -3076,6 +3076,7 @@ llm_graph_params llama_context::graph_params(
/*.layer_inp_src =*/ supports_embd_row() ? cparams.ctx_other->get_layer_inp_dev() : nullptr,
/*.h_nextn_dev =*/ cparams.embeddings_nextn_dev ? h_nextn_dev : nullptr,
/*.h_nextn_src =*/ supports_state_row() ? cparams.ctx_state_src->get_h_nextn_dev() : nullptr,
/*.w_scales =*/ &model.w_scales,
/*.samplers =*/ sampling.samplers,
/*.n_outputs =*/ n_outputs,
/*.cb =*/ graph_get_cb(),
+119 -96
View File
@@ -581,6 +581,7 @@ bool llm_graph_input_rs::can_reuse(const llm_graph_params & params) {
res &= head == mctx->get_head();
res &= rs_z == mctx->get_rs_z();
res &= rs_in_place == mctx->get_rs_in_place();
return res;
}
@@ -1309,6 +1310,7 @@ bool llm_graph_input_mem_hybrid::can_reuse(const llm_graph_params & params) {
res &= inp_rs->head == mctx->get_recr()->get_head();
res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
res &= inp_rs->rs_in_place == mctx->get_recr()->get_rs_in_place();
return res;
}
@@ -1356,6 +1358,7 @@ bool llm_graph_input_mem_hybrid_k::can_reuse(const llm_graph_params & params) {
res &= inp_rs->head == mctx->get_recr()->get_head();
res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
res &= inp_rs->rs_in_place == mctx->get_recr()->get_rs_in_place();
return res;
}
@@ -1429,6 +1432,7 @@ bool llm_graph_input_mem_hybrid_iswa::can_reuse(const llm_graph_params & params)
res &= inp_rs->head == mctx->get_recr()->get_head();
res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
res &= inp_rs->rs_in_place == mctx->get_recr()->get_rs_in_place();
return res;
}
@@ -1516,6 +1520,7 @@ bool llm_graph_input_mem_hybrid_iswa_rel::can_reuse(const llm_graph_params & par
res &= inp_rs->head == mctx->get_recr()->get_head();
res &= inp_rs->rs_z == mctx->get_recr()->get_rs_z();
res &= inp_rs->rs_in_place == mctx->get_recr()->get_rs_in_place();
return res;
}
@@ -1756,6 +1761,7 @@ llm_graph_context::llm_graph_context(const llm_graph_params & params) :
layer_inp_src (params.layer_inp_src),
h_nextn_dev (params.h_nextn_dev),
h_nextn_src (params.h_nextn_src),
w_scales (params.w_scales),
samplers (params.samplers),
cb_func (params.cb),
res (params.res),
@@ -1840,29 +1846,37 @@ ggml_tensor * llm_graph_context::build_rope_indexer(ggml_tensor * cur, ggml_tens
return rp.n_rot > 0 && rp.n_offs > 0 ? ggml_rope_set_offset(res, rp.n_offs) : res;
}
ggml_tensor * llm_graph_context::get_weight_scale(const ggml_tensor * w) const {
ggml_tensor * s = w_scales ? w_scales->get(w) : nullptr;
// weights shared from the target model
if (s == nullptr && cparams.ctx_other) {
s = llama_get_model(cparams.ctx_other)->w_scales.get(w);
}
return s;
}
ggml_tensor * llm_graph_context::get_input_scale(const ggml_tensor * w) const {
ggml_tensor * s = w_scales ? w_scales->get_input(w) : nullptr;
// weights shared from the target model
if (s == nullptr && cparams.ctx_other) {
s = llama_get_model(cparams.ctx_other)->w_scales.get_input(w);
}
return s;
}
ggml_tensor * llm_graph_context::build_lora_mm(
ggml_tensor * w,
ggml_tensor * cur,
ggml_tensor * w_s) const {
if (!w_s) {
w_s = model.get_w_scale(w);
}
ggml_tensor * cur) const {
// a Hadamard-folded weight reads the transformed input; a LoRA delta lives in the primal basis and reads `cur`
ggml_tensor * cur_mm = build_hadamard_input(w, cur);
ggml_tensor * res = ggml_mul_mat(ctx0, w, cur_mm);
ggml_tensor * res = ggml_mul_mat_ext(ctx0, w, cur_mm, get_weight_scale(w), get_input_scale(w));
if (w->type == GGML_TYPE_NVFP4) {
ggml_prec_set_acc(res, GGML_PREC_BF16);
}
prec_policy.apply(res, w);
if (w_s) {
res = ggml_mul(ctx0, res, w_s);
}
for (const auto & lora : *loras) {
llama_adapter_lora_weight * lw = lora.first->get_weight(w);
if (lw == nullptr) {
@@ -1927,13 +1941,16 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
ggml_tensor * ids,
ggml_tensor * slots,
bool cached) const {
ggml_tensor * w_s = model.get_w_scale(w);
ggml_tensor * w_s = get_weight_scale(w);
ggml_tensor * x_s = get_input_scale(w);
// as in build_lora_mm: the folded weight reads the transformed input, the LoRA delta reads `cur`
ggml_tensor * cur_mm = build_hadamard_input(w, cur);
// the experts in the MoE cache are selected by their slots
ggml_tensor * res = slots == nullptr ?
ggml_mul_mat_id(ctx0, w, cur_mm, ids) :
ggml_mul_mat_id(ctx0, cached ? moe_cache->get_experts(w) : w, cur_mm, slots);
ggml_mul_mat_id_ext(ctx0, w, cur_mm, ids, w_s, x_s) :
ggml_mul_mat_id_ext(ctx0, cached ? moe_cache->get_experts(w) : w, cur_mm, slots,
w_s ? (cached ? moe_cache->get_scales(w, LLAMA_MOE_CACHE_SCALE_WEIGHT) : w_s) : nullptr,
x_s ? (cached ? moe_cache->get_scales(w, LLAMA_MOE_CACHE_SCALE_INPUT) : x_s) : nullptr);
if (w->type == GGML_TYPE_NVFP4) {
ggml_prec_set_acc(res, GGML_PREC_BF16);
@@ -1942,14 +1959,6 @@ ggml_tensor * llm_graph_context::build_lora_mm_id(
// after the NVFP4 default, so that the policy can request a higher precision
prec_policy.apply(res, w);
if (w_s) {
const int64_t n_expert = w_s->ne[0];
const int64_t n_tokens = cur->ne[2];
ggml_tensor * s = ggml_reshape_3d(ctx0, w_s, 1, n_expert, 1);
s = ggml_repeat_4d(ctx0, s, 1, n_expert, n_tokens, 1);
s = ggml_get_rows(ctx0, s, ids);
res = ggml_mul(ctx0, res, s);
}
for (const auto & lora : *loras) {
llama_adapter_lora_weight * lw = lora.first->get_weight(w);
if (lw == nullptr) {
@@ -2041,7 +2050,7 @@ llm_graph_qkv llm_graph_context::build_qkv(
if (layer.wqkv) {
// fused QKV path
ggml_tensor * qkv = build_lora_mm(layer.wqkv, cur, layer.wqkv_s);
ggml_tensor * qkv = build_lora_mm(layer.wqkv, cur);
cb(qkv, "wqkv", il);
if (layer.wqkv_b) {
qkv = ggml_add(ctx0, qkv, layer.wqkv_b);
@@ -2079,7 +2088,7 @@ llm_graph_qkv llm_graph_context::build_qkv(
}
} else {
// separate Q/K/V path
Qcur = build_lora_mm(layer.wq, cur, layer.wq_s);
Qcur = build_lora_mm(layer.wq, cur);
if (reshape) {
cb(Qcur, "Qcur", il);
}
@@ -2093,7 +2102,7 @@ llm_graph_qkv llm_graph_context::build_qkv(
Qcur = ggml_clamp(ctx0, Qcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
cb(Qcur, "Qcur_clamped", il);
}
Kcur = build_lora_mm(layer.wk, cur, layer.wk_s);
Kcur = build_lora_mm(layer.wk, cur);
if (reshape) {
cb(Kcur, "Kcur", il);
}
@@ -2107,7 +2116,7 @@ llm_graph_qkv llm_graph_context::build_qkv(
Kcur = ggml_clamp(ctx0, Kcur, -hparams.f_clamp_kqv, hparams.f_clamp_kqv);
cb(Kcur, "Kcur_clamped", il);
}
Vcur = build_lora_mm(layer.wv, cur, layer.wv_s);
Vcur = build_lora_mm(layer.wv, cur);
if (reshape) {
cb(Vcur, "Vcur", il);
}
@@ -2142,20 +2151,17 @@ ggml_tensor * llm_graph_context::build_ffn(
ggml_tensor * cur,
ggml_tensor * up,
ggml_tensor * up_b,
ggml_tensor * up_s,
ggml_tensor * gate,
ggml_tensor * gate_b,
ggml_tensor * gate_s,
ggml_tensor * down,
ggml_tensor * down_b,
ggml_tensor * down_s,
ggml_tensor * act_scales,
llm_ffn_op_type type_op,
llm_ffn_gate_type type_gate,
int il) const {
const llm_arch arch = model.arch;
ggml_tensor * tmp = up ? build_lora_mm(up, cur, up_s) : cur;
ggml_tensor * tmp = up ? build_lora_mm(up, cur) : cur;
cb(tmp, "ffn_up", il);
if (up_b) {
@@ -2167,12 +2173,12 @@ ggml_tensor * llm_graph_context::build_ffn(
switch (type_gate) {
case LLM_FFN_SEQ:
{
cur = build_lora_mm(gate, tmp, gate_s);
cur = build_lora_mm(gate, tmp);
cb(cur, "ffn_gate", il);
} break;
case LLM_FFN_PAR:
{
cur = build_lora_mm(gate, cur, gate_s);
cur = build_lora_mm(gate, cur);
cb(cur, "ffn_gate", il);
} break;
}
@@ -2303,7 +2309,7 @@ ggml_tensor * llm_graph_context::build_ffn(
}
if (down) {
cur = build_lora_mm(down, cur, down_s);
cur = build_lora_mm(down, cur);
}
if (down_b) {
@@ -3150,7 +3156,9 @@ ggml_tensor * llm_graph_context::build_attn_mha(
float kq_scale,
int il,
ggml_tensor * bias_table,
ggml_tensor * bias_indices) const {
ggml_tensor * bias_indices,
ggml_tensor * k_scale,
ggml_tensor * v_scale) const {
const bool v_trans = v->nb[1] > v->nb[2];
// split the batch into streams if needed
@@ -3188,6 +3196,10 @@ ggml_tensor * llm_graph_context::build_attn_mha(
if (use_flash_attn) {
GGML_ASSERT(kq_b == nullptr && "Flash attention does not support dense KQ bias");
if (k_scale) {
q = ggml_mul(ctx0, q, k_scale);
}
if (v_trans) {
v = ggml_transpose(ctx0, v);
}
@@ -3230,12 +3242,12 @@ ggml_tensor * llm_graph_context::build_attn_mha(
// v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens.
// However, the code is optimized for dimensions 0 and 1 being large, so this is inefficient.
cur = ggml_reshape_4d(ctx0, cur, v_mla->ne[0], 1, n_head, n_tokens);
cur = ggml_mul_mat(ctx0, v_mla, cur);
cur = build_lora_mm(v_mla, cur);
#else
// It's preferable to do the calculation as a matrix-matrix multiplication with n_tokens in dimension 1.
// The permutations are noops and only change how the tensor data is interpreted.
cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
cur = ggml_mul_mat(ctx0, v_mla, cur);
cur = build_lora_mm(v_mla, cur);
cb(cur, "fattn_mla", il);
cur = ggml_permute(ctx0, cur, 0, 2, 1, 3);
cur = ggml_cont(ctx0, cur); // Needed because ggml_reshape_2d expects contiguous inputs.
@@ -3243,11 +3255,24 @@ ggml_tensor * llm_graph_context::build_attn_mha(
}
cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]);
if (v_scale) {
cur = ggml_mul(ctx0, cur, v_scale);
}
} else {
if (bias_table) {
kq_mask = dense_bias_mask();
}
ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
// A cache without an exported scale uses a unit scale.
if ((ggml_needs_scale(k->type) && !k_scale) || (ggml_needs_scale(v->type) && !v_scale)) {
ggml_tensor * unit_scale = ggml_fill(ctx0, ggml_new_tensor_1d(ctx0, GGML_TYPE_F32, 1), 1.0f);
if (ggml_needs_scale(k->type) && !k_scale) {
k_scale = unit_scale;
}
if (ggml_needs_scale(v->type) && !v_scale) {
v_scale = unit_scale;
}
}
ggml_tensor * kq = ggml_mul_mat_ext(ctx0, k, q, k_scale, nullptr);
cb(kq, "kq", il);
ggml_prec_set_acc(kq, GGML_PREC_BF16);
@@ -3289,12 +3314,12 @@ ggml_tensor * llm_graph_context::build_attn_mha(
cb(v, "v_cont", il);
}
ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
ggml_tensor * kqv = ggml_mul_mat_ext(ctx0, v, kq, v_scale, nullptr);
cb(kqv, "kqv", il);
// for MLA with the absorption optimization, we need to "decompress" from MQA back to MHA
if (v_mla) {
kqv = ggml_mul_mat(ctx0, v_mla, kqv);
kqv = build_lora_mm(v_mla, kqv);
cb(kqv, "kqv_mla", il);
}
@@ -3341,7 +3366,6 @@ ggml_tensor * llm_graph_context::build_attn(
llm_graph_input_attn_no_cache * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -3386,7 +3410,7 @@ ggml_tensor * llm_graph_context::build_attn(
cb(cur, "kqv_out", il);
if (wo) {
cur = build_lora_mm(wo, cur, wo_s);
cur = build_lora_mm(wo, cur);
}
if (wo_b) {
@@ -3435,45 +3459,26 @@ llm_graph_input_attn_kv * llm_graph_context::build_attn_inp_kv() const {
static void build_attn_scale_kv_inputs(
ggml_context * ctx,
const llama_kv_cache_context * mctx,
ggml_tensor * & q,
ggml_tensor * & k,
ggml_tensor * & v,
int32_t il) {
if (ggml_tensor * scale = mctx->get_k_scale(il)) {
// Store K/s and move its dequant scale to Q: (Q*s) dot (K/s) = Q dot K.
q = ggml_mul(ctx, q, scale);
if (k) {
if (k) {
if (ggml_tensor * scale = mctx->get_k_scale(il)) {
k = ggml_div(ctx, k, scale);
}
}
if (v) {
// Store V/s here and restore its dequant scale after the weighted sum.
ggml_tensor * scale = mctx->get_v_scale(il);
if (scale) {
if (ggml_tensor * scale = mctx->get_v_scale(il)) {
v = ggml_div(ctx, v, scale);
}
}
}
static ggml_tensor * build_attn_scale_kv_output(
ggml_context * ctx,
const llama_kv_cache_context * mctx,
ggml_tensor * cur,
int32_t il) {
if (ggml_tensor * scale = mctx->get_v_scale(il)) {
// P*(V/s)*s = P*V.
cur = ggml_mul(ctx, cur, scale);
}
return cur;
}
ggml_tensor * llm_graph_context::build_attn(
llm_graph_input_attn_kv * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -3495,7 +3500,7 @@ ggml_tensor * llm_graph_context::build_attn(
const auto * mctx_cur = inp->mctx;
build_attn_scale_kv_inputs(ctx0, mctx_cur, q_cur, k_cur, v_cur, il);
build_attn_scale_kv_inputs(ctx0, mctx_cur, k_cur, v_cur, il);
// these nodes are added to the graph together so that they are not reordered
// by doing so, the number of splits in the graph is reduced
@@ -3529,8 +3534,8 @@ ggml_tensor * llm_graph_context::build_attn(
const auto & kq_mask = inp->self_attn_mask.raw;
const auto & kv_rows = inp->self_attn_mask.rows;
ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il);
cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il);
ggml_tensor * cur = build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, nullptr, nullptr,
mctx_cur->get_k_scale(il), mctx_cur->get_v_scale(il));
cb(cur, "kqv_out", il);
if (inp->self_v_rot[il]) {
@@ -3538,7 +3543,7 @@ ggml_tensor * llm_graph_context::build_attn(
}
if (wo) {
cur = build_lora_mm(wo, cur, wo_s);
cur = build_lora_mm(wo, cur);
}
if (wo_b) {
@@ -3580,7 +3585,6 @@ ggml_tensor * llm_graph_context::build_attn(
llm_graph_input_attn_k * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -3616,7 +3620,7 @@ ggml_tensor * llm_graph_context::build_attn(
cb(cur, "kqv_out", il);
if (wo) {
cur = build_lora_mm(wo, cur, wo_s);
cur = build_lora_mm(wo, cur);
}
if (wo_b) {
@@ -3677,7 +3681,6 @@ ggml_tensor * llm_graph_context::build_attn(
llm_graph_input_attn_k_dsa * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -3730,7 +3733,7 @@ ggml_tensor * llm_graph_context::build_attn(
cb(cur, "kqv_out", il);
if (wo) {
cur = build_lora_mm(wo, cur, wo_s);
cur = build_lora_mm(wo, cur);
}
if (wo_b) {
@@ -3746,7 +3749,6 @@ static ggml_tensor * build_attn_iswa_impl(
llm_graph_input_attn_kv_iswa * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -3785,7 +3787,7 @@ static ggml_tensor * build_attn_iswa_impl(
const auto * mctx_iswa = inp->mctx;
const auto * mctx_cur = is_swa ? mctx_iswa->get_swa() : mctx_iswa->get_base();
build_attn_scale_kv_inputs(ctx0, mctx_cur, q_cur, k_cur, v_cur, il);
build_attn_scale_kv_inputs(ctx0, mctx_cur, k_cur, v_cur, il);
// these nodes are added to the graph together so that they are not reordered
// by doing so, the number of splits in the graph is reduced
@@ -3824,8 +3826,8 @@ static ggml_tensor * build_attn_iswa_impl(
ggml_tensor * k = use_kv_cur ? k_cur : mctx_cur->get_k(ctx0, il);
ggml_tensor * v = use_kv_cur ? v_cur : mctx_cur->get_v(ctx0, il);
ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, bias_table, bias_indices);
cur = build_attn_scale_kv_output(ctx0, mctx_cur, cur, il);
ggml_tensor * cur = gctx.build_attn_mha(q, k, v, kq_b, kq_mask, kv_rows, sinks, v_mla, 0, kq_scale, il, bias_table, bias_indices,
mctx_cur->get_k_scale(il), mctx_cur->get_v_scale(il));
gctx.cb(cur, "kqv_out", il);
if (v_rot) {
@@ -3833,7 +3835,7 @@ static ggml_tensor * build_attn_iswa_impl(
}
if (wo) {
cur = gctx.build_lora_mm(wo, cur, wo_s);
cur = gctx.build_lora_mm(wo, cur);
}
if (wo_b) {
@@ -3851,7 +3853,6 @@ ggml_tensor * llm_graph_context::build_attn(
llm_graph_input_attn_kv_iswa * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -3865,14 +3866,13 @@ ggml_tensor * llm_graph_context::build_attn(
const auto & kq_mask = is_swa ? inp->self_attn_mask_swa.raw : inp->self_attn_mask.raw;
const auto & kv_rows = is_swa ? inp->self_attn_mask_swa.rows : inp->self_attn_mask.rows;
return build_attn_iswa_impl(*this, inp, wo, wo_b, wo_s, q_cur, k_cur, v_cur, kq_b, kq_mask, kv_rows, sinks, v_mla, kq_scale, il);
return build_attn_iswa_impl(*this, inp, wo, wo_b, q_cur, k_cur, v_cur, kq_b, kq_mask, kv_rows, sinks, v_mla, kq_scale, il);
}
ggml_tensor * llm_graph_context::build_attn(
llm_graph_input_attn_k_iswa * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -3926,7 +3926,7 @@ ggml_tensor * llm_graph_context::build_attn(
}
if (wo) {
cur = build_lora_mm(wo, cur, wo_s);
cur = build_lora_mm(wo, cur);
}
if (wo_b) {
@@ -3954,7 +3954,6 @@ ggml_tensor * llm_graph_context::build_attn(
llm_graph_input_attn_cross * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -3980,7 +3979,7 @@ ggml_tensor * llm_graph_context::build_attn(
cb(cur, "kqv_out", il);
if (wo) {
cur = build_lora_mm(wo, cur, wo_s);
cur = build_lora_mm(wo, cur);
}
if (wo_b) {
@@ -4167,7 +4166,9 @@ ggml_tensor * llm_graph_context::build_rs(
uint32_t rs_head,
uint32_t rs_size,
int32_t rs_zero,
const llm_graph_get_rows_fn & get_state_rows) const {
const llm_graph_get_rows_fn & get_state_rows,
bool in_place,
bool from_cache) const {
GGML_UNUSED(rs_size);
ggml_tensor * states = ggml_reshape_2d(ctx0, s, state_size, s->ne[1]);
@@ -4185,9 +4186,22 @@ ggml_tensor * llm_graph_context::build_rs(
ggml_tensor * states_all = ggml_get_rows(ctx0, states, state_copy);
ggml_tensor * output_states = get_state_rows ?
get_state_rows(ctx0, states, state_copy_main) :
ggml_view_2d(ctx0, states_all, state_size, n_seqs, states_all->nb[1], 0);
ggml_tensor * output_states;
if (get_state_rows) {
output_states = get_state_rows(ctx0, states, state_copy_main);
} else if (!from_cache) {
// rollback snapshots: the states are never in place, so the readers read the gathered states directly
output_states = ggml_view_2d(ctx0, states_all, state_size, n_seqs, states_all->nb[1], 0);
} else {
// move the gathered states into their cells, the readers then read them from the cache
// when the states are already in place the gather and the move have no rows, so the graph only changes in size
const int64_t n_move = in_place ? 0 : n_seqs;
ggml_build_forward_expand(gf, ggml_cpy(ctx0,
ggml_view_2d(ctx0, states_all, state_size, n_move, states_all->nb[1], 0),
ggml_view_2d(ctx0, states, state_size, n_move, states->nb[1], rs_head*states->nb[1])));
// view of the cache: all readers must run after the move and before the new states are stored over it
output_states = ggml_view_2d(ctx0, states, state_size, n_seqs, states->nb[1], rs_head*states->nb[1]);
}
ggml_build_forward_expand(gf, output_states);
// copy extra states which won't be changed further (between n_seqs and n_rs)
@@ -4222,6 +4236,9 @@ static std::unique_ptr<llm_graph_input_rs> build_rs_inp_impl(
inp->head = mctx_cur->get_head();
inp->rs_z = mctx_cur->get_rs_z();
inp->rs_in_place = mctx_cur->get_rs_in_place();
inp->s_copy_rows = ggml_view_1d(ctx0, inp->s_copy, inp->rs_in_place ? 0 : n_rs, 0);
inp->has_rep = mctx_cur->get_rs_replay();
if (inp->has_rep) {
// the widest conv window of the model: the delta-net conv, or the PLE n-gram conv (qwen4exp)
@@ -4263,16 +4280,23 @@ ggml_tensor * llm_graph_context::build_rs(
ggml_tensor * s,
int32_t state_size,
int32_t n_seqs,
const llm_graph_get_rows_fn & get_state_rows) const {
const llm_graph_get_rows_fn & get_state_rows,
bool gathered) const {
const auto * kv_state = inp->mctx;
const bool in_place = inp->rs_in_place && !get_state_rows && !gathered;
// the snapshot mode is fixed per context, so the graph shape is stable
const bool from_cache = !gathered && !kv_state->get_rs_snapshots();
GGML_ASSERT(get_state_rows || !from_cache || s->type == GGML_TYPE_F32); // the states are read from the cache, the gather is F32
// a custom getter reads the states of the ubatch straight from the cache, so the gather skips the first
// state: it still holds the n_rs - n_seqs extra states and copies no state of a single sequence ubatch
ggml_tensor * state_copy = get_state_rows ? inp->s_copy_tail : inp->s_copy;
ggml_tensor * state_copy = get_state_rows ? inp->s_copy_tail : from_cache ? inp->s_copy_rows : inp->s_copy;
return build_rs(s, state_copy, inp->s_copy_main, state_size, n_seqs,
kv_state->get_n_rs(), kv_state->get_head(), kv_state->get_size(), kv_state->get_rs_z(),
get_state_rows);
get_state_rows, in_place, from_cache);
}
void llm_graph_context::build_conv_state_store(
@@ -4483,7 +4507,6 @@ ggml_tensor * llm_graph_context::build_attn(
llm_graph_input_mem_hybrid_iswa_rel * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur,
ggml_tensor * k_cur,
ggml_tensor * v_cur,
@@ -4500,7 +4523,7 @@ ggml_tensor * llm_graph_context::build_attn(
GGML_ASSERT(attn_mask.rows == nullptr);
ggml_tensor * indices = is_swa ? inp->self_rel_pos_swa : inp->self_rel_pos;
return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, wo_s, q_cur, k_cur, v_cur, nullptr, attn_mask.raw, nullptr,
return build_attn_iswa_impl(*this, inp_attn, wo, wo_b, q_cur, k_cur, v_cur, nullptr, attn_mask.raw, nullptr,
sinks, nullptr, kq_scale, il, bias_table, indices);
}
@@ -4515,13 +4538,13 @@ void llm_graph_context::build_dense_out(
GGML_ASSERT(cur != nullptr && "missing t_embd_pooled/t_embd");
if (dense_2) {
cur = ggml_mul_mat(ctx0, dense_2, cur);
cur = build_lora_mm(dense_2, cur);
}
if (dense_2_b) {
cur = ggml_add(ctx0, cur, dense_2_b);
}
if (dense_3) {
cur = ggml_mul_mat(ctx0, dense_3, cur);
cur = build_lora_mm(dense_3, cur);
}
cb(cur, "result_embd_pooled", -1);
res->t_embd_pooled = cur;
@@ -4592,7 +4615,7 @@ void llm_graph_context::build_pooling(
// classification head
// https://github.com/huggingface/transformers/blob/5af7d41e49bbfc8319f462eb45253dcb3863dfb7/src/transformers/models/roberta/modeling_roberta.py#L1566
if (cls) {
cur = ggml_mul_mat(ctx0, cls, cur);
cur = build_lora_mm(cls, cur);
if (cls_b) {
cur = ggml_add(ctx0, cur, cls_b);
}
@@ -4608,7 +4631,7 @@ void llm_graph_context::build_pooling(
// Single layer classification head (direct projection)
// https://github.com/huggingface/transformers/blob/f4fc42216cd56ab6b68270bf80d811614d8d59e4/src/transformers/models/bert/modeling_bert.py#L1476
if (cls_out) {
cur = ggml_mul_mat(ctx0, cls_out, cur);
cur = build_lora_mm(cls_out, cur);
if (cls_out_b) {
cur = ggml_add(ctx0, cur, cls_out_b);
}
+28 -19
View File
@@ -24,6 +24,7 @@ struct llama_prec_policy;
struct llama_hadamard;
class llama_moe_cache;
struct llama_weight_scales;
struct llama_memory_context_i;
@@ -341,6 +342,12 @@ public:
// used in view offsets, need to match for valid graph reuse
uint32_t head;
int32_t rs_z;
// the states are read from the cache, see llama_memory_recurrent_context::get_rs_in_place
bool rs_in_place;
// rows to gather, shared by all layers; empty when rs_in_place
ggml_tensor * s_copy_rows; // I32 [n_rs] or [0]
};
class llm_graph_input_cross_embd : public llm_graph_input_i {
@@ -877,6 +884,7 @@ struct llm_graph_params {
ggml_tensor * layer_inp_src = nullptr; // ctx_other's layer input device buffer (read)
ggml_tensor * h_nextn_dev = nullptr; // own h_nextn device buffer (write)
ggml_tensor * h_nextn_src = nullptr; // ctx_state_src's h_nextn device buffer (read)
const llama_weight_scales * w_scales = nullptr;
std::map<llama_seq_id, llama_sampler *> samplers;
@@ -1153,6 +1161,7 @@ struct llm_graph_context {
ggml_tensor * layer_inp_src;
ggml_tensor * h_nextn_dev;
ggml_tensor * h_nextn_src;
const llama_weight_scales * w_scales;
std::map<llama_seq_id, llama_sampler *> samplers;
@@ -1191,14 +1200,16 @@ struct llm_graph_context {
ggml_tensor * w,
ggml_tensor * cur) const;
// do mat_mul, while optionally apply lora and per-tensor scale
// w_s defaults to the weight scale of w
// scale tensor of a weight, nullptr if it has none
ggml_tensor * get_weight_scale(const ggml_tensor * w) const;
ggml_tensor * get_input_scale(const ggml_tensor * w) const;
// do mat_mul, while optionally apply lora and the weight scale
ggml_tensor * build_lora_mm(
ggml_tensor * w,
ggml_tensor * cur,
ggml_tensor * w_s = nullptr) const;
ggml_tensor * cur) const;
// do mat_mul_id, while optionally apply lora and per-expert scale
// do mat_mul_id, while optionally apply lora and the weight scale
// if slots is set, the experts are selected by slots instead of ids, from the MoE cache if cached (see llama_moe_cache::build_lookup)
ggml_tensor * build_lora_mm_id(
ggml_tensor * w, // ggml_tensor * as
@@ -1247,13 +1258,10 @@ struct llm_graph_context {
ggml_tensor * cur,
ggml_tensor * up,
ggml_tensor * up_b,
ggml_tensor * up_s,
ggml_tensor * gate,
ggml_tensor * gate_b,
ggml_tensor * gate_s,
ggml_tensor * down,
ggml_tensor * down_b,
ggml_tensor * down_s,
ggml_tensor * act_scales,
llm_ffn_op_type type_op,
llm_ffn_gate_type type_gate,
@@ -1351,7 +1359,9 @@ struct llm_graph_context {
float kq_scale,
int il,
ggml_tensor * bias_table = nullptr, // [n_bins, n_head_q, n_tokens]
ggml_tensor * bias_indices = nullptr) const;
ggml_tensor * bias_indices = nullptr,
ggml_tensor * k_scale = nullptr,
ggml_tensor * v_scale = nullptr) const;
llm_graph_input_attn_no_cache * build_attn_inp_no_cache() const;
@@ -1359,7 +1369,6 @@ struct llm_graph_context {
llm_graph_input_attn_no_cache * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
@@ -1375,7 +1384,6 @@ struct llm_graph_context {
llm_graph_input_attn_kv * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
@@ -1391,7 +1399,6 @@ struct llm_graph_context {
llm_graph_input_attn_k * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
@@ -1411,7 +1418,6 @@ struct llm_graph_context {
llm_graph_input_attn_k_dsa * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
@@ -1443,7 +1449,6 @@ struct llm_graph_context {
llm_graph_input_attn_kv_iswa * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] optional
ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] optional
@@ -1461,7 +1466,6 @@ struct llm_graph_context {
llm_graph_input_attn_k_iswa * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens] optional
ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens] optional
@@ -1477,7 +1481,6 @@ struct llm_graph_context {
llm_graph_input_attn_cross * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
@@ -1496,6 +1499,7 @@ struct llm_graph_context {
// when moving, avoid passing `ggml_cgraph` - only pass `ggml_context`. would likely need to split the
// implementation in 2 separate methods. the goal is to avoid calling `ggml_build_forward_expand` in
// `llama_memory_recurrent`
// note: same rules as the build_rs overload below (readers before the store, one call per state tensor per graph)
ggml_tensor * build_rs(
ggml_tensor * s,
ggml_tensor * state_copy,
@@ -1506,16 +1510,22 @@ struct llm_graph_context {
uint32_t rs_head,
uint32_t rs_size,
int32_t rs_zero,
const llm_graph_get_rows_fn & get_state_rows = nullptr) const;
const llm_graph_get_rows_fn & get_state_rows = nullptr,
bool in_place = false,
bool from_cache = true) const;
llm_graph_input_rs * build_rs_inp() const;
// the returned states can be a view of the cache, so callers must follow 2 rules:
// - expand every reader of the returned tensor before the store into s (the rwkv token shift gets this only from the expand order)
// - call it once per state tensor per graph: a second call would gather rows that the first already moved into [head, head + n_seqs)
ggml_tensor * build_rs(
llm_graph_input_rs * inp,
ggml_tensor * s,
int32_t state_size,
int32_t n_seqs,
const llm_graph_get_rows_fn & get_state_rows = nullptr) const;
const llm_graph_get_rows_fn & get_state_rows = nullptr,
bool gathered = false) const; // gathered: always read a copy, never the cache
// store the conv history of the ubatch cells, the last n_cols columns of conv_x {n_cols + n_seq_tokens, channels, n_seqs},
// at byte offset offs of each row of s, and with n_rs_seq > 0 once per rollback slot of this ubatch
@@ -1553,7 +1563,6 @@ struct llm_graph_context {
llm_graph_input_mem_hybrid_iswa_rel * inp,
ggml_tensor * wo,
ggml_tensor * wo_b,
ggml_tensor * wo_s,
ggml_tensor * q_cur, // [n_embd_head_q, n_head_q, n_tokens]
ggml_tensor * k_cur, // [n_embd_head_k, n_head_k, n_tokens]
ggml_tensor * v_cur, // [n_embd_head_v, n_head_v, n_tokens]
+3 -7
View File
@@ -1455,12 +1455,8 @@ ggml_tensor * llama_kv_cache::get_v(ggml_context * ctx, int32_t il, uint32_t n_k
ggml_row_size(v->type, kv_size*n_embd_v_gqa)*sinfo.s0);
}
static bool is_type_scaled(ggml_type type) {
return type == GGML_TYPE_F8_E4M3;
}
ggml_tensor * llama_kv_cache::get_k_scale(int32_t il) const {
if (!is_type_scaled(type_k())) {
if (!ggml_needs_scale(type_k())) {
return nullptr;
}
@@ -1470,7 +1466,7 @@ ggml_tensor * llama_kv_cache::get_k_scale(int32_t il) const {
}
ggml_tensor * llama_kv_cache::get_v_scale(int32_t il) const {
if (!is_type_scaled(type_v())) {
if (!ggml_needs_scale(type_v())) {
return nullptr;
}
@@ -2252,7 +2248,7 @@ ggml_tensor * llama_kv_cache::build_rope_shift(
const int64_t n_embd_head_k = hparams.n_embd_head_k(il);
const int64_t n_cells = ggml_nelements(k)/n_embd_k_gqa;
if (!ggml_is_quantized(k->type) && k->type != GGML_TYPE_F8_E4M3 && !rot && !rp.k_norm) {
if (!ggml_is_quantized(k->type) && !ggml_needs_scale(k->type) && !rot && !rp.k_norm) {
// we rotate only the n_rot dimensions
ggml_tensor * k_rope =
ggml_view_3d(ctx, k,
+21
View File
@@ -1461,6 +1461,22 @@ int32_t llama_memory_recurrent_context::get_rs_z() const {
return is_full ? 0 : mem->rs_z;
}
bool llama_memory_recurrent_context::get_rs_in_place() const {
// rollback snapshots, zeroed states and extra states go through the gather
if (is_full || get_rs_snapshots() || mem->rs_z >= 0 || mem->n != get_ubatch().n_seqs) {
return false;
}
for (uint32_t i = 0; i < mem->n; ++i) {
// s_copy() would also reset the rollback idx, which set_input reads later
if (mem->cells[mem->head + i].src0 != (int32_t) (mem->head + i)) {
return false;
}
}
return true;
}
uint32_t llama_memory_recurrent_context::get_size() const {
return mem->size;
}
@@ -1493,6 +1509,11 @@ bool llama_memory_recurrent_context::get_rs_replay() const {
return mem->rs_replay;
}
bool llama_memory_recurrent_context::get_rs_snapshots() const {
// rs_replay keeps one state plane, so its states can be in place like without rollback
return mem->n_rs_seq != 0 && !mem->rs_replay;
}
uint32_t llama_memory_recurrent_context::get_rs_rep(int i) const {
return is_full ? 0 : mem->cells[i + mem->head].rs_rep;
}
+2
View File
@@ -192,6 +192,7 @@ public:
uint32_t get_head() const;
int32_t get_rs_z() const;
uint32_t get_size() const;
bool get_rs_in_place() const; // every state of the ubatch is read from its own cell
ggml_tensor * get_r_l(int32_t il) const;
ggml_tensor * get_s_l(int32_t il) const;
@@ -203,6 +204,7 @@ public:
int32_t s_copy(int i) const;
bool get_rs_replay() const;
bool get_rs_snapshots() const; // rollback keeps per-seq snapshots: the states are never in place
uint32_t get_rs_rep(int i) const; // pending tokens replayed by ubatch seq i
private:
+93 -7
View File
@@ -1012,7 +1012,7 @@ const struct ggml_tensor * llama_model_loader::check_tensor_dims(
}
// checks if the weight tensor can be used with the specified buffer type and device
static bool weight_buft_supported(const llama_hparams & hparams, ggml_tensor * w, ggml_op op, ggml_backend_buffer_type_t buft, ggml_backend_dev_t dev) {
static bool weight_buft_supported(const llama_hparams & hparams, ggml_tensor * w, const ggml_tensor * scale_meta, ggml_op op, ggml_backend_buffer_type_t buft, ggml_backend_dev_t dev) {
GGML_ASSERT(w != nullptr);
if (op == GGML_OP_NONE) {
@@ -1048,7 +1048,8 @@ static bool weight_buft_supported(const llama_hparams & hparams, ggml_tensor * w
case GGML_OP_MUL_MAT:
{
ggml_tensor * b = ggml_new_tensor_4d(ctx, GGML_TYPE_F32, w->ne[0], 512, w->ne[2], w->ne[3]);
op_tensor = ggml_mul_mat(ctx, w, b);
ggml_tensor * s = scale_meta ? ggml_new_tensor(ctx, GGML_TYPE_F32, GGML_MAX_DIMS, scale_meta->ne) : nullptr;
op_tensor = ggml_mul_mat_ext(ctx, w, b, s, nullptr);
} break;
case GGML_OP_MUL_MAT_ID:
{
@@ -1057,7 +1058,8 @@ static bool weight_buft_supported(const llama_hparams & hparams, ggml_tensor * w
GGML_ASSERT(n_ids_used > 0);
ggml_tensor * b = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, w->ne[0], n_ids_used, 512);
ggml_tensor * ids = ggml_new_tensor_2d(ctx, GGML_TYPE_I32, n_ids_used, 512);
op_tensor = ggml_mul_mat_id(ctx, w, b, ids);
ggml_tensor * s = scale_meta ? ggml_new_tensor(ctx, GGML_TYPE_F32, GGML_MAX_DIMS, scale_meta->ne) : nullptr;
op_tensor = ggml_mul_mat_id_ext(ctx, w, b, ids, s, nullptr);
} break;
case GGML_OP_ADD:
{
@@ -1159,12 +1161,12 @@ static bool weight_buft_supported(const llama_hparams & hparams, ggml_tensor * w
}
// find the first buffer type in the list that can use the tensor
static ggml_backend_buffer_type_t select_weight_buft(const llama_hparams & hparams, ggml_tensor * tensor, ggml_op op, const buft_list_t * buft_list) {
static ggml_backend_buffer_type_t select_weight_buft(const llama_hparams & hparams, ggml_tensor * tensor, const ggml_tensor * scale_meta, ggml_op op, const buft_list_t * buft_list) {
GGML_ASSERT(!buft_list->empty());
for (const auto & cur : *buft_list) {
ggml_backend_dev_t cur_dev = cur.first;
ggml_backend_buffer_type_t cur_buft = cur.second;
if (weight_buft_supported(hparams, tensor, op, cur_buft, cur_dev)) {
if (weight_buft_supported(hparams, tensor, scale_meta, op, cur_buft, cur_dev)) {
return cur_buft;
}
}
@@ -1280,11 +1282,37 @@ struct ggml_tensor * llama_model_loader::create_tensor(
return nullptr;
}
const bool is_matmul = info.op == GGML_OP_MUL_MAT || info.op == GGML_OP_MUL_MAT_ID;
const bool is_matmul_weight = is_matmul && tn.suffix != nullptr && strcmp(tn.suffix, "weight") == 0 && !(flags & TENSOR_NO_SCALE);
const bool is_matmul_scale = is_matmul && tn.suffix != nullptr &&
(strcmp(tn.suffix, "scale") == 0 || strcmp(tn.suffix, "input_scale") == 0);
if ((flags & TENSOR_NO_SCALE) && ggml_needs_scale(t_meta->type)) {
throw std::runtime_error(format("tensor '%s' takes no weight scale, so type %s is not supported; re-convert the model",
tn.str().c_str(), ggml_type_name(t_meta->type)));
}
// the scale is a source of the matmul, so it goes where the weight is
if (is_matmul_scale) {
const auto it = matmul_weight_bufts.find(LLM_TN_IMPL(tn.arch, tn.tensor, "weight", tn.bid, tn.xid).str());
if (it != matmul_weight_bufts.end()) {
ggml_backend_dev_t dev = ggml_backend_buft_get_device(it->second);
// CPU extra buffers (repack, AMX, KleidiAI) only hold the layouts of their weights
if (dev && ggml_backend_dev_type(dev) == GGML_BACKEND_DEVICE_TYPE_CPU && !ggml_backend_buft_is_host(it->second)) {
return ggml_backend_dev_buffer_type(dev);
}
return it->second;
}
}
// tensors with "bias" suffix are always used with GGML_OP_ADD or GGML_OP_ADD_ID;
// embedded-adapter ".lora_a"/".lora_b" tensors are always used with GGML_OP_MUL_MAT_ID
ggml_op op;
if (tn.suffix != nullptr && strcmp(tn.suffix, "bias") == 0) {
op = info.op == GGML_OP_MUL_MAT_ID ? GGML_OP_ADD_ID : GGML_OP_ADD;
} else if (is_matmul_scale) {
// scale without a weight
op = GGML_OP_MUL;
} else if (hparams.router_layer >= 0 && tn.suffix != nullptr &&
(strcmp(tn.suffix, "lora_a") == 0 || strcmp(tn.suffix, "lora_b") == 0)) {
op = GGML_OP_MUL_MAT_ID;
@@ -1303,7 +1331,38 @@ struct ggml_tensor * llama_model_loader::create_tensor(
}
}
const ggml_tensor * scale_meta = nullptr;
ggml_tensor user_scale_meta = {};
if (is_matmul_weight && (op == GGML_OP_MUL_MAT || op == GGML_OP_MUL_MAT_ID)) {
const std::string scale_name = LLM_TN_IMPL(tn.arch, tn.tensor, "scale", tn.bid, tn.xid).str();
scale_meta = get_tensor_meta(scale_name.c_str());
if (!scale_meta && files.empty()) {
const int64_t tid = gguf_find_tensor(metadata, scale_name.c_str());
if (tid != -1) {
user_scale_meta.type = gguf_get_tensor_type(metadata, tid);
memcpy(user_scale_meta.ne, gguf_get_tensor_ne(metadata, tid), sizeof(user_scale_meta.ne));
scale_meta = &user_scale_meta;
}
}
if (!scale_meta && ggml_needs_scale(t_meta->type)) {
throw std::runtime_error(format("tensor '%s' of type %s requires a weight scale, but '%s' is missing; re-convert the model",
tn.str().c_str(), ggml_type_name(t_meta->type), scale_name.c_str()));
}
if (scale_meta && op == GGML_OP_MUL_MAT && !ggml_is_scalar(scale_meta) &&
!(ggml_is_vector(scale_meta) && scale_meta->ne[0] == t_meta->ne[1])) {
throw std::runtime_error(format("weight scale tensor '%s' must be scalar or have one value per output channel", scale_name.c_str()));
}
if (scale_meta && op == GGML_OP_MUL_MAT_ID && !ggml_is_scalar(scale_meta) &&
!(ggml_is_vector(scale_meta) && scale_meta->ne[0] == t_meta->ne[2]) &&
!(scale_meta->ne[0] == t_meta->ne[1] && scale_meta->ne[1] == t_meta->ne[2] && scale_meta->ne[2] == 1 && scale_meta->ne[3] == 1)) {
throw std::runtime_error(format("weight scale tensor '%s' must be scalar, per expert or per output channel and expert", scale_name.c_str()));
}
}
if (is_lazy) {
if (is_matmul_weight) {
matmul_weight_bufts[tn.str()] = lazy_read::buft();
}
return lazy_read::buft();
}
@@ -1334,7 +1393,7 @@ struct ggml_tensor * llama_model_loader::create_tensor(
if (std::regex_search(tensor_name, pattern)) {
if (overrides->buft == ggml_backend_cpu_buffer_type()) {
// when overriding to a CPU buffer, consider the extra buffer types
buft = select_weight_buft(hparams, t_meta, op, buft_list_cpu);
buft = select_weight_buft(hparams, t_meta, scale_meta, op, buft_list_cpu);
if (use_mmap) {
static std::once_flag once;
std::call_once(once, [] {
@@ -1355,7 +1414,7 @@ struct ggml_tensor * llama_model_loader::create_tensor(
}
if (!buft) {
buft = select_weight_buft(hparams, t_meta, op, buft_list);
buft = select_weight_buft(hparams, t_meta, scale_meta, op, buft_list);
if (!buft) {
throw std::runtime_error(format("failed to find a compatible buffer type for tensor %s", tn.str().c_str()));
}
@@ -1381,6 +1440,10 @@ struct ggml_tensor * llama_model_loader::create_tensor(
n_tensors_moved++;
}
if (is_matmul_weight) {
matmul_weight_bufts[tn.str()] = buft;
}
return buft;
};
@@ -1485,6 +1548,29 @@ struct ggml_tensor * llama_model_loader::create_tensor(
}
void llama_model_loader::done_getting_tensors(bool partial) const {
std::unordered_set<std::string> created;
for (const auto & it : ctx_map) {
for (ggml_tensor * t = ggml_get_first_tensor(it.second.get()); t; t = ggml_get_next_tensor(it.second.get(), t)) {
created.insert(ggml_get_name(t));
}
}
for (const auto & it : ctx_map) {
for (ggml_tensor * t = ggml_get_first_tensor(it.second.get()); t; t = ggml_get_next_tensor(it.second.get(), t)) {
if (!ggml_needs_scale(t->type)) {
continue;
}
std::string scale_name = ggml_get_name(t);
if (scale_name.size() > 7 && scale_name.compare(scale_name.size() - 7, 7, ".weight") == 0) {
scale_name.resize(scale_name.size() - 7);
}
scale_name += ".scale";
if (!created.count(scale_name)) {
throw std::runtime_error(format("tensor '%s' of type %s requires a weight scale, but '%s' is missing or not used by this architecture; re-convert the model",
ggml_get_name(t), ggml_type_name(t->type), scale_name.c_str()));
}
}
}
if (n_created > n_tensors) {
throw std::runtime_error(format("%s: too many tensors created; expected %d, got %d", __func__, n_tensors, n_created));
}
+4
View File
@@ -68,6 +68,7 @@ struct llama_model_loader {
static const int TENSOR_SKIP_IF_VIRTUAL = 1 << 3;
static const int TENSOR_ALLOW_RESHAPE = 1 << 4;
static const int TENSOR_READ_LAZY = 1 << 5; // read rows on demand instead of loading whole tensor; requires mmap for now
static const int TENSOR_NO_SCALE = 1 << 6; // this weight takes no dequantization scale
int n_kv = 0;
int n_tensors = 0;
@@ -162,6 +163,9 @@ struct llama_model_loader {
std::map<ctx_key, ggml_context_ptr, ctx_key_comparator> ctx_map;
// buffer types of the matmul weights, their scales are placed with them
std::unordered_map<std::string, ggml_backend_buffer_type_t> matmul_weight_bufts;
// track tensors that had to be moved for debugging:
size_t n_tensors_moved = 0;
std::string first_tensor_moved_name;
+18 -2
View File
@@ -10,9 +10,12 @@
#include "llama-model.h"
#include "llama-vocab.h"
#include <algorithm>
#include <cstdint>
#include <cstring>
#include <string>
#include <unordered_set>
#include <vector>
llama_model_saver::llama_model_saver(const struct llama_model * model) :
gguf_ctx(gguf_init_empty()), model(model), llm_kv(model->arch) {
@@ -528,8 +531,6 @@ void llama_model_saver::add_tensors_from_model() {
add_tensor(model->output);
add_tensor(model->output_b);
add_tensor(model->output_norm_enc);
add_tensor(model->output_s);
add_tensor(model->output_in_s);
add_tensor(model->output_res_score);
add_tensor(model->output_res_query);
add_tensor(model->nextn_proj_pre);
@@ -593,6 +594,21 @@ void llama_model_saver::add_tensors_from_model() {
add_tensor(tensor);
}
}
std::vector<const struct ggml_tensor *> scales;
for (const auto * map : { &model->w_scales.scale, &model->w_scales.input_scale }) {
for (const auto & [_, s] : *map) {
if (seen.insert(s).second) {
scales.push_back(s);
}
}
}
std::sort(scales.begin(), scales.end(), [](const ggml_tensor * a, const ggml_tensor * b) {
return strcmp(a->name, b->name) < 0;
});
for (const auto * s : scales) {
add_tensor(s);
}
}
void llama_model_saver::save(const std::string & path_model) {
+64 -198
View File
@@ -441,6 +441,20 @@ struct ggml_backend_meta_split_state llama_meta_device_get_split_state(const str
(ud->model->arch == LLM_ARCH_DFLASH && hparams.dsv4_hc_mult > 0);
const bool is_glm5_next = ud->model->arch == LLM_ARCH_GLM5_NEXT;
// a per-output-channel scale indexes the weight's ne[1], so it splits on ne[0] to match
if (tensor_name.size() >= 6 && tensor_name.compare(tensor_name.size() - 6, 6, ".scale") == 0) {
const std::string weight_name = tensor_name.substr(0, tensor_name.size() - 6) + ".weight";
const ggml_tensor * w = ud->model->get_tensor(weight_name.c_str());
if (w != nullptr) {
ggml_backend_meta_split_state ws = llama_meta_device_get_split_state(w, userdata);
if (ws.axis == GGML_BACKEND_SPLIT_AXIS_1 && tensor->ne[0] == w->ne[1]) {
ws.axis = GGML_BACKEND_SPLIT_AXIS_0;
return ws;
}
}
return {GGML_BACKEND_SPLIT_AXIS_MIRRORED, {0}, {1}, 1};
}
static const std::regex pattern_q_weight ("blk\\.\\d*\\.attn_q.weight");
static const std::regex pattern_kv_weight ("blk\\.\\d*\\.attn_(k|v).weight");
static const std::regex pattern_v_exps_weight ("blk\\.\\d*\\.attn_v_exps.weight"); // K2 Horizon MoVA
@@ -1949,8 +1963,6 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
// call the per-model loading function
load_arch_tensors(ml);
// generic pass: load optional per-tensor/per-expert ".scale" tensors (e.g. NVFP4 scale2)
// this avoids having to add scale loading to every architecture
for (int i = 0; i < n_layer_all; ++i) {
auto & layer = layers[i];
@@ -1963,161 +1975,6 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
throw std::runtime_error(format("KV cache scales for layer %d must be F32", i));
}
}
// attention weight scales (per-tensor, shape {1})
if (!layer.wq_s && layer.wq) {
layer.wq_s = create_tensor(tn(LLM_TENSOR_ATTN_Q, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wk_s && layer.wk) {
layer.wk_s = create_tensor(tn(LLM_TENSOR_ATTN_K, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wv_s && layer.wv) {
layer.wv_s = create_tensor(tn(LLM_TENSOR_ATTN_V, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wo_s && layer.wo) {
layer.wo_s = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wqkv_s && layer.wqkv) {
layer.wqkv_s = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wqkv_gate_s && layer.wqkv_gate) {
layer.wqkv_gate_s = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
// dense FFN weight scales (per-tensor, shape {1})
if (!layer.ffn_gate_s && layer.ffn_gate) {
layer.ffn_gate_s = create_tensor(tn(LLM_TENSOR_FFN_GATE, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_down_s && layer.ffn_down) {
layer.ffn_down_s = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_up_s && layer.ffn_up) {
layer.ffn_up_s = create_tensor(tn(LLM_TENSOR_FFN_UP, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_gate_shexp_s && layer.ffn_gate_shexp) {
layer.ffn_gate_shexp_s = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_down_shexp_s && layer.ffn_down_shexp) {
layer.ffn_down_shexp_s = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_up_shexp_s && layer.ffn_up_shexp) {
layer.ffn_up_shexp_s = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
// MoE expert weight scales (per-expert, shape {n_expert})
if (!layer.ffn_gate_exps_s && layer.ffn_gate_exps) {
layer.ffn_gate_exps_s = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "scale", i), {n_expert}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_down_exps_s && layer.ffn_down_exps) {
layer.ffn_down_exps_s = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "scale", i), {n_expert}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_up_exps_s && layer.ffn_up_exps) {
layer.ffn_up_exps_s = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "scale", i), {n_expert}, TENSOR_NOT_REQUIRED);
if (layer.ffn_up_exps_s && layer.ffn_gate_up_exps) {
throw std::runtime_error(format("ffn_up_exps.scale and ffn_gate_up_exps.weight both exist for layer %d", i));
}
}
if (!layer.ffn_up_exps_s && layer.ffn_gate_up_exps) {
layer.ffn_up_exps_s = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "scale", i), {n_expert}, TENSOR_NOT_REQUIRED);
}
// recurrent / linear-attention weight scales (per-tensor, shape {1})
if (!layer.ssm_in_s && layer.ssm_in) {
layer.ssm_in_s = create_tensor(tn(LLM_TENSOR_SSM_IN, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ssm_out_s && layer.ssm_out) {
layer.ssm_out_s = create_tensor(tn(LLM_TENSOR_SSM_OUT, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ssm_alpha_s && layer.ssm_alpha) {
layer.ssm_alpha_s = create_tensor(tn(LLM_TENSOR_SSM_ALPHA, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ssm_beta_s && layer.ssm_beta) {
layer.ssm_beta_s = create_tensor(tn(LLM_TENSOR_SSM_BETA, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.nextn.eh_proj_s && layer.nextn.eh_proj) {
layer.nextn.eh_proj_s = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.nextn.shared_head_head_s && layer.nextn.shared_head_head) {
layer.nextn.shared_head_head_s = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
// input scales
if (!layer.wq_in_s && layer.wq) {
layer.wq_in_s = create_tensor(tn(LLM_TENSOR_ATTN_Q, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wk_in_s && layer.wk) {
layer.wk_in_s = create_tensor(tn(LLM_TENSOR_ATTN_K, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wv_in_s && layer.wv) {
layer.wv_in_s = create_tensor(tn(LLM_TENSOR_ATTN_V, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wo_in_s && layer.wo) {
layer.wo_in_s = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wqkv_in_s && layer.wqkv) {
layer.wqkv_in_s = create_tensor(tn(LLM_TENSOR_ATTN_QKV, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.wqkv_gate_in_s && layer.wqkv_gate) {
layer.wqkv_gate_in_s = create_tensor(tn(LLM_TENSOR_ATTN_GATE, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_gate_in_s && layer.ffn_gate) {
layer.ffn_gate_in_s = create_tensor(tn(LLM_TENSOR_FFN_GATE, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_down_in_s && layer.ffn_down) {
layer.ffn_down_in_s = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_up_in_s && layer.ffn_up) {
layer.ffn_up_in_s = create_tensor(tn(LLM_TENSOR_FFN_UP, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_gate_exps_in_s && layer.ffn_gate_exps) {
layer.ffn_gate_exps_in_s = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "input_scale", i), {n_expert}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_down_exps_in_s && layer.ffn_down_exps) {
layer.ffn_down_exps_in_s = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "input_scale", i), {n_expert}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_up_exps_in_s && layer.ffn_up_exps) {
layer.ffn_up_exps_in_s = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "input_scale", i), {n_expert}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_gate_shexp_in_s && layer.ffn_gate_shexp) {
layer.ffn_gate_shexp_in_s = create_tensor(tn(LLM_TENSOR_FFN_GATE_SHEXP, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_down_shexp_in_s && layer.ffn_down_shexp) {
layer.ffn_down_shexp_in_s = create_tensor(tn(LLM_TENSOR_FFN_DOWN_SHEXP, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ffn_up_shexp_in_s && layer.ffn_up_shexp) {
layer.ffn_up_shexp_in_s = create_tensor(tn(LLM_TENSOR_FFN_UP_SHEXP, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ssm_in_in_s && layer.ssm_in) {
layer.ssm_in_in_s = create_tensor(tn(LLM_TENSOR_SSM_IN, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ssm_out_in_s && layer.ssm_out) {
layer.ssm_out_in_s = create_tensor(tn(LLM_TENSOR_SSM_OUT, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ssm_alpha_in_s && layer.ssm_alpha) {
layer.ssm_alpha_in_s = create_tensor(tn(LLM_TENSOR_SSM_ALPHA, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.ssm_beta_in_s && layer.ssm_beta) {
layer.ssm_beta_in_s = create_tensor(tn(LLM_TENSOR_SSM_BETA, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.nextn.eh_proj_in_s && layer.nextn.eh_proj) {
layer.nextn.eh_proj_in_s = create_tensor(tn(LLM_TENSOR_NEXTN_EH_PROJ, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
if (!layer.nextn.shared_head_head_in_s && layer.nextn.shared_head_head) {
layer.nextn.shared_head_head_in_s = create_tensor(tn(LLM_TENSOR_NEXTN_SHARED_HEAD_HEAD, "input_scale", i), {1}, TENSOR_NOT_REQUIRED);
}
}
// output scales
if (output) {
// weight scale
if (!output_s && (ml.get_weight(tn(LLM_TENSOR_OUTPUT, "scale").str().c_str()) ||
gguf_find_tensor(ml.metadata, tn(LLM_TENSOR_OUTPUT, "scale").str().c_str()) >= 0)) {
output_s = create_tensor(tn(LLM_TENSOR_OUTPUT, "scale"), {1}, TENSOR_NOT_REQUIRED);
}
// input scale
if (!output_in_s && (ml.get_weight(tn(LLM_TENSOR_OUTPUT, "input_scale").str().c_str()) ||
gguf_find_tensor(ml.metadata, tn(LLM_TENSOR_OUTPUT, "input_scale").str().c_str()) >= 0)) {
output_in_s = create_tensor(tn(LLM_TENSOR_OUTPUT, "input_scale"), {1}, TENSOR_NOT_REQUIRED);
}
}
post_arch_tensors(ml);
}
@@ -2130,11 +1987,6 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
can_prefetch.insert(per_layer_tok_embd);
}
if (output && tok_embd &&
strcmp(output->name, tok_embd->name) == 0 &&
(output_s || output_in_s)) {
throw std::runtime_error("output scales require a separate output weight");
}
// populate tensors_by_name
for (auto & [_, ctx_ptr] : ml.ctx_map) {
for (auto * cur = ggml_get_first_tensor(ctx_ptr.get()); cur != NULL; cur = ggml_get_next_tensor(ctx_ptr.get(), cur)) {
@@ -2142,35 +1994,6 @@ bool llama_model_base::load_tensors(llama_model_loader & ml) {
}
}
// map each weight to its "<name>.scale" tensor: shape {1} for a 2D weight, {n_expert} for a 3D weight
{
auto ends_with = [](const std::string & str, const std::string & suffix) {
return str.size() >= suffix.size() && str.compare(str.size() - suffix.size(), suffix.size(), suffix) == 0;
};
std::unordered_map<std::string, ggml_tensor *> weights;
for (const auto & [name, cur] : tensors_by_name) {
if (ends_with(name, ".weight")) {
weights.emplace(name.substr(0, name.size() - 7), cur);
}
}
for (const auto & [name, s] : tensors_by_name) {
if (!ends_with(name, ".scale")) {
continue;
}
const auto it = weights.find(name.substr(0, name.size() - 6));
if (it == weights.end()) {
continue;
}
ggml_tensor * w = it->second;
const bool ok = w->ne[3] == 1 && ggml_nelements(s) == w->ne[2] && s->ne[0] == w->ne[2];
if (ok) {
w_scales.emplace(w, s);
} else {
LLAMA_LOG_DEBUG("%s: '%s' is not a weight scale for '%s', skipping\n", __func__, name.c_str(), w->name);
}
}
}
load_prec_policy(ml);
ml.init_mappings(true, use_mlock ? &pimpl->mlock_mmaps : nullptr);
@@ -2682,9 +2505,56 @@ ggml_tensor * llama_model_base::create_tensor(llama_model_loader & ml, const LLM
// blocks that are not model layers (e.g. the blocks of a head) go with the output
buft_list_layer = (size_t) tn.bid < pimpl->dev_layer.size() ? pimpl->dev_layer.at(tn.bid).buft_list : pimpl->dev_output.buft_list;
}
return ml.create_tensor(
ggml_tensor * t = ml.create_tensor(
hparams, &pimpl->cpu_buft_list, pimpl->dev_input.buft_list, pimpl->dev_output.buft_list, buft_list_layer,
tn, ne, flags);
if (tn.suffix == nullptr || strcmp(tn.suffix, "weight") != 0 || (flags & llama_model_loader::TENSOR_NO_SCALE)) {
return t;
}
const ggml_op op = llm_tensor_info_for(tn.tensor).op;
if (op != GGML_OP_MUL_MAT && op != GGML_OP_MUL_MAT_ID) {
return t;
}
if (t == nullptr && !(flags & llama_model_loader::TENSOR_SKIP)) {
return t;
}
const int scale_flags = TENSOR_NOT_REQUIRED | (flags & (TENSOR_SKIP | TENSOR_DUPLICATED));
const std::pair<const char *, std::unordered_map<const ggml_tensor *, ggml_tensor *> *> scale_suffixes[] = {
{ "scale", &w_scales.scale },
{ "input_scale", &w_scales.input_scale },
};
for (const auto & [suffix, map] : scale_suffixes) {
const LLM_TN_IMPL tn_s(tn.arch, tn.tensor, suffix, tn.bid, tn.xid);
const std::string name = tn_s.str();
const ggml_tensor * meta = ml.get_tensor_meta(name.c_str());
const int64_t * ne = nullptr;
if (meta != nullptr) {
ne = meta->ne;
} else {
const int64_t tid = gguf_find_tensor(ml.metadata, name.c_str());
if (tid == -1) {
continue;
}
ne = gguf_get_tensor_ne(ml.metadata, tid);
}
ggml_tensor * s = ml.create_tensor(
hparams, &pimpl->cpu_buft_list, pimpl->dev_input.buft_list, pimpl->dev_output.buft_list, buft_list_layer,
tn_s, {ne[0], ne[1], ne[2], ne[3]}, scale_flags);
if (t != nullptr && s != nullptr) {
if (s->type != GGML_TYPE_F32) {
throw std::runtime_error(format("scale tensor %s must be F32", s->name));
}
if (strcmp(suffix, "input_scale") == 0 && !ggml_is_scalar(s) &&
!(op == GGML_OP_MUL_MAT_ID && ggml_is_vector(s) && s->ne[0] == t->ne[2])) {
throw std::runtime_error(format("input scale tensor %s must be scalar or have one value per expert", s->name));
}
(*map)[t] = s;
}
}
return t;
}
std::string llama_model::arch_name() const {
@@ -2707,11 +2577,6 @@ size_t llama_model::size() const {
return pimpl->n_bytes;
}
ggml_tensor * llama_model::get_w_scale(const ggml_tensor * w) const {
const auto it = w_scales.find(w);
return it == w_scales.end() ? nullptr : it->second;
}
size_t llama_model::n_tensors() const {
return tensors_by_name.size();
}
@@ -4274,7 +4139,8 @@ llama_model_base::llama_model_base(const struct llama_model_params & params) : l
TENSOR_SKIP (llama_model_loader::TENSOR_SKIP),
TENSOR_SKIP_IF_VIRTUAL(llama_model_loader::TENSOR_SKIP_IF_VIRTUAL),
TENSOR_ALLOW_RESHAPE (llama_model_loader::TENSOR_ALLOW_RESHAPE),
TENSOR_READ_LAZY (llama_model_loader::TENSOR_READ_LAZY) {}
TENSOR_READ_LAZY (llama_model_loader::TENSOR_READ_LAZY),
TENSOR_NO_SCALE (llama_model_loader::TENSOR_NO_SCALE) {}
ggml_tensor * llama_model_base::create_tensor(const LLM_TN_IMPL & tn, const std::initializer_list<int64_t> & ne, int flags) {
GGML_ASSERT(ml != nullptr);
+29 -68
View File
@@ -246,14 +246,10 @@ struct llama_layer_zaya1 {
struct llama_layer_nextn {
struct ggml_tensor * eh_proj = nullptr;
struct ggml_tensor * eh_proj_s = nullptr;
struct ggml_tensor * eh_proj_in_s = nullptr;
struct ggml_tensor * embed_tokens = nullptr;
struct ggml_tensor * enorm = nullptr;
struct ggml_tensor * hnorm = nullptr;
struct ggml_tensor * shared_head_head = nullptr;
struct ggml_tensor * shared_head_head_s = nullptr;
struct ggml_tensor * shared_head_head_in_s = nullptr;
struct ggml_tensor * shared_head_norm = nullptr;
// qwen4exp: the MTP block collapses its hyper-connection streams with its own mixer
@@ -378,11 +374,6 @@ struct llama_layer {
struct ggml_tensor * ffn_up_exps_b = nullptr;
struct ggml_tensor * ffn_gate_up_exps_b = nullptr;
// ff MoE per-expert scales (NVFP4 per-tensor scale2)
struct ggml_tensor * ffn_gate_exps_s = nullptr;
struct ggml_tensor * ffn_down_exps_s = nullptr;
struct ggml_tensor * ffn_up_exps_s = nullptr;
// ff MoE latent proj
struct ggml_tensor * ffn_latent_down = nullptr;
struct ggml_tensor * ffn_latent_up = nullptr;
@@ -438,13 +429,10 @@ struct llama_layer {
struct ggml_tensor * lilicorr_attn_in_proj_b = nullptr;
struct ggml_tensor * lilicorr_attn_out_proj = nullptr;
struct ggml_tensor * lilicorr_attn_out_proj_b = nullptr;
struct ggml_tensor * lilicorr_attn_out_proj_s = nullptr;
struct ggml_tensor * lilicorr_mlp_0 = nullptr;
struct ggml_tensor * lilicorr_mlp_0_b = nullptr;
struct ggml_tensor * lilicorr_mlp_0_s = nullptr;
struct ggml_tensor * lilicorr_mlp_2 = nullptr;
struct ggml_tensor * lilicorr_mlp_2_b = nullptr;
struct ggml_tensor * lilicorr_mlp_2_s = nullptr;
// mamba proj
struct ggml_tensor * ssm_in = nullptr;
@@ -520,45 +508,6 @@ struct llama_layer {
struct ggml_tensor * rope_short = nullptr;
struct ggml_tensor * rope_freqs = nullptr;
// bitnet scale
struct ggml_tensor * wq_s = nullptr;
struct ggml_tensor * wk_s = nullptr;
struct ggml_tensor * wv_s = nullptr;
struct ggml_tensor * wo_s = nullptr;
struct ggml_tensor * wqkv_s = nullptr;
struct ggml_tensor * wqkv_gate_s = nullptr;
struct ggml_tensor * ffn_gate_s = nullptr;
struct ggml_tensor * ffn_up_s = nullptr;
struct ggml_tensor * ffn_down_s = nullptr;
struct ggml_tensor * ffn_gate_shexp_s = nullptr;
struct ggml_tensor * ffn_up_shexp_s = nullptr;
struct ggml_tensor * ffn_down_shexp_s = nullptr;
struct ggml_tensor * ssm_in_s = nullptr;
struct ggml_tensor * ssm_out_s = nullptr;
struct ggml_tensor * ssm_alpha_s = nullptr;
struct ggml_tensor * ssm_beta_s = nullptr;
// input scales
struct ggml_tensor * wq_in_s = nullptr;
struct ggml_tensor * wk_in_s = nullptr;
struct ggml_tensor * wv_in_s = nullptr;
struct ggml_tensor * wo_in_s = nullptr;
struct ggml_tensor * wqkv_in_s = nullptr;
struct ggml_tensor * wqkv_gate_in_s = nullptr;
struct ggml_tensor * ffn_gate_in_s = nullptr;
struct ggml_tensor * ffn_up_in_s = nullptr;
struct ggml_tensor * ffn_down_in_s = nullptr;
struct ggml_tensor * ffn_gate_exps_in_s = nullptr;
struct ggml_tensor * ffn_down_exps_in_s = nullptr;
struct ggml_tensor * ffn_up_exps_in_s = nullptr;
struct ggml_tensor * ffn_gate_shexp_in_s= nullptr;
struct ggml_tensor * ffn_up_shexp_in_s = nullptr;
struct ggml_tensor * ffn_down_shexp_in_s= nullptr;
struct ggml_tensor * ssm_in_in_s = nullptr;
struct ggml_tensor * ssm_out_in_s = nullptr;
struct ggml_tensor * ssm_alpha_in_s = nullptr;
struct ggml_tensor * ssm_beta_in_s = nullptr;
// altup & laurel
struct ggml_tensor * per_layer_inp_gate = nullptr;
struct ggml_tensor * per_layer_proj = nullptr;
@@ -805,6 +754,32 @@ struct llama_hadamard_transform {
};
using llama_hadamard_rotations = std::unordered_map<const ggml_tensor *, llama_hadamard_transform>;
// ".scale" / ".input_scale" tensors of the matmul weights, keyed by weight
struct llama_weight_scales {
std::unordered_map<const ggml_tensor *, ggml_tensor *> scale;
std::unordered_map<const ggml_tensor *, ggml_tensor *> input_scale;
ggml_tensor * get(const ggml_tensor * w) const {
auto it = scale.find(w);
if (it == scale.end() && w->view_src) {
it = scale.find(w->view_src);
// only per-tensor scales are supported for views of a weight
GGML_ASSERT(it == scale.end() || ggml_nelements(it->second) == 1);
}
return it == scale.end() ? nullptr : it->second;
}
ggml_tensor * get_input(const ggml_tensor * w) const {
auto it = input_scale.find(w);
if (it == input_scale.end() && w->view_src) {
it = input_scale.find(w->view_src);
// only per-tensor scales are supported for views of a weight
GGML_ASSERT(it == input_scale.end() || ggml_nelements(it->second) == 1);
}
return it == input_scale.end() ? nullptr : it->second;
}
};
struct llama_hadamard {
// names and sign data come from the GGUF metadata in load_hparams, the transforms are made in load_tensors
std::unordered_map<std::string, uint32_t> weight_blocks;
@@ -850,10 +825,7 @@ struct llama_model {
llama_hadamard hdmd;
// weight -> "<name>.scale" tensor (e.g. NVFP4 scale2), applied by build_lora_mm and build_lora_mm_id
std::unordered_map<const ggml_tensor *, ggml_tensor *> w_scales;
ggml_tensor * get_w_scale(const ggml_tensor * w) const;
llama_weight_scales w_scales;
// see llama_model_set_attn_rot
bool attn_rot = true;
@@ -881,11 +853,6 @@ struct llama_model {
struct ggml_tensor * output_b = nullptr;
struct ggml_tensor * output_norm_enc = nullptr;
// NVFP4 per-tensor scale2, input_scale for LM head
struct ggml_tensor * output_s = nullptr;
struct ggml_tensor * output_in_s = nullptr;
// NextN/MTP model-level projections
struct ggml_tensor * nextn_proj_pre = nullptr;
struct ggml_tensor * nextn_proj_post = nullptr;
@@ -954,15 +921,12 @@ struct llama_model {
struct ggml_tensor * per_layer_proj_norm = nullptr;
// eagle3 / dflash feature fusion layer
struct ggml_tensor * fc = nullptr;
struct ggml_tensor * fc_s = nullptr;
struct ggml_tensor * fc_in_s = nullptr;
struct ggml_tensor * fc = nullptr;
struct ggml_tensor * d2t = nullptr; // draft to target vocabulary mapping
// dspark
struct ggml_tensor * dspark_markov_w1 = nullptr;
struct ggml_tensor * dspark_markov_w2 = nullptr;
struct ggml_tensor * dspark_markov_w2_s = nullptr;
struct ggml_tensor * dspark_conf_proj = nullptr;
struct ggml_tensor * dspark_conf_proj_b = nullptr;
struct ggml_tensor * dspark_joint_proj = nullptr; // rnn markov head
@@ -982,10 +946,8 @@ struct llama_model {
struct ggml_tensor * lilicorr_token_proj = nullptr;
struct ggml_tensor * lilicorr_token_proj_b = nullptr;
struct ggml_tensor * lilicorr_token_proj_s = nullptr;
struct ggml_tensor * lilicorr_pass_hidden_proj = nullptr;
struct ggml_tensor * lilicorr_pass_hidden_proj_b = nullptr;
struct ggml_tensor * lilicorr_pass_hidden_proj_s = nullptr;
struct ggml_tensor * lilicorr_feature_norm = nullptr;
struct ggml_tensor * lilicorr_feature_norm_b = nullptr;
struct ggml_tensor * lilicorr_feature_mlp_1 = nullptr;
@@ -997,7 +959,6 @@ struct llama_model {
struct ggml_tensor * lilicorr_attention_bias = nullptr;
struct ggml_tensor * lilicorr_context_proj = nullptr;
struct ggml_tensor * lilicorr_context_proj_b = nullptr;
struct ggml_tensor * lilicorr_context_proj_s = nullptr;
struct ggml_tensor * lilicorr_output_norm = nullptr;
struct ggml_tensor * lilicorr_anchor_norm = nullptr;
struct ggml_tensor * lilicorr_factor_input_proj = nullptr;
@@ -1009,7 +970,6 @@ struct llama_model {
struct ggml_tensor * lilicorr_anchor_out_head = nullptr;
struct ggml_tensor * lilicorr_anchor_out_head_b = nullptr;
// unified vector to store target-model extracted layer ids in eagle3, dflash, etc.
std::vector<int32_t> target_layer_ids;
@@ -1140,6 +1100,7 @@ struct llama_model_base : public llama_model {
const int TENSOR_SKIP_IF_VIRTUAL;
const int TENSOR_ALLOW_RESHAPE;
const int TENSOR_READ_LAZY;
const int TENSOR_NO_SCALE;
explicit llama_model_base(const llama_model_params & params);
virtual ~llama_model_base() = default;
+134 -17
View File
@@ -8,6 +8,7 @@
#include "ggml-cpp.h"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdio>
#include <cstdlib>
@@ -287,12 +288,17 @@ struct moe_cache_lru {
}
};
using llama_moe_cache_scales = std::array<ggml_tensor *, LLAMA_MOE_CACHE_SCALE_COUNT>;
// gate, up, down or gate_up, down
static std::vector<ggml_tensor *> llama_moe_cache_layer_experts(const llama_layer & layer) {
static std::vector<ggml_tensor *> llama_moe_cache_layer_experts(const llama_layer & layer, const llama_weight_scales * ws = nullptr, std::vector<llama_moe_cache_scales> * scales = nullptr) {
std::vector<ggml_tensor *> res;
for (ggml_tensor * t : { layer.ffn_gate_up_exps, layer.ffn_gate_exps, layer.ffn_up_exps, layer.ffn_down_exps }) {
if (t != nullptr) {
res.push_back(t);
if (scales != nullptr) {
scales->push_back({ ws->get(t), ws->get_input(t) });
}
}
}
return res;
@@ -338,6 +344,9 @@ struct llama_moe_cache::impl {
std::vector<ggml_tensor *> ref; // expert tensors of the first layer
std::vector<int32_t> layers;
std::vector<ggml_tensor *> banks; // device storage of all slots, one per expert tensor
std::vector<std::array<int64_t, LLAMA_MOE_CACHE_SCALE_COUNT>> scale_rows;
std::vector<llama_moe_cache_scales> scale_banks;
size_t n_scalar = 0; // per-tensor scales of all layers
size_t host_bytes = 0;
int32_t n_slots = 0;
moe_cache_lru lru;
@@ -350,13 +359,16 @@ struct llama_moe_cache::impl {
ggml_tensor * cpu_map = nullptr; // I32 [1, n_expert] in host memory, if cpu_share > 0
std::vector<int32_t> cpu_experts; // experts set in cpu_map
uint32_t cpu_acc = 0; // fraction of a miss carried over to the next plan, in 1/65536
int32_t n_used = 0; // experts selected per token by the graph, set by build_lookup
std::vector<ggml_tensor *> experts; // host expert tensors, in the order of the banks
std::vector<std::array<std::vector<float>, LLAMA_MOE_CACHE_SCALE_COUNT>> scales;
};
struct binding {
int32_t il;
int32_t ip; // index of the bank
ggml_tensor * cached; // view of the bank used in place of the host experts
llama_moe_cache_scales scales;
};
struct stats {
@@ -421,26 +433,47 @@ struct llama_moe_cache::impl {
// only cache layers that keep all of their experts in host memory, on the device the layer is assigned to
for (size_t il = 0; il < model.layers.size(); ++il) {
auto experts = llama_moe_cache_layer_experts(model.layers[il]);
std::vector<llama_moe_cache_scales> scales;
auto experts = llama_moe_cache_layer_experts(model.layers[il], &model.w_scales, &scales);
if (experts.empty() || !std::all_of(experts.begin(), experts.end(), llama_moe_cache_is_host_weight)) {
continue;
}
std::vector<std::array<int64_t, LLAMA_MOE_CACHE_SCALE_COUNT>> scale_rows(experts.size(), { 0, 0 });
size_t n_scalar = 0;
for (size_t ip = 0; ip < experts.size(); ++ip) {
for (int k = 0; k < LLAMA_MOE_CACHE_SCALE_COUNT; ++k) {
const ggml_tensor * s = scales[ip][k];
if (s != nullptr) {
GGML_ASSERT(s->type == GGML_TYPE_F32 && ggml_is_contiguous(s));
if (ggml_nelements(s) > 1) {
GGML_ASSERT((s->ne[0] == experts[ip]->ne[2] && s->ne[1] == 1) ||
(s->ne[0] == experts[ip]->ne[1] && s->ne[1] == experts[ip]->ne[2]));
scale_rows[ip][k] = ggml_nelements(s)/experts[ip]->ne[2];
} else {
n_scalar++;
}
}
}
}
const auto it_dev = std::find_if(devices.begin(), devices.end(), [&](const device & d) { return ggml_backend_get_device(d.backend) == model.dev_layer(il); });
if (it_dev == devices.end()) {
continue;
}
const int32_t id = (int32_t) (it_dev - devices.begin());
auto it = std::find_if(groups.begin(), groups.end(), [&](const group & g) { return g.id == id && llama_moe_cache_same_layout(g.ref, experts); });
auto it = std::find_if(groups.begin(), groups.end(), [&](const group & g) { return g.id == id && llama_moe_cache_same_layout(g.ref, experts) && g.scale_rows == scale_rows; });
if (it == groups.end()) {
groups.emplace_back();
it = groups.end() - 1;
it->id = id;
it->ref = experts;
it->scale_rows = scale_rows;
}
it->layers.push_back(il);
for (const ggml_tensor * t : experts) {
it->host_bytes += ggml_nbytes(t);
devices[id].host_bytes += ggml_nbytes(t);
it->n_scalar += n_scalar;
for (size_t ip = 0; ip < experts.size(); ++ip) {
const size_t bytes = ggml_nbytes(experts[ip]) + (scale_rows[ip][0] + scale_rows[ip][1])*experts[ip]->ne[2]*sizeof(float);
it->host_bytes += bytes;
devices[id].host_bytes += bytes;
}
}
if (groups.empty()) {
@@ -454,9 +487,15 @@ struct llama_moe_cache::impl {
auto alloc_size = [&](const group & g, int32_t n_slots) {
const size_t alignment = ggml_backend_buft_get_alignment(devices[g.id].buft);
size_t res = 0;
for (const ggml_tensor * t : g.ref) {
res += GGML_PAD(t->nb[2]*(n_slots + n_zero + 1), alignment);
for (size_t ip = 0; ip < g.ref.size(); ++ip) {
res += GGML_PAD(g.ref[ip]->nb[2]*(n_slots + n_zero + 1), alignment);
for (int64_t rows : g.scale_rows[ip]) {
if (rows > 0) {
res += GGML_PAD(rows*sizeof(float)*(n_slots + n_zero + 1), alignment);
}
}
}
res += g.n_scalar*GGML_PAD(sizeof(float), alignment);
return res;
};
@@ -515,7 +554,11 @@ struct llama_moe_cache::impl {
continue;
}
g.lru.init(model.layers.size(), n_expert, g.n_slots);
n_tensors[g.id] += g.ref.size()*(1 + g.layers.size());
size_t n_scales = 0;
for (const auto & rows : g.scale_rows) {
n_scales += std::count_if(rows.begin(), rows.end(), [](int64_t r) { return r > 0; });
}
n_tensors[g.id] += (g.ref.size() + n_scales)*(1 + g.layers.size()) + g.n_scalar;
n_tensors_host += g.layers.size()*(n_zero > 0 ? 3 : 1); // slot maps and CPU map
}
if (n_tensors_host == 0) {
@@ -542,6 +585,8 @@ struct llama_moe_cache::impl {
ctx_host = init_ctx(n_tensors_host);
ctx_views = init_ctx(2);
std::vector<std::pair<ggml_tensor *, const ggml_tensor *>> scalar_scales; // device copy, model tensor
ggml_backend_buffer_type_t buft_host = ggml_backend_cpu_buffer_type();
const size_t alignment_host = ggml_backend_buft_get_alignment(buft_host);
@@ -551,21 +596,53 @@ struct llama_moe_cache::impl {
continue;
}
ggml_context * ctx = devices[g.id].ctx.get();
for (const ggml_tensor * t : g.ref) {
for (size_t ip = 0; ip < g.ref.size(); ++ip) {
const ggml_tensor * t = g.ref[ip];
ggml_tensor * bank = ggml_new_tensor_3d(ctx, t->type, t->ne[0], t->ne[1], g.n_slots + n_zero + 1);
GGML_ASSERT(bank->nb[2] == t->nb[2]);
ggml_format_name(bank, "moe_cache.%zu.%s", ig, t->name);
g.banks.push_back(bank);
llama_moe_cache_scales scale_banks = {};
for (int k = 0; k < LLAMA_MOE_CACHE_SCALE_COUNT; ++k) {
if (g.scale_rows[ip][k] > 0) {
scale_banks[k] = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, g.scale_rows[ip][k], g.n_slots + n_zero + 1);
ggml_format_name(scale_banks[k], "moe_cache.%zu.%s.%s", ig, t->name, k == LLAMA_MOE_CACHE_SCALE_WEIGHT ? "scale" : "input_scale");
}
}
g.scale_banks.push_back(scale_banks);
}
for (int32_t il : g.layers) {
layer & l = layers[il];
l.ig = (int32_t) ig;
l.experts = llama_moe_cache_layer_experts(model.layers[il]);
std::vector<llama_moe_cache_scales> scales;
l.experts = llama_moe_cache_layer_experts(model.layers[il], &model.w_scales, &scales);
l.scales.resize(l.experts.size());
for (size_t ip = 0; ip < l.experts.size(); ++ip) {
ggml_tensor * bank = g.banks[ip];
ggml_tensor * cached = ggml_view_3d(ctx, bank, bank->ne[0], bank->ne[1], g.n_slots + n_zero, bank->nb[1], bank->nb[2], 0);
ggml_format_name(cached, "moe_cache.%s", l.experts[ip]->name);
bindings[l.experts[ip]] = { il, (int32_t) ip, cached };
llama_moe_cache_scales bound = scales[ip];
for (int k = 0; k < LLAMA_MOE_CACHE_SCALE_COUNT; ++k) {
ggml_tensor * scale = scales[ip][k];
ggml_tensor * scale_bank = g.scale_banks[ip][k];
if (scale_bank == nullptr) {
if (scale != nullptr) {
bound[k] = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
ggml_format_name(bound[k], "moe_cache.%s", scale->name);
scalar_scales.emplace_back(bound[k], scale);
}
continue;
}
if (!no_alloc) {
l.scales[ip][k].resize(ggml_nelements(scale));
ggml_backend_tensor_get(scale, l.scales[ip][k].data(), 0, ggml_nbytes(scale));
}
const int64_t rows = g.scale_rows[ip][k];
bound[k] = rows == 1 ? ggml_view_1d(ctx, scale_bank, g.n_slots + n_zero, 0) :
ggml_view_2d(ctx, scale_bank, rows, g.n_slots + n_zero, scale_bank->nb[1], 0);
ggml_format_name(bound[k], "moe_cache.%s", scale->name);
}
bindings[l.experts[ip]] = { il, (int32_t) ip, cached, bound };
}
l.slot_map = ggml_new_tensor_2d(ctx_host.get(), GGML_TYPE_I32, 1, g.ref[0]->ne[2]);
ggml_format_name(l.slot_map, "moe_cache.slot_map-%d", il);
@@ -600,6 +677,22 @@ struct llama_moe_cache::impl {
ggml_backend_buffer_clear(buf_host.get(), 0xff); // the CPU maps are -1
buf_host_size = ggml_backend_buffer_get_size(buf_host.get());
// zero and unfilled slots keep a unit input scale: activations are divided by it
for (group & g : groups) {
for (const auto & banks : g.scale_banks) {
if (ggml_tensor * bank = banks[LLAMA_MOE_CACHE_SCALE_INPUT]) {
const std::vector<float> ones(ggml_nelements(bank), 1.0f);
ggml_backend_tensor_set(bank, ones.data(), 0, ggml_nbytes(bank));
}
}
}
for (const auto & [dst, src] : scalar_scales) {
float v;
ggml_backend_tensor_get(src, &v, 0, sizeof(v));
ggml_backend_tensor_set(dst, &v, 0, sizeof(v));
}
for (group & g : groups) {
for (int32_t il : g.layers) {
if (layers[il].slot_map != nullptr) {
@@ -729,6 +822,11 @@ struct llama_moe_cache::impl {
return it != bindings.end() ? it->second.cached : nullptr;
}
ggml_tensor * get_scales(const ggml_tensor * w, llama_moe_cache_scale kind) const {
const auto it = bindings.find(w);
return it != bindings.end() ? it->second.scales[kind] : nullptr;
}
int64_t copy_experts(ggml_backend_t backend, const ggml_tensor * w, ggml_tensor * dst, int64_t e, int64_t last) {
const auto it = bindings.find(w);
if (it == bindings.end()) {
@@ -789,6 +887,7 @@ struct llama_moe_cache::impl {
// the selected experts must be computed in an earlier split
// the scheduler starts a new split at the lookup because it reads a host weight, unless the lookup is the first node of its split
// if they are selected on another backend (e.g. the loop passes of inkling2_loop), sel is the copy made by the scheduler before this callback
const ggml_tensor * sel = lookup->src[1];
for (int i = 0; i < n_nodes; ++i) {
const ggml_tensor * node = ggml_graph_node(graph, i);
@@ -797,9 +896,11 @@ struct llama_moe_cache::impl {
}
}
GGML_ASSERT(ggml_is_contiguous(sel));
GGML_ASSERT(sel->op == GGML_OP_RESHAPE); // of the [n_expert_used, n_tokens] ids, see build_lookup
const int32_t n_used = (int32_t) sel->src[0]->ne[0];
// a copy of the 1D ids has no source to read the shape from
const int32_t n_used = l.n_used;
GGML_ASSERT(n_used > 0 && ggml_nelements(sel) % n_used == 0);
const int64_t n_tokens = ggml_nelements(sel)/n_used;
ids.resize(ggml_nelements(sel));
ggml_backend_tensor_get_async(backend, sel, ids.data(), 0, ggml_nbytes(sel));
@@ -817,7 +918,7 @@ struct llama_moe_cache::impl {
return (size_t) (acc >> 16);
};
size_t n_hit = 0;
if (!g.lru.plan(il, ids.data(), ids.size(), sel->src[0]->ne[1], n_used, n_zero, n_cpu, fills, cpu, n_hit)) {
if (!g.lru.plan(il, ids.data(), ids.size(), n_tokens, n_used, n_zero, n_cpu, fills, cpu, n_hit)) {
GGML_ABORT("the MoE cache is too small for the experts selected in layer %d", il);
}
if (has_cpu) {
@@ -845,6 +946,14 @@ struct llama_moe_cache::impl {
}
ggml_backend_tensor_set_async(backend, bank, (const uint8_t *) w->data + fills[i].expert*expert_size, fills[i].slot*expert_size, n*expert_size);
bytes += n*expert_size;
for (int k = 0; k < LLAMA_MOE_CACHE_SCALE_COUNT; ++k) {
if (ggml_tensor * scale_bank = g.scale_banks[ip][k]) {
const int64_t rows = g.scale_rows[ip][k];
const size_t scale_size = rows*sizeof(float);
ggml_backend_tensor_set_async(backend, scale_bank, l.scales[ip][k].data() + fills[i].expert*rows, fills[i].slot*scale_size, n*scale_size);
bytes += n*scale_size;
}
}
i += n;
}
}
@@ -912,8 +1021,10 @@ llama_moe_cache_lookup llama_moe_cache::build_lookup(const llm_graph_context & g
return {};
}
// the device of the cache must compute the matmul, else the scheduler copies the cache to another backend
ggml_tensor * b = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, experts->ne[0], w == layer.down_exps ? selected_experts->ne[0] : 1, selected_experts->ne[1]);
if (!ggml_backend_supports_op(pimpl->backend(il), ggml_mul_mat_id(ctx0, experts, b, selected_experts))) {
ggml_tensor * w_s = g.get_weight_scale(w) ? pimpl->get_scales(w, LLAMA_MOE_CACHE_SCALE_WEIGHT) : nullptr;
ggml_tensor * x_s = g.get_input_scale(w) ? pimpl->get_scales(w, LLAMA_MOE_CACHE_SCALE_INPUT) : nullptr;
ggml_tensor * b = ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, experts->ne[0], w == layer.down_exps ? selected_experts->ne[0] : 1, selected_experts->ne[1]);
if (!ggml_backend_supports_op(pimpl->backend(il), ggml_mul_mat_id_ext(ctx0, experts, b, selected_experts, w_s, x_s))) {
return {};
}
}
@@ -933,6 +1044,8 @@ llama_moe_cache_lookup llama_moe_cache::build_lookup(const llm_graph_context & g
ggml_backend_sched_set_tensor_backend(g.sched, slots, pimpl->backend(il));
g.cb(slots, "ffn_moe_slots", il);
pimpl->layers[il].n_used = (int32_t) selected_experts->ne[0];
// add the lookup now: the transform of a Hadamard-folded expert reads host weights and would start its split first
ggml_build_forward_expand(g.gf, slots);
@@ -962,6 +1075,10 @@ ggml_tensor * llama_moe_cache::build_experts(const llm_graph_context & g, const
return experts;
}
ggml_tensor * llama_moe_cache::get_scales(const ggml_tensor * w, llama_moe_cache_scale kind) const {
return pimpl->get_scales(w, kind);
}
bool llama_moe_cache::copy(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst, ggml_cgraph * graph) {
return pimpl->copy(backend, src, dst, graph);
}
+9
View File
@@ -30,6 +30,12 @@ struct llama_moe_cache_lookup {
// cur is the expert input and ids are the selected experts, for the biases and scales (see llm_graph_context::build_moe_ffn)
using llama_moe_cache_build_experts_t = ggml_tensor * (*)(ggml_tensor * cur, ggml_tensor * ids, ggml_tensor * mm_ids, bool cached, void * user_data);
enum llama_moe_cache_scale {
LLAMA_MOE_CACHE_SCALE_WEIGHT,
LLAMA_MOE_CACHE_SCALE_INPUT,
LLAMA_MOE_CACHE_SCALE_COUNT,
};
// keeps recently and repeatedly used experts of host-resident MoE layers in a device buffer
// each layer has a slot map in host memory: when the scheduler copies it to the device, the copy callback uploads the missing experts
class llama_moe_cache {
@@ -53,6 +59,9 @@ public:
ggml_tensor * build_experts(const llm_graph_context & g, const llama_moe_cache_lookup & lookup,
ggml_tensor * cur, ggml_tensor * selected_experts, llama_moe_cache_build_experts_t build, void * user_data) const;
// weight or input scales of w on the cache device: in cache-slot order, or a copy of the per-tensor scale
ggml_tensor * get_scales(const ggml_tensor * w, llama_moe_cache_scale kind) const;
// ggml_backend_sched copy callback, returns false if src is not a slot map
bool copy(ggml_backend_t backend, const ggml_tensor * src, ggml_tensor * dst, ggml_cgraph * graph);
+7 -2
View File
@@ -235,7 +235,7 @@ static void llama_tensor_dequantize_impl(ggml_type type,
const int nthread
) {
const ggml_type_traits * qtype = ggml_get_type_traits(type);
if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) {
if (ggml_is_quantized(type) || ggml_needs_scale(type)) {
if (qtype->to_float == nullptr) {
throw std::runtime_error(format("type %s unsupported for integer quantization: no dequantization available", ggml_type_name(type)));
}
@@ -246,7 +246,7 @@ static void llama_tensor_dequantize_impl(ggml_type type,
if (nthread < 2) {
if (type == GGML_TYPE_F16) { ggml_fp16_to_fp32_row((const ggml_fp16_t *)data, f32_output, nelements); }
else if (type == GGML_TYPE_BF16) { ggml_bf16_to_fp32_row((const ggml_bf16_t *)data, f32_output, nelements); }
else if (ggml_is_quantized(type) || type == GGML_TYPE_F8_E4M3) { qtype->to_float(data, f32_output, nelements); }
else if (ggml_is_quantized(type) || ggml_needs_scale(type)) { qtype->to_float(data, f32_output, nelements); }
else { GGML_ABORT("fatal error"); }
return;
@@ -3416,6 +3416,11 @@ static void llama_model_quantize_impl(const std::string & fname_inp, const std::
__func__, metadata[i].name.c_str(), ggml_type_name(metadata[i].target_type));
}
if (metadata[i].target_type != tensor->type && ggml_needs_scale(metadata[i].target_type)) {
throw std::runtime_error(format("cannot quantize %s to %s: this type needs a weight scale that llama-quantize does not compute",
metadata[i].name.c_str(), ggml_type_name(metadata[i].target_type)));
}
metadata[i].requires_imatrix = tensor_requires_imatrix(tensor->name, metadata[i].target_type, ftype);
if (params->imatrix) { metadata[i].remapped_imatrix_name = remap_imatrix(tensor->name, mapped); }
+9 -9
View File
@@ -163,7 +163,7 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
cb(Kcur, "Kcur_rope", il);
cur = build_attn(inp_attn,
NULL, NULL, NULL, // wo will be applied after gating
NULL, NULL, // wo will be applied after gating
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_out", il);
@@ -174,7 +174,7 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
cb(cur, "attn_gated", il);
// now apply output projection
cur = build_lora_mm(model.layers[il].wo, cur, model.layers[il].wo_s);
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_o_proj", il);
}
@@ -218,9 +218,9 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
// shared expert
if (hparams.n_expert_shared > 0) {
ggml_tensor * ffn_shexp = build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, NULL,
model.layers[il].ffn_gate_shexp, NULL, NULL,
model.layers[il].ffn_down_shexp, NULL, NULL,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -233,9 +233,9 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
} else {
// dense layer
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -265,7 +265,7 @@ llama_model_afmoe::graph::graph(const llm_graph_params & params) : llm_graph_con
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
}
+2 -2
View File
@@ -102,7 +102,7 @@ llama_model_apertus::graph::graph(const llm_graph_params & params) : llm_graph_c
cb(Vcur, "Vcur_pos", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_out", il);
}
@@ -156,7 +156,7 @@ llama_model_apertus::graph::graph(const llm_graph_params & params) : llm_graph_c
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -88,7 +88,7 @@ llama_model_arcee::graph::graph(const llm_graph_params & params) : llm_graph_con
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_out", il);
}
@@ -109,9 +109,9 @@ llama_model_arcee::graph::graph(const llm_graph_params & params) : llm_graph_con
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
NULL, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
NULL, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_RELU_SQR, LLM_FFN_SEQ, il);
cb(cur, "ffn_out", il);
@@ -136,7 +136,7 @@ llama_model_arcee::graph::graph(const llm_graph_params & params) : llm_graph_con
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -94,7 +94,7 @@ llama_model_arctic::graph::graph(const llm_graph_params & params) : llm_graph_co
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
}
@@ -113,9 +113,9 @@ llama_model_arctic::graph::graph(const llm_graph_params & params) : llm_graph_co
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -162,7 +162,7 @@ llama_model_arctic::graph::graph(const llm_graph_params & params) : llm_graph_co
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+4 -4
View File
@@ -172,9 +172,9 @@ llama_model_arwkv7::graph::graph(const llm_graph_params & params) : llm_build_rw
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -193,7 +193,7 @@ llama_model_arwkv7::graph::graph(const llm_graph_params & params) : llm_build_rw
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -87,7 +87,7 @@ llama_model_baichuan::graph::graph(const llm_graph_params & params) : llm_graph_
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
}
@@ -107,9 +107,9 @@ llama_model_baichuan::graph::graph(const llm_graph_params & params) : llm_graph_
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -134,7 +134,7 @@ llama_model_baichuan::graph::graph(const llm_graph_params & params) : llm_graph_
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -95,7 +95,7 @@ llama_model_bailingmoe::graph::graph(const llm_graph_params & params) : llm_grap
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_rot)), il);
}
@@ -129,9 +129,9 @@ llama_model_bailingmoe::graph::graph(const llm_graph_params & params) : llm_grap
// FFN shared expert
{
ggml_tensor * ffn_shexp = build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, NULL,
model.layers[il].ffn_gate_shexp, NULL, NULL,
model.layers[il].ffn_down_shexp, NULL, NULL,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -159,7 +159,7 @@ llama_model_bailingmoe::graph::graph(const llm_graph_params & params) : llm_grap
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+8 -8
View File
@@ -132,7 +132,7 @@ llama_model_bailingmoe2::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
}
@@ -150,9 +150,9 @@ llama_model_bailingmoe2::graph::graph(const llm_graph_params & params) :
if (static_cast<uint32_t>(il) < hparams.n_layer_dense_lead) {
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -172,9 +172,9 @@ llama_model_bailingmoe2::graph::graph(const llm_graph_params & params) :
{
ggml_tensor * ffn_shexp =
build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, NULL,
model.layers[il].ffn_gate_shexp, NULL, NULL,
model.layers[il].ffn_down_shexp, NULL, NULL,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -200,7 +200,7 @@ llama_model_bailingmoe2::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+33 -33
View File
@@ -168,7 +168,7 @@ ggml_tensor * llama_model_bailingmoe3::graph::build_causal_conv1d(
const int64_t conv_state_size = (d_conv - 1) * d_inner;
const int64_t total_state_size = 3 * conv_state_size;
ggml_tensor * x_proj = ggml_mul_mat(ctx0, proj_w, x);
ggml_tensor * x_proj = build_lora_mm(proj_w, x);
x_proj = ggml_reshape_3d(ctx0, x_proj, d_inner, n_seq_tokens, n_seqs);
ggml_tensor * conv_x = nullptr;
@@ -247,7 +247,7 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
inp_rs, conv_states_all, conv_state_all, 2, cur, layer.wv, layer.ssm_v_conv,
d_conv, head_dim, n_head, n_seq_tokens, n_seqs, il);
ggml_tensor * gate = ggml_mul_mat(ctx0, layer.ssm_f_a, cur);
ggml_tensor * gate = build_lora_mm(layer.ssm_f_a, cur);
gate = ggml_add(ctx0, gate, layer.ssm_dt_b);
gate = ggml_reshape_3d(ctx0, gate, head_dim, n_head, n_tokens);
ggml_tensor * a = ggml_reshape_3d(ctx0, layer.ssm_a, 1, n_head, 1);
@@ -255,7 +255,7 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
gate = ggml_reshape_4d(ctx0, gate, head_dim, n_head, n_seq_tokens, n_seqs);
cb(gate, "kda_gate", il);
ggml_tensor * beta = ggml_mul_mat(ctx0, layer.ssm_beta, cur);
ggml_tensor * beta = build_lora_mm(layer.ssm_beta, cur);
beta = ggml_sigmoid(ctx0, ggml_reshape_4d(ctx0, beta, 1, n_head, n_seq_tokens, n_seqs));
q = build_gdn_l2_norm(ctx0, q, hparams.f_norm_rms_eps);
@@ -268,25 +268,25 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
ggml_tensor * out = build_recurrent_attn(
inp_rs, states_all, q, k, v, gate, beta, state, il);
ggml_tensor * out_gate = ggml_mul_mat(ctx0, layer.ssm_g_a, cur);
ggml_tensor * out_gate = build_lora_mm(layer.ssm_g_a, cur);
out_gate = ggml_reshape_3d(ctx0, out_gate, head_dim, n_head, n_tokens);
out = ggml_reshape_3d(ctx0, out, head_dim, n_head, n_tokens);
out = build_norm(out, layer.ssm_o_norm, nullptr, LLM_NORM_RMS, il);
out = ggml_mul(ctx0, out, ggml_sigmoid(ctx0, out_gate));
cur = ggml_mul_mat(ctx0, layer.wo, ggml_reshape_2d(ctx0, out, d_inner, n_tokens));
cur = build_lora_mm(layer.wo, ggml_reshape_2d(ctx0, out, d_inner, n_tokens));
cb(cur, "kda_out", il);
} else {
ggml_tensor * attn_input = cur;
ggml_tensor * q_all;
if (layer.wq_a) {
q_all = ggml_mul_mat(ctx0, layer.wq_a, cur);
q_all = build_lora_mm(layer.wq_a, cur);
cb(q_all, "q_a", il);
q_all = build_norm(q_all, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
cb(q_all, "q_a_norm", il);
q_all = ggml_mul_mat(ctx0, layer.wq_b, q_all);
q_all = build_lora_mm(layer.wq_b, q_all);
cb(q_all, "q_b", il);
} else {
q_all = ggml_mul_mat(ctx0, layer.wq, cur);
q_all = build_lora_mm(layer.wq, cur);
}
ggml_tensor * q_nope = ggml_view_3d(ctx0, q_all, qk_nope_head_dim, n_head, n_tokens,
ggml_row_size(q_all->type, qk_head_dim),
@@ -296,7 +296,7 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
ggml_row_size(q_all->type, qk_head_dim) * n_head,
ggml_row_size(q_all->type, qk_nope_head_dim));
ggml_tensor * kv_all = ggml_mul_mat(ctx0, layer.wkv_a_mqa, cur);
ggml_tensor * kv_all = build_lora_mm(layer.wkv_a_mqa, cur);
ggml_tensor * kv = ggml_view_2d(ctx0, kv_all, kv_lora_rank, n_tokens,
ggml_row_size(kv_all->type, kv_lora_rank + qk_rope_head_dim), 0);
ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_all, qk_rope_head_dim, 1, n_tokens,
@@ -309,21 +309,21 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
kv = build_norm(kv, layer.attn_kv_a_norm, nullptr, LLM_NORM_RMS, il);
q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
q_nope = ggml_mul_mat(ctx0, layer.wk_b, q_nope);
q_nope = build_lora_mm(layer.wk_b, q_nope);
q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
ggml_tensor * q = ggml_concat(ctx0, q_nope, q_pe, 0);
kv = ggml_reshape_3d(ctx0, kv, kv_lora_rank, 1, n_tokens);
ggml_tensor * k = ggml_concat(ctx0, kv, k_pe, 0);
cur = build_attn(inp_attn, nullptr, nullptr, nullptr,
cur = build_attn(inp_attn, nullptr, nullptr,
q, k, kv, nullptr, nullptr, layer.wv_b, kq_scale, il);
ggml_tensor * attn_gate = ggml_mul_mat(ctx0, layer.wqkv_gate, attn_input);
ggml_tensor * attn_gate = build_lora_mm(layer.wqkv_gate, attn_input);
attn_gate = ggml_sigmoid(ctx0, ggml_reshape_3d(ctx0, attn_gate, 1, n_head, n_tokens));
cur = ggml_reshape_3d(ctx0, cur, v_head_dim, n_head, n_tokens);
cur = ggml_mul(ctx0, cur, attn_gate);
cur = ggml_mul_mat(ctx0, layer.wo, ggml_reshape_2d(ctx0, cur, v_head_dim * n_head, n_tokens));
cur = build_lora_mm(layer.wo, ggml_reshape_2d(ctx0, cur, v_head_dim * n_head, n_tokens));
cb(cur, "mla_out", il);
}
@@ -337,9 +337,9 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
if ((uint32_t) il < hparams.n_layer_dense_lead) {
cur = build_ffn(cur,
layer.ffn_up, nullptr, nullptr,
layer.ffn_gate, nullptr, nullptr,
layer.ffn_down, nullptr, nullptr,
layer.ffn_up, nullptr,
layer.ffn_gate, nullptr,
layer.ffn_down, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
} else {
ggml_tensor * moe = build_moe_ffn(cur,
@@ -355,9 +355,9 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
(llama_expert_gating_func_type) hparams.expert_gating_func,
il);
ggml_tensor * shared = build_ffn(cur,
layer.ffn_up_shexp, nullptr, nullptr,
layer.ffn_gate_shexp, nullptr, nullptr,
layer.ffn_down_shexp, nullptr, nullptr,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cur = ggml_add(ctx0, moe, shared);
}
@@ -379,7 +379,7 @@ llama_model_bailingmoe3::graph::graph(const llm_graph_params & params) :
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = ggml_mul_mat(ctx0, model.output, cur);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
}
@@ -417,7 +417,7 @@ llama_model_bailingmoe3::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_tensor * tok_embd = ubatch.token ? ggml_get_rows(ctx0, model.tok_embd, inp->tokens) : inp->embd;
ggml_tensor * h_norm = build_norm(inp->h, layer.nextn.hnorm, nullptr, LLM_NORM_RMS, il);
ggml_tensor * e_norm = build_norm(tok_embd, layer.nextn.enorm, nullptr, LLM_NORM_RMS, il);
ggml_tensor * cur = ggml_mul_mat(ctx0, layer.nextn.eh_proj, ggml_concat(ctx0, e_norm, h_norm, 0));
ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, ggml_concat(ctx0, e_norm, h_norm, 0));
cb(cur, "mtp_eh_proj", il);
res->add_input(std::move(inp));
@@ -432,14 +432,14 @@ llama_model_bailingmoe3::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_tensor * q_all;
if (layer.wq_a) {
q_all = ggml_mul_mat(ctx0, layer.wq_a, cur);
q_all = build_lora_mm(layer.wq_a, cur);
cb(q_all, "q_a", il);
q_all = build_norm(q_all, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
cb(q_all, "q_a_norm", il);
q_all = ggml_mul_mat(ctx0, layer.wq_b, q_all);
q_all = build_lora_mm(layer.wq_b, q_all);
cb(q_all, "q_b", il);
} else {
q_all = ggml_mul_mat(ctx0, layer.wq, cur);
q_all = build_lora_mm(layer.wq, cur);
}
ggml_tensor * q_nope = ggml_view_3d(ctx0, q_all, qk_nope_head_dim, n_head, n_tokens,
ggml_row_size(q_all->type, qk_head_dim),
@@ -449,7 +449,7 @@ llama_model_bailingmoe3::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_row_size(q_all->type, qk_head_dim) * n_head,
ggml_row_size(q_all->type, qk_nope_head_dim));
ggml_tensor * kv_all = ggml_mul_mat(ctx0, layer.wkv_a_mqa, cur);
ggml_tensor * kv_all = build_lora_mm(layer.wkv_a_mqa, cur);
ggml_tensor * kv = ggml_view_2d(ctx0, kv_all, kv_lora_rank, n_tokens,
ggml_row_size(kv_all->type, kv_lora_rank + qk_rope_head_dim), 0);
ggml_tensor * k_pe = ggml_view_3d(ctx0, kv_all, qk_rope_head_dim, 1, n_tokens,
@@ -462,21 +462,21 @@ llama_model_bailingmoe3::graph_mtp::graph_mtp(const llm_graph_params & params) :
kv = build_norm(kv, layer.attn_kv_a_norm, nullptr, LLM_NORM_RMS, il);
q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
q_nope = ggml_mul_mat(ctx0, layer.wk_b, q_nope);
q_nope = build_lora_mm(layer.wk_b, q_nope);
q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
ggml_tensor * q = ggml_concat(ctx0, q_nope, q_pe, 0);
kv = ggml_reshape_3d(ctx0, kv, kv_lora_rank, 1, n_tokens);
ggml_tensor * k = ggml_concat(ctx0, kv, k_pe, 0);
cur = build_attn(inp_attn, nullptr, nullptr, nullptr,
cur = build_attn(inp_attn, nullptr, nullptr,
q, k, kv, nullptr, nullptr, layer.wv_b, kq_scale, il);
ggml_tensor * attn_gate = ggml_mul_mat(ctx0, layer.wqkv_gate, attn_input);
ggml_tensor * attn_gate = build_lora_mm(layer.wqkv_gate, attn_input);
attn_gate = ggml_sigmoid(ctx0, ggml_reshape_3d(ctx0, attn_gate, 1, n_head, n_tokens));
cur = ggml_reshape_3d(ctx0, cur, v_head_dim, n_head, n_tokens);
cur = ggml_mul(ctx0, cur, attn_gate);
cur = ggml_mul_mat(ctx0, layer.wo, ggml_cont_2d(ctx0, cur, v_head_dim * n_head, n_tokens));
cur = build_lora_mm(layer.wo, ggml_cont_2d(ctx0, cur, v_head_dim * n_head, n_tokens));
ggml_tensor * ffn_inp = ggml_add(ctx0, cur, inpSA);
cur = build_norm(ffn_inp, layer.ffn_norm, nullptr, LLM_NORM_RMS, il);
@@ -494,9 +494,9 @@ llama_model_bailingmoe3::graph_mtp::graph_mtp(const llm_graph_params & params) :
(llama_expert_gating_func_type) hparams.expert_gating_func,
il);
ggml_tensor * shared = build_ffn(cur,
layer.ffn_up_shexp, nullptr, nullptr,
layer.ffn_gate_shexp, nullptr, nullptr,
layer.ffn_down_shexp, nullptr, nullptr,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cur = ggml_add(ctx0, moe, shared);
cur = ggml_add(ctx0, cur, ffn_inp);
@@ -506,7 +506,7 @@ llama_model_bailingmoe3::graph_mtp::graph_mtp(const llm_graph_params & params) :
res->t_h_nextn = cur;
cur = ggml_get_rows(ctx0, cur, inp_out_ids);
cur = ggml_mul_mat(ctx0, model.output, cur);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
}
+6 -6
View File
@@ -167,7 +167,7 @@ llama_model_beam::graph::graph(const llm_graph_params & params) : llm_graph_cont
}
cur = build_attn(inp_attn,
NULL, NULL, NULL, // o_proj is applied after the gate
NULL, NULL, // o_proj is applied after the gate
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_out", il);
@@ -182,7 +182,7 @@ llama_model_beam::graph::graph(const llm_graph_params & params) : llm_graph_cont
cur = ggml_mul(ctx0, cur, gate);
cb(cur, "attn_gated", il);
cur = build_lora_mm(layer.wo, cur, layer.wo_s);
cur = build_lora_mm(layer.wo, cur);
cb(cur, "attn_o_proj", il);
}
@@ -203,9 +203,9 @@ llama_model_beam::graph::graph(const llm_graph_params & params) : llm_graph_cont
if ((uint32_t) il < hparams.n_layer_dense_lead) {
cur = build_ffn(cur,
layer.ffn_up, NULL, NULL,
layer.ffn_gate, NULL, NULL,
layer.ffn_down, NULL, NULL,
layer.ffn_up, NULL,
layer.ffn_gate, NULL,
layer.ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -242,7 +242,7 @@ llama_model_beam::graph::graph(const llm_graph_params & params) : llm_graph_cont
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
if (hparams.f_final_logit_softcapping != 0.0f) {
cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);
+10 -10
View File
@@ -140,7 +140,7 @@ llama_model_bert::graph::graph(const llm_graph_params & params) : llm_graph_cont
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
cb(cur, "kqv_out", il);
}
@@ -182,25 +182,25 @@ llama_model_bert::graph::graph(const llm_graph_params & params) : llm_graph_cont
} else if (model.arch == LLM_ARCH_BERT || model.arch == LLM_ARCH_NOMIC_BERT_MOE ||
model.arch == LLM_ARCH_JINA_BERT_V3) {
cur = build_ffn(cur,
model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
NULL, NULL, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL, NULL,
model.layers[il].ffn_up, model.layers[il].ffn_up_b,
NULL, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
LLM_FFN_GELU, LLM_FFN_SEQ, il);
cb(cur, "ffn_out", il);
} else if (model.arch == LLM_ARCH_JINA_BERT_V2) {
const bool up_contains_gate = !model.layers[il].ffn_gate && model.layers[il].ffn_up->ne[1] != hparams.n_ff();
auto type_op = up_contains_gate ? LLM_FFN_GEGLU : LLM_FFN_GELU;
cur = build_ffn(cur,
model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL, NULL,
model.layers[il].ffn_up, model.layers[il].ffn_up_b,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
type_op, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
}
+6 -13
View File
@@ -24,23 +24,16 @@ void llama_model_bitnet::load_arch_tensors(llama_model_loader &) {
layer.attn_sub_norm = create_tensor(tn(LLM_TENSOR_ATTN_SUB_NORM, "weight", i), {n_embd}, 0);
layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd}, 0);
layer.wq_s = create_tensor(tn(LLM_TENSOR_ATTN_Q, "scale", i), {1}, TENSOR_NOT_REQUIRED);
layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_gqa}, 0);
layer.wk_s = create_tensor(tn(LLM_TENSOR_ATTN_K, "scale", i), {1}, TENSOR_NOT_REQUIRED);
layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_gqa}, 0);
layer.wv_s = create_tensor(tn(LLM_TENSOR_ATTN_V, "scale", i), {1}, TENSOR_NOT_REQUIRED);
layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd, n_embd}, 0);
layer.wo_s = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "scale", i), {1}, TENSOR_NOT_REQUIRED);
layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);
layer.ffn_sub_norm = create_tensor(tn(LLM_TENSOR_FFN_SUB_NORM, "weight", i), {n_ff}, 0);
layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff}, 0);
layer.ffn_gate_s = create_tensor(tn(LLM_TENSOR_FFN_GATE, "scale", i), {1}, TENSOR_NOT_REQUIRED);
layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff, n_embd}, 0);
layer.ffn_down_s = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "scale", i), {1}, TENSOR_NOT_REQUIRED);
layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff}, 0);
layer.ffn_up_s = create_tensor(tn(LLM_TENSOR_FFN_UP, "scale", i), {1}, TENSOR_NOT_REQUIRED);
}
}
@@ -86,7 +79,7 @@ llama_model_bitnet::graph::graph(const llm_graph_params & params) : llm_graph_co
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
NULL, NULL, NULL,
NULL, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
cur = build_norm(cur,
@@ -94,7 +87,7 @@ llama_model_bitnet::graph::graph(const llm_graph_params & params) : llm_graph_co
LLM_NORM_RMS, il);
cb(cur, "attn_sub_norm", il);
cur = build_lora_mm(model.layers[il].wo, cur, model.layers[il].wo_s);
cur = build_lora_mm(model.layers[il].wo, cur);
if (model.layers[il].wo_b) {
cur = ggml_add(ctx0, cur, model.layers[il].wo_b);
}
@@ -116,9 +109,9 @@ llama_model_bitnet::graph::graph(const llm_graph_params & params) : llm_graph_co
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_s,
model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_s,
NULL, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
NULL, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_sub_out", il);
@@ -128,7 +121,7 @@ llama_model_bitnet::graph::graph(const llm_graph_params & params) : llm_graph_co
LLM_NORM_RMS, il);
cb(cur, "ffn_sub_norm", il);
cur = build_lora_mm(model.layers[il].ffn_down, cur, model.layers[il].ffn_down_s);
cur = build_lora_mm(model.layers[il].ffn_down, cur);
cb(cur, "ffn_down", il);
cur = ggml_add(ctx0, cur, ffn_inp);
+5 -5
View File
@@ -95,7 +95,7 @@ llama_model_bloom::graph::graph(const llm_graph_params & params) : llm_graph_con
n_embd_head, n_head, n_head_kv, il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
}
@@ -117,9 +117,9 @@ llama_model_bloom::graph::graph(const llm_graph_params & params) : llm_graph_con
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
NULL, NULL, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
model.layers[il].ffn_up, model.layers[il].ffn_up_b,
NULL, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b,
NULL,
LLM_FFN_GELU, LLM_FFN_SEQ, il);
cb(cur, "ffn_out", il);
@@ -142,7 +142,7 @@ llama_model_bloom::graph::graph(const llm_graph_params & params) : llm_graph_con
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -111,7 +111,7 @@ llama_model_chameleon::graph::graph(const llm_graph_params & params) : llm_graph
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, nullptr, model.layers[il].wo_s,
model.layers[il].wo, nullptr,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
}
@@ -138,9 +138,9 @@ llama_model_chameleon::graph::graph(const llm_graph_params & params) : llm_graph
}
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -172,7 +172,7 @@ llama_model_chameleon::graph::graph(const llm_graph_params & params) : llm_graph
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output_with_img_logits", -1);
// TODO: this suppresses the output of image tokens, which is required to enable text-only outputs.
+5 -5
View File
@@ -95,7 +95,7 @@ llama_model_chatglm::graph::graph(const llm_graph_params & params) : llm_graph_c
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
}
@@ -117,9 +117,9 @@ llama_model_chatglm::graph::graph(const llm_graph_params & params) : llm_graph_c
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
NULL, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
NULL, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SWIGLU, LLM_FFN_SEQ, il);
cb(cur, "ffn_out", il);
@@ -143,7 +143,7 @@ llama_model_chatglm::graph::graph(const llm_graph_params & params) : llm_graph_c
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+24 -24
View File
@@ -298,9 +298,9 @@ llama_model_clef::graph::graph(const llm_graph_params & params) :
cb(cur, "attn_post_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_s,
model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_s,
model.layers[il].ffn_down, NULL, model.layers[il].ffn_down_s,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -406,13 +406,13 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn(
const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f / sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
cur = build_attn(inp,
nullptr, nullptr, nullptr,
nullptr, nullptr,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_pregate", il);
cur = ggml_mul(ctx0, cur, ggml_sigmoid(ctx0, gate));
cur = build_lora_mm(model.layers[il].wo, cur, model.layers[il].wo_s);
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_output", il);
return cur;
@@ -431,16 +431,16 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn_linear(
const int64_t head_v_dim = d_inner / num_v_heads;
const int64_t n_seqs = 1;
ggml_tensor * qkv_mixed = build_lora_mm(layer.wqkv, cur, layer.wqkv_s);
ggml_tensor * qkv_mixed = build_lora_mm(layer.wqkv, cur);
qkv_mixed = ggml_reshape_3d(ctx0, qkv_mixed, qkv_mixed->ne[0], n_tokens, n_seqs);
ggml_tensor * z = build_lora_mm(layer.wqkv_gate, cur, layer.wqkv_gate_s);
ggml_tensor * z = build_lora_mm(layer.wqkv_gate, cur);
ggml_tensor * beta = build_lora_mm(layer.ssm_beta, cur, layer.ssm_beta_s);
ggml_tensor * beta = build_lora_mm(layer.ssm_beta, cur);
beta = ggml_reshape_4d(ctx0, beta, 1, num_v_heads, n_tokens, n_seqs);
beta = ggml_sigmoid(ctx0, beta);
ggml_tensor * alpha = build_lora_mm(layer.ssm_alpha, cur, layer.ssm_alpha_s);
ggml_tensor * alpha = build_lora_mm(layer.ssm_alpha, cur);
alpha = ggml_reshape_3d(ctx0, alpha, num_v_heads, n_tokens, n_seqs);
ggml_tensor * gate = ggml_softplus(ctx0, ggml_add(ctx0, alpha, layer.ssm_dt));
@@ -484,7 +484,7 @@ ggml_tensor * llama_model_clef::graph::build_layer_attn_linear(
output = ggml_reshape_3d(ctx0, output, head_v_dim * num_v_heads, n_tokens, n_seqs);
cur = build_lora_mm(layer.ssm_out, output, layer.ssm_out_s);
cur = build_lora_mm(layer.ssm_out, output);
cb(cur, "linear_attn_out", il);
return ggml_reshape_2d(ctx0, cur, n_embd, n_tokens);
@@ -502,9 +502,9 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten
const int64_t n_q = q->ne[1];
const int64_t n_kv = kv->ne[1];
ggml_tensor * Qcur = ggml_add(ctx0, ggml_mul_mat(ctx0, a.wq, q), a.bq);
ggml_tensor * Kcur = ggml_add(ctx0, ggml_mul_mat(ctx0, a.wk, kv), a.bk);
ggml_tensor * Vcur = ggml_add(ctx0, ggml_mul_mat(ctx0, a.wv, kv), a.bv);
ggml_tensor * Qcur = ggml_add(ctx0, build_lora_mm(a.wq, q), a.bq);
ggml_tensor * Kcur = ggml_add(ctx0, build_lora_mm(a.wk, kv), a.bk);
ggml_tensor * Vcur = ggml_add(ctx0, build_lora_mm(a.wv, kv), a.bv);
Qcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Qcur, d_head, n_head_h, n_q), 0, 2, 1, 3); // [d_head, n_q, n_head]
Kcur = ggml_permute(ctx0, ggml_reshape_3d(ctx0, Kcur, d_head, n_head_h, n_kv), 0, 2, 1, 3); // [d_head, n_kv, n_head]
@@ -517,14 +517,14 @@ ggml_tensor * llama_model_clef::graph::build_head_attn(ggml_tensor * q, ggml_ten
ggml_tensor * cur = ggml_mul_mat(ctx0, Vcur, kq); // [d_head, n_q, n_head]
cur = ggml_cont_2d(ctx0, ggml_permute(ctx0, cur, 0, 2, 1, 3), n_embd_h, n_q);
return ggml_add(ctx0, ggml_mul_mat(ctx0, a.wo, cur), a.bo);
return ggml_add(ctx0, build_lora_mm(a.wo, cur), a.bo);
}
ggml_tensor * llama_model_clef::graph::build_head_ffn(ggml_tensor * cur, const head_layer & layer) {
cur = build_head_norm(cur, layer.ffn_norm);
cur = ggml_add(ctx0, ggml_mul_mat(ctx0, layer.ffn_up, cur), layer.ffn_up_b);
cur = ggml_add(ctx0, build_lora_mm(layer.ffn_up, cur), layer.ffn_up_b);
cur = ggml_gelu_erf(ctx0, cur);
return ggml_add(ctx0, ggml_mul_mat(ctx0, layer.ffn_down, cur), layer.ffn_down_b);
return ggml_add(ctx0, build_lora_mm(layer.ffn_down, cur), layer.ffn_down_b);
}
// ref: JointSchemaHead in joint_schema_model.py of the model repo
@@ -546,7 +546,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
hidden = build_head_norm(hidden, model.hidden_norm);
ggml_tensor * memory = ggml_mul_mat(ctx0, model.proj_memory, hidden); // [n_embd_h, n_tokens]
ggml_tensor * memory = build_lora_mm(model.proj_memory, hidden); // [n_embd_h, n_tokens]
const int64_t n_embd_h = memory->ne[0];
@@ -563,9 +563,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
lexical = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, lexical)), inp->pool_o); // [n_embd, n_options]
// one query per option
ggml_tensor * options = ggml_mul_mat(ctx0, model.proj_option_context, opt_ctx);
options = ggml_add(ctx0, options, ggml_mul_mat(ctx0, model.proj_option_lexical, lexical));
options = ggml_add(ctx0, options, ggml_get_rows(ctx0, ggml_mul_mat(ctx0, model.proj_option_question, question), inp->option_question));
ggml_tensor * options = build_lora_mm(model.proj_option_context, opt_ctx);
options = ggml_add(ctx0, options, build_lora_mm(model.proj_option_lexical, lexical));
options = ggml_add(ctx0, options, ggml_get_rows(ctx0, build_lora_mm(model.proj_option_question, question), inp->option_question));
// the options read the prompt
for (uint32_t il = 0; il < model.n_layer_routing; ++il) {
@@ -581,7 +581,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
cb(options, "decision_options", -1);
// one vector per question: its text, a summary of its options, the end of the prompt and its type
ggml_tensor * fields = ggml_mul_mat(ctx0, model.proj_question, question); // [n_embd_h, n_questions]
ggml_tensor * fields = build_lora_mm(model.proj_question, question); // [n_embd_h, n_questions]
{
// each question weights its own options
ggml_tensor * weights = ggml_mul_mat(ctx0, options, fields); // [n_options, n_questions]
@@ -591,7 +591,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
ggml_tensor * summary = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, options)), weights);
fields = ggml_add(ctx0, fields, build_head_norm(summary, model.option_summary_norm));
fields = ggml_add(ctx0, fields, ggml_mul_mat(ctx0, model.proj_global, global));
fields = ggml_add(ctx0, fields, build_lora_mm(model.proj_global, global));
fields = ggml_add(ctx0, fields, ggml_get_rows(ctx0, model.type_embd, inp->question_type));
}
@@ -627,9 +627,9 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
features = ggml_concat(ctx0, features, ggml_mul(ctx0, field, options), 0);
features = ggml_concat(ctx0, features, ggml_abs(ctx0, ggml_sub(ctx0, field, options)), 0);
ggml_tensor * residual = ggml_add(ctx0, ggml_mul_mat(ctx0, model.scorer, features), model.scorer_b);
ggml_tensor * residual = ggml_add(ctx0, build_lora_mm(model.scorer, features), model.scorer_b);
residual = ggml_gelu_erf(ctx0, residual);
residual = ggml_add(ctx0, ggml_mul_mat(ctx0, model.scorer_out, residual), model.scorer_out_b); // [1, n_options]
residual = ggml_add(ctx0, build_lora_mm(model.scorer_out, residual), model.scorer_out_b); // [1, n_options]
auto scale = [&](int i) {
return ggml_view_1d(ctx0, model.scales, 1, i * ggml_element_size(model.scales));
+11 -11
View File
@@ -181,7 +181,7 @@ llama_model_clover_moe::graph::graph(const llm_graph_params & params) :
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
@@ -193,11 +193,11 @@ std::pair<ggml_tensor *, ggml_tensor *> llama_model_clover_moe::graph::build_qkv
const int64_t n_seqs = ubatch.n_seqs;
const int64_t n_seq_tokens = ubatch.n_seq_tokens;
ggml_tensor * qkv_mixed = build_lora_mm(model.layers[il].wqkv, input, model.layers[il].wqkv_s);
ggml_tensor * qkv_mixed = build_lora_mm(model.layers[il].wqkv, input);
qkv_mixed = ggml_reshape_3d(ctx0, qkv_mixed, qkv_mixed->ne[0], n_seq_tokens, n_seqs);
cb(qkv_mixed, "linear_attn_qkv_mixed", il);
ggml_tensor * z = build_lora_mm(model.layers[il].wqkv_gate, input, model.layers[il].wqkv_gate_s);
ggml_tensor * z = build_lora_mm(model.layers[il].wqkv_gate, input);
cb(z, "z", il);
return { qkv_mixed, z };
@@ -262,7 +262,7 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_attn(
const float kq_scale = hparams.f_attention_scale == 0.0f ? 1.0f / sqrtf(float(n_embd_head)) : hparams.f_attention_scale;
cur = build_attn(inp,
nullptr, nullptr, nullptr,
nullptr, nullptr,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_pregate", il);
@@ -272,7 +272,7 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_attn(
cur = ggml_mul(ctx0, cur, gate_sigmoid);
cb(cur, "attn_gated", il);
cur = build_lora_mm(model.layers[il].wo, cur, model.layers[il].wo_s);
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_output", il);
return cur;
@@ -300,8 +300,8 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_attn_linear(
ggml_tensor * qkv_mixed = qkvz.first;
ggml_tensor * z = qkvz.second;
ggml_tensor * beta = build_lora_mm(model.layers[il].ssm_beta, cur, model.layers[il].ssm_beta_s);
ggml_tensor * alpha = build_lora_mm(model.layers[il].ssm_alpha, cur, model.layers[il].ssm_alpha_s);
ggml_tensor * beta = build_lora_mm(model.layers[il].ssm_beta, cur);
ggml_tensor * alpha = build_lora_mm(model.layers[il].ssm_alpha, cur);
beta = ggml_reshape_4d(ctx0, beta, 1, num_v_heads, n_seq_tokens, n_seqs);
cb(beta, "beta", il);
@@ -378,7 +378,7 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_attn_linear(
ggml_tensor * final_output = ggml_reshape_2d(ctx0, attn_out_norm, head_v_dim * num_v_heads, n_seq_tokens * n_seqs);
cb(final_output, "final_output", il);
cur = build_lora_mm(model.layers[il].ssm_out, final_output, model.layers[il].ssm_out_s);
cur = build_lora_mm(model.layers[il].ssm_out, final_output);
cb(cur, "linear_attn_out", il);
return cur;
@@ -403,9 +403,9 @@ ggml_tensor * llama_model_clover_moe::graph::build_layer_ffn(ggml_tensor * cur,
if (model.layers[il].ffn_up_shexp != nullptr) {
ggml_tensor * ffn_shexp = build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, model.layers[il].ffn_up_shexp_s,
model.layers[il].ffn_gate_shexp, NULL, model.layers[il].ffn_gate_shexp_s,
model.layers[il].ffn_down_shexp, NULL, model.layers[il].ffn_down_shexp_s,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
+5 -5
View File
@@ -88,7 +88,7 @@ llama_model_codeshell::graph::graph(const llm_graph_params & params) : llm_graph
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
}
@@ -110,9 +110,9 @@ llama_model_codeshell::graph::graph(const llm_graph_params & params) : llm_graph
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
NULL, NULL, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
model.layers[il].ffn_up, model.layers[il].ffn_up_b,
NULL, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b,
NULL,
LLM_FFN_GELU, LLM_FFN_SEQ, il);
cb(cur, "ffn_out", il);
@@ -135,7 +135,7 @@ llama_model_codeshell::graph::graph(const llm_graph_params & params) : llm_graph
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+6 -8
View File
@@ -95,20 +95,18 @@ llama_model_cogvlm::graph::graph(const llm_graph_params & params) :
for (int il = 0; il < n_layer; ++il) {
// get either the text or image weight tensors
ggml_tensor *wqkv, *wo, *wo_s;
ggml_tensor *wqkv, *wo;
ggml_tensor *ffn_gate, *ffn_down, *ffn_up;
if (is_text) {
wqkv = model.layers[il].wqkv;
wo = model.layers[il].wo;
wo_s = model.layers[il].wo_s;
ffn_gate = model.layers[il].ffn_gate;
ffn_down = model.layers[il].ffn_down;
ffn_up = model.layers[il].ffn_up;
} else {
wqkv = model.layers[il].visexp_attn_wqkv;
wo = model.layers[il].visexp_attn_wo;
wo_s = nullptr;
ffn_gate = model.layers[il].visexp_ffn_gate;
ffn_down = model.layers[il].visexp_ffn_down;
ffn_up = model.layers[il].visexp_ffn_up;
@@ -133,7 +131,7 @@ llama_model_cogvlm::graph::graph(const llm_graph_params & params) :
Kcur = build_rope(Kcur, inp_pos, il);
cur = build_attn(inp_attn,
wo, nullptr, wo_s,
wo, nullptr,
Qcur, Kcur, Vcur,
nullptr, nullptr, nullptr,
kq_scale, il);
@@ -147,9 +145,9 @@ llama_model_cogvlm::graph::graph(const llm_graph_params & params) :
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
ffn_up, NULL, NULL,
ffn_gate, NULL, NULL,
ffn_down, NULL, NULL,
ffn_up, NULL,
ffn_gate, NULL,
ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cur = ggml_add(ctx0, cur, ffn_inp);
@@ -168,7 +166,7 @@ llama_model_cogvlm::graph::graph(const llm_graph_params & params) :
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
}
+5 -5
View File
@@ -99,7 +99,7 @@ llama_model_cohere2::graph::graph(const llm_graph_params & params) : llm_graph_c
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
}
@@ -114,9 +114,9 @@ llama_model_cohere2::graph::graph(const llm_graph_params & params) : llm_graph_c
// feed-forward network
{
cur = build_ffn(ffn_inp,
model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_s,
model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_s,
model.layers[il].ffn_down, NULL, model.layers[il].ffn_down_s,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
}
@@ -140,7 +140,7 @@ llama_model_cohere2::graph::graph(const llm_graph_params & params) : llm_graph_c
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
if (f_logit_scale) {
cur = ggml_scale(ctx0, cur, f_logit_scale);
+13 -13
View File
@@ -192,7 +192,7 @@ llama_model_cohere2moe::graph::graph(const llm_graph_params & params) : llm_grap
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
layer.wo, layer.wo_b, layer.wo_s,
layer.wo, layer.wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr,
1.0f / sqrtf(float(n_embd_head)), il);
}
@@ -209,9 +209,9 @@ llama_model_cohere2moe::graph::graph(const llm_graph_params & params) : llm_grap
if (layer.ffn_gate_inp == nullptr) {
cur = build_ffn(ffn_inp,
layer.ffn_up, nullptr, layer.ffn_up_s,
layer.ffn_gate, nullptr, layer.ffn_gate_s,
layer.ffn_down, nullptr, layer.ffn_down_s,
layer.ffn_up, nullptr,
layer.ffn_gate, nullptr,
layer.ffn_down, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -231,9 +231,9 @@ llama_model_cohere2moe::graph::graph(const llm_graph_params & params) : llm_grap
if (layer.ffn_up_shexp) {
ggml_tensor * ffn_shexp = build_ffn(ffn_inp,
layer.ffn_up_shexp, nullptr, layer.ffn_up_shexp_s,
layer.ffn_gate_shexp, nullptr, layer.ffn_gate_shexp_s,
layer.ffn_down_shexp, nullptr, layer.ffn_down_shexp_s,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -332,7 +332,7 @@ llama_model_cohere2moe::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, /*dim=*/ 0);
cb(concat, "mtp_concat", il);
ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat, layer.nextn.eh_proj_s);
ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat);
cb(cur, "mtp_eh_proj", il);
ggml_tensor * inpL = cur;
@@ -350,7 +350,7 @@ llama_model_cohere2moe::graph_mtp::graph_mtp(const llm_graph_params & params) :
cb(Vcur, "mtp_Vcur", il);
cur = build_attn(inp_attn,
layer.wo, layer.wo_b, layer.wo_s,
layer.wo, layer.wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr,
1.0f / sqrtf(float(n_embd_head)), il);
cb(cur, "mtp_attn_out", il);
@@ -373,9 +373,9 @@ llama_model_cohere2moe::graph_mtp::graph_mtp(const llm_graph_params & params) :
if (layer.ffn_up_shexp) {
ggml_tensor * ffn_shexp = build_ffn(ffn_inp,
layer.ffn_up_shexp, nullptr, layer.ffn_up_shexp_s,
layer.ffn_gate_shexp, nullptr, layer.ffn_gate_shexp_s,
layer.ffn_down_shexp, nullptr, layer.ffn_down_shexp_s,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "mtp_ffn_shexp", il);
@@ -402,7 +402,7 @@ llama_model_cohere2moe::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_tensor * head_w = layer.nextn.shared_head_head ? layer.nextn.shared_head_head : model.output;
GGML_ASSERT(head_w && "COHERE2MOE MTP: missing LM head (nextn.shared_head_head or model.output)");
cur = build_lora_mm(head_w, cur, layer.nextn.shared_head_head ? layer.nextn.shared_head_head_s : nullptr);
cur = build_lora_mm(head_w, cur);
if (hparams.f_logit_scale) {
cur = ggml_scale(ctx0, cur, hparams.f_logit_scale);
+5 -5
View File
@@ -93,7 +93,7 @@ llama_model_command_r::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
}
if (il == n_layer - 1 && inp_out_ids) {
@@ -106,9 +106,9 @@ llama_model_command_r::graph::graph(const llm_graph_params & params) :
// feed-forward network
{
cur = build_ffn(ffn_inp,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
}
@@ -130,7 +130,7 @@ llama_model_command_r::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
if (f_logit_scale) {
cur = ggml_scale(ctx0, cur, f_logit_scale);
+2 -2
View File
@@ -84,7 +84,7 @@ llama_model_dbrx::graph::graph(const llm_graph_params & params) : llm_graph_cont
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
}
@@ -136,7 +136,7 @@ llama_model_dbrx::graph::graph(const llm_graph_params & params) : llm_graph_cont
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -131,7 +131,7 @@ llama_model_deci::graph::graph(const llm_graph_params & params) : llm_graph_cont
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
}
if (il == n_layer - 1 && inp_out_ids) {
@@ -154,9 +154,9 @@ llama_model_deci::graph::graph(const llm_graph_params & params) : llm_graph_cont
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, model.layers[il].ffn_up_b, NULL,
model.layers[il].ffn_gate, model.layers[il].ffn_gate_b, NULL,
model.layers[il].ffn_down, model.layers[il].ffn_down_b, NULL,
model.layers[il].ffn_up, model.layers[il].ffn_up_b,
model.layers[il].ffn_gate, model.layers[il].ffn_gate_b,
model.layers[il].ffn_down, model.layers[il].ffn_down_b,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
}
@@ -177,7 +177,7 @@ llama_model_deci::graph::graph(const llm_graph_params & params) : llm_graph_cont
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+8 -8
View File
@@ -114,7 +114,7 @@ llama_model_deepseek::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
}
if (il == n_layer - 1 && inp_out_ids) {
@@ -129,9 +129,9 @@ llama_model_deepseek::graph::graph(const llm_graph_params & params) :
if ((uint32_t) il < hparams.n_layer_dense_lead) {
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -153,9 +153,9 @@ llama_model_deepseek::graph::graph(const llm_graph_params & params) :
{
ggml_tensor * ffn_shexp =
build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, NULL,
model.layers[il].ffn_gate_shexp, NULL, NULL,
model.layers[il].ffn_down_shexp, NULL, NULL,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -179,7 +179,7 @@ llama_model_deepseek::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+26 -30
View File
@@ -247,7 +247,7 @@ llama_model_deepseek2::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, 0);
cb(concat, "mtp_concat", il);
ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat, layer.nextn.eh_proj_s);
ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat);
cb(cur, "mtp_eh_proj", il);
ggml_tensor * inpSA = cur;
@@ -255,13 +255,13 @@ llama_model_deepseek2::graph_mtp::graph_mtp(const llm_graph_params & params) :
cur = build_norm(cur, layer.attn_norm, nullptr, LLM_NORM_RMS, il);
cb(cur, "mtp_attn_norm", il);
ggml_tensor * q = ggml_mul_mat(ctx0, layer.wq_a, cur);
ggml_tensor * q = build_lora_mm(layer.wq_a, cur);
cb(q, "mtp_q_a", il);
q = build_norm(q, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
cb(q, "mtp_q_a_norm", il);
q = ggml_mul_mat(ctx0, layer.wq_b, q);
q = build_lora_mm(layer.wq_b, q);
cb(q, "mtp_q_b", il);
ggml_tensor * q_nope =
@@ -277,7 +277,7 @@ llama_model_deepseek2::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_row_size(q->type, n_embd_head_qk_nope));
cb(q_pe, "mtp_q_pe", il);
ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, layer.wkv_a_mqa, cur);
ggml_tensor * kv_cmpr_pe = build_lora_mm(layer.wkv_a_mqa, cur);
cb(kv_cmpr_pe, "mtp_kv_cmpr_pe", il);
ggml_tensor * kv_cmpr =
@@ -315,7 +315,7 @@ llama_model_deepseek2::graph_mtp::graph_mtp(const llm_graph_params & params) :
q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
cb(q_nope, "mtp_q_nope_perm", il);
ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, layer.wk_b, q_nope);
ggml_tensor * q_nope_absorbed = build_lora_mm(layer.wk_b, q_nope);
cb(q_nope_absorbed, "mtp_q_nope_absorbed", il);
q_nope_absorbed = ggml_permute(ctx0, q_nope_absorbed, 0, 2, 1, 3);
@@ -334,7 +334,7 @@ llama_model_deepseek2::graph_mtp::graph_mtp(const llm_graph_params & params) :
cb(Vcur, "mtp_Vcur", il);
cur = build_attn(inp_attn_k,
layer.wo, nullptr, layer.wo_s,
layer.wo, nullptr,
Qcur, Kcur, Vcur, nullptr, nullptr, layer.wv_b, kq_scale, il);
cb(cur, "mtp_attn_out", il);
@@ -360,9 +360,9 @@ llama_model_deepseek2::graph_mtp::graph_mtp(const llm_graph_params & params) :
cb(moe_out, "mtp_ffn_moe_out", il);
ggml_tensor * ffn_shexp = build_ffn(cur,
layer.ffn_up_shexp, nullptr, nullptr,
layer.ffn_gate_shexp, nullptr, nullptr,
layer.ffn_down_shexp, nullptr, nullptr,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "mtp_ffn_shexp", il);
@@ -390,13 +390,9 @@ llama_model_deepseek2::graph_mtp::graph_mtp(const llm_graph_params & params) :
? layer.nextn.shared_head_head
: model.output;
ggml_tensor * head_s = layer.nextn.shared_head_head
? layer.nextn.shared_head_head_s
: model.output_s;
GGML_ASSERT(head_w && "GLM4 MTP: missing LM head (nextn.shared_head_head or model.output)");
cur = build_lora_mm(head_w, cur, head_s);
cur = build_lora_mm(head_w, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
@@ -475,7 +471,7 @@ llama_model_deepseek2::graph::graph(const llm_graph_params & params) :
cb(Kcur, "k_pe", il);
cur = build_attn(inp_attn_kv,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_out", il);
}
@@ -485,23 +481,23 @@ llama_model_deepseek2::graph::graph(const llm_graph_params & params) :
const bool is_lite = model.layers[il].wq;
if (!is_lite) {
q = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
q = build_lora_mm(model.layers[il].wq_a, cur);
cb(q, "q", il);
q = build_norm(q, model.layers[il].attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
cb(q, "q", il);
q = ggml_mul_mat(ctx0, model.layers[il].wq_b, q);
q = build_lora_mm(model.layers[il].wq_b, q);
cb(q, "q", il);
} else {
q = ggml_mul_mat(ctx0, model.layers[il].wq, cur);
q = build_lora_mm(model.layers[il].wq, cur);
cb(q, "q", il);
}
// {n_embd_head_k, n_head, n_tokens}
q = ggml_reshape_3d(ctx0, q, n_embd_head_k, n_head, n_tokens);
cb(q, "q", il);
ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
ggml_tensor * kv_cmpr_pe = build_lora_mm(model.layers[il].wkv_a_mqa, cur);
cb(kv_cmpr_pe, "kv_cmpr_pe", il);
// split into {kv_lora_rank, n_tokens}
@@ -542,7 +538,7 @@ llama_model_deepseek2::graph::graph(const llm_graph_params & params) :
cb(q_nope, "q_nope_perm", il);
// {n_embd_head_qk_nope, kv_lora_rank, n_head} x {n_embd_head_qk_nope, n_tokens, n_head}
ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, model.layers[il].wk_b, q_nope);
ggml_tensor * q_nope_absorbed = build_lora_mm(model.layers[il].wk_b, q_nope);
cb(q_nope_absorbed, "q_nope_absorbed", il);
// {kv_lora_rank, n_head, n_tokens}
@@ -573,10 +569,10 @@ llama_model_deepseek2::graph::graph(const llm_graph_params & params) :
// note: MLA with the absorption optimization converts into MQA (ie: GQA with 1 group)
cur = build_attn(inp_attn_k,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, model.layers[il].wv_b, kq_scale, il);
} else {
ggml_tensor * kv = ggml_mul_mat(ctx0, model.layers[il].wkv_b, kv_cmpr);
ggml_tensor * kv = build_lora_mm(model.layers[il].wkv_b, kv_cmpr);
cb(kv, "kv", il);
// split into {n_embd_head_qk_nope, n_head, n_tokens}
@@ -613,7 +609,7 @@ llama_model_deepseek2::graph::graph(const llm_graph_params & params) :
// note: MLA without the absorption optimization converts into MHA (ie: GQA with full n_head groups)
cur = build_attn(inp_attn_kv,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
}
}
@@ -629,9 +625,9 @@ llama_model_deepseek2::graph::graph(const llm_graph_params & params) :
if ((uint32_t) il < hparams.n_layer_dense_lead) {
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -655,9 +651,9 @@ llama_model_deepseek2::graph::graph(const llm_graph_params & params) :
{
ggml_tensor * ffn_shexp =
build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, NULL,
model.layers[il].ffn_gate_shexp, NULL, NULL,
model.layers[il].ffn_down_shexp, NULL, NULL,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -688,7 +684,7 @@ llama_model_deepseek2::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = ggml_mul_mat(ctx0, model.output, cur);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+25 -26
View File
@@ -209,7 +209,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
// self_attention
{
ggml_tensor * qr = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
ggml_tensor * qr = build_lora_mm(model.layers[il].wq_a, cur);
cb(qr, "qr", il);
qr = build_norm(qr, model.layers[il].attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
@@ -219,7 +219,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
// lightning indexer
{
ggml_tensor * indexer_q = ggml_mul_mat(ctx0, model.layers[il].indexer_attn_q_b, qr);
ggml_tensor * indexer_q = build_lora_mm(model.layers[il].indexer_attn_q_b, qr);
cb(indexer_q, "indexer_q", il);
// {n_embd_indexer_head, n_indexer_head, n_tokens}
@@ -227,7 +227,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
indexer_q = build_rope_indexer(indexer_q, inp_pos, il);
cb(indexer_q, "indexer_q", il);
ggml_tensor * indexer_k = ggml_mul_mat(ctx0, model.layers[il].indexer_attn_k, cur);
ggml_tensor * indexer_k = build_lora_mm(model.layers[il].indexer_attn_k, cur);
cb(indexer_k, "indexer_k", il);
indexer_k = build_norm(indexer_k, model.layers[il].indexer_k_norm, model.layers[il].indexer_k_norm_b, LLM_NORM, il);
@@ -250,7 +250,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
ggml_build_forward_expand(gf, mctx_lid->cpy_k(ctx0, indexer_k, k_idxs_lid, il));
// prepare indexer weights
ggml_tensor * indexer_weights = ggml_mul_mat(ctx0, model.layers[il].indexer_proj, cur);
ggml_tensor * indexer_weights = build_lora_mm(model.layers[il].indexer_proj, cur);
cb(indexer_weights, "indexer_weights", il);
// get cached indexer keys
@@ -274,7 +274,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
cb(top_k, "top_k", il);
}
ggml_tensor * q = ggml_mul_mat(ctx0, model.layers[il].wq_b, qr);
ggml_tensor * q = build_lora_mm(model.layers[il].wq_b, qr);
cb(q, "q", il);
// split into {n_embd_head_qk_nope, n_head, n_tokens}
@@ -289,7 +289,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
ggml_row_size(q->type, n_embd_head_k) * n_head, ggml_row_size(q->type, n_embd_head_qk_nope));
cb(q_pe, "q_pe", il);
ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
ggml_tensor * kv_cmpr_pe = build_lora_mm(model.layers[il].wkv_a_mqa, cur);
cb(kv_cmpr_pe, "kv_cmpr_pe", il);
// split into {kv_lora_rank, n_tokens}
@@ -321,7 +321,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
cb(q_nope, "q_nope_perm", il);
// {n_embd_head_qk_nope, kv_lora_rank, n_head} x {n_embd_head_qk_nope, n_tokens, n_head}
ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, model.layers[il].wk_b, q_nope);
ggml_tensor * q_nope_absorbed = build_lora_mm(model.layers[il].wk_b, q_nope);
cb(q_nope_absorbed, "q_nope_absorbed", il);
// {kv_lora_rank, n_head, n_tokens}
@@ -346,7 +346,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
// note: MLA with the absorption optimization converts into MQA (ie: GQA with 1 group)
cur = build_attn(inp_attn_dsa,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, model.layers[il].wv_b, top_k, kq_scale, il);
}
}
@@ -364,9 +364,9 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
if ((uint32_t) il < hparams.n_layer_dense_lead) {
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_s,
model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_s,
model.layers[il].ffn_down, NULL, model.layers[il].ffn_down_s,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -390,9 +390,9 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
{
ggml_tensor * ffn_shexp =
build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, model.layers[il].ffn_up_shexp_s,
model.layers[il].ffn_gate_shexp, NULL, model.layers[il].ffn_gate_shexp_s,
model.layers[il].ffn_down_shexp, NULL, model.layers[il].ffn_down_shexp_s,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -424,7 +424,7 @@ llama_model_deepseek32::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = ggml_mul_mat(ctx0, model.output, cur);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
@@ -511,7 +511,7 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params)
ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, /*dim=*/ 0);
cb(concat, "mtp_concat", il);
ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat, layer.nextn.eh_proj_s);
ggml_tensor * cur = build_lora_mm(layer.nextn.eh_proj, concat);
cb(cur, "mtp_eh_proj", il);
ggml_tensor * inpSA = cur;
@@ -521,13 +521,13 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params)
// self-attention: dense MLA, same construction as the deepseek2 trunk graph
{
ggml_tensor * q = ggml_mul_mat(ctx0, layer.wq_a, cur);
ggml_tensor * q = build_lora_mm(layer.wq_a, cur);
cb(q, "mtp_q", il);
q = build_norm(q, layer.attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
cb(q, "mtp_q", il);
q = ggml_mul_mat(ctx0, layer.wq_b, q);
q = build_lora_mm(layer.wq_b, q);
cb(q, "mtp_q", il);
// split into {n_embd_head_qk_nope, n_head, n_tokens}
@@ -542,7 +542,7 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params)
ggml_row_size(q->type, n_embd_head_k) * n_head, ggml_row_size(q->type, n_embd_head_qk_nope));
cb(q_pe, "mtp_q_pe", il);
ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, layer.wkv_a_mqa, cur);
ggml_tensor * kv_cmpr_pe = build_lora_mm(layer.wkv_a_mqa, cur);
cb(kv_cmpr_pe, "mtp_kv_cmpr_pe", il);
// split into {kv_lora_rank, n_tokens}
@@ -572,7 +572,7 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params)
cb(q_nope, "mtp_q_nope_perm", il);
// {n_embd_head_qk_nope, kv_lora_rank, n_head} x {n_embd_head_qk_nope, n_tokens, n_head}
ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, layer.wk_b, q_nope);
ggml_tensor * q_nope_absorbed = build_lora_mm(layer.wk_b, q_nope);
cb(q_nope_absorbed, "mtp_q_nope_absorbed", il);
// {kv_lora_rank, n_head, n_tokens}
@@ -597,7 +597,7 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params)
// note: MLA with the absorption optimization converts into MQA (ie: GQA with 1 group)
cur = build_attn(inp_attn,
layer.wo, NULL, layer.wo_s,
layer.wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, layer.wv_b, kq_scale, il);
cb(cur, "mtp_attn_out", il);
}
@@ -627,9 +627,9 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params)
// FFN shared expert
ggml_tensor * ffn_shexp =
build_ffn(cur,
layer.ffn_up_shexp, NULL, layer.ffn_up_shexp_s,
layer.ffn_gate_shexp, NULL, layer.ffn_gate_shexp_s,
layer.ffn_down_shexp, NULL, layer.ffn_down_shexp_s,
layer.ffn_up_shexp, NULL,
layer.ffn_gate_shexp, NULL,
layer.ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "mtp_ffn_shexp", il);
@@ -654,9 +654,8 @@ llama_model_deepseek32::graph_mtp::graph_mtp(const llm_graph_params & params)
cb(cur, "mtp_shared_head_norm", -1);
ggml_tensor * head_w = layer.nextn.shared_head_head ? layer.nextn.shared_head_head : model.output;
ggml_tensor * head_s = layer.nextn.shared_head_head ? layer.nextn.shared_head_head_s : model.output_s;
GGML_ASSERT(head_w && "DEEPSEEK32 MTP: missing LM head (nextn.shared_head_head or model.output)");
cur = build_lora_mm(head_w, cur, head_s);
cur = build_lora_mm(head_w, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+13 -13
View File
@@ -370,7 +370,7 @@ llama_model_deepseek4::graph::build_hc_mixes(
ggml_tensor * flat = ggml_reshape_2d(ctx0, x, hc_dim, nt);
ggml_tensor * flat_norm = ggml_rms_norm(ctx0, flat, norm_rms_eps);
ggml_tensor * mixes = ggml_mul_mat(ctx0, hc_fn, flat_norm);
ggml_tensor * mixes = build_lora_mm(hc_fn, flat_norm);
cb(mixes, "hc_mixes", il);
ggml_tensor * scale_pre = dsv4_view_1d(ctx0, hc_scale, 1, 0);
@@ -458,7 +458,7 @@ ggml_tensor * llama_model_deepseek4::graph::build_hc_head(
ggml_tensor * flat = ggml_reshape_2d(ctx0, x, hc_dim, nt);
ggml_tensor * flat_norm = ggml_rms_norm(ctx0, flat, norm_rms_eps);
ggml_tensor * mixes = ggml_mul_mat(ctx0, hc_fn, flat_norm);
ggml_tensor * mixes = build_lora_mm(hc_fn, flat_norm);
cb(mixes, "hc_head_mixes", -1);
ggml_tensor * pre = dsv4_hc_affine(ctx0, mixes, hc_scale, hc_base);
@@ -1160,7 +1160,7 @@ ggml_tensor * llama_model_deepseek4::graph::build_attention_impl(
ggml_tensor * out = nullptr;
if (inp_mtp) {
out = build_attn(inp_mtp,
nullptr, nullptr, nullptr,
nullptr, nullptr,
q, kv, kv,
nullptr, layer.attn_sinks, nullptr,
1.0f/sqrtf(float(n_embd_head)), il);
@@ -1188,7 +1188,7 @@ ggml_tensor * llama_model_deepseek4::graph::build_attention_impl(
out = ggml_reshape_3d(ctx0, out, o_group_dim, n_groups, nt);
out = ggml_permute(ctx0, out, 0, 2, 1, 3);
ggml_tensor * oa = ggml_mul_mat(ctx0, layer.wo_a, out);
ggml_tensor * oa = build_lora_mm(layer.wo_a, out);
cb(oa, "attn_wo_a", il);
oa = ggml_permute(ctx0, oa, 0, 2, 1, 3);
oa = ggml_cont_2d(ctx0, oa, o_lora_rank*n_groups, nt);
@@ -1288,9 +1288,9 @@ llama_model_deepseek4::graph::graph(const llm_graph_params & params) :
cb(moe_out, "ffn_moe_out", il);
ggml_tensor * ffn_shexp = build_ffn(cur,
layer.ffn_up_shexp, nullptr, nullptr,
layer.ffn_gate_shexp, nullptr, nullptr,
layer.ffn_down_shexp, nullptr, nullptr,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -1326,7 +1326,7 @@ llama_model_deepseek4::graph::graph(const llm_graph_params & params) :
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = ggml_mul_mat(ctx0, model.output, cur);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
}
@@ -1391,7 +1391,7 @@ llama_model_deepseek4::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_tensor * concat = ggml_concat(ctx0, e_norm, h_norm, 0);
cb(concat, "mtp_concat", il);
ggml_tensor * inpL = build_lora_mm(layer.nextn.eh_proj, concat, layer.nextn.eh_proj_s);
ggml_tensor * inpL = build_lora_mm(layer.nextn.eh_proj, concat);
cb(inpL, "mtp_eh_proj", il);
ggml_tensor * residual = inpL;
@@ -1438,9 +1438,9 @@ llama_model_deepseek4::graph_mtp::graph_mtp(const llm_graph_params & params) :
cb(moe_out, "mtp_ffn_moe_out", il);
ggml_tensor * ffn_shexp = build_ffn(cur,
layer.ffn_up_shexp, nullptr, nullptr,
layer.ffn_gate_shexp, nullptr, nullptr,
layer.ffn_down_shexp, nullptr, nullptr,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "mtp_ffn_shexp", il);
@@ -1469,7 +1469,7 @@ llama_model_deepseek4::graph_mtp::graph_mtp(const llm_graph_params & params) :
ggml_tensor * head_w = layer.nextn.shared_head_head ? layer.nextn.shared_head_head : model.output;
GGML_ASSERT(head_w && "DEEPSEEK4 MTP missing LM head");
cur = ggml_mul_mat(ctx0, head_w, cur);
cur = build_lora_mm(head_w, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -756,7 +756,7 @@ ggml_tensor * llama_model_deepseek41::graph::build_attention41(
cb(out, "attn_derope", il);
out = ggml_permute(ctx0, ggml_reshape_3d(ctx0, out, n_head/n_groups*n_embd_head, n_groups, nt), 0, 2, 1, 3);
ggml_tensor * oa = ggml_mul_mat(ctx0, layer.wo_a, out);
ggml_tensor * oa = build_lora_mm(layer.wo_a, out);
cb(oa, "attn_wo_a", il);
oa = ggml_cont_2d(ctx0, ggml_permute(ctx0, oa, 0, 2, 1, 3), o_lora_rank*n_groups, nt);
@@ -900,9 +900,9 @@ llama_model_deepseek41::graph::graph(const llm_graph_params & params) :
cb(moe_out, "ffn_moe_out", il);
ggml_tensor * ffn_shexp = build_ffn(cur,
layer.ffn_up_shexp, nullptr, nullptr,
layer.ffn_gate_shexp, nullptr, nullptr,
layer.ffn_down_shexp, nullptr, nullptr,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -926,7 +926,7 @@ llama_model_deepseek41::graph::graph(const llm_graph_params & params) :
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = ggml_mul_mat(ctx0, model.output, cur);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
}
+2 -1
View File
@@ -235,7 +235,8 @@ ggml_tensor * llm_build_delta_net_base::build_recurrent_attn_replay(
ggml_tensor * cgb = ggml_reshape_4d(ctx0, spgb, g0, H_v, 2*n_pend, spgb->ne[1]);
const auto gather = [&](ggml_tensor * rows, ggml_tensor * c) {
return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs), c->ne[0], c->ne[1], c->ne[2], n_seqs);
// the gdn op can store the new inputs into these rows while it replays them, so it reads a copy
return ggml_reshape_4d(ctx0, build_rs(inp, rows, rows->ne[0], n_seqs, nullptr, true), c->ne[0], c->ne[1], c->ne[2], n_seqs);
};
ggml_tensor * pk = gather(spk, ck);
+19 -21
View File
@@ -116,8 +116,6 @@ void llama_model_dflash::load_arch_tensors(llama_model_loader &) {
const int fc_flags = ml->get_tensor_meta("blk.0.ctx_mix.weight") ? TENSOR_NOT_REQUIRED : 0;
fc = create_tensor(tn(LLM_TENSOR_FC, "weight"), { n_embd_inp, n_embd }, fc_flags);
fc_s = create_tensor(tn(LLM_TENSOR_FC, "scale"), { 1 }, TENSOR_NOT_REQUIRED);
fc_in_s = create_tensor(tn(LLM_TENSOR_FC, "input_scale"), { 1 }, TENSOR_NOT_REQUIRED);
output_norm_enc = create_tensor(tn(LLM_TENSOR_ENC_OUTPUT_NORM, "weight"), { n_embd }, fc_flags); // encoder hidden_norm (after fc)
output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0); // decoder final norm
@@ -211,7 +209,7 @@ template <>
llama_model_dflash::graph<true>::graph(const llm_graph_params & params) : llm_graph_context(params) {
ggml_tensor * cur = build_inp_embd_enc();
cur = build_lora_mm(model.fc, cur, model.fc_s);
cur = build_lora_mm(model.fc, cur);
cb(cur, "fc_out", -1);
cur = build_norm(cur, model.output_norm_enc, NULL, LLM_NORM_RMS, -1);
@@ -251,7 +249,7 @@ ggml_tensor * llama_model_dflash::build_inject_inp(llm_graph_context & g, const
g.res->add_input(std::move(inp));
ggml_tensor * inp_g = g.build_lora_mm(model.fc, inp_target, model.fc_s);
ggml_tensor * inp_g = g.build_lora_mm(model.fc, inp_target);
return g.build_norm(inp_g, model.output_norm_enc, nullptr, LLM_NORM_RMS, -1);
}
@@ -267,16 +265,16 @@ ggml_tensor * llama_model_dflash::get_tok_embd(const llm_graph_context & g, cons
return model_other->tok_embd;
}
// lm_head and its scale from the target model (shared via ctx_other) when the draft has none
std::pair<ggml_tensor *, ggml_tensor *> llama_model_dflash::get_lm_head(const llm_graph_context & g, const llama_model & model) {
// lm_head from the target model (shared via ctx_other) when the draft has none
ggml_tensor * llama_model_dflash::get_lm_head(const llm_graph_context & g, const llama_model & model) {
if (model.output) {
return { model.output, model.output_s };
return model.output;
}
GGML_ASSERT(g.cparams.ctx_other != nullptr);
const auto * model_other = llama_get_model(g.cparams.ctx_other);
GGML_ASSERT(model_other->output != nullptr && "DFlash draft requires the target model's output projection");
return { model_other->output, model_other->output_s };
return model_other->output;
}
// DFlash decoder, dual-mode by batch type:
@@ -361,9 +359,9 @@ ggml_tensor * llama_model_dflash::graph_base::build_inject() {
for (int il = 0; il < n_layer; ++il) {
const auto & layer = model.layers[il];
ggml_tensor * Kcur = build_lora_mm(layer.wk, inp_g, layer.wk_s);
ggml_tensor * Kcur = build_lora_mm(layer.wk, inp_g);
const bool shared_kv = layer.wv == nullptr;
ggml_tensor * Vcur = shared_kv ? Kcur : build_lora_mm(layer.wv, inp_g, layer.wv_s);
ggml_tensor * Vcur = shared_kv ? Kcur : build_lora_mm(layer.wv, inp_g);
Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens);
@@ -401,7 +399,7 @@ void llama_model_dflash::graph_base::build_inject_ctx_mix() {
cb(feats, "inp_target_features", -1);
const auto build_mix = [&](ggml_tensor * mix, ggml_tensor * norm, int il) {
ggml_tensor * cur = ggml_reshape_2d(ctx0, ggml_mul_mat(ctx0, mix, feats), n_embd, n_tokens);
ggml_tensor * cur = ggml_reshape_2d(ctx0, build_lora_mm(mix, feats), n_embd, n_tokens);
return build_norm(cur, norm, nullptr, LLM_NORM_RMS, il);
};
@@ -469,10 +467,10 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok
cb(noise_norm, "attn_conv_in", il);
}
ggml_tensor * Qcur = build_lora_mm(layer.wq, noise_norm, layer.wq_s);
ggml_tensor * Kcur = build_lora_mm(layer.wk, noise_norm, layer.wk_s);
ggml_tensor * Qcur = build_lora_mm(layer.wq, noise_norm);
ggml_tensor * Kcur = build_lora_mm(layer.wk, noise_norm);
const bool shared_kv = layer.wv == nullptr;
ggml_tensor * Vcur = shared_kv ? Kcur : build_lora_mm(layer.wv, noise_norm, layer.wv_s);
ggml_tensor * Vcur = shared_kv ? Kcur : build_lora_mm(layer.wv, noise_norm);
Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);
Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);
@@ -492,8 +490,8 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok
// cache-aware, non-causal attention
ggml_tensor * cur = use_iswa
? build_attn(inp_attn_iswa, layer.wo, NULL, layer.wo_s, Qcur, Kcur, Vcur, nullptr, layer.attn_sinks, nullptr, kq_scale, il)
: build_attn(inp_attn, layer.wo, NULL, layer.wo_s, Qcur, Kcur, Vcur, nullptr, layer.attn_sinks, nullptr, kq_scale, il);
? build_attn(inp_attn_iswa, layer.wo, NULL, Qcur, Kcur, Vcur, nullptr, layer.attn_sinks, nullptr, kq_scale, il)
: build_attn(inp_attn, layer.wo, NULL, Qcur, Kcur, Vcur, nullptr, layer.attn_sinks, nullptr, kq_scale, il);
if (hparams.f_attn_value_scale != 0.0f) {
cur = ggml_scale(ctx0, cur, hparams.f_attn_value_scale);
@@ -524,9 +522,9 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok
}
cur = build_ffn(cur,
layer.ffn_up, NULL, layer.ffn_up_s,
layer.ffn_gate, NULL, layer.ffn_gate_s,
layer.ffn_down, NULL, layer.ffn_down_s,
layer.ffn_up, NULL,
layer.ffn_gate, NULL,
layer.ffn_down, NULL,
NULL,
hparams.llm_ffn_op, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -559,8 +557,8 @@ ggml_tensor * llama_model_dflash::graph_base::build_layers(ggml_tensor * inp_tok
}
ggml_tensor * llama_model_dflash::graph_base::build_logits(ggml_tensor * cur) {
const auto [output, output_s] = get_lm_head(*this, model);
cur = build_lora_mm(output, cur, output_s);
auto * output = get_lm_head(*this, model);
cur = build_lora_mm(output, cur);
// a padded lm head (e.g. shared from the target): drop the rows past the vocabulary
if (!model.d2t && cur->ne[0] > (int64_t) model.vocab.n_tokens()) {
+5 -5
View File
@@ -113,7 +113,7 @@ llama_model_domyn_edge::graph::graph(const llm_graph_params & params)
cb(Kcur, "Kcur_rope", il);
cur = build_attn(inp_attn,
layer.wo, NULL, layer.wo_s,
layer.wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
cb(cur, "attn_out", il);
@@ -135,9 +135,9 @@ llama_model_domyn_edge::graph::graph(const llm_graph_params & params)
// SwiGLU FFN
cur = build_ffn(cur,
layer.ffn_up, NULL, NULL,
layer.ffn_gate, NULL, NULL,
layer.ffn_down, NULL, NULL, NULL,
layer.ffn_up, NULL,
layer.ffn_gate, NULL,
layer.ffn_down, NULL, NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -154,7 +154,7 @@ llama_model_domyn_edge::graph::graph(const llm_graph_params & params)
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
}
+8 -8
View File
@@ -118,7 +118,7 @@ llama_model_dots1::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
}
if (il == n_layer - 1 && inp_out_ids) {
@@ -134,9 +134,9 @@ llama_model_dots1::graph::graph(const llm_graph_params & params) :
if ((uint32_t) il < hparams.n_layer_dense_lead) {
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -156,9 +156,9 @@ llama_model_dots1::graph::graph(const llm_graph_params & params) :
{
ggml_tensor * ffn_shexp =
build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, NULL,
model.layers[il].ffn_gate_shexp, NULL, NULL,
model.layers[il].ffn_down_shexp, NULL, NULL,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -182,7 +182,7 @@ llama_model_dots1::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+17 -17
View File
@@ -203,7 +203,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
{
ggml_tensor * attn_inp = cur;
ggml_tensor * qr = ggml_mul_mat(ctx0, model.layers[il].wq_a, cur);
ggml_tensor * qr = build_lora_mm(model.layers[il].wq_a, cur);
cb(qr, "qr", il);
qr = build_norm(qr, model.layers[il].attn_q_a_norm, nullptr, LLM_NORM_RMS, il);
@@ -213,7 +213,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
// lightning indexer (full-attention layers only)
if (!is_swa) {
ggml_tensor * indexer_q = ggml_mul_mat(ctx0, model.layers[il].indexer_attn_q_b, qr);
ggml_tensor * indexer_q = build_lora_mm(model.layers[il].indexer_attn_q_b, qr);
cb(indexer_q, "indexer_q", il);
// {n_embd_indexer_head, n_indexer_head, n_tokens}
@@ -221,7 +221,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
indexer_q = build_rope_indexer(indexer_q, inp_pos, il);
cb(indexer_q, "indexer_q", il);
ggml_tensor * indexer_k = ggml_mul_mat(ctx0, model.layers[il].indexer_attn_k, cur);
ggml_tensor * indexer_k = build_lora_mm(model.layers[il].indexer_attn_k, cur);
cb(indexer_k, "indexer_k", il);
indexer_k = build_norm(indexer_k, model.layers[il].indexer_k_norm, model.layers[il].indexer_k_norm_b, LLM_NORM, il);
@@ -243,7 +243,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
const auto & k_idxs_lid = inp_attn->get_dsa()->get_k_idxs_lid();
ggml_build_forward_expand(gf, mctx_lid->cpy_k(ctx0, indexer_k, k_idxs_lid, il));
ggml_tensor * indexer_weights = ggml_mul_mat(ctx0, model.layers[il].indexer_proj, cur);
ggml_tensor * indexer_weights = build_lora_mm(model.layers[il].indexer_proj, cur);
cb(indexer_weights, "indexer_weights", il);
indexer_k = mctx_lid->get_k(ctx0, il);
@@ -266,7 +266,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
cb(top_k, "top_k", il);
}
ggml_tensor * q = ggml_mul_mat(ctx0, model.layers[il].wq_b, qr);
ggml_tensor * q = build_lora_mm(model.layers[il].wq_b, qr);
cb(q, "q", il);
// split into {n_embd_head_qk_nope, n_head_l, n_tokens}
@@ -281,7 +281,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
ggml_row_size(q->type, n_embd_head_k_mla) * n_head_l, ggml_row_size(q->type, n_embd_head_qk_nope));
cb(q_pe, "q_pe", il);
ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, model.layers[il].wkv_a_mqa, cur);
ggml_tensor * kv_cmpr_pe = build_lora_mm(model.layers[il].wkv_a_mqa, cur);
cb(kv_cmpr_pe, "kv_cmpr_pe", il);
// split into {kv_lora_rank, n_tokens}
@@ -317,7 +317,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
cb(q_nope, "q_nope_perm", il);
// {n_embd_head_qk_nope, kv_lora_rank, n_head_l} x {n_embd_head_qk_nope, n_tokens, n_head_l}
ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, model.layers[il].wk_b, q_nope);
ggml_tensor * q_nope_absorbed = build_lora_mm(model.layers[il].wk_b, q_nope);
cb(q_nope_absorbed, "q_nope_absorbed", il);
// {kv_lora_rank, n_head_l, n_tokens}
@@ -342,11 +342,11 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
// apply the head-wise output gate before o_proj, so wo stays out of build_attn
if (is_swa) {
cur = build_attn(inp_attn->get_swa(),
nullptr, nullptr, nullptr,
nullptr, nullptr,
Qcur, Kcur, Vcur, nullptr, nullptr, model.layers[il].wv_b, kq_scale, il);
} else {
cur = build_attn(inp_attn->get_dsa(),
nullptr, nullptr, nullptr,
nullptr, nullptr,
Qcur, Kcur, Vcur, nullptr, nullptr, model.layers[il].wv_b, top_k, kq_scale, il);
}
cb(cur, "attn_out", il);
@@ -365,7 +365,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
cur = ggml_reshape_2d(ctx0, attn_3d, n_embd_head_v_mla * n_head_l, n_tokens);
cur = build_lora_mm(model.layers[il].wo, cur, model.layers[il].wo_s);
cur = build_lora_mm(model.layers[il].wo, cur);
cb(cur, "attn_output", il);
}
}
@@ -383,9 +383,9 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
if ((uint32_t) il < hparams.n_layer_dense_lead) {
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, model.layers[il].ffn_up_s,
model.layers[il].ffn_gate, NULL, model.layers[il].ffn_gate_s,
model.layers[il].ffn_down, NULL, model.layers[il].ffn_down_s,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -406,9 +406,9 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
ggml_tensor * ffn_shexp =
build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, model.layers[il].ffn_up_shexp_s,
model.layers[il].ffn_gate_shexp, NULL, model.layers[il].ffn_gate_shexp_s,
model.layers[il].ffn_down_shexp, NULL, model.layers[il].ffn_down_shexp_s,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -431,7 +431,7 @@ llama_model_dots3note::graph::graph(const llm_graph_params & params) :
cb(cur, "result_norm", -1);
res->t_embd = cur;
cur = ggml_mul_mat(ctx0, model.output, cur);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -89,7 +89,7 @@ llama_model_dream::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
}
if (il == n_layer - 1 && inp_out_ids) {
@@ -104,9 +104,9 @@ llama_model_dream::graph::graph(const llm_graph_params & params) :
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -126,7 +126,7 @@ llama_model_dream::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+26 -27
View File
@@ -83,7 +83,6 @@ void llama_model_dflash::load_tensors_dspark(int64_t n_vocab_draft) {
dspark_markov_w1 = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_W1, "weight"), { dspark_markov_rank, n_vocab }, 0);
dspark_markov_w2 = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_W2, "weight"), { dspark_markov_rank, n_vocab_draft }, 0);
dspark_markov_w2_s = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_W2, "scale"), { 1 }, TENSOR_NOT_REQUIRED);
dspark_markov_w2_b = create_tensor(tn(LLM_TENSOR_DSPARK_MARKOV_W2, "bias"), { n_vocab_draft }, TENSOR_NOT_REQUIRED);
dspark_conf_proj = create_tensor(tn(LLM_TENSOR_DSPARK_CONF_PROJ, "weight"), { n_embd + dspark_markov_rank, 1 }, TENSOR_NOT_REQUIRED);
@@ -366,7 +365,7 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model &
if (f_rnn) {
joint = ggml_concat(ctx0, joint, f_rnn, 0);
}
joint = ggml_add(ctx0, ggml_mul_mat(ctx0, model.dspark_joint_proj, joint), model.dspark_joint_proj_b); // [3R, n_blocks]
joint = ggml_add(ctx0, g.build_lora_mm(model.dspark_joint_proj, joint), model.dspark_joint_proj_b); // [3R, n_blocks]
const auto chunk = [&](int64_t k) {
return ggml_cont(ctx0, ggml_view_2d(ctx0, joint, rank, n_blocks, joint->nb[1], k*rank*ggml_element_size(joint)));
@@ -379,7 +378,7 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model &
markov = ggml_tanh(ctx0, chunk(2));
}
ggml_tensor * bias = g.build_lora_mm(w2, markov, model.dspark_markov_w2_s); // [n_vocab_draft, n_blocks]
ggml_tensor * bias = g.build_lora_mm(w2, markov); // [n_vocab_draft, n_blocks]
if (model.dspark_markov_w2_b) {
bias = ggml_add(ctx0, bias, model.dspark_markov_w2_b);
}
@@ -409,7 +408,7 @@ static void build_dspark_markov_head(llm_graph_context & g, const llama_model &
ggml_tensor * conf_inp_i = ggml_view_2d(ctx0, conf_inp, conf_inp->ne[0], n_blocks,
(size_t) block_drafts * conf_inp->nb[1], i*conf_inp->nb[1]);
ggml_tensor * feat = ggml_concat(ctx0, ggml_cont(ctx0, conf_inp_i), markov, 0);
ggml_tensor * conf = ggml_mul_mat(ctx0, model.dspark_conf_proj, feat);
ggml_tensor * conf = g.build_lora_mm(model.dspark_conf_proj, feat);
if (model.dspark_conf_proj_b) {
conf = ggml_add(ctx0, conf, model.dspark_conf_proj_b);
}
@@ -606,9 +605,9 @@ llama_model_dflash::graph_dsv4::graph_dsv4(const llm_graph_params & params) :
cb(moe_out, "ffn_moe_out", il);
ggml_tensor * ffn_shexp = build_ffn(cur,
layer.ffn_up_shexp, nullptr, nullptr,
layer.ffn_gate_shexp, nullptr, nullptr,
layer.ffn_down_shexp, nullptr, nullptr,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -628,8 +627,8 @@ llama_model_dflash::graph_dsv4::graph_dsv4(const llm_graph_params & params) :
cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1);
cb(cur, "result_norm", -1);
const auto [output, output_s] = get_lm_head(*this, model);
cur = build_lora_mm(output, cur, output_s);
auto * output = get_lm_head(*this, model);
cur = build_lora_mm(output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
@@ -757,7 +756,7 @@ llama_model_dflash::graph_dsv41::graph_dsv41(const llm_graph_params & params) :
cb(kv, "kv", il);
ggml_tensor * out = build_attn(inp_attn,
nullptr, nullptr, nullptr,
nullptr, nullptr,
q, kv, kv,
nullptr, layer.attn_sinks, nullptr,
kq_scale, il);
@@ -771,7 +770,7 @@ llama_model_dflash::graph_dsv41::graph_dsv41(const llm_graph_params & params) :
out = ggml_reshape_3d(ctx0, out, o_group_dim, n_groups, n_tokens);
out = ggml_permute(ctx0, out, 0, 2, 1, 3);
ggml_tensor * oa = ggml_mul_mat(ctx0, layer.wo_a, out);
ggml_tensor * oa = build_lora_mm(layer.wo_a, out);
cb(oa, "attn_wo_a", il);
oa = ggml_permute(ctx0, oa, 0, 2, 1, 3);
oa = ggml_cont_2d(ctx0, oa, o_lora_rank*n_groups, n_tokens);
@@ -807,9 +806,9 @@ llama_model_dflash::graph_dsv41::graph_dsv41(const llm_graph_params & params) :
cb(moe_out, "ffn_moe_out", il);
ggml_tensor * ffn_shexp = build_ffn(cur,
layer.ffn_up_shexp, nullptr, nullptr,
layer.ffn_gate_shexp, nullptr, nullptr,
layer.ffn_down_shexp, nullptr, nullptr,
layer.ffn_up_shexp, nullptr,
layer.ffn_gate_shexp, nullptr,
layer.ffn_down_shexp, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -833,8 +832,8 @@ llama_model_dflash::graph_dsv41::graph_dsv41(const llm_graph_params & params) :
cur = build_norm(cur, model.output_norm, nullptr, LLM_NORM_RMS, -1);
cb(cur, "result_norm", -1);
const auto [output, output_s] = get_lm_head(*this, model);
cur = build_lora_mm(output, cur, output_s);
auto * output = get_lm_head(*this, model);
cur = build_lora_mm(output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
@@ -867,7 +866,7 @@ llama_model_dflash::graph_mistral_large4::graph_mistral_large4(const llm_graph_p
const auto build_kv = [&](ggml_tensor * x, int il) -> std::pair<ggml_tensor *, ggml_tensor *> {
const auto & layer = model.layers[il];
ggml_tensor * kv_cmpr_pe = ggml_mul_mat(ctx0, layer.wkv_a_mqa, x);
ggml_tensor * kv_cmpr_pe = build_lora_mm(layer.wkv_a_mqa, x);
cb(kv_cmpr_pe, "kv_cmpr_pe", il);
ggml_tensor * kv_cmpr = ggml_view_2d(ctx0, kv_cmpr_pe, kv_lora_rank, n_tokens,
@@ -929,7 +928,7 @@ llama_model_dflash::graph_mistral_large4::graph_mistral_large4(const llm_graph_p
cb(cur, "attn_norm", il);
{
ggml_tensor * q = ggml_mul_mat(ctx0, layer.wq, cur);
ggml_tensor * q = build_lora_mm(layer.wq, cur);
cb(q, "q", il);
// {n_embd_head_nope, n_tokens, n_head}
@@ -939,7 +938,7 @@ llama_model_dflash::graph_mistral_large4::graph_mistral_large4(const llm_graph_p
q_nope = ggml_permute(ctx0, q_nope, 0, 2, 1, 3);
// {kv_lora_rank, n_head, n_tokens}
ggml_tensor * q_nope_absorbed = ggml_mul_mat(ctx0, layer.wk_b, q_nope);
ggml_tensor * q_nope_absorbed = build_lora_mm(layer.wk_b, q_nope);
q_nope_absorbed = ggml_permute(ctx0, q_nope_absorbed, 0, 2, 1, 3);
cb(q_nope_absorbed, "q_nope_absorbed", il);
@@ -958,7 +957,7 @@ llama_model_dflash::graph_mistral_large4::graph_mistral_large4(const llm_graph_p
// apply wv_b after attn, so the K rotation is already undone
ggml_tensor * out = build_attn(inp_attn,
nullptr, nullptr, nullptr,
nullptr, nullptr,
Qcur, Kcur, Vcur,
nullptr, nullptr, nullptr,
kq_scale, il);
@@ -966,10 +965,10 @@ llama_model_dflash::graph_mistral_large4::graph_mistral_large4(const llm_graph_p
// {kv_lora_rank, n_tokens, n_head} -> {n_embd_head_v_mla, n_tokens, n_head}
out = ggml_reshape_3d(ctx0, out, kv_lora_rank, n_head, n_tokens);
out = ggml_mul_mat(ctx0, layer.wv_b, ggml_permute(ctx0, out, 0, 2, 1, 3));
out = build_lora_mm(layer.wv_b, ggml_permute(ctx0, out, 0, 2, 1, 3));
out = ggml_cont_2d(ctx0, ggml_permute(ctx0, out, 0, 2, 1, 3), n_embd_head_v_mla*n_head, n_tokens);
cur = build_lora_mm(layer.wo, out, layer.wo_s);
cur = build_lora_mm(layer.wo, out);
cb(cur, "attn_out", il);
}
@@ -980,9 +979,9 @@ llama_model_dflash::graph_mistral_large4::graph_mistral_large4(const llm_graph_p
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
layer.ffn_up, nullptr, nullptr,
layer.ffn_gate, nullptr, nullptr,
layer.ffn_down, nullptr, nullptr,
layer.ffn_up, nullptr,
layer.ffn_gate, nullptr,
layer.ffn_down, nullptr,
nullptr, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -994,8 +993,8 @@ llama_model_dflash::graph_mistral_large4::graph_mistral_large4(const llm_graph_p
cb(cur, "result_norm", -1);
res->t_embd = cur;
const auto [output, output_s] = get_lm_head(*this, model);
ggml_tensor * logits = build_lora_mm(output, cur, output_s);
auto * output = get_lm_head(*this, model);
ggml_tensor * logits = build_lora_mm(output, cur);
// softcap does not apply to the markov bias
if (hparams.f_final_logit_softcapping) {
+4 -4
View File
@@ -242,7 +242,7 @@ llama_model_eagle3::graph<false>::graph(const llm_graph_params & params) : llm_g
cb(Kcur, "Kcur_rope", il);
cur = build_attn(inp_attn,
model.layers[il].wo, NULL, nullptr,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, kq_scale, il);
// Add residual and update it
@@ -256,9 +256,9 @@ llama_model_eagle3::graph<false>::graph(const llm_graph_params & params) : llm_g
cb(cur, "post_attn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
+8 -8
View File
@@ -45,7 +45,7 @@ llama_model_ernie4_5_moe::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
cb(cur, "attn_out", il);
}
@@ -65,9 +65,9 @@ llama_model_ernie4_5_moe::graph::graph(const llm_graph_params & params) :
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -92,9 +92,9 @@ llama_model_ernie4_5_moe::graph::graph(const llm_graph_params & params) :
if (hparams.n_ff_shexp > 0) {
ggml_tensor * ffn_shexp =
build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, NULL,
model.layers[il].ffn_gate_shexp, NULL, NULL,
model.layers[il].ffn_down_shexp, NULL, NULL,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -121,7 +121,7 @@ llama_model_ernie4_5_moe::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -113,7 +113,7 @@ llama_model_ernie4_5::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
}
if (il == n_layer - 1) {
@@ -130,9 +130,9 @@ llama_model_ernie4_5::graph::graph(const llm_graph_params & params) :
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
}
@@ -152,7 +152,7 @@ llama_model_ernie4_5::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+4 -4
View File
@@ -70,7 +70,7 @@ llama_model_eurobert::graph::graph(const llm_graph_params & params) : llm_graph_
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, nullptr, model.layers[il].wo_s,
model.layers[il].wo, nullptr,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f/sqrtf(float(n_embd_head)), il);
cb(cur, "kqv_out", il);
}
@@ -91,9 +91,9 @@ llama_model_eurobert::graph::graph(const llm_graph_params & params) : llm_graph_
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
+8 -8
View File
@@ -160,7 +160,7 @@ llama_model_exaone_moe::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn_iswa,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
cb(cur, "attn_out", il);
}
@@ -179,9 +179,9 @@ llama_model_exaone_moe::graph::graph(const llm_graph_params & params) :
if (model.layers[il].ffn_gate_inp == nullptr) {
// dense branch
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL, NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
} else {
@@ -203,9 +203,9 @@ llama_model_exaone_moe::graph::graph(const llm_graph_params & params) :
{
ggml_tensor * ffn_shexp =
build_ffn(cur,
model.layers[il].ffn_up_shexp, NULL, NULL,
model.layers[il].ffn_gate_shexp, NULL, NULL,
model.layers[il].ffn_down_shexp, NULL, NULL,
model.layers[il].ffn_up_shexp, NULL,
model.layers[il].ffn_gate_shexp, NULL,
model.layers[il].ffn_down_shexp, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(ffn_shexp, "ffn_shexp", il);
@@ -231,7 +231,7 @@ llama_model_exaone_moe::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -83,7 +83,7 @@ llama_model_exaone::graph::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, model.layers[il].wo_b, model.layers[il].wo_s,
model.layers[il].wo, model.layers[il].wo_b,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
}
if (il == n_layer - 1 && inp_out_ids) {
@@ -98,9 +98,9 @@ llama_model_exaone::graph::graph(const llm_graph_params & params) :
cb(cur, "ffn_norm", il);
cur = build_ffn(cur,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL,
NULL, LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -121,7 +121,7 @@ llama_model_exaone::graph::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;
+5 -5
View File
@@ -140,7 +140,7 @@ llama_model_exaone4::graph<iswa>::graph(const llm_graph_params & params) :
cb(Vcur, "Vcur", il);
cur = build_attn(inp_attn,
model.layers[il].wo, NULL, model.layers[il].wo_s,
model.layers[il].wo, NULL,
Qcur, Kcur, Vcur, nullptr, nullptr, nullptr, 1.0f / sqrtf(float(n_embd_head)), il);
cb(cur, "attn_out", il);
}
@@ -156,9 +156,9 @@ llama_model_exaone4::graph<iswa>::graph(const llm_graph_params & params) :
// feed-forward network
cur = build_ffn(ffn_inp,
model.layers[il].ffn_up, NULL, NULL,
model.layers[il].ffn_gate, NULL, NULL,
model.layers[il].ffn_down, NULL, NULL, NULL,
model.layers[il].ffn_up, NULL,
model.layers[il].ffn_gate, NULL,
model.layers[il].ffn_down, NULL, NULL,
LLM_FFN_SILU, LLM_FFN_PAR, il);
cb(cur, "ffn_out", il);
@@ -181,7 +181,7 @@ llama_model_exaone4::graph<iswa>::graph(const llm_graph_params & params) :
res->t_embd = cur;
// lm_head
cur = build_lora_mm(model.output, cur, model.output_s);
cur = build_lora_mm(model.output, cur);
cb(cur, "result_output", -1);
res->t_logits = cur;

Some files were not shown because too many files have changed in this diff Show More