mirror of
https://github.com/ggml-org/llama.cpp.git
synced 2026-11-30 22:57:40 -06:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b1ba66b59 | ||
|
|
713fee7fb0 | ||
|
|
e89795bf78 | ||
|
|
1f1e6cb26a | ||
|
|
db503b89fd | ||
|
|
78c9ca4b06 | ||
|
|
abeb9e7bd7 | ||
|
|
c8476ae546 | ||
|
|
779b413a67 | ||
|
|
7dfa241048 | ||
|
|
49f972e139 | ||
|
|
019951ec44 | ||
|
|
616c931e4b | ||
|
|
e1b9f46453 | ||
|
|
559afe384f | ||
|
|
2d48484127 | ||
|
|
22d68b8ac3 | ||
|
|
7778397892 |
@@ -9,6 +9,7 @@
|
||||
# ggml-org/ggml-et : marty1885
|
||||
# ggml-org/ggml-hexagon : lhez, max-krasnyansky
|
||||
# ggml-org/ggml-hip : IMbackK, thelittlefireman
|
||||
# ggml-org/ggml-hrx : AaronStGeorge, Geramy, IMbackK, pwilkin
|
||||
# ggml-org/ggml-metal : forforever73, ggerganov, jhen0409, masterFoad
|
||||
# ggml-org/ggml-opencl : lhez, max-krasnyansky
|
||||
# ggml-org/ggml-openvino : ravi9, wine99
|
||||
@@ -56,6 +57,7 @@
|
||||
/ggml/src/ggml-cuda/vendors/hip.h @IMbackK
|
||||
/ggml/src/ggml-hexagon/ @ggml-org/ggml-hexagon
|
||||
/ggml/src/ggml-hip/ @ggml-org/ggml-hip
|
||||
/ggml/src/ggml-hrx/ @ggml-org/ggml-hrx @AaronStGeorge @Geramy @IMbackK @pwilkin
|
||||
/ggml/src/ggml-et/ @marty1885
|
||||
/ggml/src/ggml-impl.h @ggerganov
|
||||
/ggml/src/ggml-metal/ @ggml-org/ggml-metal
|
||||
|
||||
@@ -37,6 +37,9 @@
|
||||
# with OPENVINO support
|
||||
# GG_BUILD_OPENVINO=1 GG_BUILD_LOW_PERF=1 GGML_OPENVINO_DEVICE=CPU bash ./ci/run.sh ./tmp/results ./tmp/mnt
|
||||
#
|
||||
# with HRX support
|
||||
# GG_BUILD_HRX=1 HRX_SDK_PATH=/path/to/hrx-sdk bash ./ci/run.sh ./tmp/results ./tmp/mnt
|
||||
#
|
||||
|
||||
if [ -z "$2" ]; then
|
||||
echo "usage: $0 <output-dir> <mnt-dir>"
|
||||
@@ -99,6 +102,17 @@ if [ ! -z ${GG_BUILD_ROCM} ]; then
|
||||
CMAKE_EXTRA="${CMAKE_EXTRA} -DGPU_TARGETS=${GG_BUILD_AMDGPU_TARGETS}"
|
||||
fi
|
||||
|
||||
if [ ! -z ${GG_BUILD_HRX} ]; then
|
||||
CMAKE_EXTRA="${CMAKE_EXTRA} -DGGML_HRX=ON"
|
||||
|
||||
if [ ! -z "${HRX_SDK_PATH}" ]; then
|
||||
export CMAKE_PREFIX_PATH="${HRX_SDK_PATH}${CMAKE_PREFIX_PATH:+:${CMAKE_PREFIX_PATH}}"
|
||||
fi
|
||||
|
||||
# TODO: HRX has no quantized KV cache yet (SET_ROWS into q8_0)
|
||||
CTEST_EXTRA="-E test-llama-context"
|
||||
fi
|
||||
|
||||
if [ ! -z ${GG_BUILD_SYCL} ]; then
|
||||
if [ -z ${ONEAPI_ROOT} ]; then
|
||||
echo "Not detected ONEAPI_ROOT, please install oneAPI base toolkit and enable it by:"
|
||||
@@ -439,10 +453,13 @@ function gg_run_qwen3_0_6b {
|
||||
|
||||
(time ./bin/llama-imatrix --model ${model_f16} -f ${wiki_test} -ngl 99 -c 1024 -b 512 --chunks 2 ) 2>&1 | tee -a $OUT/${ci}-imatrix.log
|
||||
|
||||
(time ./bin/test-llama-context --model ${model_q4_0} -ngl 10 -c 1024 -fa off --no-op-offload) 2>&1 | tee -a $OUT/${ci}-test-llama-context.log
|
||||
(time ./bin/test-llama-context --model ${model_q4_0} -ngl 99 -c 1024 -fa off ) 2>&1 | tee -a $OUT/${ci}-test-llama-context.log
|
||||
(time ./bin/test-llama-context --model ${model_q4_0} -ngl 10 -c 1024 -fa on --no-op-offload) 2>&1 | tee -a $OUT/${ci}-test-llama-context.log
|
||||
(time ./bin/test-llama-context --model ${model_q4_0} -ngl 99 -c 1024 -fa on ) 2>&1 | tee -a $OUT/${ci}-test-llama-context.log
|
||||
# TODO: HRX has no quantized KV cache yet (SET_ROWS into q8_0)
|
||||
if [ -z ${GG_BUILD_HRX} ]; then
|
||||
(time ./bin/test-llama-context --model ${model_q4_0} -ngl 10 -c 1024 -fa off --no-op-offload) 2>&1 | tee -a $OUT/${ci}-test-llama-context.log
|
||||
(time ./bin/test-llama-context --model ${model_q4_0} -ngl 99 -c 1024 -fa off ) 2>&1 | tee -a $OUT/${ci}-test-llama-context.log
|
||||
(time ./bin/test-llama-context --model ${model_q4_0} -ngl 10 -c 1024 -fa on --no-op-offload) 2>&1 | tee -a $OUT/${ci}-test-llama-context.log
|
||||
(time ./bin/test-llama-context --model ${model_q4_0} -ngl 99 -c 1024 -fa on ) 2>&1 | tee -a $OUT/${ci}-test-llama-context.log
|
||||
fi
|
||||
|
||||
check_ppl "f16" "$(cat $OUT/${ci}-tg-f16.log | grep "^\[1\]")"
|
||||
if [ -z ${GG_BUILD_NO_BF16} ]; then
|
||||
|
||||
@@ -216,14 +216,33 @@ static value exec_binary_op(context & ctx, const token & op, value left_val, val
|
||||
}
|
||||
return mk_val<value_float>(std::floor(a / b));
|
||||
} else if (op.value == "%") {
|
||||
double rem = std::fmod(a, b);
|
||||
JJ_DEBUG("Modulo operation: %f %% %f = %f", a, b, rem);
|
||||
bool is_float = is_val<value_float>(left_val) || is_val<value_float>(right_val);
|
||||
if (is_float) {
|
||||
return mk_val<value_float>(rem);
|
||||
} else {
|
||||
return mk_val<value_int>(float_to_int(rem));
|
||||
// python semantics: result has the sign of the divisor
|
||||
if (is_val<value_int>(left_val) && is_val<value_int>(right_val)) {
|
||||
const int64_t x = left_val->as_int();
|
||||
const int64_t y = right_val->as_int();
|
||||
if (y == 0) {
|
||||
throw std::runtime_error("integer modulo by zero");
|
||||
}
|
||||
if (y == -1) {
|
||||
// INT64_MIN % -1 is UB
|
||||
return mk_val<value_int>(0);
|
||||
}
|
||||
int64_t r = x % y;
|
||||
if (r != 0 && (r < 0) != (y < 0)) {
|
||||
r += y;
|
||||
}
|
||||
return mk_val<value_int>(r);
|
||||
}
|
||||
double rem = std::fmod(a, b);
|
||||
if (rem != 0) {
|
||||
if ((rem < 0) != (b < 0)) {
|
||||
rem += b;
|
||||
}
|
||||
} else {
|
||||
rem = std::copysign(0.0, b);
|
||||
}
|
||||
JJ_DEBUG("Modulo operation: %f %% %f = %f", a, b, rem);
|
||||
return mk_val<value_float>(rem);
|
||||
} else if (op.value == "<") {
|
||||
JJ_DEBUG("Comparison operation: %f < %f is %d", a, b, a < b);
|
||||
return mk_val<value_bool>(a < b);
|
||||
|
||||
@@ -1071,6 +1071,7 @@ class ModelBase:
|
||||
gguf.MODEL_ARCH.QWEN35,
|
||||
gguf.MODEL_ARCH.QWEN35MOE,
|
||||
gguf.MODEL_ARCH.QWEN3NEXT,
|
||||
gguf.MODEL_ARCH.LFM3,
|
||||
}
|
||||
if self.model_arch not in _HADAMARD_ARCHS:
|
||||
raise ValueError(
|
||||
@@ -1085,6 +1086,7 @@ class ModelBase:
|
||||
r"|ffn_gate_exps|ffn_up_exps|ffn_down_exps|ffn_gate_up_exps"
|
||||
r"|ffn_gate_shexp|ffn_up_shexp|ffn_down_shexp"
|
||||
r"|ssm_out"
|
||||
r"|shortconv\.in_proj|shortconv\.out_proj"
|
||||
r")\.weight"
|
||||
)
|
||||
weight_names: list[str] = []
|
||||
|
||||
@@ -72,6 +72,8 @@ However, A6x GPUs in phones are likely not supported due to the outdated driver
|
||||
| MXFP4 | Support |
|
||||
| IQ4_NL | Support |
|
||||
|
||||
`MUL_MAT` supports F32 weight scales per tensor or per output channel. `MUL_MAT_ID` supports F32 weight scales per tensor, per expert, or per output channel of each expert.
|
||||
|
||||
`MUL_MAT_ID` accepts an expert id of `-1` and writes zeros to that slot. `ADD_ID` adds no bias for `-1`, including in fused MoE operations.
|
||||
|
||||
## Model Preparation
|
||||
|
||||
@@ -20,6 +20,7 @@ The following sections describe how to build with different backends and options
|
||||
* [CUDA](#cuda)
|
||||
* [MUSA](#musa)
|
||||
* [HIP](#hip)
|
||||
* [HRX](#hrx)
|
||||
* [Vulkan](#vulkan)
|
||||
* [CANN](#cann)
|
||||
* [ZenDNN](#zendnn)
|
||||
@@ -434,6 +435,39 @@ If your GPU is not officially supported you can use the environment variable [`H
|
||||
|
||||
On Linux it is possible to use unified memory architecture (UMA) to share main memory between the CPU and integrated GPU by setting environment variable `GGML_CUDA_ENABLE_UNIFIED_MEMORY=1`. However, this hurts performance for non-integrated GPUs (but enables working with integrated GPUs).
|
||||
|
||||
## HRX
|
||||
|
||||
This provides GPU acceleration on AMD RDNA3, RDNA3.5 and RDNA4 GPUs (gfx1100, gfx1101, gfx1102, gfx1103, gfx1150, gfx1151, gfx1152, gfx1200, gfx1201) through the HRX runtime. The backend is experimental. Kernels are written in Loom and compiled for the GPU at first use, so ROCm is not required.
|
||||
|
||||
Build and install the HRX SDK v0.2.0 from the [hrx-system release](https://github.com/ROCm/hrx-system/releases/tag/v0.2.0) source:
|
||||
|
||||
```bash
|
||||
curl -L https://github.com/ROCm/hrx-system/archive/refs/tags/v0.2.0.tar.gz | tar xz
|
||||
cd hrx-system-0.2.0
|
||||
python3 dev.py cmake setup
|
||||
source .venv/bin/activate
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=RelWithDebInfo -DBUILD_SHARED_LIBS=OFF -DIREE_ENABLE_WERROR_FLAG=OFF \
|
||||
-DLIBHRX_BUILD=ON -DLIBHRX_BUILD_HIP_BINDING=OFF -DLIBHRX_BUILD_PASSTHROUGH=OFF -DLIBHRX_BUILD_CTS=OFF
|
||||
cmake --build build --target hrx hrx-info loomc_shared
|
||||
cmake --install build --prefix /path/to/hrx-sdk --component HrxPublicDist
|
||||
```
|
||||
|
||||
Then build llama.cpp with:
|
||||
|
||||
```bash
|
||||
cmake -B build -DGGML_HRX=ON -DCMAKE_PREFIX_PATH=/path/to/hrx-sdk
|
||||
cmake --build build --config Release
|
||||
```
|
||||
|
||||
The devices are named `HRX0`, `HRX1`, ... Use `--list-devices` to show them and `--device HRX0` to select one.
|
||||
|
||||
This version of the backend targets TinyStories-15M (`stories15M-q4_0.gguf`, the model of the llama.cpp tests). It supports only these ops:
|
||||
|
||||
* `MUL_MAT` with Q4_0 weights and F32 activations
|
||||
* `SET_ROWS`, `CPY`, `DUP` and `CONT` (F32 to F32 or F16) and `FILL` (F32 and F16). llama.cpp runs these ops in place on the KV cache and the recurrent state in GPU memory. The CPU cannot run them there.
|
||||
|
||||
All other ops and types run on the CPU.
|
||||
|
||||
## Vulkan
|
||||
|
||||
### For Windows Users:
|
||||
|
||||
+126
-124
@@ -12,127 +12,129 @@ Legend:
|
||||
- 🟡 Partially supported by this backend
|
||||
- ❌ Not supported by this backend
|
||||
|
||||
| Operation | BLAS | CANN | CPU | CUDA | ET | HTP | MTL | OPENVINO | OpenCL | SYCL | Vulkan | WebGPU | ZenDNN | zDNN |
|
||||
|-----------|------|------|------|------|------|------|------|------|------|------|------|------|------|------|
|
||||
| ABS | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ACC | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ADD | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ADD1 | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| ADD_ID | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ARANGE | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ARGMAX | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ARGSORT | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CEIL | ❌ | ❌ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CLAMP | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONCAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONT | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONV_1D_DW | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
|
||||
| CONV_2D | ❌ | ❌ | 🟡 | ✅ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
|
||||
| CONV_2D_DW | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ❌ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CONV_3D | ❌ | ❌ | ✅ | ✅ | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| CONV_TRANSPOSE_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CONV_TRANSPOSE_2D | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| COS | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| COUNT_EQUAL | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CPY | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| CROSS_ENTROPY_LOSS | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| CROSS_ENTROPY_LOSS_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| CUMSUM | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| DIAG | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| DIV | ❌ | ✅ | ✅ | ✅ | ❌ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| DSV4_HC_COMB | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| DSV4_HC_POST | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| DSV4_HC_PRE | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| DUP | ❌ | ✅ | ✅ | ✅ | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| EXP | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| EXPM1 | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| FILL | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| FLASH_ATTN_EXT | ❌ | 🟡 | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| FLOOR | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GATED_DELTA_NET | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GATED_LINEAR_ATTN | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| GEGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GEGLU_ERF | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GEGLU_QUICK | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GELU_ERF | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GELU_QUICK | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GET_ROWS | ❌ | 🟡 | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | ❌ | ❌ |
|
||||
| GET_ROWS_BACK | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ |
|
||||
| GROUP_NORM | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| HARDSIGMOID | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| HARDSWISH | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| IM2COL | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| IM2COL_3D | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| L2_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| LEAKY_RELU | ❌ | ✅ | ✅ | ✅ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| LIGHTNING_INDEXER | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| MEAN | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | 🟡 | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| MUL | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| MUL_MAT | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 |
|
||||
| MUL_MAT_HADAMARD | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | 🟡 |
|
||||
| MUL_MAT_ID | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ❌ |
|
||||
| MUL_MAT_ID_W4A4 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_ID_W4A8 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_BF16 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_BF16_SRC0 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_F32 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_W4A4 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_W4A8 | ❌ | ❌ | ✅ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| NEG | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| OPT_STEP_ADAMW | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| OPT_STEP_SGD | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| OUT_PROD | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ |
|
||||
| PAD | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| PAD_REFLECT_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ |
|
||||
| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| POOL_2D | ❌ | 🟡 | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| REGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| REPEAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| REPEAT_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| RMS_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RMS_NORM_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROUND | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RWKV_WKV6 | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| RWKV_WKV7 | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| SCALE | ❌ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SET | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| SET_ROWS | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| SGN | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SIGMOID | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SIGMOID_BACK | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| SILU | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SILU_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
||||
| SIN | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SLEEP | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| SOFTPLUS | ❌ | ❌ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SOFT_MAX | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SOFT_MAX_BACK | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ |
|
||||
| SOLVE_TRI | ❌ | ❌ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ❌ | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| SQR | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SQRT | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SSM_CONV | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SSM_SCAN | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | 🟡 | 🟡 | 🟡 | ✅ | ❌ | ❌ |
|
||||
| STEP | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SUB | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SUM | ❌ | 🟡 | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| SUM_ROWS | ❌ | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| SWIGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SWIGLU_CLAMP | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| SWIGLU_OAI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TANH | ❌ | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TIMESTEP_EMBEDDING | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TOP_K | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
|
||||
| TOP_K_MASK | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
||||
| TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| Operation | BLAS | CANN | CPU | CUDA | ET | HRX | HTP | MTL | OPENVINO | OpenCL | SYCL | Vulkan | WebGPU | ZenDNN | zDNN |
|
||||
|-----------|------|------|------|------|------|------|------|------|------|------|------|------|------|------|------|
|
||||
| ABS | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ACC | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ADD | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ADD1 | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| ADD_ID | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ARANGE | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ARGMAX | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ARGSORT | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CEIL | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CLAMP | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| COL2IM_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONCAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONT | ❌ | 🟡 | ✅ | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| CONV_1D_DW | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ |
|
||||
| CONV_2D | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
|
||||
| CONV_2D_DW | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CONV_3D | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | 🟡 | ✅ | 🟡 | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| CONV_TRANSPOSE_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CONV_TRANSPOSE_2D | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| COS | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| COUNT_EQUAL | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| CPY | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| CROSS_ENTROPY_LOSS | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| CROSS_ENTROPY_LOSS_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| CUMSUM | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| DIAG | ❌ | ❌ | ✅ | ✅ | 🟡 | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| DIV | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | 🟡 | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| DSV4_HC_COMB | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| DSV4_HC_POST | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| DSV4_HC_PRE | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| DUP | ❌ | ✅ | ✅ | ✅ | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| EXP | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| EXPM1 | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ❌ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| FILL | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| FLASH_ATTN_EXT | ❌ | 🟡 | ✅ | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| FLOOR | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GATED_DELTA_NET | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GATED_LINEAR_ATTN | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| GEGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GEGLU_ERF | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GEGLU_QUICK | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GELU_ERF | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GELU_QUICK | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| GET_ROWS | ❌ | 🟡 | ✅ | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | ❌ | ❌ |
|
||||
| GET_ROWS_BACK | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ |
|
||||
| GROUP_NORM | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| HARDSIGMOID | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| HARDSWISH | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| IM2COL | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| IM2COL_3D | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| L2_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| LEAKY_RELU | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| LIGHTNING_INDEXER | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| LOG | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| MEAN | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | 🟡 | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| MUL | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| MUL_MAT | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 |
|
||||
| MUL_MAT_HADAMARD | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | 🟡 |
|
||||
| MUL_MAT_ID | ❌ | 🟡 | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | 🟡 | 🟡 | ❌ |
|
||||
| MUL_MAT_ID_PREC_SRC1_BF16 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_ID_PREC_SRC1_F32 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_ID_W4A4 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_ID_W4A8 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_BF16 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_BF16_SRC0 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_PREC_SRC1_F32 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_W4A4 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| MUL_MAT_W4A8 | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | 🟡 | ❌ | 🟡 | 🟡 | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| NEG | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| OPT_STEP_ADAMW | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| OPT_STEP_SGD | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| OUT_PROD | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ |
|
||||
| PAD | ❌ | 🟡 | ✅ | 🟡 | ❌ | ❌ | ✅ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| PAD_REFLECT_1D | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ❌ | ✅ | ❌ | ❌ |
|
||||
| POOL_1D | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| POOL_2D | ❌ | 🟡 | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| REGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RELU | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| REPEAT | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | 🟡 | ❌ | ❌ |
|
||||
| REPEAT_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| RMS_NORM | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | ✅ | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RMS_NORM_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROLL | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | 🟡 | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| ROPE_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| ROUND | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| RWKV_WKV6 | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| RWKV_WKV7 | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ |
|
||||
| SCALE | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | 🟡 | ✅ | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SET | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| SET_ROWS | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| SGN | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SIGMOID | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SIGMOID_BACK | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| SILU | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SILU_BACK | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
||||
| SIN | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SLEEP | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ |
|
||||
| SOFTPLUS | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SOFT_MAX | ❌ | 🟡 | ✅ | ✅ | 🟡 | ❌ | 🟡 | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SOFT_MAX_BACK | ❌ | ❌ | 🟡 | 🟡 | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | 🟡 | ✅ | ❌ | ❌ | ❌ |
|
||||
| SOLVE_TRI | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ✅ | ✅ | ❌ | ✅ | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| SQR | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SQRT | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SSM_CONV | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SSM_SCAN | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ❌ | 🟡 | 🟡 | 🟡 | ✅ | ❌ | ❌ |
|
||||
| STEP | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SUB | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SUM | ❌ | 🟡 | ✅ | 🟡 | ❌ | ❌ | 🟡 | 🟡 | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | ❌ | ❌ |
|
||||
| SUM_ROWS | ❌ | ✅ | ✅ | 🟡 | ❌ | ❌ | 🟡 | ✅ | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ❌ | ❌ |
|
||||
| SWIGLU | ❌ | ✅ | ✅ | ✅ | 🟡 | ❌ | 🟡 | 🟡 | 🟡 | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| SWIGLU_CLAMP | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ❌ |
|
||||
| SWIGLU_OAI | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TANH | ❌ | ✅ | ✅ | 🟡 | 🟡 | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TIMESTEP_EMBEDDING | ❌ | ✅ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TOP_K | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ✅ | ❌ | ✅ | ✅ | 🟡 | ✅ | ❌ | ❌ |
|
||||
| TOP_K_MASK | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ | ❌ | ✅ | ❌ | ❌ | ❌ |
|
||||
| TRI | ❌ | ❌ | ✅ | ✅ | ✅ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| TRUNC | ❌ | ❌ | ✅ | 🟡 | 🟡 | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| UPSCALE | ❌ | 🟡 | ✅ | ✅ | ❌ | ❌ | 🟡 | ✅ | ✅ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
| XIELU | ❌ | ❌ | ✅ | ✅ | ❌ | ❌ | ❌ | ✅ | ❌ | 🟡 | ✅ | ✅ | ✅ | ❌ | ❌ |
|
||||
|
||||
+24215
File diff suppressed because it is too large
Load Diff
@@ -217,6 +217,7 @@ option(GGML_HIP "ggml: use HIP"
|
||||
option(GGML_HIP_GRAPHS "ggml: use HIP graph" ON)
|
||||
option(GGML_HIP_RCCL "ggml: use ROCm Collective Comm. Library" OFF)
|
||||
option(GGML_HIP_NO_VMM "ggml: do not try to use HIP VMM" ON)
|
||||
option(GGML_HRX "ggml: use HRX (experimental)" OFF)
|
||||
option(GGML_HIP_MMQ_MFMA "ggml: enable MFMA MMA for CDNA in MMQ" ON)
|
||||
option(GGML_HIP_EXPORT_METRICS "ggml: enable kernel perf metrics output" OFF)
|
||||
option(GGML_MUSA_GRAPHS "ggml: use MUSA graph, experimental, unstable" OFF)
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
#pragma once
|
||||
|
||||
#include "ggml-backend.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif // __cplusplus
|
||||
|
||||
#define GGML_HRX_NAME "HRX"
|
||||
|
||||
GGML_BACKEND_API ggml_backend_t ggml_backend_hrx_init(size_t device);
|
||||
GGML_BACKEND_API bool ggml_backend_is_hrx(ggml_backend_t backend);
|
||||
GGML_BACKEND_API int ggml_backend_hrx_get_device_count(void);
|
||||
GGML_BACKEND_API ggml_backend_buffer_type_t ggml_backend_hrx_buffer_type(size_t device);
|
||||
GGML_BACKEND_API ggml_backend_reg_t ggml_backend_hrx_reg(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif // __cplusplus
|
||||
@@ -601,6 +601,7 @@ ggml_add_backend(CANN)
|
||||
ggml_add_backend(CUDA)
|
||||
ggml_add_backend(ET)
|
||||
ggml_add_backend(HIP)
|
||||
ggml_add_backend(HRX)
|
||||
ggml_add_backend(METAL)
|
||||
ggml_add_backend(MUSA)
|
||||
ggml_add_backend(RPC)
|
||||
|
||||
@@ -38,6 +38,10 @@
|
||||
#include "ggml-metal.h"
|
||||
#endif
|
||||
|
||||
#ifdef GGML_USE_HRX
|
||||
#include "ggml-hrx.h"
|
||||
#endif // GGML_USE_HRX
|
||||
|
||||
#ifdef GGML_USE_SYCL
|
||||
#include "ggml-sycl.h"
|
||||
#endif
|
||||
@@ -123,6 +127,9 @@ struct ggml_backend_registry {
|
||||
#ifdef GGML_USE_METAL
|
||||
register_backend(ggml_backend_metal_reg());
|
||||
#endif
|
||||
#ifdef GGML_USE_HRX
|
||||
register_backend(ggml_backend_hrx_reg());
|
||||
#endif // GGML_USE_HRX
|
||||
#ifdef GGML_USE_SYCL
|
||||
register_backend(ggml_backend_sycl_reg());
|
||||
#endif
|
||||
@@ -581,6 +588,7 @@ void ggml_backend_load_all_from_path(const char * dir_path) {
|
||||
ggml_backend_load_best("cann", silent, dir_path);
|
||||
ggml_backend_load_best("cuda", silent, dir_path);
|
||||
ggml_backend_load_best("hip", silent, dir_path);
|
||||
ggml_backend_load_best("hrx", silent, dir_path);
|
||||
ggml_backend_load_best("metal", silent, dir_path);
|
||||
ggml_backend_load_best("rpc", silent, dir_path);
|
||||
ggml_backend_load_best("sycl", silent, dir_path);
|
||||
|
||||
@@ -574,6 +574,11 @@ void ggml_cuda_flash_attn_ext_vec_case_impl(ggml_backend_cuda_context & ctx, ggm
|
||||
const int nthreads = ggml_cuda_fattn_vec_get_nthreads_host(cc);
|
||||
const int nwarps = nthreads / WARP_SIZE;
|
||||
fattn_kernel_t fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, false>;
|
||||
if constexpr (cols_per_block == 1 && !use_logit_softcap) {
|
||||
if (dst->src[5]) {
|
||||
fattn_kernel = flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, false, true>;
|
||||
}
|
||||
}
|
||||
if constexpr (cols_per_block == 1 && (D == 64 || D == 128) && !use_logit_softcap) {
|
||||
if (ggml_flash_attn_ext_bias_is_indexed(dst)) {
|
||||
fattn_kernel = dst->src[5] ? flash_attn_ext_vec<D, cols_per_block, type_K, type_V, use_logit_softcap, true, true>
|
||||
@@ -594,6 +599,9 @@ void ggml_cuda_flash_attn_ext_vec_case(ggml_backend_cuda_context & ctx, ggml_ten
|
||||
float logit_softcap;
|
||||
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
|
||||
|
||||
// the kv_rows variant exists for one query per sequence without softcap
|
||||
GGML_ASSERT(!dst->src[5] || (Q->ne[1] == 1 && logit_softcap == 0.0f));
|
||||
|
||||
if (Q->ne[1] == 1) {
|
||||
constexpr int cols_per_block = 1;
|
||||
if (logit_softcap == 0.0f) {
|
||||
|
||||
@@ -765,10 +765,23 @@ static best_fattn_kernel ggml_cuda_get_best_fattn_kernel(const int device, const
|
||||
}
|
||||
}
|
||||
|
||||
// without a bias only the MMA kernel reads K/V through kv_rows
|
||||
// without a bias only the MMA and vec kernels read K/V through kv_rows
|
||||
if (kv_rows) {
|
||||
return GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask && Q->ne[0] != 40 && Q->ne[0] != 72 ?
|
||||
BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE;
|
||||
if (!(GGML_CUDA_CC_IS_NVIDIA(cc) && turing_mma_available(cc) && mask)) {
|
||||
return BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
float logit_softcap = 0.0f;
|
||||
memcpy(&logit_softcap, (const float *) KQV->op_params + 2, sizeof(float));
|
||||
|
||||
// the vec kernel reads quantized/bf16/f8 K/V in place, the MMA kernel would convert the whole cache to f16
|
||||
// only for K/V pairs with a compiled vec kernel, the f16 fallback of the vec kernel also converts the whole cache
|
||||
const bool vec_rows = n_kv % FATTN_KQ_STRIDE == 0 &&
|
||||
(K->type != GGML_TYPE_F16 || V->type != GGML_TYPE_F16) && K->type != GGML_TYPE_F32 && V->type != GGML_TYPE_F32 &&
|
||||
Q->ne[1] == 1 && logit_softcap == 0.0f && ggml_cuda_get_fattn_vec_case(Q->ne[0], K->type, V->type) != nullptr;
|
||||
if (vec_rows) {
|
||||
return BEST_FATTN_KERNEL_VEC;
|
||||
}
|
||||
return Q->ne[0] != 40 && Q->ne[0] != 72 ? BEST_FATTN_KERNEL_MMA_F16 : BEST_FATTN_KERNEL_NONE;
|
||||
}
|
||||
|
||||
// For small batch sizes the vector kernel may be preferable over the kernels optimized for large batch sizes:
|
||||
|
||||
@@ -33,6 +33,27 @@ static __device__ __forceinline__ float reduce_row_f32(const float * x, const in
|
||||
return sum;
|
||||
}
|
||||
|
||||
#define CUDA_REDUCE_ROWS_SHORT_NCOLS 8
|
||||
|
||||
template <bool norm>
|
||||
static __global__ void reduce_rows_f32_short(const float * x_ptr, float * dst_ptr, const int ncols, const int64_t nrows) {
|
||||
const int64_t row = (int64_t) blockIdx.x*blockDim.x + threadIdx.x;
|
||||
|
||||
ggml_cuda_pdl_sync();
|
||||
if (row >= nrows) {
|
||||
return;
|
||||
}
|
||||
|
||||
const float * GGML_CUDA_RESTRICT x = x_ptr + row*ncols;
|
||||
|
||||
float sum = 0.0f;
|
||||
for (int i = 0; i < ncols; ++i) {
|
||||
sum += x[i];
|
||||
}
|
||||
|
||||
dst_ptr[row] = norm ? sum / ncols : sum;
|
||||
}
|
||||
|
||||
// Row reduction kernel template - compute sum (norm=false) or mean (norm=true)
|
||||
template <bool norm>
|
||||
static __global__ void reduce_rows_f32(const float * x_ptr, float * dst_ptr, const int ncols) {
|
||||
|
||||
@@ -142,6 +142,64 @@ static __global__ void soft_max_f32(
|
||||
}
|
||||
}
|
||||
|
||||
#define CUDA_SOFT_MAX_SHORT_NCOLS 8
|
||||
|
||||
template <typename T>
|
||||
static __global__ void soft_max_f32_short(
|
||||
const float * x, const T * mask, const float * sinks, float * dst, const soft_max_params p,
|
||||
const uint3 ne01_fdv, const uint3 ne02_fdv, const uint3 ne12_fdv, const uint3 ne13_fdv) {
|
||||
const uint32_t rowx = blockIdx.x*blockDim.x + threadIdx.x;
|
||||
if (rowx >= p.nrows_x) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint32_t i012 = fastdiv(rowx, ne01_fdv);
|
||||
const uint32_t i01 = rowx - i012*ne01_fdv.z;
|
||||
const uint32_t i03 = fastdiv(i012, ne02_fdv);
|
||||
const uint32_t i02 = i012 - i03*ne02_fdv.z;
|
||||
|
||||
const uint32_t i12 = fastmodulo(i02, ne12_fdv);
|
||||
const uint32_t i13 = fastmodulo(i03, ne13_fdv);
|
||||
|
||||
const int ncols = p.ncols;
|
||||
|
||||
x += (int64_t) rowx*ncols;
|
||||
mask += (i01*p.nb11 + i12*p.nb12 + i13*p.nb13) / sizeof(T) * (mask != nullptr);
|
||||
dst += (int64_t) rowx*ncols;
|
||||
|
||||
const float slope = get_alibi_slope(p.max_bias, i02, p.n_head_log2, p.m0, p.m1);
|
||||
|
||||
float vals[CUDA_SOFT_MAX_SHORT_NCOLS];
|
||||
float max_val = sinks ? sinks[i02] : -INFINITY;
|
||||
|
||||
#pragma unroll
|
||||
for (int col = 0; col < CUDA_SOFT_MAX_SHORT_NCOLS; ++col) {
|
||||
if (col < ncols) {
|
||||
vals[col] = x[col]*p.scale + (mask ? slope*t2f32(mask[col]) : 0.0f);
|
||||
max_val = max(max_val, vals[col]);
|
||||
}
|
||||
}
|
||||
|
||||
float sum = sinks ? expf(sinks[i02] - max_val) : 0.0f;
|
||||
|
||||
#pragma unroll
|
||||
for (int col = 0; col < CUDA_SOFT_MAX_SHORT_NCOLS; ++col) {
|
||||
if (col < ncols) {
|
||||
vals[col] = expf(vals[col] - max_val);
|
||||
sum += vals[col];
|
||||
}
|
||||
}
|
||||
|
||||
const float inv_sum = 1.0f / sum;
|
||||
|
||||
#pragma unroll
|
||||
for (int col = 0; col < CUDA_SOFT_MAX_SHORT_NCOLS; ++col) {
|
||||
if (col < ncols) {
|
||||
dst[col] = vals[col]*inv_sum;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <int n_elem_per_thread = 0>
|
||||
static __device__ void soft_max_f32_parallelize_cols_single_row(const float * __restrict__ x,
|
||||
float * __restrict__ dst,
|
||||
@@ -392,6 +450,15 @@ static void soft_max_f32_cuda(const float * x,
|
||||
int nth = WARP_SIZE;
|
||||
const int64_t ncols_x = params.ncols;
|
||||
|
||||
if (ncols_x <= CUDA_SOFT_MAX_SHORT_NCOLS && params.nrows_x <= INT_MAX) {
|
||||
const uint3 ne01_fdv = init_fastdiv_values(params.ne01);
|
||||
const uint3 ne02_fdv = init_fastdiv_values(params.ne02);
|
||||
const uint3 ne12_fdv = init_fastdiv_values(params.ne12);
|
||||
const uint3 ne13_fdv = init_fastdiv_values(params.ne13);
|
||||
soft_max_f32_short<<<(params.nrows_x + 255) / 256, 256, 0, stream>>>(x, mask, sinks, dst, params, ne01_fdv, ne02_fdv, ne12_fdv, ne13_fdv);
|
||||
return;
|
||||
}
|
||||
|
||||
while (nth < ncols_x && nth < CUDA_SOFT_MAX_BLOCK_SIZE) nth *= 2;
|
||||
const dim3 block_dims(nth, 1, 1);
|
||||
const dim3 block_nums(params.ne01, params.ne02, params.ne03);
|
||||
|
||||
@@ -4,6 +4,13 @@
|
||||
void sum_rows_f32_cuda(const float * x, float * dst, const int ncols, const int nrows, cudaStream_t stream) {
|
||||
const int id = ggml_cuda_get_device();
|
||||
const int nsm = ggml_cuda_info().devices[id].nsm;
|
||||
if (ncols <= CUDA_REDUCE_ROWS_SHORT_NCOLS) {
|
||||
const dim3 block_dims(256, 1, 1);
|
||||
const dim3 block_nums((nrows + 255) / 256, 1, 1);
|
||||
const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(block_nums, block_dims, 0, stream);
|
||||
ggml_cuda_kernel_launch(reduce_rows_f32_short</*norm=*/false>, launch_params, x, dst, ncols, (int64_t) nrows);
|
||||
return;
|
||||
}
|
||||
const dim3 block_nums(nrows, 1, 1);
|
||||
if ((nrows / nsm) < 2) {
|
||||
const dim3 block_dims(512, 1, 1);
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
find_package(hrx CONFIG REQUIRED)
|
||||
find_package(loomc CONFIG REQUIRED)
|
||||
|
||||
set(GGML_HRX_KERNEL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/kernels")
|
||||
set(GGML_HRX_KERNELS_CPP "${CMAKE_CURRENT_BINARY_DIR}/ggml-hrx-kernels.cpp")
|
||||
|
||||
file(GLOB_RECURSE GGML_HRX_KERNEL_FILES CONFIGURE_DEPENDS "${GGML_HRX_KERNEL_DIR}/*.loom")
|
||||
|
||||
add_custom_command(
|
||||
OUTPUT "${GGML_HRX_KERNELS_CPP}"
|
||||
COMMAND "${CMAKE_COMMAND}"
|
||||
-DKERNEL_DIR=${GGML_HRX_KERNEL_DIR}
|
||||
-DOUTPUT=${GGML_HRX_KERNELS_CPP}
|
||||
-P "${CMAKE_CURRENT_SOURCE_DIR}/embed-kernels.cmake"
|
||||
DEPENDS ${GGML_HRX_KERNEL_FILES} "${CMAKE_CURRENT_SOURCE_DIR}/embed-kernels.cmake"
|
||||
COMMENT "Embedding HRX Loom kernels"
|
||||
VERBATIM
|
||||
)
|
||||
|
||||
file(GLOB GGML_HRX_SOURCES CONFIGURE_DEPENDS "*.cpp" "ops/*.cpp")
|
||||
file(GLOB GGML_HRX_HEADERS CONFIGURE_DEPENDS "*.h")
|
||||
|
||||
ggml_add_backend_library(ggml-hrx
|
||||
${GGML_HRX_HEADERS}
|
||||
${GGML_HRX_SOURCES}
|
||||
"${GGML_HRX_KERNELS_CPP}"
|
||||
../../include/ggml-hrx.h
|
||||
)
|
||||
|
||||
target_link_libraries(ggml-hrx PRIVATE hrx::hrx loomc::loomc)
|
||||
target_include_directories(ggml-hrx PRIVATE .)
|
||||
target_compile_features(ggml-hrx PRIVATE cxx_std_17)
|
||||
@@ -0,0 +1,27 @@
|
||||
# Usage: cmake -DKERNEL_DIR=<dir> -DOUTPUT=<file.cpp> -P embed-kernels.cmake
|
||||
|
||||
file(GLOB_RECURSE kernel_files RELATIVE "${KERNEL_DIR}" "${KERNEL_DIR}/*.loom")
|
||||
list(SORT kernel_files)
|
||||
|
||||
set(arrays "")
|
||||
set(table "")
|
||||
set(index 0)
|
||||
foreach(file IN LISTS kernel_files)
|
||||
file(READ "${KERNEL_DIR}/${file}" hex HEX)
|
||||
string(LENGTH "${hex}" hex_len)
|
||||
math(EXPR size "${hex_len} / 2")
|
||||
string(REGEX REPLACE "([0-9a-f][0-9a-f])" "0x\\1," bytes "${hex}")
|
||||
string(APPEND arrays "static const unsigned char ggml_hrx_kernel_${index}[] = { ${bytes}0x00 };\n")
|
||||
string(APPEND table " { \"${file}\", ggml_hrx_kernel_${index}, ${size} },\n")
|
||||
math(EXPR index "${index} + 1")
|
||||
endforeach()
|
||||
|
||||
set(content "// generated by embed-kernels.cmake, do not edit\n")
|
||||
string(APPEND content "#include \"ggml-hrx-common.h\"\n\n")
|
||||
string(APPEND content "${arrays}\n")
|
||||
string(APPEND content "const ggml_hrx_kernel_source ggml_hrx_kernel_sources[] = {\n${table} { nullptr, nullptr, 0 },\n};\n\n")
|
||||
string(APPEND content "const size_t ggml_hrx_kernel_source_count = ${index};\n")
|
||||
|
||||
file(WRITE "${OUTPUT}.tmp" "${content}")
|
||||
execute_process(COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${OUTPUT}.tmp" "${OUTPUT}")
|
||||
file(REMOVE "${OUTPUT}.tmp")
|
||||
@@ -0,0 +1,93 @@
|
||||
#include "ggml-hrx-arch.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
// The limits follow from the kernel layouts.
|
||||
static constexpr bool ggml_hrx_tune_valid(const ggml_hrx_tune & t) {
|
||||
for (int i = 0; i < GGML_TYPE_COUNT; ++i) {
|
||||
const ggml_hrx_mul_mat_vec_tune & mv = t.mul_mat_vec[i];
|
||||
if (mv.max_cols < 1 || mv.max_cols > 8 || mv.xs_max_k < 256 || mv.xs_max_k > 4096 || mv.xs_wg_per_cu < 1 ||
|
||||
mv.xs_depth < 1 || mv.xs_depth > 4) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const bool wg_size = t.elementwise_wg_size >= 64 && t.elementwise_wg_size <= 1024 && t.elementwise_wg_size % 64 == 0;
|
||||
const bool stream = t.stream_wg_per_cu >= 0 && t.stream_wg_per_cu <= 16;
|
||||
return wg_size && stream;
|
||||
}
|
||||
|
||||
// Tuned on gfx1151.
|
||||
static constexpr ggml_hrx_tune ggml_hrx_tune_rdna3_5 = [] {
|
||||
ggml_hrx_tune t = {};
|
||||
t.nodes_per_submit = 64;
|
||||
t.nodes_first_submit = 8;
|
||||
t.mapped_readback = false;
|
||||
for (int i = 0; i < GGML_TYPE_COUNT; ++i) {
|
||||
t.mul_mat_vec[i] = {
|
||||
/* .max_cols = */ 8,
|
||||
/* .xs_max_k = */ 4096,
|
||||
/* .xs_wg_per_cu = */ 4,
|
||||
/* .xs_depth = */ 2,
|
||||
};
|
||||
}
|
||||
t.elementwise_wg_size = 256;
|
||||
t.stream_wg_per_cu = 0;
|
||||
return t;
|
||||
}();
|
||||
|
||||
// Untuned. These families use the RDNA3.5 values.
|
||||
static constexpr ggml_hrx_tune ggml_hrx_tune_rdna3 = ggml_hrx_tune_rdna3_5;
|
||||
static constexpr ggml_hrx_tune ggml_hrx_tune_rdna4 = ggml_hrx_tune_rdna3_5;
|
||||
|
||||
// Tuned on gfx1201.
|
||||
static constexpr ggml_hrx_tune ggml_hrx_tune_gfx1201 = [] {
|
||||
ggml_hrx_tune t = ggml_hrx_tune_rdna4;
|
||||
t.nodes_per_submit = 256;
|
||||
// hrx_stream_copy_d2h over the host link is slow. A device copy to mapped host memory is faster.
|
||||
t.mapped_readback = true;
|
||||
for (int i = 0; i < GGML_TYPE_COUNT; ++i) {
|
||||
t.mul_mat_vec[i].xs_wg_per_cu = 2;
|
||||
}
|
||||
// A dispatch that fills all wave slots of the device costs approximately 30 us more on gfx1201.
|
||||
// 4 workgroups of 256 lanes for each CU use half of the slots.
|
||||
t.stream_wg_per_cu = 4;
|
||||
return t;
|
||||
}();
|
||||
|
||||
static constexpr uint32_t GGML_HRX_WG_32BIT = UINT32_MAX;
|
||||
// Architected workgroup ids pack y and z into one 32-bit register.
|
||||
static constexpr uint32_t GGML_HRX_WG_16BIT = 65536;
|
||||
|
||||
static constexpr ggml_hrx_arch ggml_hrx_archs[] = {
|
||||
// RDNA3. Untuned.
|
||||
{ "gfx1100", "gfx1100", true, GGML_HRX_MATRIX_OP_WMMA_GFX11, GGML_HRX_WG_32BIT, &ggml_hrx_tune_rdna3 },
|
||||
{ "gfx1101", "gfx1101", true, GGML_HRX_MATRIX_OP_WMMA_GFX11, GGML_HRX_WG_32BIT, &ggml_hrx_tune_rdna3 },
|
||||
{ "gfx1102", "gfx1102", true, GGML_HRX_MATRIX_OP_WMMA_GFX11, GGML_HRX_WG_32BIT, &ggml_hrx_tune_rdna3 },
|
||||
{ "gfx1103", "gfx1103", true, GGML_HRX_MATRIX_OP_WMMA_GFX11, GGML_HRX_WG_32BIT, &ggml_hrx_tune_rdna3 },
|
||||
// RDNA3.5. Only gfx1151 is tuned.
|
||||
{ "gfx1150", "gfx1150", true, GGML_HRX_MATRIX_OP_WMMA_GFX11, GGML_HRX_WG_32BIT, &ggml_hrx_tune_rdna3_5 },
|
||||
{ "gfx1151", "gfx1151", true, GGML_HRX_MATRIX_OP_WMMA_GFX11, GGML_HRX_WG_32BIT, &ggml_hrx_tune_rdna3_5 },
|
||||
{ "gfx1152", "gfx1152", true, GGML_HRX_MATRIX_OP_WMMA_GFX11, GGML_HRX_WG_32BIT, &ggml_hrx_tune_rdna3_5 },
|
||||
// RDNA4. Only gfx1201 is tuned.
|
||||
{ "gfx1200", "gfx1200", true, GGML_HRX_MATRIX_OP_WMMA_GFX12, GGML_HRX_WG_16BIT, &ggml_hrx_tune_rdna4 },
|
||||
{ "gfx1201", "gfx1201", true, GGML_HRX_MATRIX_OP_WMMA_GFX12, GGML_HRX_WG_16BIT, &ggml_hrx_tune_gfx1201 },
|
||||
};
|
||||
|
||||
static constexpr bool ggml_hrx_archs_valid() {
|
||||
for (const ggml_hrx_arch & arch : ggml_hrx_archs) {
|
||||
if (!ggml_hrx_tune_valid(*arch.tune)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
static_assert(ggml_hrx_archs_valid(), "ggml_hrx_tune value out of range");
|
||||
|
||||
const ggml_hrx_arch * ggml_hrx_arch_find(const char * name) {
|
||||
for (const ggml_hrx_arch & arch : ggml_hrx_archs) {
|
||||
if (std::strcmp(arch.name, name) == 0) {
|
||||
return &arch;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include "ggml.h"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
enum ggml_hrx_matrix_op {
|
||||
GGML_HRX_MATRIX_OP_NONE,
|
||||
GGML_HRX_MATRIX_OP_WMMA_GFX11,
|
||||
GGML_HRX_MATRIX_OP_WMMA_GFX12, // The operand layout is different from gfx11. The WMMA motifs have gfx12 providers.
|
||||
};
|
||||
|
||||
// ggml_mul_mat_vec_xs.
|
||||
struct ggml_hrx_mul_mat_vec_tune {
|
||||
int64_t max_cols; // At most 8. More input columns use the tiled kernels.
|
||||
int64_t xs_max_k; // At most 4096. The vec_xs kernel keeps 16 superblocks of activations in registers.
|
||||
int64_t xs_wg_per_cu;
|
||||
int64_t xs_depth; // At most 4. Pipeline depth of the vec_xs row passes.
|
||||
};
|
||||
|
||||
// Op dispatch values for one architecture.
|
||||
struct ggml_hrx_tune {
|
||||
int nodes_per_submit; // Nodes between stream flushes.
|
||||
int nodes_first_submit; // The interval starts here and doubles up to nodes_per_submit.
|
||||
// get_tensor_async copies through mapped host memory instead of hrx_stream_copy_d2h.
|
||||
bool mapped_readback;
|
||||
|
||||
// Index: the weight tensor type (src0).
|
||||
ggml_hrx_mul_mat_vec_tune mul_mat_vec[GGML_TYPE_COUNT];
|
||||
|
||||
int64_t elementwise_wg_size; // Multiple of 64, at most 1024.
|
||||
// At most 16. Workgroup limit for each CU of the grid-stride copy kernel. 0 disables this kernel.
|
||||
int64_t stream_wg_per_cu;
|
||||
};
|
||||
|
||||
struct ggml_hrx_arch {
|
||||
const char * name; // Architecture that the device reports.
|
||||
const char * loom_target; // Loom AMDGPU target of the kernels.
|
||||
bool wave32;
|
||||
ggml_hrx_matrix_op matrix_op;
|
||||
uint32_t max_workgroups_yz; // Workgroup count limit in y and z.
|
||||
const ggml_hrx_tune * tune;
|
||||
};
|
||||
|
||||
// Returns nullptr if the backend does not support the architecture.
|
||||
const ggml_hrx_arch * ggml_hrx_arch_find(const char * name);
|
||||
@@ -0,0 +1,135 @@
|
||||
#pragma once
|
||||
|
||||
#include "ggml-backend-impl.h"
|
||||
#include "ggml-impl.h"
|
||||
#include "ggml-hrx-arch.h"
|
||||
#include "hrx_runtime.h"
|
||||
#include "loom-jit.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// embed-kernels.cmake generates these sources.
|
||||
struct ggml_hrx_kernel_source {
|
||||
const char * path;
|
||||
const unsigned char * data;
|
||||
size_t size;
|
||||
};
|
||||
|
||||
extern const ggml_hrx_kernel_source ggml_hrx_kernel_sources[];
|
||||
extern const size_t ggml_hrx_kernel_source_count;
|
||||
|
||||
struct ggml_hrx_kernel {
|
||||
hrx_executable_t executable = nullptr;
|
||||
uint32_t export_ordinal = 0;
|
||||
hrx_executable_export_info_t export_info = {};
|
||||
ggml_hrx_loom_launch_program * launch = nullptr;
|
||||
size_t n_scalars = 0;
|
||||
size_t scalar_size = 0;
|
||||
|
||||
~ggml_hrx_kernel();
|
||||
};
|
||||
|
||||
struct ggml_hrx_kernel_desc {
|
||||
const char * file = nullptr; // Path relative to kernels/.
|
||||
const char * symbol = nullptr;
|
||||
std::vector<const char *> libs;
|
||||
std::vector<std::pair<std::string, std::string>> config;
|
||||
};
|
||||
|
||||
struct ggml_hrx_device_context {
|
||||
int index = 0;
|
||||
std::string name;
|
||||
std::string description;
|
||||
size_t memory_total = 0;
|
||||
uint32_t n_cu = 0;
|
||||
|
||||
const ggml_hrx_arch * arch = nullptr;
|
||||
const ggml_hrx_tune * tune = nullptr;
|
||||
|
||||
hrx_device_t device = nullptr;
|
||||
hrx_queue_t transfer_queue = nullptr;
|
||||
hrx_queue_t stream_queue = nullptr;
|
||||
|
||||
// Locks buffer fills, copies and uploads that run outside a backend stream.
|
||||
std::mutex buffer_mutex;
|
||||
hrx_stream_t buffer_stream = nullptr;
|
||||
// True until the host waits for buffer_stream. A flush is not enough: transfer_queue reads do not wait for buffer_stream.
|
||||
bool upload_pending = false;
|
||||
|
||||
ggml_backend_buffer_type buft = {};
|
||||
|
||||
std::mutex kernel_mutex;
|
||||
ggml_hrx_loom_jit * jit = nullptr;
|
||||
std::map<std::string, std::unique_ptr<ggml_hrx_kernel>> kernels;
|
||||
};
|
||||
|
||||
struct ggml_backend_hrx_context {
|
||||
ggml_hrx_device_context * device = nullptr;
|
||||
hrx_stream_t stream = nullptr;
|
||||
std::string name;
|
||||
uint64_t upload_wait = 0; // Last buffer_stream timeline value that this stream waits on.
|
||||
|
||||
// Mapped host memory for get_tensor_async. The stream copies into it. synchronize copies it to the caller memory.
|
||||
struct readback_copy {
|
||||
void * dst;
|
||||
size_t offset;
|
||||
size_t size;
|
||||
};
|
||||
hrx_buffer_t readback = nullptr;
|
||||
const uint8_t * readback_host = nullptr;
|
||||
size_t readback_size = 0;
|
||||
size_t readback_used = 0;
|
||||
bool readback_failed = false;
|
||||
std::vector<readback_copy> readback_copies;
|
||||
};
|
||||
|
||||
// Logs a failed status and returns false. It frees the status.
|
||||
bool ggml_hrx_check(hrx_status_t status, const char * expr, const char * file, int line);
|
||||
#define GGML_HRX_CHECK(expr) ggml_hrx_check((expr), #expr, __FILE__, __LINE__)
|
||||
|
||||
// Compiles each kernel one time for each device. Returns nullptr on failure.
|
||||
ggml_hrx_kernel * ggml_hrx_get_kernel(ggml_hrx_device_context * dev, const ggml_hrx_kernel_desc & desc);
|
||||
|
||||
// workload: the root kernel.def arguments. They set the launch config.
|
||||
// scalars: the launch() index arguments, in order. Each value must be >= 0.
|
||||
// buffers: the launch() buffer arguments, in order. Each binds the data range of its tensor, with the view offset.
|
||||
bool ggml_hrx_dispatch(ggml_backend_hrx_context * ctx,
|
||||
ggml_hrx_kernel * kernel,
|
||||
const std::vector<int64_t> & workload,
|
||||
const std::vector<int64_t> & scalars,
|
||||
const std::vector<const ggml_tensor *> & buffers);
|
||||
|
||||
inline bool ggml_hrx_elem_strides(const ggml_tensor * t, int64_t s[GGML_MAX_DIMS]) {
|
||||
const size_t ts = ggml_type_size(t->type);
|
||||
if (ggml_blck_size(t->type) != 1) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < GGML_MAX_DIMS; ++i) {
|
||||
if (t->nb[i] % ts != 0) {
|
||||
return false;
|
||||
}
|
||||
s[i] = (int64_t) (t->nb[i] / ts);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Config of the kernels that use @ggml.elementwise.wg_size.
|
||||
inline std::pair<std::string, std::string> ggml_hrx_elementwise_wg_config(const ggml_hrx_device_context * dev) {
|
||||
return { "ggml.elementwise.wg_size", std::to_string(dev->tune->elementwise_wg_size) };
|
||||
}
|
||||
|
||||
// Workgroups of a grid-stride kernel that moves n f32 values, 4 for each lane in one pass.
|
||||
// Returns 0 if the tune disables the grid-stride kernels.
|
||||
inline int64_t ggml_hrx_stream_groups(const ggml_hrx_device_context * dev, int64_t n) {
|
||||
const int64_t per_group = 4 * dev->tune->elementwise_wg_size;
|
||||
const int64_t limit = dev->tune->stream_wg_per_cu * dev->n_cu;
|
||||
return limit > 0 ? std::min((n + per_group - 1) / per_group, limit) : 0;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include "ggml-hrx-common.h"
|
||||
|
||||
// supports_X must return true only for nodes that op_X can run. op_X returns false on failure.
|
||||
|
||||
bool ggml_hrx_supports_cpy(const ggml_hrx_device_context * dev, const ggml_tensor * op); // CPY DUP CONT
|
||||
bool ggml_hrx_op_cpy(ggml_backend_hrx_context * ctx, const ggml_tensor * node);
|
||||
|
||||
bool ggml_hrx_supports_set_rows(const ggml_hrx_device_context * dev, const ggml_tensor * op);
|
||||
bool ggml_hrx_op_set_rows(ggml_backend_hrx_context * ctx, const ggml_tensor * node);
|
||||
|
||||
bool ggml_hrx_supports_mul_mat(const ggml_hrx_device_context * dev, const ggml_tensor * op);
|
||||
bool ggml_hrx_op_mul_mat(ggml_backend_hrx_context * ctx, const ggml_tensor * node);
|
||||
@@ -0,0 +1,962 @@
|
||||
#include "ggml-hrx.h"
|
||||
|
||||
#include "ggml-hrx-common.h"
|
||||
#include "ggml-hrx-ops.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cinttypes>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <optional>
|
||||
|
||||
static constexpr size_t GGML_HRX_ALIGNMENT = 256;
|
||||
|
||||
// Device memory has no host address. Tensor data pointers are offsets from this fake base. The Vulkan backend uses the same method.
|
||||
static uint8_t * const GGML_HRX_BASE = (uint8_t *) (uintptr_t) 0x1000;
|
||||
|
||||
bool ggml_hrx_check(hrx_status_t status, const char * expr, const char * file, int line) {
|
||||
if (hrx_status_is_ok(status)) {
|
||||
return true;
|
||||
}
|
||||
char * message = nullptr;
|
||||
size_t length = 0;
|
||||
hrx_status_t format_status = hrx_status_to_string(status, &message, &length);
|
||||
if (!hrx_status_is_ok(format_status)) {
|
||||
hrx_status_ignore(format_status);
|
||||
}
|
||||
GGML_LOG_ERROR("%s:%d: %s failed: %s\n", file, line, expr, message != nullptr ? message : "unknown HRX error");
|
||||
hrx_status_free_message(message);
|
||||
hrx_status_ignore(status);
|
||||
return false;
|
||||
}
|
||||
|
||||
struct ggml_hrx_buffer_context {
|
||||
ggml_hrx_device_context * dev = nullptr;
|
||||
hrx_buffer_t buffer = nullptr;
|
||||
};
|
||||
|
||||
static void * ggml_backend_hrx_buffer_get_base(ggml_backend_buffer_t buffer) {
|
||||
GGML_UNUSED(buffer);
|
||||
return GGML_HRX_BASE;
|
||||
}
|
||||
|
||||
static size_t ggml_hrx_tensor_offset(const ggml_tensor * t) {
|
||||
return (size_t) ((const uint8_t *) t->data - GGML_HRX_BASE);
|
||||
}
|
||||
|
||||
static ggml_backend_buffer_t ggml_hrx_tensor_buffer(const ggml_tensor * t) {
|
||||
return t->view_src != nullptr ? t->view_src->buffer : t->buffer;
|
||||
}
|
||||
|
||||
static bool ggml_hrx_tensor_on_device(const ggml_tensor * t) {
|
||||
ggml_backend_buffer_t buffer = ggml_hrx_tensor_buffer(t);
|
||||
return buffer != nullptr && buffer->iface.get_base == ggml_backend_hrx_buffer_get_base;
|
||||
}
|
||||
|
||||
// buffer_stream records uploads up to this size. They run before the next graph or read.
|
||||
static constexpr size_t GGML_HRX_MAX_RECORDED_UPLOAD = 1024 * 1024;
|
||||
// This is the HAL limit for one update_buffer command.
|
||||
static constexpr size_t GGML_HRX_UPDATE_CHUNK = 64 * 1024;
|
||||
|
||||
// Hold buffer_mutex when you call this function.
|
||||
static bool ggml_hrx_sync_buffer_stream(ggml_hrx_device_context * dev) {
|
||||
dev->upload_pending = false;
|
||||
return GGML_HRX_CHECK(hrx_stream_synchronize(dev->buffer_stream));
|
||||
}
|
||||
|
||||
static bool ggml_hrx_finish_uploads(ggml_hrx_device_context * dev) {
|
||||
std::lock_guard<std::mutex> lock(dev->buffer_mutex);
|
||||
return !dev->upload_pending || ggml_hrx_sync_buffer_stream(dev);
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_buffer_free_buffer(ggml_backend_buffer_t buffer) {
|
||||
auto * ctx = (ggml_hrx_buffer_context *) buffer->context;
|
||||
if (ctx->buffer != nullptr) {
|
||||
ggml_hrx_finish_uploads(ctx->dev);
|
||||
hrx_buffer_release(ctx->buffer);
|
||||
}
|
||||
delete ctx;
|
||||
}
|
||||
|
||||
struct ggml_hrx_fill_args {
|
||||
hrx_buffer_t buffer;
|
||||
size_t offset;
|
||||
size_t size;
|
||||
uint8_t value;
|
||||
};
|
||||
|
||||
static bool ggml_hrx_fill(ggml_hrx_device_context * dev, const ggml_hrx_fill_args & args) {
|
||||
std::lock_guard<std::mutex> lock(dev->buffer_mutex);
|
||||
if (!GGML_HRX_CHECK(hrx_stream_fill_buffer(dev->buffer_stream, args.buffer, args.offset, args.size, &args.value, sizeof(args.value)))) {
|
||||
return false;
|
||||
}
|
||||
return ggml_hrx_sync_buffer_stream(dev);
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_buffer_memset_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, uint8_t value,
|
||||
size_t offset, size_t size) {
|
||||
auto * ctx = (ggml_hrx_buffer_context *) buffer->context;
|
||||
const size_t dst = ggml_hrx_tensor_offset(tensor) + offset;
|
||||
GGML_ASSERT(dst <= buffer->size && size <= buffer->size - dst);
|
||||
if (!ggml_hrx_fill(ctx->dev, { ctx->buffer, dst, size, value })) {
|
||||
GGML_ABORT("%s: HRX buffer fill failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_buffer_set_tensor(ggml_backend_buffer_t buffer, ggml_tensor * tensor, const void * data,
|
||||
size_t offset, size_t size) {
|
||||
auto * ctx = (ggml_hrx_buffer_context *) buffer->context;
|
||||
const size_t dst = ggml_hrx_tensor_offset(tensor) + offset;
|
||||
GGML_ASSERT(dst <= buffer->size && size <= buffer->size - dst);
|
||||
ggml_hrx_device_context * dev = ctx->dev;
|
||||
if (size <= GGML_HRX_MAX_RECORDED_UPLOAD) {
|
||||
std::lock_guard<std::mutex> lock(dev->buffer_mutex);
|
||||
// The stream copies the data now. The caller can reuse it.
|
||||
for (size_t i = 0; i < size; i += GGML_HRX_UPDATE_CHUNK) {
|
||||
const size_t n = std::min(GGML_HRX_UPDATE_CHUNK, size - i);
|
||||
if (!GGML_HRX_CHECK(hrx_stream_update_buffer(dev->buffer_stream, (const uint8_t *) data + i, n, ctx->buffer, dst + i))) {
|
||||
GGML_ABORT("%s: HRX upload failed", __func__);
|
||||
}
|
||||
}
|
||||
dev->upload_pending = true;
|
||||
return;
|
||||
}
|
||||
if (!ggml_hrx_finish_uploads(dev) || !GGML_HRX_CHECK(hrx_synchronous_h2d(dev->transfer_queue, data, ctx->buffer, dst, size))) {
|
||||
GGML_ABORT("%s: HRX upload failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_buffer_get_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * tensor, void * data,
|
||||
size_t offset, size_t size) {
|
||||
auto * ctx = (ggml_hrx_buffer_context *) buffer->context;
|
||||
const size_t src = ggml_hrx_tensor_offset(tensor) + offset;
|
||||
GGML_ASSERT(src <= buffer->size && size <= buffer->size - src);
|
||||
if (!ggml_hrx_finish_uploads(ctx->dev) ||
|
||||
!GGML_HRX_CHECK(hrx_synchronous_d2h(ctx->dev->transfer_queue, ctx->buffer, src, data, size))) {
|
||||
GGML_ABORT("%s: HRX download failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
static bool ggml_backend_hrx_buffer_cpy_tensor(ggml_backend_buffer_t buffer, const ggml_tensor * src, ggml_tensor * dst) {
|
||||
if (!ggml_hrx_tensor_on_device(src)) {
|
||||
return false;
|
||||
}
|
||||
auto * src_ctx = (ggml_hrx_buffer_context *) ggml_hrx_tensor_buffer(src)->context;
|
||||
auto * dst_ctx = (ggml_hrx_buffer_context *) buffer->context;
|
||||
if (src_ctx->dev != dst_ctx->dev) {
|
||||
return false;
|
||||
}
|
||||
const size_t size = ggml_nbytes(src);
|
||||
if (size == 0) {
|
||||
return true;
|
||||
}
|
||||
ggml_hrx_device_context * dev = dst_ctx->dev;
|
||||
std::lock_guard<std::mutex> lock(dev->buffer_mutex);
|
||||
if (!GGML_HRX_CHECK(hrx_stream_copy_buffer(dev->buffer_stream, src_ctx->buffer, ggml_hrx_tensor_offset(src),
|
||||
dst_ctx->buffer, ggml_hrx_tensor_offset(dst), size))) {
|
||||
return false;
|
||||
}
|
||||
return ggml_hrx_sync_buffer_stream(dev);
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_buffer_clear(ggml_backend_buffer_t buffer, uint8_t value) {
|
||||
auto * ctx = (ggml_hrx_buffer_context *) buffer->context;
|
||||
if (ctx->buffer == nullptr) {
|
||||
return;
|
||||
}
|
||||
if (!ggml_hrx_fill(ctx->dev, { ctx->buffer, 0, buffer->size, value })) {
|
||||
GGML_ABORT("%s: HRX buffer clear failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
static const ggml_backend_buffer_i ggml_backend_hrx_buffer_interface = {
|
||||
/* .free_buffer = */ ggml_backend_hrx_buffer_free_buffer,
|
||||
/* .get_base = */ ggml_backend_hrx_buffer_get_base,
|
||||
/* .init_tensor = */ nullptr,
|
||||
/* .memset_tensor = */ ggml_backend_hrx_buffer_memset_tensor,
|
||||
/* .set_tensor = */ ggml_backend_hrx_buffer_set_tensor,
|
||||
/* .get_tensor = */ ggml_backend_hrx_buffer_get_tensor,
|
||||
/* .set_tensor_2d = */ nullptr,
|
||||
/* .get_tensor_2d = */ nullptr,
|
||||
/* .cpy_tensor = */ ggml_backend_hrx_buffer_cpy_tensor,
|
||||
/* .clear = */ ggml_backend_hrx_buffer_clear,
|
||||
/* .reset = */ nullptr,
|
||||
/* .set_tensor_n = */ nullptr,
|
||||
/* .get_tensor_n = */ nullptr,
|
||||
/* .cpy_tensor_n = */ nullptr,
|
||||
};
|
||||
|
||||
static const char * ggml_backend_hrx_buffer_type_get_name(ggml_backend_buffer_type_t buft) {
|
||||
return ((ggml_hrx_device_context *) buft->context)->name.c_str();
|
||||
}
|
||||
|
||||
static ggml_backend_buffer_t ggml_backend_hrx_buffer_type_alloc_buffer(ggml_backend_buffer_type_t buft, size_t size) {
|
||||
auto * dev = (ggml_hrx_device_context *) buft->context;
|
||||
|
||||
hrx_buffer_t allocation = nullptr;
|
||||
if (size > 0) {
|
||||
const hrx_buffer_params_t params = {
|
||||
HRX_MEMORY_TYPE_DEVICE_LOCAL,
|
||||
HRX_MEMORY_ACCESS_ALL,
|
||||
HRX_BUFFER_USAGE_DEFAULT,
|
||||
};
|
||||
if (!GGML_HRX_CHECK(hrx_allocator_allocate_buffer(hrx_device_allocator(dev->device), params, size, &allocation))) {
|
||||
GGML_LOG_ERROR("%s: failed to allocate %.2f MiB on %s\n", __func__, size / 1024.0 / 1024.0, dev->name.c_str());
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
auto * ctx = new ggml_hrx_buffer_context;
|
||||
ctx->dev = dev;
|
||||
ctx->buffer = allocation;
|
||||
return ggml_backend_buffer_init(buft, ggml_backend_hrx_buffer_interface, ctx, size);
|
||||
}
|
||||
|
||||
static size_t ggml_backend_hrx_buffer_type_get_alignment(ggml_backend_buffer_type_t buft) {
|
||||
GGML_UNUSED(buft);
|
||||
return GGML_HRX_ALIGNMENT;
|
||||
}
|
||||
|
||||
static size_t ggml_backend_hrx_buffer_type_get_max_size(ggml_backend_buffer_type_t buft) {
|
||||
return ((ggml_hrx_device_context *) buft->context)->memory_total;
|
||||
}
|
||||
|
||||
static const ggml_backend_buffer_type_i ggml_backend_hrx_buffer_type_interface = {
|
||||
/* .get_name = */ ggml_backend_hrx_buffer_type_get_name,
|
||||
/* .alloc_buffer = */ ggml_backend_hrx_buffer_type_alloc_buffer,
|
||||
/* .alloc_buffer_n = */ nullptr,
|
||||
/* .get_alignment = */ ggml_backend_hrx_buffer_type_get_alignment,
|
||||
/* .get_max_size = */ ggml_backend_hrx_buffer_type_get_max_size,
|
||||
/* .get_alloc_size = */ nullptr,
|
||||
/* .get_alloc_size_n = */ nullptr,
|
||||
/* .is_host = */ nullptr,
|
||||
};
|
||||
|
||||
ggml_hrx_kernel::~ggml_hrx_kernel() {
|
||||
ggml_hrx_loom_launch_program_free(launch);
|
||||
if (executable != nullptr) {
|
||||
hrx_executable_release(executable);
|
||||
}
|
||||
}
|
||||
|
||||
static const ggml_hrx_kernel_source * ggml_hrx_find_source(const char * path) {
|
||||
for (size_t i = 0; i < ggml_hrx_kernel_source_count; ++i) {
|
||||
if (std::strcmp(ggml_hrx_kernel_sources[i].path, path) == 0) {
|
||||
return &ggml_hrx_kernel_sources[i];
|
||||
}
|
||||
}
|
||||
GGML_LOG_ERROR("%s: kernel source %s is not embedded\n", __func__, path);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static std::unique_ptr<ggml_hrx_kernel> ggml_hrx_build_kernel(ggml_hrx_device_context * dev, const ggml_hrx_kernel_desc & desc) {
|
||||
if (dev->jit == nullptr && !GGML_HRX_CHECK(ggml_hrx_loom_jit_create(dev->arch->name, dev->arch->loom_target, &dev->jit))) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const ggml_hrx_kernel_source * source = ggml_hrx_find_source(desc.file);
|
||||
if (source == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
std::vector<ggml_hrx_loom_source> deps;
|
||||
for (const char * lib : desc.libs) {
|
||||
const ggml_hrx_kernel_source * dep = ggml_hrx_find_source(lib);
|
||||
if (dep == nullptr) {
|
||||
return nullptr;
|
||||
}
|
||||
deps.push_back({ dep->data, dep->size, dep->path });
|
||||
}
|
||||
std::vector<ggml_hrx_loom_config_binding> config;
|
||||
for (const auto & kv : desc.config) {
|
||||
config.push_back({ kv.first.c_str(), kv.second.c_str() });
|
||||
}
|
||||
|
||||
ggml_hrx_loom_compile_options options;
|
||||
options.source = { source->data, source->size, source->path };
|
||||
options.deps = deps.data();
|
||||
options.n_deps = deps.size();
|
||||
options.config = config.data();
|
||||
options.n_config = config.size();
|
||||
options.symbol = desc.symbol;
|
||||
|
||||
ggml_hrx_loom_compile_result compiled;
|
||||
if (!GGML_HRX_CHECK(ggml_hrx_loom_compile(dev->jit, &options, &compiled))) {
|
||||
GGML_LOG_ERROR("%s: failed to compile %s from %s\n", __func__, desc.symbol, desc.file);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto kernel = std::make_unique<ggml_hrx_kernel>();
|
||||
kernel->launch = compiled.launch;
|
||||
if (!GGML_HRX_CHECK(hrx_executable_load_data(dev->device, compiled.hsaco.data(), compiled.hsaco.size(), "amdgpu",
|
||||
dev->arch->name, &kernel->executable)) ||
|
||||
!GGML_HRX_CHECK(hrx_executable_lookup_export_by_name(kernel->executable, desc.symbol, &kernel->export_ordinal)) ||
|
||||
!GGML_HRX_CHECK(hrx_executable_export_info(kernel->executable, kernel->export_ordinal, &kernel->export_info))) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const hrx_executable_export_info_t & info = kernel->export_info;
|
||||
if (info.parameter_count < info.binding_count) {
|
||||
GGML_LOG_ERROR("%s: %s has an invalid parameter count\n", __func__, desc.symbol);
|
||||
return nullptr;
|
||||
}
|
||||
kernel->n_scalars = info.parameter_count - info.binding_count;
|
||||
if (kernel->n_scalars == 0) {
|
||||
if (info.constant_byte_length != 0) {
|
||||
GGML_LOG_ERROR("%s: %s has constants but no scalar parameters\n", __func__, desc.symbol);
|
||||
return nullptr;
|
||||
}
|
||||
} else {
|
||||
kernel->scalar_size = info.constant_byte_length / kernel->n_scalars;
|
||||
if (info.constant_byte_length % kernel->n_scalars != 0 || (kernel->scalar_size != 4 && kernel->scalar_size != 8)) {
|
||||
GGML_LOG_ERROR("%s: %s has an unsupported scalar ABI\n", __func__, desc.symbol);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
return kernel;
|
||||
}
|
||||
|
||||
ggml_hrx_kernel * ggml_hrx_get_kernel(ggml_hrx_device_context * dev, const ggml_hrx_kernel_desc & desc) {
|
||||
std::string key = std::string(desc.file) + "|" + desc.symbol;
|
||||
for (const auto & kv : desc.config) {
|
||||
key += "|" + kv.first + "=" + kv.second;
|
||||
}
|
||||
|
||||
std::lock_guard<std::mutex> lock(dev->kernel_mutex);
|
||||
auto it = dev->kernels.find(key);
|
||||
if (it != dev->kernels.end()) {
|
||||
return it->second.get();
|
||||
}
|
||||
// Cache a failed build as nullptr. This prevents a retry for each node.
|
||||
auto & slot = dev->kernels[key];
|
||||
slot = ggml_hrx_build_kernel(dev, desc);
|
||||
return slot.get();
|
||||
}
|
||||
|
||||
bool ggml_hrx_dispatch(ggml_backend_hrx_context * ctx, ggml_hrx_kernel * kernel, const std::vector<int64_t> & workload,
|
||||
const std::vector<int64_t> & scalars, const std::vector<const ggml_tensor *> & buffers) {
|
||||
if (kernel == nullptr) {
|
||||
return false;
|
||||
}
|
||||
if (scalars.size() != kernel->n_scalars || buffers.size() != kernel->export_info.binding_count) {
|
||||
GGML_LOG_ERROR("%s: argument count mismatch: %zu scalars, %zu buffers\n", __func__, scalars.size(), buffers.size());
|
||||
return false;
|
||||
}
|
||||
|
||||
ggml_hrx_loom_launch_config launch;
|
||||
if (!GGML_HRX_CHECK(ggml_hrx_loom_launch_program_eval(kernel->launch, workload.data(), workload.size(), &launch))) {
|
||||
return false;
|
||||
}
|
||||
const uint32_t max_yz = ctx->device->arch->max_workgroups_yz;
|
||||
if (launch.workgroup_count[1] > max_yz || launch.workgroup_count[2] > max_yz) {
|
||||
GGML_LOG_ERROR("%s: workgroup count y or z is above %u\n", __func__, max_yz);
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<uint8_t> constants(kernel->n_scalars * kernel->scalar_size);
|
||||
for (size_t i = 0; i < scalars.size(); ++i) {
|
||||
const int64_t value = scalars[i];
|
||||
if (value < 0 || (kernel->scalar_size == 4 && (uint64_t) value > std::numeric_limits<uint32_t>::max())) {
|
||||
GGML_LOG_ERROR("%s: launch scalar %zu out of range: %" PRId64 "\n", __func__, i, value);
|
||||
return false;
|
||||
}
|
||||
if (kernel->scalar_size == 4) {
|
||||
const uint32_t v = (uint32_t) value;
|
||||
std::memcpy(constants.data() + i * 4, &v, 4);
|
||||
} else {
|
||||
const uint64_t v = (uint64_t) value;
|
||||
std::memcpy(constants.data() + i * 8, &v, 8);
|
||||
}
|
||||
}
|
||||
|
||||
std::vector<hrx_buffer_ref_t> refs;
|
||||
refs.reserve(buffers.size());
|
||||
for (const ggml_tensor * t : buffers) {
|
||||
if (t == nullptr || !ggml_hrx_tensor_on_device(t)) {
|
||||
GGML_LOG_ERROR("%s: tensor %s is not in an HRX buffer\n", __func__, t != nullptr ? t->name : "(null)");
|
||||
return false;
|
||||
}
|
||||
auto * bctx = (ggml_hrx_buffer_context *) ggml_hrx_tensor_buffer(t)->context;
|
||||
refs.push_back({ bctx->buffer, ggml_hrx_tensor_offset(t), ggml_nbytes(t) });
|
||||
}
|
||||
|
||||
const hrx_dispatch_config_t config = {
|
||||
{ launch.workgroup_count[0], launch.workgroup_count[1], launch.workgroup_count[2] },
|
||||
{ launch.workgroup_size[0], launch.workgroup_size[1], launch.workgroup_size[2] },
|
||||
launch.subgroup_size,
|
||||
};
|
||||
return GGML_HRX_CHECK(hrx_stream_dispatch(ctx->stream, kernel->executable, kernel->export_ordinal, &config,
|
||||
constants.data(), constants.size(), refs.data(), refs.size(), 0));
|
||||
}
|
||||
|
||||
static ggml_guid_t ggml_backend_hrx_guid() {
|
||||
static ggml_guid guid = { 0xd2, 0x3d, 0x72, 0x83, 0xb2, 0x82, 0x4d, 0xe0, 0x8a, 0x3e, 0x21, 0x1d, 0x68, 0x87, 0x2f, 0x4b };
|
||||
return &guid;
|
||||
}
|
||||
|
||||
static const char * ggml_backend_hrx_get_name(ggml_backend_t backend) {
|
||||
return ((ggml_backend_hrx_context *) backend->context)->name.c_str();
|
||||
}
|
||||
|
||||
static void ggml_hrx_readback_release(ggml_backend_hrx_context * ctx) {
|
||||
if (ctx->readback != nullptr) {
|
||||
GGML_HRX_CHECK(hrx_buffer_unmap(ctx->readback));
|
||||
hrx_buffer_release(ctx->readback);
|
||||
}
|
||||
ctx->readback = nullptr;
|
||||
ctx->readback_host = nullptr;
|
||||
ctx->readback_size = 0;
|
||||
}
|
||||
|
||||
// Returns false if the readback buffer cannot take size more bytes now.
|
||||
static bool ggml_hrx_readback_reserve(ggml_backend_hrx_context * ctx, size_t size) {
|
||||
if (ctx->readback_used + size <= ctx->readback_size) {
|
||||
return true;
|
||||
}
|
||||
// Pending copies use the current buffer.
|
||||
if (ctx->readback_failed || !ctx->readback_copies.empty()) {
|
||||
return false;
|
||||
}
|
||||
size = std::max(size, 2 * ctx->readback_size);
|
||||
ggml_hrx_readback_release(ctx);
|
||||
const hrx_buffer_params_t params = {
|
||||
HRX_MEMORY_TYPE_HOST_LOCAL | HRX_MEMORY_TYPE_HOST_COHERENT,
|
||||
HRX_MEMORY_ACCESS_ALL,
|
||||
HRX_BUFFER_USAGE_DEFAULT | HRX_BUFFER_USAGE_MAPPING_PERSISTENT,
|
||||
};
|
||||
void * host = nullptr;
|
||||
if (!GGML_HRX_CHECK(hrx_allocator_allocate_buffer(hrx_device_allocator(ctx->device->device), params, size, &ctx->readback)) ||
|
||||
!GGML_HRX_CHECK(hrx_buffer_map(ctx->readback, HRX_MAP_READ, 0, size, &host))) {
|
||||
if (ctx->readback != nullptr) {
|
||||
hrx_buffer_release(ctx->readback);
|
||||
ctx->readback = nullptr;
|
||||
}
|
||||
ctx->readback_failed = true;
|
||||
return false;
|
||||
}
|
||||
ctx->readback_host = (const uint8_t *) host;
|
||||
ctx->readback_size = size;
|
||||
return true;
|
||||
}
|
||||
|
||||
static void ggml_hrx_stream_finish(ggml_backend_hrx_context * ctx) {
|
||||
if (!GGML_HRX_CHECK(hrx_stream_synchronize(ctx->stream))) {
|
||||
GGML_ABORT("%s: HRX synchronize failed", __func__);
|
||||
}
|
||||
for (const auto & c : ctx->readback_copies) {
|
||||
std::memcpy(c.dst, ctx->readback_host + c.offset, c.size);
|
||||
}
|
||||
ctx->readback_copies.clear();
|
||||
ctx->readback_used = 0;
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_free(ggml_backend_t backend) {
|
||||
auto * ctx = (ggml_backend_hrx_context *) backend->context;
|
||||
GGML_HRX_CHECK(hrx_stream_synchronize(ctx->stream));
|
||||
hrx_stream_release(ctx->stream);
|
||||
ggml_hrx_readback_release(ctx);
|
||||
delete ctx;
|
||||
delete backend;
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_synchronize(ggml_backend_t backend) {
|
||||
ggml_hrx_stream_finish((ggml_backend_hrx_context *) backend->context);
|
||||
}
|
||||
|
||||
// Make the backend stream wait for the uploads recorded in buffer_stream.
|
||||
static bool ggml_hrx_wait_uploads(ggml_backend_hrx_context * ctx) {
|
||||
ggml_hrx_device_context * dev = ctx->device;
|
||||
hrx_timeline_point_t point;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(dev->buffer_mutex);
|
||||
if (dev->upload_pending && !GGML_HRX_CHECK(hrx_stream_flush(dev->buffer_stream))) {
|
||||
return false;
|
||||
}
|
||||
if (!GGML_HRX_CHECK(hrx_stream_get_timeline_position(dev->buffer_stream, &point))) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (point.value <= ctx->upload_wait) {
|
||||
return true;
|
||||
}
|
||||
ctx->upload_wait = point.value;
|
||||
return GGML_HRX_CHECK(hrx_stream_wait_on(ctx->stream, point));
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_set_tensor_async(ggml_backend_t backend, ggml_tensor * tensor, const void * data,
|
||||
size_t offset, size_t size) {
|
||||
auto * ctx = (ggml_backend_hrx_context *) backend->context;
|
||||
if (size == 0) {
|
||||
return;
|
||||
}
|
||||
GGML_ASSERT(ggml_hrx_tensor_on_device(tensor));
|
||||
auto * bctx = (ggml_hrx_buffer_context *) ggml_hrx_tensor_buffer(tensor)->context;
|
||||
const size_t dst = ggml_hrx_tensor_offset(tensor) + offset;
|
||||
const bool ok = ggml_hrx_wait_uploads(ctx) &&
|
||||
(size <= GGML_HRX_UPDATE_CHUNK ?
|
||||
GGML_HRX_CHECK(hrx_stream_update_buffer(ctx->stream, data, size, bctx->buffer, dst)) :
|
||||
GGML_HRX_CHECK(hrx_stream_copy_h2d(ctx->stream, data, bctx->buffer, dst, size)));
|
||||
if (!ok) {
|
||||
GGML_ABORT("%s: HRX upload failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_get_tensor_async(ggml_backend_t backend, const ggml_tensor * tensor, void * data,
|
||||
size_t offset, size_t size) {
|
||||
auto * ctx = (ggml_backend_hrx_context *) backend->context;
|
||||
if (size == 0) {
|
||||
return;
|
||||
}
|
||||
GGML_ASSERT(ggml_hrx_tensor_on_device(tensor));
|
||||
auto * bctx = (ggml_hrx_buffer_context *) ggml_hrx_tensor_buffer(tensor)->context;
|
||||
const size_t src = ggml_hrx_tensor_offset(tensor) + offset;
|
||||
if (!ggml_hrx_wait_uploads(ctx)) {
|
||||
GGML_ABORT("%s: HRX download failed", __func__);
|
||||
}
|
||||
if (ctx->device->tune->mapped_readback && ggml_hrx_readback_reserve(ctx, size)) {
|
||||
const size_t dst = ctx->readback_used;
|
||||
if (!GGML_HRX_CHECK(hrx_stream_copy_buffer(ctx->stream, bctx->buffer, src, ctx->readback, dst, size))) {
|
||||
GGML_ABORT("%s: HRX download failed", __func__);
|
||||
}
|
||||
ctx->readback_copies.push_back({ data, dst, size });
|
||||
ctx->readback_used = dst + GGML_PAD(size, GGML_HRX_ALIGNMENT);
|
||||
return;
|
||||
}
|
||||
if (!GGML_HRX_CHECK(hrx_stream_copy_d2h(ctx->stream, bctx->buffer, src, data, size))) {
|
||||
GGML_ABORT("%s: HRX download failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_event_record(ggml_backend_t backend, ggml_backend_event_t event) {
|
||||
auto * ctx = (ggml_backend_hrx_context *) backend->context;
|
||||
// The host copies of earlier get_tensor_async calls must be done when the event completes.
|
||||
if (!ctx->readback_copies.empty()) {
|
||||
ggml_hrx_stream_finish(ctx);
|
||||
}
|
||||
if (!GGML_HRX_CHECK(hrx_event_record((hrx_event_t) event->context, ctx->stream))) {
|
||||
GGML_ABORT("%s: HRX event record failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_event_wait(ggml_backend_t backend, ggml_backend_event_t event) {
|
||||
auto * ctx = (ggml_backend_hrx_context *) backend->context;
|
||||
if (!GGML_HRX_CHECK(hrx_stream_wait_event(ctx->stream, (hrx_event_t) event->context))) {
|
||||
GGML_ABORT("%s: HRX event wait failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
// llama.cpp runs FILL in place on recurrent state in device buffers. The CPU cannot run it there.
|
||||
static bool ggml_hrx_supports_fill(const ggml_tensor * op) {
|
||||
return (op->type == GGML_TYPE_F32 || op->type == GGML_TYPE_F16) && ggml_is_contiguous(op);
|
||||
}
|
||||
|
||||
static bool ggml_hrx_op_fill(ggml_backend_hrx_context * ctx, const ggml_tensor * node) {
|
||||
const size_t size = ggml_nbytes(node);
|
||||
if (size == 0) {
|
||||
return true;
|
||||
}
|
||||
const float c = ggml_get_op_params_f32(node, 0);
|
||||
uint32_t pattern;
|
||||
size_t pattern_size;
|
||||
if (node->type == GGML_TYPE_F32) {
|
||||
std::memcpy(&pattern, &c, sizeof(c));
|
||||
pattern_size = sizeof(float);
|
||||
} else {
|
||||
pattern = ggml_fp32_to_fp16(c);
|
||||
pattern_size = sizeof(ggml_fp16_t);
|
||||
}
|
||||
auto * bctx = (ggml_hrx_buffer_context *) ggml_hrx_tensor_buffer(node)->context;
|
||||
return GGML_HRX_CHECK(
|
||||
hrx_stream_fill_buffer(ctx->stream, bctx->buffer, ggml_hrx_tensor_offset(node), size, &pattern, pattern_size));
|
||||
}
|
||||
|
||||
static bool ggml_hrx_compute_node(ggml_backend_hrx_context * ctx, const ggml_tensor * node) {
|
||||
switch (node->op) {
|
||||
case GGML_OP_FILL: return ggml_hrx_op_fill(ctx, node);
|
||||
case GGML_OP_CPY:
|
||||
case GGML_OP_DUP:
|
||||
case GGML_OP_CONT: return ggml_hrx_op_cpy(ctx, node);
|
||||
case GGML_OP_SET_ROWS: return ggml_hrx_op_set_rows(ctx, node);
|
||||
case GGML_OP_MUL_MAT: return ggml_hrx_op_mul_mat(ctx, node);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
static enum ggml_status ggml_backend_hrx_graph_compute(ggml_backend_t backend, ggml_cgraph * cgraph) {
|
||||
auto * ctx = (ggml_backend_hrx_context *) backend->context;
|
||||
const ggml_hrx_tune * tune = ctx->device->tune;
|
||||
int n_pending = 0;
|
||||
// The GPU starts work while the host records the next nodes. A short first interval starts a small graph sooner.
|
||||
int n_submit = tune->nodes_first_submit;
|
||||
|
||||
if (!ggml_hrx_wait_uploads(ctx)) {
|
||||
return GGML_STATUS_FAILED;
|
||||
}
|
||||
|
||||
for (int i = 0; i < cgraph->n_nodes; i++) {
|
||||
const ggml_tensor * node = cgraph->nodes[i];
|
||||
if (ggml_is_empty(node) || ggml_op_is_empty(node->op) || (node->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
|
||||
continue;
|
||||
}
|
||||
if (!ggml_hrx_compute_node(ctx, node)) {
|
||||
GGML_LOG_ERROR("%s: failed to run node %d (%s, %s)\n", __func__, i, ggml_op_desc(node), node->name);
|
||||
return GGML_STATUS_FAILED;
|
||||
}
|
||||
if (++n_pending >= n_submit) {
|
||||
n_pending = 0;
|
||||
n_submit = std::min(2 * n_submit, tune->nodes_per_submit);
|
||||
if (!GGML_HRX_CHECK(hrx_stream_flush(ctx->stream))) {
|
||||
return GGML_STATUS_FAILED;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// synchronize waits for the graph.
|
||||
if (!GGML_HRX_CHECK(hrx_stream_flush(ctx->stream))) {
|
||||
return GGML_STATUS_FAILED;
|
||||
}
|
||||
return GGML_STATUS_SUCCESS;
|
||||
}
|
||||
|
||||
static const ggml_backend_i ggml_backend_hrx_interface = {
|
||||
/* .get_name = */ ggml_backend_hrx_get_name,
|
||||
/* .free = */ ggml_backend_hrx_free,
|
||||
/* .set_tensor_async = */ ggml_backend_hrx_set_tensor_async,
|
||||
/* .get_tensor_async = */ ggml_backend_hrx_get_tensor_async,
|
||||
/* .set_tensor_2d_async = */ nullptr,
|
||||
/* .get_tensor_2d_async = */ nullptr,
|
||||
/* .cpy_tensor_async = */ nullptr,
|
||||
/* .synchronize = */ ggml_backend_hrx_synchronize,
|
||||
/* .graph_plan_create = */ nullptr,
|
||||
/* .graph_plan_free = */ nullptr,
|
||||
/* .graph_plan_update = */ nullptr,
|
||||
/* .graph_plan_compute = */ nullptr,
|
||||
/* .graph_compute = */ ggml_backend_hrx_graph_compute,
|
||||
/* .event_record = */ ggml_backend_hrx_event_record,
|
||||
/* .event_wait = */ ggml_backend_hrx_event_wait,
|
||||
/* .graph_optimize = */ nullptr,
|
||||
};
|
||||
|
||||
static ggml_hrx_device_context * ggml_hrx_dev_ctx(ggml_backend_dev_t dev) {
|
||||
return (ggml_hrx_device_context *) dev->context;
|
||||
}
|
||||
|
||||
static const char * ggml_backend_hrx_device_get_name(ggml_backend_dev_t dev) {
|
||||
return ggml_hrx_dev_ctx(dev)->name.c_str();
|
||||
}
|
||||
|
||||
static const char * ggml_backend_hrx_device_get_description(ggml_backend_dev_t dev) {
|
||||
return ggml_hrx_dev_ctx(dev)->description.c_str();
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_device_get_memory(ggml_backend_dev_t dev, size_t * free, size_t * total) {
|
||||
// HRX does not report free memory yet.
|
||||
*free = ggml_hrx_dev_ctx(dev)->memory_total;
|
||||
*total = ggml_hrx_dev_ctx(dev)->memory_total;
|
||||
}
|
||||
|
||||
static enum ggml_backend_dev_type ggml_backend_hrx_device_get_type(ggml_backend_dev_t dev) {
|
||||
GGML_UNUSED(dev);
|
||||
return GGML_BACKEND_DEVICE_TYPE_GPU;
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_device_get_props(ggml_backend_dev_t dev, ggml_backend_dev_props * props) {
|
||||
props->name = ggml_backend_hrx_device_get_name(dev);
|
||||
props->description = ggml_backend_hrx_device_get_description(dev);
|
||||
props->type = ggml_backend_hrx_device_get_type(dev);
|
||||
props->device_id = nullptr;
|
||||
ggml_backend_hrx_device_get_memory(dev, &props->memory_free, &props->memory_total);
|
||||
props->caps = {
|
||||
/* .async = */ true,
|
||||
/* .host_buffer = */ false,
|
||||
/* .buffer_from_host_ptr = */ false,
|
||||
/* .events = */ true,
|
||||
/* .mmap_support = */ true,
|
||||
/* .fast_async_host_input = */ false,
|
||||
};
|
||||
}
|
||||
|
||||
static ggml_backend_t ggml_backend_hrx_device_init_backend(ggml_backend_dev_t dev, const char * params) {
|
||||
GGML_UNUSED(params);
|
||||
ggml_hrx_device_context * dev_ctx = ggml_hrx_dev_ctx(dev);
|
||||
|
||||
hrx_stream_t stream = nullptr;
|
||||
if (!GGML_HRX_CHECK(hrx_stream_create(dev_ctx->stream_queue, 0, &stream))) {
|
||||
return nullptr;
|
||||
}
|
||||
auto * ctx = new ggml_backend_hrx_context;
|
||||
ctx->device = dev_ctx;
|
||||
ctx->stream = stream;
|
||||
ctx->name = dev_ctx->name;
|
||||
return new ggml_backend{ ggml_backend_hrx_guid(), ggml_backend_hrx_interface, dev, ctx };
|
||||
}
|
||||
|
||||
static ggml_backend_buffer_type_t ggml_backend_hrx_device_get_buffer_type(ggml_backend_dev_t dev) {
|
||||
return &ggml_hrx_dev_ctx(dev)->buft;
|
||||
}
|
||||
|
||||
static bool ggml_backend_hrx_device_supports_op(ggml_backend_dev_t dev, const ggml_tensor * op) {
|
||||
const ggml_hrx_device_context * ctx = ggml_hrx_dev_ctx(dev);
|
||||
switch (op->op) {
|
||||
case GGML_OP_NONE:
|
||||
case GGML_OP_VIEW:
|
||||
case GGML_OP_RESHAPE:
|
||||
case GGML_OP_PERMUTE:
|
||||
case GGML_OP_TRANSPOSE: return true;
|
||||
case GGML_OP_FILL: return ggml_hrx_supports_fill(op);
|
||||
case GGML_OP_CPY:
|
||||
case GGML_OP_DUP:
|
||||
case GGML_OP_CONT: return ggml_hrx_supports_cpy(ctx, op);
|
||||
case GGML_OP_SET_ROWS: return ggml_hrx_supports_set_rows(ctx, op);
|
||||
case GGML_OP_MUL_MAT: return ggml_hrx_supports_mul_mat(ctx, op);
|
||||
default: return false;
|
||||
}
|
||||
}
|
||||
|
||||
static bool ggml_backend_hrx_device_supports_buft(ggml_backend_dev_t dev, ggml_backend_buffer_type_t buft) {
|
||||
return buft == &ggml_hrx_dev_ctx(dev)->buft;
|
||||
}
|
||||
|
||||
static ggml_backend_event_t ggml_backend_hrx_device_event_new(ggml_backend_dev_t dev) {
|
||||
hrx_event_t event = nullptr;
|
||||
if (!GGML_HRX_CHECK(hrx_event_create(ggml_hrx_dev_ctx(dev)->device, HRX_EVENT_FLAG_DISABLE_TIMING, &event))) {
|
||||
return nullptr;
|
||||
}
|
||||
return new ggml_backend_event{ dev, event };
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_device_event_free(ggml_backend_dev_t dev, ggml_backend_event_t event) {
|
||||
GGML_UNUSED(dev);
|
||||
hrx_event_release((hrx_event_t) event->context);
|
||||
delete event;
|
||||
}
|
||||
|
||||
static void ggml_backend_hrx_device_event_synchronize(ggml_backend_dev_t dev, ggml_backend_event_t event) {
|
||||
GGML_UNUSED(dev);
|
||||
if (!GGML_HRX_CHECK(hrx_event_synchronize((hrx_event_t) event->context))) {
|
||||
GGML_ABORT("%s: HRX event synchronize failed", __func__);
|
||||
}
|
||||
}
|
||||
|
||||
static const ggml_backend_device_i ggml_backend_hrx_device_interface = {
|
||||
/* .get_name = */ ggml_backend_hrx_device_get_name,
|
||||
/* .get_description = */ ggml_backend_hrx_device_get_description,
|
||||
/* .get_memory = */ ggml_backend_hrx_device_get_memory,
|
||||
/* .get_type = */ ggml_backend_hrx_device_get_type,
|
||||
/* .get_props = */ ggml_backend_hrx_device_get_props,
|
||||
/* .init_backend = */ ggml_backend_hrx_device_init_backend,
|
||||
/* .get_buffer_type = */ ggml_backend_hrx_device_get_buffer_type,
|
||||
/* .get_host_buffer_type = */ nullptr,
|
||||
/* .buffer_from_host_ptr = */ nullptr,
|
||||
/* .supports_op = */ ggml_backend_hrx_device_supports_op,
|
||||
/* .supports_buft = */ ggml_backend_hrx_device_supports_buft,
|
||||
/* .offload_op = */ nullptr,
|
||||
/* .event_new = */ ggml_backend_hrx_device_event_new,
|
||||
/* .event_free = */ ggml_backend_hrx_device_event_free,
|
||||
/* .event_synchronize = */ ggml_backend_hrx_device_event_synchronize,
|
||||
};
|
||||
|
||||
struct ggml_hrx_reg_context {
|
||||
hrx_runtime_t runtime = nullptr;
|
||||
std::vector<hrx_device_group_t> groups;
|
||||
|
||||
std::vector<std::unique_ptr<ggml_hrx_device_context>> contexts;
|
||||
std::vector<ggml_backend_device> devices;
|
||||
|
||||
~ggml_hrx_reg_context() {
|
||||
for (auto & dev : contexts) {
|
||||
dev->kernels.clear();
|
||||
ggml_hrx_loom_jit_free(dev->jit);
|
||||
if (dev->buffer_stream != nullptr) {
|
||||
hrx_stream_release(dev->buffer_stream);
|
||||
}
|
||||
hrx_device_release(dev->device);
|
||||
}
|
||||
for (hrx_device_group_t group : groups) {
|
||||
hrx_device_group_release(group);
|
||||
}
|
||||
if (runtime != nullptr) {
|
||||
hrx_runtime_release(runtime);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static std::optional<std::string> ggml_hrx_device_string(hrx_device_t device, hrx_device_property_t property) {
|
||||
std::vector<char> buffer(64);
|
||||
while (buffer.size() <= 4096) {
|
||||
hrx_status_t status = hrx_device_get_property(device, property, buffer.data(), buffer.size());
|
||||
if (hrx_status_is_ok(status)) {
|
||||
return std::string(buffer.data());
|
||||
}
|
||||
if (hrx_status_code(status) != HRX_STATUS_OUT_OF_RANGE) {
|
||||
GGML_HRX_CHECK(status);
|
||||
return std::nullopt;
|
||||
}
|
||||
hrx_status_ignore(status);
|
||||
buffer.resize(buffer.size() * 2);
|
||||
}
|
||||
return std::nullopt;
|
||||
}
|
||||
|
||||
static bool ggml_hrx_find_queue(hrx_device_t device, hrx_queue_role_flags_t roles, uint32_t index, hrx_queue_t * queue) {
|
||||
*queue = nullptr;
|
||||
const size_t n_families = hrx_device_queue_family_count(device);
|
||||
for (size_t i = 0; i < n_families; ++i) {
|
||||
hrx_queue_family_info_t family = {};
|
||||
if (!GGML_HRX_CHECK(hrx_device_query_queue_family(device, (uint32_t) i, &family))) {
|
||||
return false;
|
||||
}
|
||||
if ((family.roles & roles) == roles && family.provisioned_queue_count > index) {
|
||||
*queue = hrx_device_get_queue(device, (uint32_t) i, index);
|
||||
if (*queue != nullptr) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Returns nullptr if the device is not usable. In that case, it releases all that it took.
|
||||
static std::unique_ptr<ggml_hrx_device_context> ggml_hrx_init_device(hrx_device_t device, int index) {
|
||||
const std::optional<std::string> name = ggml_hrx_device_string(device, HRX_DEVICE_PROPERTY_NAME);
|
||||
const std::optional<std::string> arch = ggml_hrx_device_string(device, HRX_DEVICE_PROPERTY_ARCHITECTURE);
|
||||
if (!name || !arch) {
|
||||
return nullptr;
|
||||
}
|
||||
const ggml_hrx_arch * info = ggml_hrx_arch_find(arch->c_str());
|
||||
if (info == nullptr) {
|
||||
GGML_LOG_INFO("ggml_hrx: skipping %s (%s): architecture is not supported\n", name->c_str(), arch->c_str());
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto ctx = std::make_unique<ggml_hrx_device_context>();
|
||||
ctx->device = device;
|
||||
ctx->arch = info;
|
||||
ctx->tune = info->tune;
|
||||
ctx->name = GGML_HRX_NAME + std::to_string(index);
|
||||
ctx->index = index;
|
||||
ctx->description = *name + " (" + *arch + ")";
|
||||
|
||||
uint64_t memory = 0;
|
||||
if (!GGML_HRX_CHECK(hrx_device_get_property(device, HRX_DEVICE_PROPERTY_TOTAL_MEMORY, &memory, sizeof(memory))) ||
|
||||
!GGML_HRX_CHECK(hrx_device_get_property(device, HRX_DEVICE_PROPERTY_COMPUTE_UNITS, &ctx->n_cu, sizeof(ctx->n_cu)))) {
|
||||
return nullptr;
|
||||
}
|
||||
ctx->memory_total = (size_t) memory;
|
||||
|
||||
// Synchronous transfers use a second queue if there is one. Then they do not wait for queued graphs.
|
||||
if ((!ggml_hrx_find_queue(device, HRX_QUEUE_ROLE_TRANSFER, 1, &ctx->transfer_queue) &&
|
||||
!ggml_hrx_find_queue(device, HRX_QUEUE_ROLE_TRANSFER, 0, &ctx->transfer_queue)) ||
|
||||
!ggml_hrx_find_queue(device, HRX_QUEUE_ROLE_DISPATCH | HRX_QUEUE_ROLE_TRANSFER, 0, &ctx->stream_queue)) {
|
||||
GGML_LOG_ERROR("ggml_hrx: %s has no usable queues\n", name->c_str());
|
||||
return nullptr;
|
||||
}
|
||||
if (!GGML_HRX_CHECK(hrx_stream_create(ctx->stream_queue, 0, &ctx->buffer_stream))) {
|
||||
return nullptr;
|
||||
}
|
||||
return ctx;
|
||||
}
|
||||
|
||||
static void ggml_hrx_discover(ggml_hrx_reg_context * reg) {
|
||||
hrx_runtime_options_t options = {};
|
||||
const hrx_host_allocator_t allocator = hrx_host_allocator_system();
|
||||
if (!GGML_HRX_CHECK(hrx_runtime_create(&options, allocator, ®->runtime))) {
|
||||
return;
|
||||
}
|
||||
|
||||
size_t count = 0;
|
||||
hrx_device_info_t * infos = nullptr;
|
||||
if (!GGML_HRX_CHECK(hrx_runtime_query_available_devices(reg->runtime, "amdgpu", allocator, &count, &infos))) {
|
||||
return;
|
||||
}
|
||||
// One group per device.
|
||||
for (size_t i = 0; i < count; ++i) {
|
||||
const hrx_device_create_params_t params = { infos[i].uri, HRX_WAIT_FLAG_NONE };
|
||||
hrx_device_group_t group = nullptr;
|
||||
if (!GGML_HRX_CHECK(hrx_device_group_create(reg->runtime, 1, ¶ms, &group))) {
|
||||
continue;
|
||||
}
|
||||
hrx_device_t device = hrx_device_group_get_device(group, 0);
|
||||
if (device == nullptr) {
|
||||
hrx_device_group_release(group);
|
||||
continue;
|
||||
}
|
||||
hrx_device_retain(device);
|
||||
auto ctx = ggml_hrx_init_device(device, (int) reg->contexts.size());
|
||||
if (!ctx) {
|
||||
hrx_device_release(device);
|
||||
hrx_device_group_release(group);
|
||||
continue;
|
||||
}
|
||||
reg->groups.push_back(group);
|
||||
reg->contexts.push_back(std::move(ctx));
|
||||
}
|
||||
hrx_host_allocator_free(allocator, infos);
|
||||
}
|
||||
|
||||
static const char * ggml_backend_hrx_reg_get_name(ggml_backend_reg_t reg) {
|
||||
GGML_UNUSED(reg);
|
||||
return GGML_HRX_NAME;
|
||||
}
|
||||
|
||||
static size_t ggml_backend_hrx_reg_get_device_count(ggml_backend_reg_t reg) {
|
||||
return ((ggml_hrx_reg_context *) reg->context)->devices.size();
|
||||
}
|
||||
|
||||
static ggml_backend_dev_t ggml_backend_hrx_reg_get_device(ggml_backend_reg_t reg, size_t index) {
|
||||
auto * ctx = (ggml_hrx_reg_context *) reg->context;
|
||||
GGML_ASSERT(index < ctx->devices.size());
|
||||
return &ctx->devices[index];
|
||||
}
|
||||
|
||||
static const ggml_backend_reg_i ggml_backend_hrx_reg_interface = {
|
||||
/* .get_name = */ ggml_backend_hrx_reg_get_name,
|
||||
/* .get_device_count = */ ggml_backend_hrx_reg_get_device_count,
|
||||
/* .get_device = */ ggml_backend_hrx_reg_get_device,
|
||||
/* .get_proc_address = */ nullptr,
|
||||
};
|
||||
|
||||
ggml_backend_reg_t ggml_backend_hrx_reg(void) {
|
||||
static ggml_hrx_reg_context reg_ctx;
|
||||
static ggml_backend_reg reg = { GGML_BACKEND_API_VERSION, ggml_backend_hrx_reg_interface, ®_ctx };
|
||||
|
||||
static std::once_flag once;
|
||||
std::call_once(once, [] {
|
||||
ggml_hrx_discover(®_ctx);
|
||||
reg_ctx.devices.reserve(reg_ctx.contexts.size());
|
||||
for (auto & ctx : reg_ctx.contexts) {
|
||||
reg_ctx.devices.push_back({ ggml_backend_hrx_device_interface, ®, ctx.get() });
|
||||
}
|
||||
for (size_t i = 0; i < reg_ctx.contexts.size(); ++i) {
|
||||
ggml_hrx_device_context * ctx = reg_ctx.contexts[i].get();
|
||||
ctx->buft = { ggml_backend_hrx_buffer_type_interface, ®_ctx.devices[i], ctx };
|
||||
}
|
||||
});
|
||||
return ®
|
||||
}
|
||||
|
||||
ggml_backend_t ggml_backend_hrx_init(size_t device) {
|
||||
ggml_backend_reg_t reg = ggml_backend_hrx_reg();
|
||||
if (device >= ggml_backend_reg_dev_count(reg)) {
|
||||
GGML_LOG_ERROR("%s: invalid device %zu\n", __func__, device);
|
||||
return nullptr;
|
||||
}
|
||||
return ggml_backend_dev_init(ggml_backend_reg_dev_get(reg, device), nullptr);
|
||||
}
|
||||
|
||||
bool ggml_backend_is_hrx(ggml_backend_t backend) {
|
||||
return backend != nullptr && ggml_guid_matches(backend->guid, ggml_backend_hrx_guid());
|
||||
}
|
||||
|
||||
int ggml_backend_hrx_get_device_count(void) {
|
||||
return (int) ggml_backend_reg_dev_count(ggml_backend_hrx_reg());
|
||||
}
|
||||
|
||||
ggml_backend_buffer_type_t ggml_backend_hrx_buffer_type(size_t device) {
|
||||
ggml_backend_reg_t reg = ggml_backend_hrx_reg();
|
||||
if (device >= ggml_backend_reg_dev_count(reg)) {
|
||||
return nullptr;
|
||||
}
|
||||
return ggml_backend_dev_buffer_type(ggml_backend_reg_dev_get(reg, device));
|
||||
}
|
||||
|
||||
GGML_BACKEND_DL_IMPL(ggml_backend_hrx_reg)
|
||||
@@ -0,0 +1,134 @@
|
||||
config.decl @ggml.cpy.dst_type : %value: index where [range(%value, 0, 3)]
|
||||
|
||||
config.decl @ggml.elementwise.wg_size : %value: index where [range(%value, 64, 1024), multiple_of(%value, 64)]
|
||||
|
||||
target.decl @ggml_wave64
|
||||
|
||||
kernel.def target(@ggml_wave64) export("ggml_cpy_f32") @ggml_cpy_f32(%n: index) {
|
||||
%one = index.constant 1 : index
|
||||
%wg_size = config.get @ggml.elementwise.wg_size : index
|
||||
%round = index.sub %wg_size, %one : index
|
||||
%n_round = index.add %n, %round : index
|
||||
%groups = index.div %n_round, %wg_size : index
|
||||
kernel.launch.config workgroups(%groups, %one, %one) workgroup_size(%wg_size, %one, %one) : index
|
||||
} launch(%n_in: index, %s_ne0_in: index, %s_ne1_in: index, %s_ne2_in: index, %s0_in: index, %s1_in: index, %s2_in: index, %s3_in: index, %s_span_in: index, %t_ne0_in: index, %t_ne1_in: index, %t_ne2_in: index, %t0_in: index, %t1_in: index, %t2_in: index, %t3_in: index, %t_span_in: index, %src: buffer, %dst: buffer) {
|
||||
// supports_cpy checks these ranges.
|
||||
%n = index.assume %n_in [range(%n_in, 1, 2147483647)] : index
|
||||
%s_ne0 = index.assume %s_ne0_in [range(%s_ne0_in, 1, 2147483647)] : index
|
||||
%s_ne1 = index.assume %s_ne1_in [range(%s_ne1_in, 1, 2147483647)] : index
|
||||
%s_ne2 = index.assume %s_ne2_in [range(%s_ne2_in, 1, 2147483647)] : index
|
||||
%s0 = index.assume %s0_in [range(%s0_in, 0, 2147483647)] : index
|
||||
%s1 = index.assume %s1_in [range(%s1_in, 0, 2147483647)] : index
|
||||
%s2 = index.assume %s2_in [range(%s2_in, 0, 2147483647)] : index
|
||||
%s3 = index.assume %s3_in [range(%s3_in, 0, 2147483647)] : index
|
||||
%s_span = index.assume %s_span_in [range(%s_span_in, 1, 2147483647)] : index
|
||||
%t_ne0 = index.assume %t_ne0_in [range(%t_ne0_in, 1, 2147483647)] : index
|
||||
%t_ne1 = index.assume %t_ne1_in [range(%t_ne1_in, 1, 2147483647)] : index
|
||||
%t_ne2 = index.assume %t_ne2_in [range(%t_ne2_in, 1, 2147483647)] : index
|
||||
%t0 = index.assume %t0_in [range(%t0_in, 0, 2147483647)] : index
|
||||
%t1 = index.assume %t1_in [range(%t1_in, 0, 2147483647)] : index
|
||||
%t2 = index.assume %t2_in [range(%t2_in, 0, 2147483647)] : index
|
||||
%t3 = index.assume %t3_in [range(%t3_in, 0, 2147483647)] : index
|
||||
%t_span = index.assume %t_span_in [range(%t_span_in, 1, 2147483647)] : index
|
||||
%dst_type = config.get @ggml.cpy.dst_type : index
|
||||
%wg_size = config.get @ggml.elementwise.wg_size : index
|
||||
%group = kernel.workgroup.id<x> : index
|
||||
%item = kernel.workitem.id<x> : index
|
||||
%base = index.mul %group, %wg_size : index
|
||||
%i = index.add %base, %item : index
|
||||
%in_bounds = index.cmp ult, %i, %n : index
|
||||
%zero = index.constant 0 : offset
|
||||
%src_view = buffer.view %src[%zero] : buffer -> view<[%s_span]xf32>
|
||||
scf.if %in_bounds {
|
||||
%a0 = index.rem %i, %s_ne0 : index
|
||||
%aq0 = index.div %i, %s_ne0 : index
|
||||
%a1 = index.rem %aq0, %s_ne1 : index
|
||||
%aq1 = index.div %aq0, %s_ne1 : index
|
||||
%a2 = index.rem %aq1, %s_ne2 : index
|
||||
%a3 = index.div %aq1, %s_ne2 : index
|
||||
%so0 = index.mul %a0, %s0 : index
|
||||
%so1 = index.mul %a1, %s1 : index
|
||||
%so2 = index.mul %a2, %s2 : index
|
||||
%so3 = index.mul %a3, %s3 : index
|
||||
%so01 = index.add %so0, %so1 : index
|
||||
%so23 = index.add %so2, %so3 : index
|
||||
%s_idx = index.add %so01, %so23 : index
|
||||
|
||||
%b0 = index.rem %i, %t_ne0 : index
|
||||
%bq0 = index.div %i, %t_ne0 : index
|
||||
%b1 = index.rem %bq0, %t_ne1 : index
|
||||
%bq1 = index.div %bq0, %t_ne1 : index
|
||||
%b2 = index.rem %bq1, %t_ne2 : index
|
||||
%b3 = index.div %bq1, %t_ne2 : index
|
||||
%to0 = index.mul %b0, %t0 : index
|
||||
%to1 = index.mul %b1, %t1 : index
|
||||
%to2 = index.mul %b2, %t2 : index
|
||||
%to3 = index.mul %b3, %t3 : index
|
||||
%to01 = index.add %to0, %to1 : index
|
||||
%to23 = index.add %to2, %to3 : index
|
||||
%t_idx = index.add %to01, %to23 : index
|
||||
|
||||
// The prover reads only branch conditions. Thus cap the offsets and check one bound in each scf.if.
|
||||
%s_off = index.assume %s_idx [range(%s_idx, 0, 2147483646)] : index
|
||||
%t_off = index.assume %t_idx [range(%t_idx, 0, 2147483646)] : index
|
||||
%s_ok = index.cmp ult, %s_off, %s_span : index
|
||||
scf.if %s_ok {
|
||||
%t_ok = index.cmp ult, %t_off, %t_span : index
|
||||
scf.if %t_ok {
|
||||
%x = view.load %src_view[%s_off] : view<[%s_span]xf32> -> f32
|
||||
%type_f16 = index.constant 1 : index
|
||||
%type_i32 = index.constant 2 : index
|
||||
%is_f16 = index.cmp eq, %dst_type, %type_f16 : index
|
||||
%is_i32 = index.cmp eq, %dst_type, %type_i32 : index
|
||||
scf.if %is_f16 {
|
||||
%h = scalar.fptrunc %x : f32 to f16
|
||||
%dst_f16 = buffer.view %dst[%zero] : buffer -> view<[%t_span]xf16>
|
||||
view.store %h, %dst_f16[%t_off] : f16, view<[%t_span]xf16>
|
||||
} else {
|
||||
scf.if %is_i32 {
|
||||
%v = scalar.fptosi %x : f32 to i32
|
||||
%dst_i32 = buffer.view %dst[%zero] : buffer -> view<[%t_span]xi32>
|
||||
view.store %v, %dst_i32[%t_off] : i32, view<[%t_span]xi32>
|
||||
} else {
|
||||
%dst_f32 = buffer.view %dst[%zero] : buffer -> view<[%t_span]xf32>
|
||||
view.store %x, %dst_f32[%t_off] : f32, view<[%t_span]xf32>
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
kernel.return
|
||||
}
|
||||
|
||||
kernel.def target(@ggml_wave64) export("ggml_cpy_f32_stream") @ggml_cpy_f32_stream(%groups: index) {
|
||||
%one = index.constant 1 : index
|
||||
%wg_size = config.get @ggml.elementwise.wg_size : index
|
||||
kernel.launch.config workgroups(%groups, %one, %one) workgroup_size(%wg_size, %one, %one) : index
|
||||
} launch(%n_in: index, %groups_in: index, %src: buffer, %dst: buffer) {
|
||||
// The caller checks these ranges. n must be a multiple of 4. src and dst are contiguous f32.
|
||||
%n = index.assume %n_in [range(%n_in, 4, 2147483644)] : index
|
||||
%groups = index.assume %groups_in [range(%groups_in, 1, 65535)] : index
|
||||
%c3 = index.constant 3 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%wg_size = config.get @ggml.elementwise.wg_size : index
|
||||
%group = kernel.workgroup.id<x> : index
|
||||
%item = kernel.workitem.id<x> : index
|
||||
%base = index.mul %group, %wg_size : index
|
||||
%lane = index.add %base, %item : index
|
||||
%first = index.mul %lane, %c4 : index
|
||||
%lanes = index.mul %groups, %wg_size : index
|
||||
%stride = index.mul %lanes, %c4 : index
|
||||
%zero = index.constant 0 : offset
|
||||
%src_view = buffer.view %src[%zero] : buffer -> view<[%n]xf32>
|
||||
%dst_view = buffer.view %dst[%zero] : buffer -> view<[%n]xf32>
|
||||
scf.for %j_raw = [%first to %n step %stride] {
|
||||
%j = index.assume %j_raw [range(%j_raw, 0, 2147483640)] : index
|
||||
%j_last = index.add %j, %c3 : index
|
||||
%ok = index.cmp ult, %j_last, %n : index
|
||||
scf.if %ok {
|
||||
%x = vector.load %src_view[%j] : view<[%n]xf32> -> vector<4xf32>
|
||||
vector.store %x, %dst_view[%j] : vector<4xf32>, view<[%n]xf32>
|
||||
}
|
||||
}
|
||||
kernel.return
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
// Weight type 2 is Q4_0. Weight units are 16-bit halves.
|
||||
|
||||
template.decl @ggml.weight.block(%wtype: index) -> (index, index)
|
||||
|
||||
template.decl @ggml.weight.values4(%wtype: index, %weight: buffer, %w_span: index, %block_base: index, %j: index) -> (vector<4xf32>)
|
||||
|
||||
// k is a multiple of 4 and below K.
|
||||
func.def inline @ggml_hrx_mm_quant4(%wtype: index, %weight: buffer, %w_span: index, %row_base: index, %k: index) -> (vector<4xf32>) {
|
||||
%block_values, %block_units = template.apply<@ggml.weight.block>(%wtype) : (index) -> (index, index)
|
||||
%block = index.div %k, %block_values : index
|
||||
%j = index.rem %k, %block_values : index
|
||||
%block_offset = index.mul %block, %block_units : index
|
||||
%block_base = index.add %row_base, %block_offset : index
|
||||
%values = template.apply<@ggml.weight.values4>(%wtype, %weight, %w_span, %block_base, %j) : (index, buffer, index, index, index) -> (vector<4xf32>)
|
||||
func.return %values : vector<4xf32>
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_load_input(%input: buffer, %x_span: index, %index: index) -> (f32) {
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%zero = scalar.constant 0.0 : f32
|
||||
%input_view = buffer.view %input[%c0_offset] : buffer -> view<[%x_span]xf32>
|
||||
%off = index.assume %index [range(%index, 0, 2147483646)] : index
|
||||
%ok = index.cmp ult, %off, %x_span : index
|
||||
%value = scf.if %ok -> (f32) {
|
||||
%loaded = view.load %input_view[%off] : view<[%x_span]xf32> -> f32
|
||||
scf.yield %loaded : f32
|
||||
} else {
|
||||
scf.yield %zero : f32
|
||||
}
|
||||
func.return %value : f32
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_input_at(%input: buffer, %x_span: index, %x_col_base: index, %x_s0: index, %k: index, %k_size: index) -> (f32) {
|
||||
%zero = scalar.constant 0.0 : f32
|
||||
%k_in = index.cmp ult, %k, %k_size : index
|
||||
%value = scf.if %k_in -> (f32) {
|
||||
%offset = index.mul %k, %x_s0 : index
|
||||
%index = index.add %x_col_base, %offset : index
|
||||
%loaded = func.call @ggml_hrx_mm_load_input(%input, %x_span, %index) : (buffer, index, index) -> (f32)
|
||||
scf.yield %loaded : f32
|
||||
} else {
|
||||
scf.yield %zero : f32
|
||||
}
|
||||
func.return %value : f32
|
||||
}
|
||||
|
||||
// k is a multiple of 4. K is a multiple of the block size. Thus k < K covers all four values.
|
||||
func.def inline @ggml_hrx_mm_weight4(%wtype: index, %weight: buffer, %w_span: index, %row_base: index, %row_valid: i1, %k: index, %k_size: index) -> (vector<4xf32>) {
|
||||
%zero4 = vector.splatf 0.0 : vector<4xf32>
|
||||
%values = scf.if %row_valid -> (vector<4xf32>) {
|
||||
%k_in = index.cmp ult, %k, %k_size : index
|
||||
%quant_values = scf.if %k_in -> (vector<4xf32>) {
|
||||
%decoded = func.call @ggml_hrx_mm_quant4(%wtype, %weight, %w_span, %row_base, %k) : (index, buffer, index, index, index) -> (vector<4xf32>)
|
||||
scf.yield %decoded : vector<4xf32>
|
||||
} else {
|
||||
scf.yield %zero4 : vector<4xf32>
|
||||
}
|
||||
scf.yield %quant_values : vector<4xf32>
|
||||
} else {
|
||||
scf.yield %zero4 : vector<4xf32>
|
||||
}
|
||||
func.return %values : vector<4xf32>
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_stage_input(%input: buffer, %x_span: index, %x_base: index, %x_valid: i1, %x_s0: index, %k: index, %k_size: index) -> (f32) {
|
||||
%zero = scalar.constant 0.0 : f32
|
||||
%value = scf.if %x_valid -> (f32) {
|
||||
%loaded = func.call @ggml_hrx_mm_input_at(%input, %x_span, %x_base, %x_s0, %k, %k_size) : (buffer, index, index, index, index, index) -> (f32)
|
||||
scf.yield %loaded : f32
|
||||
} else {
|
||||
scf.yield %zero : f32
|
||||
}
|
||||
func.return %value : f32
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_tile(%wtype: index, %k_size: index, %w_base0: index, %w_valid0: i1, %w_base1: index, %w_valid1: i1, %x_base0: index, %x_valid0: i1, %x_base1: index, %x_valid1: i1, %x_base2: index, %x_valid2: i1, %x_base3: index, %x_valid3: i1, %x_s0: index, %w_span: index, %x_span: index, %weight: buffer, %input: buffer, %w_stage: buffer, %x_stage: buffer) -> (vector<4xf32>, vector<4xf32>) {
|
||||
%t0 = kernel.workitem.id<x> : index
|
||||
%t = index.assume %t0 [range(%t0, 0, 255)] : index
|
||||
%c0 = index.constant 0 : index
|
||||
%c1 = index.constant 1 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c3 = index.constant 3 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c24 = index.constant 24 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%zero4 = vector.splatf 0.0 : vector<4xf32>
|
||||
%w_view = buffer.view %w_stage[%c0_offset] : buffer -> view<32x64xf32>
|
||||
// Odd pitch prevents LDS bank conflicts.
|
||||
%x_view = buffer.view %x_stage[%c0_offset] : buffer -> view<32x33xf32>
|
||||
%w_packet = index.rem %t, %c8 : index
|
||||
%w_k0 = index.mul %w_packet, %c4 : index
|
||||
%w_k1 = index.add %w_k0, %c1 : index
|
||||
%w_k2 = index.add %w_k0, %c2 : index
|
||||
%w_k3 = index.add %w_k0, %c3 : index
|
||||
%w_row0 = index.div %t, %c8 : index
|
||||
%w_row1 = index.add %w_row0, %c32 : index
|
||||
%x_k = index.rem %t, %c32 : index
|
||||
%x_col0 = index.div %t, %c32 : index
|
||||
%x_col1 = index.add %x_col0, %c8 : index
|
||||
%x_col2 = index.add %x_col0, %c16 : index
|
||||
%x_col3 = index.add %x_col0, %c24 : index
|
||||
%out_row_group = index.rem %t, %c16 : index
|
||||
%out_row = index.mul %out_row_group, %c4 : index
|
||||
%out_col0 = index.div %t, %c16 : index
|
||||
%out_col1 = index.add %out_col0, %c16 : index
|
||||
%acc0, %acc1 = scf.for %k0 = [%c0 to %k_size step %c32](%tile_acc0 = %zero4 : vector<4xf32>, %tile_acc1 = %zero4 : vector<4xf32>) -> (vector<4xf32>, vector<4xf32>) {
|
||||
%w_k = index.add %k0, %w_k0 : index
|
||||
%w0 = func.call @ggml_hrx_mm_weight4(%wtype, %weight, %w_span, %w_base0, %w_valid0, %w_k, %k_size) : (index, buffer, index, index, i1, index, index) -> (vector<4xf32>)
|
||||
%w1 = func.call @ggml_hrx_mm_weight4(%wtype, %weight, %w_span, %w_base1, %w_valid1, %w_k, %k_size) : (index, buffer, index, index, i1, index, index) -> (vector<4xf32>)
|
||||
%w0_0 = vector.extract %w0[0] : vector<4xf32> -> f32
|
||||
%w0_1 = vector.extract %w0[1] : vector<4xf32> -> f32
|
||||
%w0_2 = vector.extract %w0[2] : vector<4xf32> -> f32
|
||||
%w0_3 = vector.extract %w0[3] : vector<4xf32> -> f32
|
||||
%w1_0 = vector.extract %w1[0] : vector<4xf32> -> f32
|
||||
%w1_1 = vector.extract %w1[1] : vector<4xf32> -> f32
|
||||
%w1_2 = vector.extract %w1[2] : vector<4xf32> -> f32
|
||||
%w1_3 = vector.extract %w1[3] : vector<4xf32> -> f32
|
||||
view.store %w0_0, %w_view[%w_k0, %w_row0] : f32, view<32x64xf32>
|
||||
view.store %w0_1, %w_view[%w_k1, %w_row0] : f32, view<32x64xf32>
|
||||
view.store %w0_2, %w_view[%w_k2, %w_row0] : f32, view<32x64xf32>
|
||||
view.store %w0_3, %w_view[%w_k3, %w_row0] : f32, view<32x64xf32>
|
||||
view.store %w1_0, %w_view[%w_k0, %w_row1] : f32, view<32x64xf32>
|
||||
view.store %w1_1, %w_view[%w_k1, %w_row1] : f32, view<32x64xf32>
|
||||
view.store %w1_2, %w_view[%w_k2, %w_row1] : f32, view<32x64xf32>
|
||||
view.store %w1_3, %w_view[%w_k3, %w_row1] : f32, view<32x64xf32>
|
||||
%x_k_abs = index.add %k0, %x_k : index
|
||||
%x0 = func.call @ggml_hrx_mm_stage_input(%input, %x_span, %x_base0, %x_valid0, %x_s0, %x_k_abs, %k_size) : (buffer, index, index, i1, index, index, index) -> (f32)
|
||||
%x1 = func.call @ggml_hrx_mm_stage_input(%input, %x_span, %x_base1, %x_valid1, %x_s0, %x_k_abs, %k_size) : (buffer, index, index, i1, index, index, index) -> (f32)
|
||||
%x2 = func.call @ggml_hrx_mm_stage_input(%input, %x_span, %x_base2, %x_valid2, %x_s0, %x_k_abs, %k_size) : (buffer, index, index, i1, index, index, index) -> (f32)
|
||||
%x3 = func.call @ggml_hrx_mm_stage_input(%input, %x_span, %x_base3, %x_valid3, %x_s0, %x_k_abs, %k_size) : (buffer, index, index, i1, index, index, index) -> (f32)
|
||||
view.store %x0, %x_view[%x_col0, %x_k] : f32, view<32x33xf32>
|
||||
view.store %x1, %x_view[%x_col1, %x_k] : f32, view<32x33xf32>
|
||||
view.store %x2, %x_view[%x_col2, %x_k] : f32, view<32x33xf32>
|
||||
view.store %x3, %x_view[%x_col3, %x_k] : f32, view<32x33xf32>
|
||||
kernel.barrier<workgroup> scope(workgroup) ordering(acq_rel)
|
||||
%next0, %next1 = scf.for %kk = [%c0 to %c32 step %c1](%k_acc0 = %tile_acc0 : vector<4xf32>, %k_acc1 = %tile_acc1 : vector<4xf32>) -> (vector<4xf32>, vector<4xf32>) {
|
||||
%w = vector.load %w_view[%kk, %out_row] : view<32x64xf32> -> vector<4xf32>
|
||||
%a0 = view.load %x_view[%out_col0, %kk] : view<32x33xf32> -> f32
|
||||
%a1 = view.load %x_view[%out_col1, %kk] : view<32x33xf32> -> f32
|
||||
%a0_vector = vector.splat %a0 : vector<4xf32>
|
||||
%a1_vector = vector.splat %a1 : vector<4xf32>
|
||||
%k_next0 = vector.fmaf %w, %a0_vector, %k_acc0 : vector<4xf32>
|
||||
%k_next1 = vector.fmaf %w, %a1_vector, %k_acc1 : vector<4xf32>
|
||||
scf.yield %k_next0, %k_next1 : vector<4xf32>, vector<4xf32>
|
||||
}
|
||||
// The next K step overwrites the stages.
|
||||
kernel.barrier<workgroup> scope(workgroup) ordering(acq_rel)
|
||||
scf.yield %next0, %next1 : vector<4xf32>, vector<4xf32>
|
||||
}
|
||||
func.return %acc0, %acc1 : vector<4xf32>, vector<4xf32>
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_store(%dst: buffer, %d_span: index, %index: index, %value: f32) {
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%dst_view = buffer.view %dst[%c0_offset] : buffer -> view<[%d_span]xf32>
|
||||
%off = index.assume %index [range(%index, 0, 2147483646)] : index
|
||||
%ok = index.cmp ult, %off, %d_span : index
|
||||
scf.if %ok {
|
||||
view.store %value, %dst_view[%off] : f32, view<[%d_span]xf32>
|
||||
}
|
||||
func.return
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_store_row(%dst: buffer, %d_span: index, %d_col_base: index, %row: index, %n_rows: index, %value: f32) {
|
||||
%row_in = index.cmp ult, %row, %n_rows : index
|
||||
scf.if %row_in {
|
||||
%index = index.add %d_col_base, %row : index
|
||||
func.call @ggml_hrx_mm_store(%dst, %d_span, %index, %value) : (buffer, index, index, f32)
|
||||
}
|
||||
func.return
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_store4(%dst: buffer, %d_span: index, %d_col_base: index, %row0: index, %n_rows: index, %col_valid: i1, %values: vector<4xf32>) {
|
||||
%c1 = index.constant 1 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c3 = index.constant 3 : index
|
||||
scf.if %col_valid {
|
||||
%row1 = index.add %row0, %c1 : index
|
||||
%row2 = index.add %row0, %c2 : index
|
||||
%row3 = index.add %row0, %c3 : index
|
||||
%value0 = vector.extract %values[0] : vector<4xf32> -> f32
|
||||
%value1 = vector.extract %values[1] : vector<4xf32> -> f32
|
||||
%value2 = vector.extract %values[2] : vector<4xf32> -> f32
|
||||
%value3 = vector.extract %values[3] : vector<4xf32> -> f32
|
||||
func.call @ggml_hrx_mm_store_row(%dst, %d_span, %d_col_base, %row0, %n_rows, %value0) : (buffer, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_store_row(%dst, %d_span, %d_col_base, %row1, %n_rows, %value1) : (buffer, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_store_row(%dst, %d_span, %d_col_base, %row2, %n_rows, %value2) : (buffer, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_store_row(%dst, %d_span, %d_col_base, %row3, %n_rows, %value3) : (buffer, index, index, index, index, f32)
|
||||
}
|
||||
func.return
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// n_tile is a config constant. Thus use folds at compile time.
|
||||
func.def inline @ggml_hrx_mv_col_base(%i: index, %n_tile: index, %n_cols: index, %x_batch: index, %x_s1: index, %k_size: index, %x_span: index, %ok_in: i1) -> (index, i1, i1, i1) {
|
||||
%false = scalar.constant false : i1
|
||||
%use = index.cmp ult, %i, %n_tile : index
|
||||
%in_cols = index.cmp ult, %i, %n_cols : index
|
||||
%store = scf.select %use, %in_cols, %false : i1
|
||||
%x_offset = index.mul %i, %x_s1 : index
|
||||
%x_base = index.add %x_batch, %x_offset : index
|
||||
%x_end = index.add %x_base, %k_size : index
|
||||
%fits = index.cmp ule, %x_end, %x_span : index
|
||||
%col_ok = scf.select %use, %fits, %ok_in : i1
|
||||
%ok = scf.select %ok_in, %col_ok, %false : i1
|
||||
func.return %x_base, %use, %store, %ok : index, i1, i1, i1
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mv_xload(%use: i1, %input: buffer, %x_base: index, %sb: index, %o0: index, %o1: index, %o2: index, %o3: index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) {
|
||||
%c256 = index.constant 256 : index
|
||||
%b4 = index.constant 4 : offset
|
||||
%zero4 = vector.splatf 0.0 : vector<4xf32>
|
||||
%x0, %x1, %x2, %x3 = scf.if %use -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) {
|
||||
%sb_values = index.mul %sb, %c256 : index
|
||||
%x_index = index.add %x_base, %sb_values : index
|
||||
%x_byte = index.scale %x_index, %b4 : index, offset -> offset
|
||||
%x_view = buffer.view %input[%x_byte] : buffer -> view<256xf32>
|
||||
%y0 = vector.load %x_view[%o0] : view<256xf32> -> vector<4xf32>
|
||||
%y1 = vector.load %x_view[%o1] : view<256xf32> -> vector<4xf32>
|
||||
%y2 = vector.load %x_view[%o2] : view<256xf32> -> vector<4xf32>
|
||||
%y3 = vector.load %x_view[%o3] : view<256xf32> -> vector<4xf32>
|
||||
scf.yield %y0, %y1, %y2, %y3 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>
|
||||
} else {
|
||||
scf.yield %zero4, %zero4, %zero4, %zero4 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>
|
||||
}
|
||||
func.return %x0, %x1, %x2, %x3 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mv_dot16(%use: i1, %w0: vector<4xf32>, %w1: vector<4xf32>, %w2: vector<4xf32>, %w3: vector<4xf32>, %x0: vector<4xf32>, %x1: vector<4xf32>, %x2: vector<4xf32>, %x3: vector<4xf32>) -> (f32) {
|
||||
%zero = scalar.constant 0.0 : f32
|
||||
%result = scf.if %use -> (f32) {
|
||||
%p0 = vector.mulf %w0, %x0 : vector<4xf32>
|
||||
%p1 = vector.fmaf %w1, %x1, %p0 : vector<4xf32>
|
||||
%p2 = vector.fmaf %w2, %x2, %p1 : vector<4xf32>
|
||||
%p3 = vector.fmaf %w3, %x3, %p2 : vector<4xf32>
|
||||
%lane_sum = vector.reduce<addf> %p3, %zero : vector<4xf32>, f32
|
||||
%sum = kernel.subgroup.reduce<addf> %lane_sum {cluster_size = 16} : f32
|
||||
scf.yield %sum : f32
|
||||
} else {
|
||||
scf.yield %zero : f32
|
||||
}
|
||||
func.return %result : f32
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// Weights and activations are rounded to f16. The sums are in f32.
|
||||
// Each stage row has 8 pad halves. The pad prevents LDS bank conflicts.
|
||||
|
||||
template.decl @ggml.weight.wmma16(%wtype: index, %weight: buffer, %w_span: index, %row_base: index, %row_valid: i1, %k: index, %k_size: index, %part: index) -> (vector<8xf16>, vector<8xf16>)
|
||||
|
||||
func.decl @ggml_hrx_mm_store_row(%dst: buffer, %d_span: index, %d_col_base: index, %row: index, %n_rows: index, %value: f32)
|
||||
|
||||
func.def inline @ggml_hrx_mm_wmma_store1(%dst: buffer, %d_span: index, %d_base: index, %d_s1: index, %col: index, %n_cols: index, %row: index, %n_rows: index, %value: f32) {
|
||||
%col_valid = index.cmp ult, %col, %n_cols : index
|
||||
scf.if %col_valid {
|
||||
%d_col_offset = index.mul %col, %d_s1 : index
|
||||
%d_col_base = index.add %d_base, %d_col_offset : index
|
||||
func.call @ggml_hrx_mm_store_row(%dst, %d_span, %d_col_base, %row, %n_rows, %value) : (buffer, index, index, index, index, f32)
|
||||
}
|
||||
func.return
|
||||
}
|
||||
|
||||
// The fragment layout is the gfx11 wave32 result layout.
|
||||
// Values out of range are not stored.
|
||||
func.def inline @ggml_hrx_mm_wmma_store(%dst: buffer, %d_span: index, %d_base: index, %d_s1: index, %col0: index, %n_cols: index, %row0: index, %n_rows: index, %acc: vector<8xf32>) {
|
||||
%lane0 = kernel.subgroup.lane.id : index
|
||||
%lane = index.assume %lane0 [range(%lane0, 0, 31)] : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c6 = index.constant 6 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c10 = index.constant 10 : index
|
||||
%c12 = index.constant 12 : index
|
||||
%c14 = index.constant 14 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%lane_col = index.div %lane, %c16 : index
|
||||
%lane_row = index.rem %lane, %c16 : index
|
||||
%row = index.add %row0, %lane_row : index
|
||||
%col_e0 = index.add %col0, %lane_col : index
|
||||
%col_e1 = index.add %col_e0, %c2 : index
|
||||
%col_e2 = index.add %col_e0, %c4 : index
|
||||
%col_e3 = index.add %col_e0, %c6 : index
|
||||
%col_e4 = index.add %col_e0, %c8 : index
|
||||
%col_e5 = index.add %col_e0, %c10 : index
|
||||
%col_e6 = index.add %col_e0, %c12 : index
|
||||
%col_e7 = index.add %col_e0, %c14 : index
|
||||
%v0 = vector.extract %acc[0] : vector<8xf32> -> f32
|
||||
%v1 = vector.extract %acc[1] : vector<8xf32> -> f32
|
||||
%v2 = vector.extract %acc[2] : vector<8xf32> -> f32
|
||||
%v3 = vector.extract %acc[3] : vector<8xf32> -> f32
|
||||
%v4 = vector.extract %acc[4] : vector<8xf32> -> f32
|
||||
%v5 = vector.extract %acc[5] : vector<8xf32> -> f32
|
||||
%v6 = vector.extract %acc[6] : vector<8xf32> -> f32
|
||||
%v7 = vector.extract %acc[7] : vector<8xf32> -> f32
|
||||
func.call @ggml_hrx_mm_wmma_store1(%dst, %d_span, %d_base, %d_s1, %col_e0, %n_cols, %row, %n_rows, %v0) : (buffer, index, index, index, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_wmma_store1(%dst, %d_span, %d_base, %d_s1, %col_e1, %n_cols, %row, %n_rows, %v1) : (buffer, index, index, index, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_wmma_store1(%dst, %d_span, %d_base, %d_s1, %col_e2, %n_cols, %row, %n_rows, %v2) : (buffer, index, index, index, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_wmma_store1(%dst, %d_span, %d_base, %d_s1, %col_e3, %n_cols, %row, %n_rows, %v3) : (buffer, index, index, index, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_wmma_store1(%dst, %d_span, %d_base, %d_s1, %col_e4, %n_cols, %row, %n_rows, %v4) : (buffer, index, index, index, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_wmma_store1(%dst, %d_span, %d_base, %d_s1, %col_e5, %n_cols, %row, %n_rows, %v5) : (buffer, index, index, index, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_wmma_store1(%dst, %d_span, %d_base, %d_s1, %col_e6, %n_cols, %row, %n_rows, %v6) : (buffer, index, index, index, index, index, index, index, f32)
|
||||
func.call @ggml_hrx_mm_wmma_store1(%dst, %d_span, %d_base, %d_s1, %col_e7, %n_cols, %row, %n_rows, %v7) : (buffer, index, index, index, index, index, index, index, f32)
|
||||
func.return
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_wmma_stage_weights64(%wtype: index, %weight: buffer, %w_span: index, %row_base: index, %row_valid: i1, %k: index, %k_size: index, %w_stage: buffer) {
|
||||
%t0 = kernel.workitem.id<x> : index
|
||||
%t = index.assume %t0 [range(%t0, 0, 255)] : index
|
||||
%c1 = index.constant 1 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%row = index.div %t, %c2 : index
|
||||
%pair = index.rem %t, %c2 : index
|
||||
%part0 = index.mul %pair, %c2 : index
|
||||
%part1 = index.add %part0, %c1 : index
|
||||
%k_local0 = index.mul %part0, %c8 : index
|
||||
%k_local0_high = index.add %k_local0, %c32 : index
|
||||
%k_local1 = index.mul %part1, %c8 : index
|
||||
%k_local1_high = index.add %k_local1, %c32 : index
|
||||
%w0_low, %w0_high = template.apply<@ggml.weight.wmma16>(%wtype, %weight, %w_span, %row_base, %row_valid, %k, %k_size, %part0) : (index, buffer, index, index, i1, index, index, index) -> (vector<8xf16>, vector<8xf16>)
|
||||
%w1_low, %w1_high = template.apply<@ggml.weight.wmma16>(%wtype, %weight, %w_span, %row_base, %row_valid, %k, %k_size, %part1) : (index, buffer, index, index, i1, index, index, index) -> (vector<8xf16>, vector<8xf16>)
|
||||
%w_view = buffer.view %w_stage[%c0_offset] : buffer -> view<128x72xf16>
|
||||
vector.store %w0_low, %w_view[%row, %k_local0] : vector<8xf16>, view<128x72xf16>
|
||||
vector.store %w0_high, %w_view[%row, %k_local0_high] : vector<8xf16>, view<128x72xf16>
|
||||
vector.store %w1_low, %w_view[%row, %k_local1] : vector<8xf16>, view<128x72xf16>
|
||||
vector.store %w1_high, %w_view[%row, %k_local1_high] : vector<8xf16>, view<128x72xf16>
|
||||
func.return
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_wmma_input8(%input: buffer, %x_span: index, %col_base: index, %col_valid: i1, %k: index, %k_size: index) -> (vector<8xf16>) {
|
||||
%c7 = index.constant 7 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%zero8 = vector.splatf 0.0 : vector<8xf32>
|
||||
%input_view = buffer.view %input[%c0_offset] : buffer -> view<[%x_span]xf32>
|
||||
%values = scf.if %col_valid -> (vector<8xf32>) {
|
||||
%k_in = index.cmp ult, %k, %k_size : index
|
||||
%k_values = scf.if %k_in -> (vector<8xf32>) {
|
||||
%index0 = index.add %col_base, %k : index
|
||||
%index = index.assume %index0 [range(%index0, 0, 2147483646)] : index
|
||||
%last0 = index.add %index, %c7 : index
|
||||
%last = index.assume %last0 [range(%last0, 0, 2147483646)] : index
|
||||
%in_span = index.cmp ult, %last, %x_span : index
|
||||
%loaded = scf.if %in_span -> (vector<8xf32>) {
|
||||
%v = vector.load %input_view[%index] : view<[%x_span]xf32> -> vector<8xf32>
|
||||
scf.yield %v : vector<8xf32>
|
||||
} else {
|
||||
scf.yield %zero8 : vector<8xf32>
|
||||
}
|
||||
scf.yield %loaded : vector<8xf32>
|
||||
} else {
|
||||
scf.yield %zero8 : vector<8xf32>
|
||||
}
|
||||
scf.yield %k_values : vector<8xf32>
|
||||
} else {
|
||||
scf.yield %zero8 : vector<8xf32>
|
||||
}
|
||||
%values_f16 = vector.fptrunc %values : vector<8xf32> to vector<8xf16>
|
||||
func.return %values_f16 : vector<8xf16>
|
||||
}
|
||||
|
||||
func.def inline @ggml_hrx_mm_wmma_stage_input64(%input: buffer, %x_span: index, %col_base: index, %col_valid: i1, %k: index, %k_size: index, %x_stage: buffer) {
|
||||
%t0 = kernel.workitem.id<x> : index
|
||||
%t = index.assume %t0 [range(%t0, 0, 255)] : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%col = index.div %t, %c4 : index
|
||||
%part = index.rem %t, %c4 : index
|
||||
%k_local0 = index.mul %part, %c16 : index
|
||||
%k_local1 = index.add %k_local0, %c8 : index
|
||||
%k0 = index.add %k, %k_local0 : index
|
||||
%k1 = index.add %k, %k_local1 : index
|
||||
%x0 = func.call @ggml_hrx_mm_wmma_input8(%input, %x_span, %col_base, %col_valid, %k0, %k_size) : (buffer, index, index, i1, index, index) -> (vector<8xf16>)
|
||||
%x1 = func.call @ggml_hrx_mm_wmma_input8(%input, %x_span, %col_base, %col_valid, %k1, %k_size) : (buffer, index, index, i1, index, index) -> (vector<8xf16>)
|
||||
%x_view = buffer.view %x_stage[%c0_offset] : buffer -> view<64x72xf16>
|
||||
vector.store %x0, %x_view[%col, %k_local0] : vector<8xf16>, view<64x72xf16>
|
||||
vector.store %x1, %x_view[%col, %k_local1] : vector<8xf16>, view<64x72xf16>
|
||||
func.return
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
// Weight strides and span are in weight units (see lib/mm_core.loom). Input and dst strides are in elements.
|
||||
// All kernels have the same launch arguments.
|
||||
|
||||
config.decl @ggml.mul_mat.weight_type : %value: index where [range(%value, 2, 2)]
|
||||
|
||||
// ggml_mul_mat_vec_xs unrolls one dot product for each column.
|
||||
config.decl @ggml.mul_mat.vec_cols : %value: index where [range(%value, 1, 8)]
|
||||
|
||||
config.decl @ggml.mul_mat.vec_xs_workgroups : %value: index where [range(%value, 1, 65536)]
|
||||
|
||||
config.decl @ggml.mul_mat.vec_xs_depth : %value: index where [range(%value, 1, 4)]
|
||||
|
||||
// 1: the last superblock is partial.
|
||||
config.decl @ggml.mul_mat.vec_k_tail : %value: index where [range(%value, 0, 1)]
|
||||
|
||||
target.decl @ggml_wave64
|
||||
|
||||
target.decl @ggml_wave32
|
||||
|
||||
// @ggml.weight.offsets16 gives the same offsets as @ggml.weight.part16.
|
||||
template.decl @ggml.weight.offsets16(%wtype: index, %part: index) -> (index, index, index, index)
|
||||
|
||||
template.decl @ggml.weight.part16(%wtype: index, %weight: buffer, %sb_byte: offset, %part: index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, index, index, index, index)
|
||||
|
||||
template.decl @ggml.weight.superblock(%wtype: index) -> (offset, offset, index)
|
||||
|
||||
func.decl @ggml_hrx_mm_tile(%wtype: index, %k_size: index, %w_base0: index, %w_valid0: i1, %w_base1: index, %w_valid1: i1, %x_base0: index, %x_valid0: i1, %x_base1: index, %x_valid1: i1, %x_base2: index, %x_valid2: i1, %x_base3: index, %x_valid3: i1, %x_s0: index, %w_span: index, %x_span: index, %weight: buffer, %input: buffer, %w_stage: buffer, %x_stage: buffer) -> (vector<4xf32>, vector<4xf32>)
|
||||
|
||||
func.decl @ggml_hrx_mm_store(%dst: buffer, %d_span: index, %index: index, %value: f32)
|
||||
|
||||
func.decl @ggml_hrx_mv_col_base(%i: index, %n_tile: index, %n_cols: index, %x_batch: index, %x_s1: index, %k_size: index, %x_span: index, %ok_in: i1) -> (index, i1, i1, i1)
|
||||
|
||||
func.decl @ggml_hrx_mv_xload(%use: i1, %input: buffer, %x_base: index, %sb: index, %o0: index, %o1: index, %o2: index, %o3: index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
|
||||
func.decl @ggml_hrx_mv_dot16(%use: i1, %w0: vector<4xf32>, %w1: vector<4xf32>, %w2: vector<4xf32>, %w3: vector<4xf32>, %x0: vector<4xf32>, %x1: vector<4xf32>, %x2: vector<4xf32>, %x3: vector<4xf32>) -> (f32)
|
||||
|
||||
func.decl @ggml_hrx_mm_store4(%dst: buffer, %d_span: index, %d_col_base: index, %row0: index, %n_rows: index, %col_valid: i1, %values: vector<4xf32>)
|
||||
|
||||
func.def inline @ggml_hrx_mul_mat_batch(%batch: index, %ne12: index, %r2: index, %r3: index, %w_s2: index, %w_s3: index, %x_s2: index, %x_s3: index, %d_s2: index, %d_s3: index) -> (index, index, index) {
|
||||
%i12 = index.rem %batch, %ne12 : index
|
||||
%i13 = index.div %batch, %ne12 : index
|
||||
%i02 = index.div %i12, %r2 : index
|
||||
%i03 = index.div %i13, %r3 : index
|
||||
%w2 = index.mul %i02, %w_s2 : index
|
||||
%w3 = index.mul %i03, %w_s3 : index
|
||||
%w_base = index.add %w2, %w3 : index
|
||||
%x2 = index.mul %i12, %x_s2 : index
|
||||
%x3 = index.mul %i13, %x_s3 : index
|
||||
%x_base = index.add %x2, %x3 : index
|
||||
%d2 = index.mul %i12, %d_s2 : index
|
||||
%d3 = index.mul %i13, %d_s3 : index
|
||||
%d_base = index.add %d2, %d3 : index
|
||||
func.return %w_base, %x_base, %d_base : index, index, index
|
||||
}
|
||||
|
||||
// vec_xs_workgroups is a multiple of the CU count. Fewer workgroups give a long tail.
|
||||
func.def inline @ggml_hrx_mv_xs_plan(%n_rows: index, %k_size: index) -> (index, index, index, index) {
|
||||
%c0 = index.constant 0 : index
|
||||
%c1 = index.constant 1 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%n_wg_target = config.get @ggml.mul_mat.vec_xs_workgroups : index
|
||||
%n_wg_target_m1 = index.sub %n_wg_target, %c1 : index
|
||||
%c255 = index.constant 255 : index
|
||||
%c256 = index.constant 256 : index
|
||||
%k_tail = config.get @ggml.mul_mat.vec_k_tail : index
|
||||
%k_pad = index.mul %k_tail, %c255 : index
|
||||
%k_round = index.add %k_size, %k_pad : index
|
||||
%n_sb0 = index.div %k_round, %c256 : index
|
||||
%n_sb1 = index.min %n_sb0, %c16 : index
|
||||
%no_sb = index.cmp eq, %n_sb1, %c0 : index
|
||||
%n_sb2 = scf.select %no_sb, %c1, %n_sb1 : index
|
||||
%n_sb = index.assume %n_sb2 [range(%n_sb2, 1, 16)] : index
|
||||
%rows_par0 = index.div %c16, %n_sb : index
|
||||
%rows_par = index.assume %rows_par0 [range(%rows_par0, 1, 16)] : index
|
||||
%rows_par_m1 = index.sub %rows_par, %c1 : index
|
||||
%rows_round = index.add %n_rows, %rows_par_m1 : index
|
||||
%total_pass = index.div %rows_round, %rows_par : index
|
||||
%pass_round = index.add %total_pass, %n_wg_target_m1 : index
|
||||
%n_pass0 = index.div %pass_round, %n_wg_target : index
|
||||
%n_pass1 = index.min %n_pass0, %c32 : index
|
||||
// Each workgroup loads all activations once. Thus use at least 4 passes when this keeps 16 workgroups.
|
||||
%c4 = index.constant 4 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%many_pass = index.cmp uge, %total_pass, %c64 : index
|
||||
%min_pass = scf.select %many_pass, %c4, %c1 : index
|
||||
%few_pass = index.cmp ult, %n_pass1, %min_pass : index
|
||||
%n_pass2 = scf.select %few_pass, %min_pass, %n_pass1 : index
|
||||
%n_pass = index.assume %n_pass2 [range(%n_pass2, 1, 32)] : index
|
||||
%n_pass_m1 = index.sub %n_pass, %c1 : index
|
||||
%wg_round = index.add %total_pass, %n_pass_m1 : index
|
||||
%n_wg = index.div %wg_round, %n_pass : index
|
||||
func.return %n_sb, %rows_par, %n_pass, %n_wg : index, index, index, index
|
||||
}
|
||||
|
||||
// Callers keep p < 32, col < 8 and slot < 16. Thus the index is below 4096.
|
||||
func.def inline @ggml_hrx_mv_xs_stage_index(%p: index, %col: index, %slot: index) -> (index) {
|
||||
%c7 = index.constant 7 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c15 = index.constant 15 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c31 = index.constant 31 : index
|
||||
%p_min = index.min %p, %c31 : index
|
||||
%col_min = index.min %col, %c7 : index
|
||||
%slot_min = index.min %slot, %c15 : index
|
||||
%p_in = index.assume %p_min [range(%p_min, 0, 31)] : index
|
||||
%col_in = index.assume %col_min [range(%col_min, 0, 7)] : index
|
||||
%slot_in = index.assume %slot_min [range(%slot_min, 0, 15)] : index
|
||||
%p_cols = index.mul %p_in, %c8 : index
|
||||
%p_col = index.add %p_cols, %col_in : index
|
||||
%p_slots = index.mul %p_col, %c16 : index
|
||||
%index = index.add %p_slots, %slot_in : index
|
||||
func.return %index : index
|
||||
}
|
||||
|
||||
// For few input columns and K <= 4096. The activations stay in registers for all passes of a workgroup.
|
||||
// The caller makes sure that K is a multiple of 256 (32 with vec_k_tail) and that x is contiguous along K.
|
||||
kernel.def target(@ggml_wave32) export("ggml_mul_mat_vec_xs") @ggml_mul_mat_vec_xs(%n_rows: index, %k_size: index, %n_batch: index) {
|
||||
// Launch configuration cannot call functions. Thus this repeats @ggml_hrx_mv_xs_plan.
|
||||
%c0 = index.constant 0 : index
|
||||
%one = index.constant 1 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%n_wg_target = config.get @ggml.mul_mat.vec_xs_workgroups : index
|
||||
%n_wg_target_m1 = index.sub %n_wg_target, %one : index
|
||||
%wg_size = index.constant 256 : index
|
||||
%c255 = index.constant 255 : index
|
||||
%k_tail = config.get @ggml.mul_mat.vec_k_tail : index
|
||||
%k_pad = index.mul %k_tail, %c255 : index
|
||||
%k_round = index.add %k_size, %k_pad : index
|
||||
%n_sb0 = index.div %k_round, %wg_size : index
|
||||
%n_sb1 = index.min %n_sb0, %c16 : index
|
||||
%no_sb = index.cmp eq, %n_sb1, %c0 : index
|
||||
%n_sb2 = scf.select %no_sb, %one, %n_sb1 : index
|
||||
%n_sb = index.assume %n_sb2 [range(%n_sb2, 1, 16)] : index
|
||||
%rows_par0 = index.div %c16, %n_sb : index
|
||||
%rows_par = index.assume %rows_par0 [range(%rows_par0, 1, 16)] : index
|
||||
%rows_par_m1 = index.sub %rows_par, %one : index
|
||||
%rows_round = index.add %n_rows, %rows_par_m1 : index
|
||||
%total_pass = index.div %rows_round, %rows_par : index
|
||||
%pass_round = index.add %total_pass, %n_wg_target_m1 : index
|
||||
%n_pass0 = index.div %pass_round, %n_wg_target : index
|
||||
%n_pass1 = index.min %n_pass0, %c32 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%many_pass = index.cmp uge, %total_pass, %c64 : index
|
||||
%min_pass = scf.select %many_pass, %c4, %one : index
|
||||
%few_pass = index.cmp ult, %n_pass1, %min_pass : index
|
||||
%n_pass2 = scf.select %few_pass, %min_pass, %n_pass1 : index
|
||||
%n_pass = index.assume %n_pass2 [range(%n_pass2, 1, 32)] : index
|
||||
%n_pass_m1 = index.sub %n_pass, %one : index
|
||||
%wg_round = index.add %total_pass, %n_pass_m1 : index
|
||||
%n_wg = index.div %wg_round, %n_pass : index
|
||||
kernel.launch.config workgroups(%n_wg, %one, %n_batch) workgroup_size(%wg_size, %one, %one) : index
|
||||
} launch(%k_size_in: index, %n_rows_in: index, %n_cols_in: index, %ne12_in: index, %r2_in: index, %r3_in: index, %w_s1_in: index, %w_s2_in: index, %w_s3_in: index, %w_span_in: index, %x_s0_in: index, %x_s1_in: index, %x_s2_in: index, %x_s3_in: index, %x_span_in: index, %d_s1_in: index, %d_s2_in: index, %d_s3_in: index, %d_span_in: index, %weight: buffer, %input: buffer, %dst: buffer) {
|
||||
// supports_mul_mat checks these ranges.
|
||||
%k_size = index.assume %k_size_in [range(%k_size_in, 1, 2147483647)] : index
|
||||
%n_rows = index.assume %n_rows_in [range(%n_rows_in, 1, 2147483647)] : index
|
||||
%n_cols = index.assume %n_cols_in [range(%n_cols_in, 1, 2147483647)] : index
|
||||
%ne12 = index.assume %ne12_in [range(%ne12_in, 1, 2147483647)] : index
|
||||
%r2 = index.assume %r2_in [range(%r2_in, 1, 2147483647)] : index
|
||||
%r3 = index.assume %r3_in [range(%r3_in, 1, 2147483647)] : index
|
||||
%w_s1 = index.assume %w_s1_in [range(%w_s1_in, 0, 2147483647)] : index
|
||||
%w_s2 = index.assume %w_s2_in [range(%w_s2_in, 0, 2147483647)] : index
|
||||
%w_s3 = index.assume %w_s3_in [range(%w_s3_in, 0, 2147483647)] : index
|
||||
%w_span = index.assume %w_span_in [range(%w_span_in, 1, 2147483647)] : index
|
||||
%x_s1 = index.assume %x_s1_in [range(%x_s1_in, 0, 2147483647)] : index
|
||||
%x_s2 = index.assume %x_s2_in [range(%x_s2_in, 0, 2147483647)] : index
|
||||
%x_s3 = index.assume %x_s3_in [range(%x_s3_in, 0, 2147483647)] : index
|
||||
%x_span = index.assume %x_span_in [range(%x_span_in, 1, 2147483647)] : index
|
||||
%d_s1 = index.assume %d_s1_in [range(%d_s1_in, 0, 2147483647)] : index
|
||||
%d_s2 = index.assume %d_s2_in [range(%d_s2_in, 0, 2147483647)] : index
|
||||
%d_s3 = index.assume %d_s3_in [range(%d_s3_in, 0, 2147483647)] : index
|
||||
%d_span = index.assume %d_span_in [range(%d_span_in, 1, 2147483647)] : index
|
||||
%wtype = config.get @ggml.mul_mat.weight_type : index
|
||||
%n_tile = config.get @ggml.mul_mat.vec_cols : index
|
||||
%c0 = index.constant 0 : index
|
||||
%c1 = index.constant 1 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c3 = index.constant 3 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c5 = index.constant 5 : index
|
||||
%c6 = index.constant 6 : index
|
||||
%c7 = index.constant 7 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c256 = index.constant 256 : index
|
||||
%c4096 = index.constant 4096 : index
|
||||
%stage_bytes = index.constant 16384 : offset
|
||||
%b0 = index.constant 0 : offset
|
||||
%zero = scalar.constant 0.0 : f32
|
||||
%zero4 = vector.splatf 0.0 : vector<4xf32>
|
||||
%true = scalar.constant true : i1
|
||||
%false = scalar.constant false : i1
|
||||
%depth = config.get @ggml.mul_mat.vec_xs_depth : index
|
||||
%t0 = kernel.workitem.id<x> : index
|
||||
%t = index.assume %t0 [range(%t0, 0, 255)] : index
|
||||
%slot = index.div %t, %c16 : index
|
||||
%part = index.rem %t, %c16 : index
|
||||
%wg = kernel.workgroup.id<x> : index
|
||||
%batch = kernel.workgroup.id<z> : index
|
||||
%weight_noalias, %input_noalias, %dst_noalias = buffer.assume.noalias %weight, %input, %dst : buffer, buffer, buffer
|
||||
%stage = buffer.alloca<workgroup> align(16) %stage_bytes : buffer
|
||||
%stage_view = buffer.view %stage[%b0] : buffer -> view<4096xf32>
|
||||
%unit_bytes, %sb_bytes, %sb_units = template.apply<@ggml.weight.superblock>(%wtype) : (index) -> (offset, offset, index)
|
||||
%n_sb, %rows_par, %n_pass, %n_wg = func.call @ggml_hrx_mv_xs_plan(%n_rows, %k_size) : (index, index) -> (index, index, index, index)
|
||||
%row_off = index.div %slot, %n_sb : index
|
||||
%sb = index.rem %slot, %n_sb : index
|
||||
%slot_on = index.cmp ult, %row_off, %rows_par : index
|
||||
%pass0 = index.mul %wg, %n_pass : index
|
||||
%row0 = index.mul %pass0, %rows_par : index
|
||||
%wg_rows = index.mul %n_pass, %rows_par : index
|
||||
%row_end_raw = index.add %row0, %wg_rows : index
|
||||
%row_end = index.min %row_end_raw, %n_rows : index
|
||||
%last_row = index.sub %row_end, %c1 : index
|
||||
%w_batch, %x_batch, %d_batch = func.call @ggml_hrx_mul_mat_batch(%batch, %ne12, %r2, %r3, %w_s2, %w_s3, %x_s2, %x_s3, %d_s2, %d_s3) : (index, index, index, index, index, index, index, index, index, index) -> (index, index, index)
|
||||
// If the last row is in the weight span, all rows of the workgroup are in it.
|
||||
%w_last_offset = index.mul %last_row, %w_s1 : index
|
||||
%w_last_base = index.add %w_batch, %w_last_offset : index
|
||||
%k_tail = config.get @ggml.mul_mat.vec_k_tail : index
|
||||
%has_tail = index.cmp ne, %k_tail, %c0 : index
|
||||
%full_units = index.mul %n_sb, %sb_units : index
|
||||
%k_units = index.mul %k_size, %sb_units : index
|
||||
%tail_units = index.div %k_units, %c256 : index
|
||||
%row_units = scf.select %has_tail, %tail_units, %full_units : index
|
||||
%w_last_end = index.add %w_last_base, %row_units : index
|
||||
%w_ok = index.cmp ule, %w_last_end, %w_span : index
|
||||
%x_base0, %use0, %store0, %x_ok0 = func.call @ggml_hrx_mv_col_base(%c0, %n_tile, %n_cols, %x_batch, %x_s1, %k_size, %x_span, %true) : (index, index, index, index, index, index, index, i1) -> (index, i1, i1, i1)
|
||||
%x_base1, %use1, %store1, %x_ok1 = func.call @ggml_hrx_mv_col_base(%c1, %n_tile, %n_cols, %x_batch, %x_s1, %k_size, %x_span, %x_ok0) : (index, index, index, index, index, index, index, i1) -> (index, i1, i1, i1)
|
||||
%x_base2, %use2, %store2, %x_ok2 = func.call @ggml_hrx_mv_col_base(%c2, %n_tile, %n_cols, %x_batch, %x_s1, %k_size, %x_span, %x_ok1) : (index, index, index, index, index, index, index, i1) -> (index, i1, i1, i1)
|
||||
%x_base3, %use3, %store3, %x_ok3 = func.call @ggml_hrx_mv_col_base(%c3, %n_tile, %n_cols, %x_batch, %x_s1, %k_size, %x_span, %x_ok2) : (index, index, index, index, index, index, index, i1) -> (index, i1, i1, i1)
|
||||
%x_base4, %use4, %store4, %x_ok4 = func.call @ggml_hrx_mv_col_base(%c4, %n_tile, %n_cols, %x_batch, %x_s1, %k_size, %x_span, %x_ok3) : (index, index, index, index, index, index, index, i1) -> (index, i1, i1, i1)
|
||||
%x_base5, %use5, %store5, %x_ok5 = func.call @ggml_hrx_mv_col_base(%c5, %n_tile, %n_cols, %x_batch, %x_s1, %k_size, %x_span, %x_ok4) : (index, index, index, index, index, index, index, i1) -> (index, i1, i1, i1)
|
||||
%x_base6, %use6, %store6, %x_ok6 = func.call @ggml_hrx_mv_col_base(%c6, %n_tile, %n_cols, %x_batch, %x_s1, %k_size, %x_span, %x_ok5) : (index, index, index, index, index, index, index, i1) -> (index, i1, i1, i1)
|
||||
%x_base7, %use7, %store7, %x_ok = func.call @ggml_hrx_mv_col_base(%c7, %n_tile, %n_cols, %x_batch, %x_s1, %k_size, %x_span, %x_ok6) : (index, index, index, index, index, index, index, i1) -> (index, i1, i1, i1)
|
||||
%ok = scf.select %w_ok, %x_ok, %false : i1
|
||||
scf.if %ok {
|
||||
%o0, %o1, %o2, %o3 = template.apply<@ggml.weight.offsets16>(%wtype, %part) : (index, index) -> (index, index, index, index)
|
||||
// A lane past K in the partial superblock loads no data. The dot products stay uniform in each group of 16 lanes.
|
||||
%sb_k = index.mul %sb, %c256 : index
|
||||
%lane_last = index.add %o3, %c4 : index
|
||||
%lane_end = index.add %sb_k, %lane_last : index
|
||||
%lane_in = index.cmp ule, %lane_end, %k_size : index
|
||||
%lane_ok = scf.select %has_tail, %lane_in, %true : i1
|
||||
%xu0 = scf.select %lane_ok, %use0, %false : i1
|
||||
%xu1 = scf.select %lane_ok, %use1, %false : i1
|
||||
%xu2 = scf.select %lane_ok, %use2, %false : i1
|
||||
%xu3 = scf.select %lane_ok, %use3, %false : i1
|
||||
%xu4 = scf.select %lane_ok, %use4, %false : i1
|
||||
%xu5 = scf.select %lane_ok, %use5, %false : i1
|
||||
%xu6 = scf.select %lane_ok, %use6, %false : i1
|
||||
%xu7 = scf.select %lane_ok, %use7, %false : i1
|
||||
%x00, %x01, %x02, %x03 = func.call @ggml_hrx_mv_xload(%xu0, %input_noalias, %x_base0, %sb, %o0, %o1, %o2, %o3) : (i1, buffer, index, index, index, index, index, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
%x10, %x11, %x12, %x13 = func.call @ggml_hrx_mv_xload(%xu1, %input_noalias, %x_base1, %sb, %o0, %o1, %o2, %o3) : (i1, buffer, index, index, index, index, index, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
%x20, %x21, %x22, %x23 = func.call @ggml_hrx_mv_xload(%xu2, %input_noalias, %x_base2, %sb, %o0, %o1, %o2, %o3) : (i1, buffer, index, index, index, index, index, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
%x30, %x31, %x32, %x33 = func.call @ggml_hrx_mv_xload(%xu3, %input_noalias, %x_base3, %sb, %o0, %o1, %o2, %o3) : (i1, buffer, index, index, index, index, index, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
%x40, %x41, %x42, %x43 = func.call @ggml_hrx_mv_xload(%xu4, %input_noalias, %x_base4, %sb, %o0, %o1, %o2, %o3) : (i1, buffer, index, index, index, index, index, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
%x50, %x51, %x52, %x53 = func.call @ggml_hrx_mv_xload(%xu5, %input_noalias, %x_base5, %sb, %o0, %o1, %o2, %o3) : (i1, buffer, index, index, index, index, index, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
%x60, %x61, %x62, %x63 = func.call @ggml_hrx_mv_xload(%xu6, %input_noalias, %x_base6, %sb, %o0, %o1, %o2, %o3) : (i1, buffer, index, index, index, index, index, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
%x70, %x71, %x72, %x73 = func.call @ggml_hrx_mv_xload(%xu7, %input_noalias, %x_base7, %sb, %o0, %o1, %o2, %o3) : (i1, buffer, index, index, index, index, index, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>)
|
||||
%w_batch_byte = index.scale %w_batch, %unit_bytes : index, offset -> offset
|
||||
%sb_offset = index.scale %sb, %sb_bytes : index, offset -> offset
|
||||
%w_sb_byte = index.add %w_batch_byte, %sb_offset : offset
|
||||
%in_tile = index.cmp ult, %part, %n_tile : index
|
||||
%writer = scf.select %slot_on, %in_tile, %false : i1
|
||||
%is1 = index.cmp eq, %part, %c1 : index
|
||||
%is2 = index.cmp eq, %part, %c2 : index
|
||||
%is3 = index.cmp eq, %part, %c3 : index
|
||||
%is4 = index.cmp eq, %part, %c4 : index
|
||||
%is5 = index.cmp eq, %part, %c5 : index
|
||||
%is6 = index.cmp eq, %part, %c6 : index
|
||||
%is7 = index.cmp eq, %part, %c7 : index
|
||||
scf.for %p = [%c0 to %n_pass step %c1] pipeline(%depth) {
|
||||
// A row past the end reads the last row. The final sum skips its partial.
|
||||
%pass = index.add %pass0, %p : index
|
||||
%pass_row = index.mul %pass, %rows_par : index
|
||||
%row_raw = index.add %pass_row, %row_off : index
|
||||
%row_in = index.cmp ult, %row_raw, %n_rows : index
|
||||
%row = scf.select %row_in, %row_raw, %last_row : index
|
||||
%w_row = index.mul %row, %w_s1 : index
|
||||
%w_row_byte = index.scale %w_row, %unit_bytes : index, offset -> offset
|
||||
%sb_byte = index.add %w_sb_byte, %w_row_byte : offset
|
||||
%d0, %d1, %d2, %d3 = scf.if %lane_ok -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) {
|
||||
%e0, %e1, %e2, %e3, %q0, %q1, %q2, %q3 = template.apply<@ggml.weight.part16>(%wtype, %weight_noalias, %sb_byte, %part) : (index, buffer, offset, index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, index, index, index, index)
|
||||
scf.yield %e0, %e1, %e2, %e3 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>
|
||||
} else {
|
||||
scf.yield %zero4, %zero4, %zero4, %zero4 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>
|
||||
}
|
||||
%s0 = func.call @ggml_hrx_mv_dot16(%use0, %d0, %d1, %d2, %d3, %x00, %x01, %x02, %x03) : (i1, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) -> (f32)
|
||||
%s1 = func.call @ggml_hrx_mv_dot16(%use1, %d0, %d1, %d2, %d3, %x10, %x11, %x12, %x13) : (i1, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) -> (f32)
|
||||
%s2 = func.call @ggml_hrx_mv_dot16(%use2, %d0, %d1, %d2, %d3, %x20, %x21, %x22, %x23) : (i1, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) -> (f32)
|
||||
%s3 = func.call @ggml_hrx_mv_dot16(%use3, %d0, %d1, %d2, %d3, %x30, %x31, %x32, %x33) : (i1, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) -> (f32)
|
||||
%s4 = func.call @ggml_hrx_mv_dot16(%use4, %d0, %d1, %d2, %d3, %x40, %x41, %x42, %x43) : (i1, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) -> (f32)
|
||||
%s5 = func.call @ggml_hrx_mv_dot16(%use5, %d0, %d1, %d2, %d3, %x50, %x51, %x52, %x53) : (i1, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) -> (f32)
|
||||
%s6 = func.call @ggml_hrx_mv_dot16(%use6, %d0, %d1, %d2, %d3, %x60, %x61, %x62, %x63) : (i1, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) -> (f32)
|
||||
%s7 = func.call @ggml_hrx_mv_dot16(%use7, %d0, %d1, %d2, %d3, %x70, %x71, %x72, %x73) : (i1, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>) -> (f32)
|
||||
%v1 = scf.select %is1, %s1, %s0 : f32
|
||||
%v2 = scf.select %is2, %s2, %v1 : f32
|
||||
%v3 = scf.select %is3, %s3, %v2 : f32
|
||||
%v4 = scf.select %is4, %s4, %v3 : f32
|
||||
%v5 = scf.select %is5, %s5, %v4 : f32
|
||||
%v6 = scf.select %is6, %s6, %v5 : f32
|
||||
%v7 = scf.select %is7, %s7, %v6 : f32
|
||||
scf.if %writer {
|
||||
%i_raw = func.call @ggml_hrx_mv_xs_stage_index(%p, %part, %slot) : (index, index, index) -> (index)
|
||||
%i = index.assume %i_raw [range(%i_raw, 0, 4095)] : index
|
||||
%i_in = index.cmp ult, %i, %c4096 : index
|
||||
scf.if %i_in {
|
||||
view.store %v7, %stage_view[%i] : f32, view<4096xf32>
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
kernel.barrier<workgroup> scope(workgroup) ordering(acq_rel)
|
||||
scf.if %ok {
|
||||
%n_out = index.mul %wg_rows, %n_tile : index
|
||||
scf.for %o_raw = [%t to %n_out step %c256] {
|
||||
%o = index.assume %o_raw [range(%o_raw, 0, 4095)] : index
|
||||
%row_local = index.div %o, %n_tile : index
|
||||
%col = index.rem %o, %n_tile : index
|
||||
%p = index.div %row_local, %rows_par : index
|
||||
%ro = index.rem %row_local, %rows_par : index
|
||||
%row = index.add %row0, %row_local : index
|
||||
%row_in = index.cmp ult, %row, %n_rows : index
|
||||
%col_in = index.cmp ult, %col, %n_cols : index
|
||||
%st = scf.select %row_in, %col_in, %false : i1
|
||||
scf.if %st {
|
||||
%ro_slots = index.mul %ro, %n_sb : index
|
||||
%sum = scf.for %j = [%c0 to %n_sb step %c1](%acc = %zero : f32) -> (f32) {
|
||||
%slot_j = index.add %ro_slots, %j : index
|
||||
%i_raw = func.call @ggml_hrx_mv_xs_stage_index(%p, %col, %slot_j) : (index, index, index) -> (index)
|
||||
%i = index.assume %i_raw [range(%i_raw, 0, 4095)] : index
|
||||
%i_in = index.cmp ult, %i, %c4096 : index
|
||||
%next = scf.if %i_in -> (f32) {
|
||||
%part_sum = view.load %stage_view[%i] : view<4096xf32> -> f32
|
||||
%a = scalar.addf %acc, %part_sum : f32
|
||||
scf.yield %a : f32
|
||||
} else {
|
||||
scf.yield %acc : f32
|
||||
}
|
||||
scf.yield %next : f32
|
||||
}
|
||||
%d_offset = index.mul %col, %d_s1 : index
|
||||
%d_col = index.add %d_batch, %d_offset : index
|
||||
%d_index = index.add %d_col, %row : index
|
||||
func.call @ggml_hrx_mm_store(%dst_noalias, %d_span, %d_index, %sum) : (buffer, index, index, f32)
|
||||
}
|
||||
}
|
||||
}
|
||||
kernel.return
|
||||
}
|
||||
|
||||
kernel.def target(@ggml_wave64) export("ggml_mul_mat_tiled") @ggml_mul_mat_tiled(%n_rows: index, %n_cols: index, %n_batch: index) {
|
||||
%one = index.constant 1 : index
|
||||
%wg_size = index.constant 256 : index
|
||||
%c31 = index.constant 31 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%c63 = index.constant 63 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%rows_round = index.add %n_rows, %c63 : index
|
||||
%row_tiles = index.div %rows_round, %c64 : index
|
||||
%cols_round = index.add %n_cols, %c31 : index
|
||||
%col_tiles = index.div %cols_round, %c32 : index
|
||||
kernel.launch.config workgroups(%row_tiles, %col_tiles, %n_batch) workgroup_size(%wg_size, %one, %one) : index
|
||||
} launch(%k_size_in: index, %n_rows_in: index, %n_cols_in: index, %ne12_in: index, %r2_in: index, %r3_in: index, %w_s1_in: index, %w_s2_in: index, %w_s3_in: index, %w_span_in: index, %x_s0_in: index, %x_s1_in: index, %x_s2_in: index, %x_s3_in: index, %x_span_in: index, %d_s1_in: index, %d_s2_in: index, %d_s3_in: index, %d_span_in: index, %weight: buffer, %input: buffer, %dst: buffer) {
|
||||
// supports_mul_mat checks these ranges.
|
||||
%k_size = index.assume %k_size_in [range(%k_size_in, 1, 2147483647)] : index
|
||||
%n_rows = index.assume %n_rows_in [range(%n_rows_in, 1, 2147483647)] : index
|
||||
%n_cols = index.assume %n_cols_in [range(%n_cols_in, 1, 2147483647)] : index
|
||||
%ne12 = index.assume %ne12_in [range(%ne12_in, 1, 2147483647)] : index
|
||||
%r2 = index.assume %r2_in [range(%r2_in, 1, 2147483647)] : index
|
||||
%r3 = index.assume %r3_in [range(%r3_in, 1, 2147483647)] : index
|
||||
%w_s1 = index.assume %w_s1_in [range(%w_s1_in, 0, 2147483647)] : index
|
||||
%w_s2 = index.assume %w_s2_in [range(%w_s2_in, 0, 2147483647)] : index
|
||||
%w_s3 = index.assume %w_s3_in [range(%w_s3_in, 0, 2147483647)] : index
|
||||
%w_span = index.assume %w_span_in [range(%w_span_in, 1, 2147483647)] : index
|
||||
%x_s0 = index.assume %x_s0_in [range(%x_s0_in, 0, 2147483647)] : index
|
||||
%x_s1 = index.assume %x_s1_in [range(%x_s1_in, 0, 2147483647)] : index
|
||||
%x_s2 = index.assume %x_s2_in [range(%x_s2_in, 0, 2147483647)] : index
|
||||
%x_s3 = index.assume %x_s3_in [range(%x_s3_in, 0, 2147483647)] : index
|
||||
%x_span = index.assume %x_span_in [range(%x_span_in, 1, 2147483647)] : index
|
||||
%d_s1 = index.assume %d_s1_in [range(%d_s1_in, 0, 2147483647)] : index
|
||||
%d_s2 = index.assume %d_s2_in [range(%d_s2_in, 0, 2147483647)] : index
|
||||
%d_s3 = index.assume %d_s3_in [range(%d_s3_in, 0, 2147483647)] : index
|
||||
%d_span = index.assume %d_span_in [range(%d_span_in, 1, 2147483647)] : index
|
||||
%wtype = config.get @ggml.mul_mat.weight_type : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c24 = index.constant 24 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%w_stage_bytes = index.constant 8192 : offset
|
||||
%x_stage_bytes = index.constant 4224 : offset
|
||||
%t0 = kernel.workitem.id<x> : index
|
||||
%t = index.assume %t0 [range(%t0, 0, 255)] : index
|
||||
%row_tile = kernel.workgroup.id<x> : index
|
||||
%col_tile = kernel.workgroup.id<y> : index
|
||||
%batch = kernel.workgroup.id<z> : index
|
||||
%weight_noalias, %input_noalias, %dst_noalias = buffer.assume.noalias %weight, %input, %dst : buffer, buffer, buffer
|
||||
%w_stage = buffer.alloca<workgroup> align(16) %w_stage_bytes : buffer
|
||||
%x_stage = buffer.alloca<workgroup> align(16) %x_stage_bytes : buffer
|
||||
%w_batch, %x_batch, %d_batch = func.call @ggml_hrx_mul_mat_batch(%batch, %ne12, %r2, %r3, %w_s2, %w_s3, %x_s2, %x_s3, %d_s2, %d_s3) : (index, index, index, index, index, index, index, index, index, index) -> (index, index, index)
|
||||
%tile_row0 = index.mul %row_tile, %c64 : index
|
||||
%tile_col0 = index.mul %col_tile, %c32 : index
|
||||
|
||||
%w_local0 = index.div %t, %c8 : index
|
||||
%w_row0 = index.add %tile_row0, %w_local0 : index
|
||||
%w_row1 = index.add %w_row0, %c32 : index
|
||||
%w_valid0 = index.cmp ult, %w_row0, %n_rows : index
|
||||
%w_valid1 = index.cmp ult, %w_row1, %n_rows : index
|
||||
%w_offset0 = index.mul %w_row0, %w_s1 : index
|
||||
%w_offset1 = index.mul %w_row1, %w_s1 : index
|
||||
%w_base0 = index.add %w_batch, %w_offset0 : index
|
||||
%w_base1 = index.add %w_batch, %w_offset1 : index
|
||||
|
||||
%x_local0 = index.div %t, %c32 : index
|
||||
%x_col0 = index.add %tile_col0, %x_local0 : index
|
||||
%x_col1 = index.add %x_col0, %c8 : index
|
||||
%x_col2 = index.add %x_col0, %c16 : index
|
||||
%x_col3 = index.add %x_col0, %c24 : index
|
||||
%x_valid0 = index.cmp ult, %x_col0, %n_cols : index
|
||||
%x_valid1 = index.cmp ult, %x_col1, %n_cols : index
|
||||
%x_valid2 = index.cmp ult, %x_col2, %n_cols : index
|
||||
%x_valid3 = index.cmp ult, %x_col3, %n_cols : index
|
||||
%x_offset0 = index.mul %x_col0, %x_s1 : index
|
||||
%x_offset1 = index.mul %x_col1, %x_s1 : index
|
||||
%x_offset2 = index.mul %x_col2, %x_s1 : index
|
||||
%x_offset3 = index.mul %x_col3, %x_s1 : index
|
||||
%x_base0 = index.add %x_batch, %x_offset0 : index
|
||||
%x_base1 = index.add %x_batch, %x_offset1 : index
|
||||
%x_base2 = index.add %x_batch, %x_offset2 : index
|
||||
%x_base3 = index.add %x_batch, %x_offset3 : index
|
||||
|
||||
%acc0, %acc1 = func.call @ggml_hrx_mm_tile(%wtype, %k_size, %w_base0, %w_valid0, %w_base1, %w_valid1, %x_base0, %x_valid0, %x_base1, %x_valid1, %x_base2, %x_valid2, %x_base3, %x_valid3, %x_s0, %w_span, %x_span, %weight_noalias, %input_noalias, %w_stage, %x_stage) : (index, index, index, i1, index, i1, index, i1, index, i1, index, i1, index, i1, index, index, index, buffer, buffer, buffer, buffer) -> (vector<4xf32>, vector<4xf32>)
|
||||
|
||||
%out_row_group = index.rem %t, %c16 : index
|
||||
%out_row_local = index.mul %out_row_group, %c4 : index
|
||||
%out_row = index.add %tile_row0, %out_row_local : index
|
||||
%out_local0 = index.div %t, %c16 : index
|
||||
%out_col0 = index.add %tile_col0, %out_local0 : index
|
||||
%out_col1 = index.add %out_col0, %c16 : index
|
||||
%out_valid0 = index.cmp ult, %out_col0, %n_cols : index
|
||||
%out_valid1 = index.cmp ult, %out_col1, %n_cols : index
|
||||
%d_offset0 = index.mul %out_col0, %d_s1 : index
|
||||
%d_offset1 = index.mul %out_col1, %d_s1 : index
|
||||
%d_base0 = index.add %d_batch, %d_offset0 : index
|
||||
%d_base1 = index.add %d_batch, %d_offset1 : index
|
||||
func.call @ggml_hrx_mm_store4(%dst_noalias, %d_span, %d_base0, %out_row, %n_rows, %out_valid0, %acc0) : (buffer, index, index, index, index, i1, vector<4xf32>)
|
||||
func.call @ggml_hrx_mm_store4(%dst_noalias, %d_span, %d_base1, %out_row, %n_rows, %out_valid1, %acc1) : (buffer, index, index, index, index, i1, vector<4xf32>)
|
||||
kernel.return
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
// Weights and activations are rounded to f16. The sums are in f32.
|
||||
// The launch arguments are the same as in mul_mat.loom. The caller makes sure that K is a multiple of 32 and that x_s0 is 1.
|
||||
|
||||
config.decl @ggml.mul_mat.weight_type : %value: index where [range(%value, 2, 2)]
|
||||
|
||||
target.decl @ggml_wave32
|
||||
|
||||
template.decl @ggml.mma.k64_2x2(%x_stage: buffer, %w_stage: buffer, %col0: index, %row0: index, %acc00: vector<8xf32>, %acc01: vector<8xf32>, %acc10: vector<8xf32>, %acc11: vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>)
|
||||
|
||||
template.decl @ggml.mma.zero_acc() -> (vector<8xf32>)
|
||||
|
||||
func.decl @ggml_hrx_mm_wmma_stage_weights64(%wtype: index, %weight: buffer, %w_span: index, %row_base: index, %row_valid: i1, %k: index, %k_size: index, %w_stage: buffer)
|
||||
|
||||
func.decl @ggml_hrx_mm_wmma_stage_input64(%input: buffer, %x_span: index, %col_base: index, %col_valid: i1, %k: index, %k_size: index, %x_stage: buffer)
|
||||
|
||||
func.decl @ggml_hrx_mm_wmma_store(%dst: buffer, %d_span: index, %d_base: index, %d_s1: index, %col0: index, %n_cols: index, %row0: index, %n_rows: index, %acc: vector<8xf32>)
|
||||
|
||||
kernel.def target(@ggml_wave32) export("ggml_mul_mat_wmma") @ggml_mul_mat_wmma(%n_rows: index, %n_cols: index, %n_batch: index) {
|
||||
%one = index.constant 1 : index
|
||||
%wg_size = index.constant 256 : index
|
||||
%c63 = index.constant 63 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%c127 = index.constant 127 : index
|
||||
%c128 = index.constant 128 : index
|
||||
%rows_round = index.add %n_rows, %c127 : index
|
||||
%row_tiles = index.div %rows_round, %c128 : index
|
||||
%cols_round = index.add %n_cols, %c63 : index
|
||||
%col_tiles = index.div %cols_round, %c64 : index
|
||||
kernel.launch.config workgroups(%row_tiles, %col_tiles, %n_batch) workgroup_size(%wg_size, %one, %one) : index
|
||||
} launch(%k_size_in: index, %n_rows_in: index, %n_cols_in: index, %ne12_in: index, %r2_in: index, %r3_in: index, %w_s1_in: index, %w_s2_in: index, %w_s3_in: index, %w_span_in: index, %x_s0_in: index, %x_s1_in: index, %x_s2_in: index, %x_s3_in: index, %x_span_in: index, %d_s1_in: index, %d_s2_in: index, %d_s3_in: index, %d_span_in: index, %weight: buffer, %input: buffer, %dst: buffer) {
|
||||
// supports_mul_mat checks these ranges.
|
||||
%k_size = index.assume %k_size_in [range(%k_size_in, 1, 2147483647)] : index
|
||||
%n_rows = index.assume %n_rows_in [range(%n_rows_in, 1, 2147483647)] : index
|
||||
%n_cols = index.assume %n_cols_in [range(%n_cols_in, 1, 2147483647)] : index
|
||||
%ne12 = index.assume %ne12_in [range(%ne12_in, 1, 2147483647)] : index
|
||||
%r2 = index.assume %r2_in [range(%r2_in, 1, 2147483647)] : index
|
||||
%r3 = index.assume %r3_in [range(%r3_in, 1, 2147483647)] : index
|
||||
%w_s1 = index.assume %w_s1_in [range(%w_s1_in, 0, 2147483647)] : index
|
||||
%w_s2 = index.assume %w_s2_in [range(%w_s2_in, 0, 2147483647)] : index
|
||||
%w_s3 = index.assume %w_s3_in [range(%w_s3_in, 0, 2147483647)] : index
|
||||
%w_span = index.assume %w_span_in [range(%w_span_in, 1, 2147483647)] : index
|
||||
%x_s1 = index.assume %x_s1_in [range(%x_s1_in, 0, 2147483647)] : index
|
||||
%x_s2 = index.assume %x_s2_in [range(%x_s2_in, 0, 2147483647)] : index
|
||||
%x_s3 = index.assume %x_s3_in [range(%x_s3_in, 0, 2147483647)] : index
|
||||
%x_span = index.assume %x_span_in [range(%x_span_in, 1, 2147483647)] : index
|
||||
%d_s1 = index.assume %d_s1_in [range(%d_s1_in, 0, 2147483647)] : index
|
||||
%d_s2 = index.assume %d_s2_in [range(%d_s2_in, 0, 2147483647)] : index
|
||||
%d_s3 = index.assume %d_s3_in [range(%d_s3_in, 0, 2147483647)] : index
|
||||
%d_span = index.assume %d_span_in [range(%d_span_in, 1, 2147483647)] : index
|
||||
%wtype = config.get @ggml.mul_mat.weight_type : index
|
||||
%c0 = index.constant 0 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%c128 = index.constant 128 : index
|
||||
%w_stage_bytes = index.constant 18432 : offset
|
||||
%x_stage_bytes = index.constant 9216 : offset
|
||||
%t0 = kernel.workitem.id<x> : index
|
||||
%t = index.assume %t0 [range(%t0, 0, 255)] : index
|
||||
%s0 = kernel.subgroup.id : index
|
||||
%s = index.assume %s0 [range(%s0, 0, 7)] : index
|
||||
%row_tile = kernel.workgroup.id<x> : index
|
||||
%col_tile = kernel.workgroup.id<y> : index
|
||||
%batch = kernel.workgroup.id<z> : index
|
||||
%weight_noalias, %input_noalias, %dst_noalias = buffer.assume.noalias %weight, %input, %dst : buffer, buffer, buffer
|
||||
%w_stage = buffer.alloca<workgroup> align(16) %w_stage_bytes : buffer
|
||||
%x_stage = buffer.alloca<workgroup> align(16) %x_stage_bytes : buffer
|
||||
|
||||
%i12 = index.rem %batch, %ne12 : index
|
||||
%i13 = index.div %batch, %ne12 : index
|
||||
%i02 = index.div %i12, %r2 : index
|
||||
%i03 = index.div %i13, %r3 : index
|
||||
%w2 = index.mul %i02, %w_s2 : index
|
||||
%w3 = index.mul %i03, %w_s3 : index
|
||||
%w_batch = index.add %w2, %w3 : index
|
||||
%x2 = index.mul %i12, %x_s2 : index
|
||||
%x3 = index.mul %i13, %x_s3 : index
|
||||
%x_batch = index.add %x2, %x3 : index
|
||||
%d2 = index.mul %i12, %d_s2 : index
|
||||
%d3 = index.mul %i13, %d_s3 : index
|
||||
%d_batch = index.add %d2, %d3 : index
|
||||
%tile_row0 = index.mul %row_tile, %c128 : index
|
||||
%tile_col0 = index.mul %col_tile, %c64 : index
|
||||
|
||||
%w_local = index.div %t, %c2 : index
|
||||
%w_row = index.add %tile_row0, %w_local : index
|
||||
%w_valid = index.cmp ult, %w_row, %n_rows : index
|
||||
%w_offset = index.mul %w_row, %w_s1 : index
|
||||
%w_base = index.add %w_batch, %w_offset : index
|
||||
|
||||
%x_local = index.div %t, %c4 : index
|
||||
%x_col = index.add %tile_col0, %x_local : index
|
||||
%x_valid = index.cmp ult, %x_col, %n_cols : index
|
||||
%x_offset = index.mul %x_col, %x_s1 : index
|
||||
%x_base = index.add %x_batch, %x_offset : index
|
||||
|
||||
%sub_col_group = index.rem %s, %c2 : index
|
||||
%sub_row_group = index.div %s, %c2 : index
|
||||
%sub_col0 = index.mul %sub_col_group, %c32 : index
|
||||
%sub_row0 = index.mul %sub_row_group, %c32 : index
|
||||
|
||||
%init = template.apply<@ggml.mma.zero_acc>() : () -> (vector<8xf32>)
|
||||
%acc00, %acc01, %acc10, %acc11 = scf.for %k0 = [%c0 to %k_size step %c64](%a00 = %init : vector<8xf32>, %a01 = %init : vector<8xf32>, %a10 = %init : vector<8xf32>, %a11 = %init : vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>) {
|
||||
func.call @ggml_hrx_mm_wmma_stage_weights64(%wtype, %weight_noalias, %w_span, %w_base, %w_valid, %k0, %k_size, %w_stage) : (index, buffer, index, index, i1, index, index, buffer)
|
||||
func.call @ggml_hrx_mm_wmma_stage_input64(%input_noalias, %x_span, %x_base, %x_valid, %k0, %k_size, %x_stage) : (buffer, index, index, i1, index, index, buffer)
|
||||
kernel.barrier<workgroup> scope(workgroup) ordering(acq_rel)
|
||||
%n00, %n01, %n10, %n11 = template.apply<@ggml.mma.k64_2x2>(%x_stage, %w_stage, %sub_col0, %sub_row0, %a00, %a01, %a10, %a11) : (buffer, buffer, index, index, vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>)
|
||||
// The next K step overwrites the stages.
|
||||
kernel.barrier<workgroup> scope(workgroup) ordering(acq_rel)
|
||||
scf.yield %n00, %n01, %n10, %n11 : vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>
|
||||
}
|
||||
|
||||
%out_col0 = index.add %tile_col0, %sub_col0 : index
|
||||
%out_col1 = index.add %out_col0, %c16 : index
|
||||
%out_row0 = index.add %tile_row0, %sub_row0 : index
|
||||
%out_row1 = index.add %out_row0, %c16 : index
|
||||
func.call @ggml_hrx_mm_wmma_store(%dst_noalias, %d_span, %d_batch, %d_s1, %out_col0, %n_cols, %out_row0, %n_rows, %acc00) : (buffer, index, index, index, index, index, index, index, vector<8xf32>)
|
||||
func.call @ggml_hrx_mm_wmma_store(%dst_noalias, %d_span, %d_batch, %d_s1, %out_col0, %n_cols, %out_row1, %n_rows, %acc01) : (buffer, index, index, index, index, index, index, index, vector<8xf32>)
|
||||
func.call @ggml_hrx_mm_wmma_store(%dst_noalias, %d_span, %d_batch, %d_s1, %out_col1, %n_cols, %out_row0, %n_rows, %acc10) : (buffer, index, index, index, index, index, index, index, vector<8xf32>)
|
||||
func.call @ggml_hrx_mm_wmma_store(%dst_noalias, %d_span, %d_batch, %d_s1, %out_col1, %n_cols, %out_row1, %n_rows, %acc11) : (buffer, index, index, index, index, index, index, index, vector<8xf32>)
|
||||
kernel.return
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
// Raw loads and decodes that the weight formats use.
|
||||
|
||||
template.decl @ggml.u8.affine4(%word: i32, %scale: f32, %bias: f32) -> (vector<4xf32>)
|
||||
|
||||
template.def<@ggml.u8.affine4> device @ggml_u8_affine4(%word: i32, %scale: f32, %bias: f32) -> (vector<4xf32>) {
|
||||
%word_vector = vector.from_elements %word : vector<1xi32>
|
||||
%bytes = vector.bitcast %word_vector : vector<1xi32> to vector<4xi8>
|
||||
%values = vector.uitofp %bytes : vector<4xi8> to vector<4xf32>
|
||||
%scale_vector = vector.splat %scale : vector<4xf32>
|
||||
%bias_vector = vector.splat %bias : vector<4xf32>
|
||||
%result = vector.fmaf %values, %scale_vector, %bias_vector : vector<4xf32>
|
||||
template.return %result : vector<4xf32>
|
||||
}
|
||||
|
||||
template.decl @ggml.mem.half(%weight: buffer, %span: index, %index: index) -> (i16)
|
||||
|
||||
template.def<@ggml.mem.half> device @ggml_mem_half(%weight: buffer, %span: index, %index: index) -> (i16) {
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%c0_i16 = scalar.constant 0 : i16
|
||||
%halves = buffer.view %weight[%c0_offset] : buffer -> view<[%span]xi16>
|
||||
%off = index.assume %index [range(%index, 0, 2147483646)] : index
|
||||
%ok = index.cmp ult, %off, %span : index
|
||||
%value = scf.if %ok -> (i16) {
|
||||
%loaded = view.load %halves[%off] : view<[%span]xi16> -> i16
|
||||
scf.yield %loaded : i16
|
||||
} else {
|
||||
scf.yield %c0_i16 : i16
|
||||
}
|
||||
template.return %value : i16
|
||||
}
|
||||
|
||||
template.decl @ggml.mem.half_word(%weight: buffer, %span: index, %index: index) -> (vector<1xi32>)
|
||||
|
||||
// The packed data is only 2-byte aligned. Thus this makes one word from two halves.
|
||||
template.def<@ggml.mem.half_word> device @ggml_mem_half_word(%weight: buffer, %span: index, %index: index) -> (vector<1xi32>) {
|
||||
%c1 = index.constant 1 : index
|
||||
%index1 = index.add %index, %c1 : index
|
||||
%lo = template.apply<@ggml.mem.half>(%weight, %span, %index) : (buffer, index, index) -> (i16)
|
||||
%hi = template.apply<@ggml.mem.half>(%weight, %span, %index1) : (buffer, index, index) -> (i16)
|
||||
%pair = vector.from_elements %lo, %hi : vector<2xi16>
|
||||
%word = vector.bitcast %pair : vector<2xi16> to vector<1xi32>
|
||||
template.return %word : vector<1xi32>
|
||||
}
|
||||
|
||||
template.decl @ggml.f16.bits_f32(%bits: i16) -> (f32)
|
||||
|
||||
template.def<@ggml.f16.bits_f32> device @ggml_f16_bits_f32(%bits: i16) -> (f32) {
|
||||
%bits_vector = vector.from_elements %bits : vector<1xi16>
|
||||
%half_vector = vector.bitcast %bits_vector : vector<1xi16> to vector<1xf16>
|
||||
%half = vector.extract %half_vector[0] : vector<1xf16> -> f16
|
||||
%value = scalar.extf %half : f16 to f32
|
||||
template.return %value : f32
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Plain ggml block_q4_0: f16 scale, then 16 bytes of 4-bit codes. A block has 18 bytes and only 2-byte alignment.
|
||||
// The low nibbles are values 0 to 15. The high nibbles are values 16 to 31.
|
||||
|
||||
template.decl @ggml.f16.bits_f32(%bits: i16) -> (f32)
|
||||
|
||||
template.decl @ggml.mem.half(%weight: buffer, %span: index, %index: index) -> (i16)
|
||||
|
||||
template.decl @ggml.mem.half_word(%weight: buffer, %span: index, %index: index) -> (vector<1xi32>)
|
||||
|
||||
template.decl @ggml.u8.affine4(%word: i32, %scale: f32, %bias: f32) -> (vector<4xf32>)
|
||||
|
||||
// A superblock is 8 blocks of 32 values. A part is one half of a block.
|
||||
func.def inline @ggml_block32_offsets16(%part: index) -> (index, index, index, index) {
|
||||
%c2 = index.constant 2 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c12 = index.constant 12 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%part_in = index.assume %part [range(%part, 0, 15)] : index
|
||||
%blk = index.div %part_in, %c2 : index
|
||||
%half = index.rem %part_in, %c2 : index
|
||||
%o_blk = index.mul %blk, %c32 : index
|
||||
%o_half = index.mul %half, %c16 : index
|
||||
%o0 = index.add %o_blk, %o_half : index
|
||||
%o1 = index.add %o0, %c4 : index
|
||||
%o2 = index.add %o0, %c8 : index
|
||||
%o3 = index.add %o0, %c12 : index
|
||||
func.return %o0, %o1, %o2, %o3 : index, index, index, index
|
||||
}
|
||||
|
||||
template.decl @ggml.weight.block(%wtype: index) -> (index, index)
|
||||
|
||||
template.def<@ggml.weight.block> device @ggml_q4_0_block_shape(%wtype: index) -> (index, index) where [eq(%wtype, 2)] {
|
||||
%values = index.constant 32 : index
|
||||
%units = index.constant 9 : index
|
||||
template.return %values, %units : index, index
|
||||
}
|
||||
|
||||
template.decl @ggml.weight.values4(%wtype: index, %weight: buffer, %w_span: index, %block_base: index, %j: index) -> (vector<4xf32>)
|
||||
|
||||
// j is a multiple of 4 and below 32.
|
||||
template.def<@ggml.weight.values4> device @ggml_q4_0_values4(%wtype: index, %weight: buffer, %w_span: index, %block_base: index, %j: index) -> (vector<4xf32>) where [eq(%wtype, 2)] {
|
||||
%c1 = index.constant 1 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%nibbles = scalar.constant 252645135 : i32
|
||||
%minus_8 = scalar.constant -8.0 : f32
|
||||
%d_bits = template.apply<@ggml.mem.half>(%weight, %w_span, %block_base) : (buffer, index, index) -> (i16)
|
||||
%d = template.apply<@ggml.f16.bits_f32>(%d_bits) : (i16) -> (f32)
|
||||
%byte = index.rem %j, %c16 : index
|
||||
%high = index.div %j, %c16 : index
|
||||
%q_half0 = index.div %byte, %c2 : index
|
||||
%q_half = index.add %q_half0, %c1 : index
|
||||
%q_index = index.add %block_base, %q_half : index
|
||||
%q_word = template.apply<@ggml.mem.half_word>(%weight, %w_span, %q_index) : (buffer, index, index) -> (vector<1xi32>)
|
||||
%q_packed = vector.extract %q_word[0] : vector<1xi32> -> i32
|
||||
%shift_index = index.mul %high, %c4 : index
|
||||
%shift = index.cast %shift_index : index to i32
|
||||
%q_shifted = scalar.shrui %q_packed, %shift : i32
|
||||
%q = scalar.andi %q_shifted, %nibbles : i32
|
||||
%bias = scalar.mulf %d, %minus_8 : f32
|
||||
%result = template.apply<@ggml.u8.affine4>(%q, %d, %bias) : (i32, f32, f32) -> (vector<4xf32>)
|
||||
template.return %result : vector<4xf32>
|
||||
}
|
||||
|
||||
template.decl @ggml.weight.superblock(%wtype: index) -> (offset, offset, index)
|
||||
|
||||
template.def<@ggml.weight.superblock> device @ggml_q4_0_superblock(%wtype: index) -> (offset, offset, index) where [eq(%wtype, 2)] {
|
||||
%unit = index.constant 2 : offset
|
||||
%sb = index.constant 144 : offset
|
||||
%units = index.constant 72 : index
|
||||
template.return %unit, %sb, %units : offset, offset, index
|
||||
}
|
||||
|
||||
template.decl @ggml.weight.part16(%wtype: index, %weight: buffer, %sb_byte: offset, %part: index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, index, index, index, index)
|
||||
|
||||
template.def<@ggml.weight.part16> device @ggml_q4_0_part16(%wtype: index, %weight: buffer, %sb_byte: offset, %part: index) -> (vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, index, index, index, index) where [eq(%wtype, 2)] {
|
||||
%c0 = index.constant 0 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%b2 = index.constant 2 : offset
|
||||
%b18 = index.constant 18 : offset
|
||||
%nibbles = vector.splati 252645135 : vector<4xi32>
|
||||
%minus_8 = scalar.constant -8.0 : f32
|
||||
%part_in = index.assume %part [range(%part, 0, 15)] : index
|
||||
%blk = index.div %part_in, %c2 : index
|
||||
%high = index.rem %part_in, %c2 : index
|
||||
%blk_add = index.scale %blk, %b18 : index, offset -> offset
|
||||
%blk_byte = index.add %sb_byte, %blk_add : offset
|
||||
%qs_byte = index.add %blk_byte, %b2 : offset
|
||||
%d_view = buffer.view %weight[%blk_byte] : buffer -> view<1xf16>
|
||||
%qs_view = buffer.view %weight[%qs_byte] : buffer -> view<4xi32>
|
||||
%d_half = view.load %d_view[%c0] : view<1xf16> -> f16
|
||||
%qs = vector.load %qs_view[%c0] : view<4xi32> -> vector<4xi32>
|
||||
%d = scalar.extf %d_half : f16 to f32
|
||||
%bias = scalar.mulf %d, %minus_8 : f32
|
||||
%shift_index = index.mul %high, %c4 : index
|
||||
%shift_i32 = index.cast %shift_index : index to i32
|
||||
%shift = vector.splat %shift_i32 : vector<4xi32>
|
||||
%qs_shifted = vector.shrui %qs, %shift : vector<4xi32>
|
||||
%q = vector.andi %qs_shifted, %nibbles : vector<4xi32>
|
||||
%q0 = vector.extract %q[0] : vector<4xi32> -> i32
|
||||
%q1 = vector.extract %q[1] : vector<4xi32> -> i32
|
||||
%q2 = vector.extract %q[2] : vector<4xi32> -> i32
|
||||
%q3 = vector.extract %q[3] : vector<4xi32> -> i32
|
||||
%w0 = template.apply<@ggml.u8.affine4>(%q0, %d, %bias) : (i32, f32, f32) -> (vector<4xf32>)
|
||||
%w1 = template.apply<@ggml.u8.affine4>(%q1, %d, %bias) : (i32, f32, f32) -> (vector<4xf32>)
|
||||
%w2 = template.apply<@ggml.u8.affine4>(%q2, %d, %bias) : (i32, f32, f32) -> (vector<4xf32>)
|
||||
%w3 = template.apply<@ggml.u8.affine4>(%q3, %d, %bias) : (i32, f32, f32) -> (vector<4xf32>)
|
||||
%o0, %o1, %o2, %o3 = func.call @ggml_block32_offsets16(%part_in) : (index) -> (index, index, index, index)
|
||||
template.return %w0, %w1, %w2, %w3, %o0, %o1, %o2, %o3 : vector<4xf32>, vector<4xf32>, vector<4xf32>, vector<4xf32>, index, index, index, index
|
||||
}
|
||||
|
||||
template.decl @ggml.weight.offsets16(%wtype: index, %part: index) -> (index, index, index, index)
|
||||
|
||||
template.def<@ggml.weight.offsets16> device @ggml_q4_0_offsets16(%wtype: index, %part: index) -> (index, index, index, index) where [eq(%wtype, 2)] {
|
||||
%o0, %o1, %o2, %o3 = func.call @ggml_block32_offsets16(%part) : (index) -> (index, index, index, index)
|
||||
template.return %o0, %o1, %o2, %o3 : index, index, index, index
|
||||
}
|
||||
|
||||
// part is below 4. A part has 8 values.
|
||||
func.def inline @ggml_q4_0_block8(%weight: buffer, %w_span: index, %block_base0: index, %valid: i1, %part: index) -> (vector<8xf16>) {
|
||||
%c1 = index.constant 1 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%c0_i16 = scalar.constant 0 : i16
|
||||
%minus_8 = scalar.constant -8.0 : f32
|
||||
%zero4 = vector.splati 0 : vector<4xi16>
|
||||
%nibbles = vector.splati 252645135 : vector<2xi32>
|
||||
%halves = buffer.view %weight[%c0_offset] : buffer -> view<[%w_span]xi16>
|
||||
%block_base = index.assume %block_base0 [range(%block_base0, 0, 2147483600)] : index
|
||||
%byte_part = index.rem %part, %c2 : index
|
||||
%high = index.div %part, %c2 : index
|
||||
%part_halves = index.mul %byte_part, %c4 : index
|
||||
%q_local = index.add %part_halves, %c1 : index
|
||||
%q_index = index.add %block_base, %q_local : index
|
||||
%block_last = index.add %block_base, %c8 : index
|
||||
%q, %d_bits = scf.if %valid -> (vector<4xi16>, i16) {
|
||||
%in_span = index.cmp ult, %block_last, %w_span : index
|
||||
%l_q, %l_d = scf.if %in_span -> (vector<4xi16>, i16) {
|
||||
%v_d = view.load %halves[%block_base] : view<[%w_span]xi16> -> i16
|
||||
%v_q = vector.load %halves[%q_index] : view<[%w_span]xi16> -> vector<4xi16>
|
||||
scf.yield %v_q, %v_d : vector<4xi16>, i16
|
||||
} else {
|
||||
scf.yield %zero4, %c0_i16 : vector<4xi16>, i16
|
||||
}
|
||||
scf.yield %l_q, %l_d : vector<4xi16>, i16
|
||||
} else {
|
||||
scf.yield %zero4, %c0_i16 : vector<4xi16>, i16
|
||||
}
|
||||
%words = vector.bitcast %q : vector<4xi16> to vector<2xi32>
|
||||
%shift_index = index.mul %high, %c4 : index
|
||||
%shift_i32 = index.cast %shift_index : index to i32
|
||||
%shift = vector.splat %shift_i32 : vector<2xi32>
|
||||
%words_shifted = vector.shrui %words, %shift : vector<2xi32>
|
||||
%codes = vector.andi %words_shifted, %nibbles : vector<2xi32>
|
||||
%bytes = vector.bitcast %codes : vector<2xi32> to vector<8xi8>
|
||||
%q_f32 = vector.uitofp %bytes : vector<8xi8> to vector<8xf32>
|
||||
%d = template.apply<@ggml.f16.bits_f32>(%d_bits) : (i16) -> (f32)
|
||||
%bias = scalar.mulf %d, %minus_8 : f32
|
||||
%d_splat = vector.splat %d : vector<8xf32>
|
||||
%bias_splat = vector.splat %bias : vector<8xf32>
|
||||
%values = vector.fmaf %q_f32, %d_splat, %bias_splat : vector<8xf32>
|
||||
%values_f16 = vector.fptrunc %values : vector<8xf32> to vector<8xf16>
|
||||
func.return %values_f16 : vector<8xf16>
|
||||
}
|
||||
|
||||
template.decl @ggml.weight.wmma16(%wtype: index, %weight: buffer, %w_span: index, %row_base: index, %row_valid: i1, %k: index, %k_size: index, %part: index) -> (vector<8xf16>, vector<8xf16>)
|
||||
|
||||
// The second block can be past K.
|
||||
template.def<@ggml.weight.wmma16> device @ggml_q4_0_wmma16(%wtype: index, %weight: buffer, %w_span: index, %row_base: index, %row_valid: i1, %k: index, %k_size: index, %part: index) -> (vector<8xf16>, vector<8xf16>) where [eq(%wtype, 2)] {
|
||||
%c9 = index.constant 9 : index
|
||||
%c32 = index.constant 32 : index
|
||||
%k_bounded = index.assume %k [range(%k, 0, 2147483646)] : index
|
||||
%block = index.div %k_bounded, %c32 : index
|
||||
%block_offset = index.mul %block, %c9 : index
|
||||
%block_base = index.add %row_base, %block_offset : index
|
||||
%block_base1 = index.add %block_base, %c9 : index
|
||||
%k1 = index.add %k_bounded, %c32 : index
|
||||
%k1_in = index.cmp ult, %k1, %k_size : index
|
||||
%valid1 = scalar.andi %row_valid, %k1_in : i1
|
||||
%low = func.call @ggml_q4_0_block8(%weight, %w_span, %block_base, %row_valid, %part) : (buffer, index, index, i1, index) -> (vector<8xf16>)
|
||||
%high = func.call @ggml_q4_0_block8(%weight, %w_span, %block_base1, %valid1, %part) : (buffer, index, index, i1, index) -> (vector<8xf16>)
|
||||
template.return %low, %high : vector<8xf16>, vector<8xf16>
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// The accumulator of a 16x16 tile has the gfx11 wave32 WMMA layout: element e of lane l is column col + l / 16 + 2 * e and row row + l % 16.
|
||||
// x_stage holds [col][k] f16 rows with a pitch of 72. w_stage holds [k][row] f16 with a row pitch of 72.
|
||||
|
||||
target.decl @ggml_gfx11
|
||||
target.decl @ggml_gfx12
|
||||
|
||||
template.decl @ggml.mma.zero_acc() -> (vector<8xf32>)
|
||||
|
||||
template.def<@ggml.mma.zero_acc> device target(@ggml_gfx11) requires [#target.subgroup.size<32>] priority(20) @ggml_mma_zero_acc_gfx11() -> (vector<8xf32>) {
|
||||
%c16 = index.constant 16 : index
|
||||
%zero8 = vector.splatf 0.0 : vector<8xf32>
|
||||
%init = vector.fragment<init> %zero8 shape [%c16, %c16] : vector<8xf32>
|
||||
template.return %init : vector<8xf32>
|
||||
}
|
||||
|
||||
template.def<@ggml.mma.zero_acc> device requires [#target.subgroup.size<32>] priority(1) @ggml_mma_zero_acc() -> (vector<8xf32>) {
|
||||
%zero8 = vector.splatf 0.0 : vector<8xf32>
|
||||
template.return %zero8 : vector<8xf32>
|
||||
}
|
||||
|
||||
template.decl @ggml.mma.k64_2x2(%x_stage: buffer, %w_stage: buffer, %col0: index, %row0: index, %acc00: vector<8xf32>, %acc01: vector<8xf32>, %acc10: vector<8xf32>, %acc11: vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>)
|
||||
|
||||
template.def<@ggml.mma.k64_2x2> device target(@ggml_gfx11) requires [#target.subgroup.size<32>] priority(20) @ggml_mma_k64_2x2_gfx11(%x_stage: buffer, %w_stage: buffer, %col0: index, %row0: index, %acc00: vector<8xf32>, %acc01: vector<8xf32>, %acc10: vector<8xf32>, %acc11: vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>) {
|
||||
%c0 = index.constant 0 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%m = index.constant 16 : index
|
||||
%n = index.constant 16 : index
|
||||
%k = index.constant 16 : index
|
||||
%w_layout = encoding.layout.strided [1, 72] : encoding<layout>
|
||||
%x_view = buffer.view %x_stage[%c0_offset] : buffer -> view<64x72xf16>
|
||||
%w_view = buffer.view %w_stage[%c0_offset] : buffer -> view<64x128xf16, %w_layout>
|
||||
%col1 = index.add %col0, %c16 : index
|
||||
%row1 = index.add %row0, %c16 : index
|
||||
%r00, %r01, %r10, %r11 = scf.for %kh = [%c0 to %c64 step %c16](%a00 = %acc00 : vector<8xf32>, %a01 = %acc01 : vector<8xf32>, %a10 = %acc10 : vector<8xf32>, %a11 = %acc11 : vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>) unroll {
|
||||
%lhs0 = vector.fragment.load<lhs> %x_view[%col0, %kh] shape [%m, %k] : view<64x72xf16> -> vector<16xf16>
|
||||
%lhs1 = vector.fragment.load<lhs> %x_view[%col1, %kh] shape [%m, %k] : view<64x72xf16> -> vector<16xf16>
|
||||
%rhs0 = vector.fragment.load<rhs> %w_view[%kh, %row0] shape [%k, %n] : view<64x128xf16, %w_layout> -> vector<16xf16>
|
||||
%rhs1 = vector.fragment.load<rhs> %w_view[%kh, %row1] shape [%k, %n] : view<64x128xf16, %w_layout> -> vector<16xf16>
|
||||
%n00 = vector.mma %lhs0, %rhs0, %a00 : vector<16xf16>, vector<16xf16>, vector<8xf32>
|
||||
%n01 = vector.mma %lhs0, %rhs1, %a01 : vector<16xf16>, vector<16xf16>, vector<8xf32>
|
||||
%n10 = vector.mma %lhs1, %rhs0, %a10 : vector<16xf16>, vector<16xf16>, vector<8xf32>
|
||||
%n11 = vector.mma %lhs1, %rhs1, %a11 : vector<16xf16>, vector<16xf16>, vector<8xf32>
|
||||
scf.yield %n00, %n01, %n10, %n11 : vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>
|
||||
}
|
||||
template.return %r00, %r01, %r10, %r11 : vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>
|
||||
}
|
||||
|
||||
template.def<@ggml.mma.zero_acc> device target(@ggml_gfx12) requires [#target.subgroup.size<32>] priority(20) @ggml_mma_zero_acc_gfx12() -> (vector<8xf32>) {
|
||||
%c16 = index.constant 16 : index
|
||||
%zero8 = vector.splatf 0.0 : vector<8xf32>
|
||||
%init = vector.fragment<init> %zero8 shape [%c16, %c16] : vector<8xf32>
|
||||
template.return %init : vector<8xf32>
|
||||
}
|
||||
|
||||
// The gfx12 result layout is different from the gfx11 layout. The lhs row order changes the result to the gfx11 layout.
|
||||
func.def inline @ggml_mma_lhs_lane_gfx12() -> (index, index) {
|
||||
%c2 = index.constant 2 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%lane0 = kernel.subgroup.lane.id : index
|
||||
%lane = index.assume %lane0 [range(%lane0, 0, 31)] : index
|
||||
%m = index.rem %lane, %c16 : index
|
||||
%half = index.div %lane, %c16 : index
|
||||
%m_high = index.div %m, %c8 : index
|
||||
%m_low = index.rem %m, %c8 : index
|
||||
%m_low2 = index.mul %m_low, %c2 : index
|
||||
%row = index.add %m_high, %m_low2 : index
|
||||
%k = index.mul %half, %c8 : index
|
||||
func.return %row, %k : index, index
|
||||
}
|
||||
|
||||
template.def<@ggml.mma.k64_2x2> device target(@ggml_gfx12) requires [#target.subgroup.size<32>] priority(20) @ggml_mma_k64_2x2_gfx12(%x_stage: buffer, %w_stage: buffer, %col0: index, %row0: index, %acc00: vector<8xf32>, %acc01: vector<8xf32>, %acc10: vector<8xf32>, %acc11: vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>) {
|
||||
%c0 = index.constant 0 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%m = index.constant 16 : index
|
||||
%w_layout = encoding.layout.strided [1, 72] : encoding<layout>
|
||||
%x_view = buffer.view %x_stage[%c0_offset] : buffer -> view<64x72xf16>
|
||||
%w_view = buffer.view %w_stage[%c0_offset] : buffer -> view<64x128xf16, %w_layout>
|
||||
%lane_row, %lane_k = func.call @ggml_mma_lhs_lane_gfx12() : () -> (index, index)
|
||||
%x_row0 = index.add %col0, %lane_row : index
|
||||
%x_row1 = index.add %x_row0, %c16 : index
|
||||
%row1 = index.add %row0, %c16 : index
|
||||
%r00, %r01, %r10, %r11 = scf.for %kh = [%c0 to %c64 step %c16](%a00 = %acc00 : vector<8xf32>, %a01 = %acc01 : vector<8xf32>, %a10 = %acc10 : vector<8xf32>, %a11 = %acc11 : vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>) unroll {
|
||||
%xk = index.add %kh, %lane_k : index
|
||||
%x0 = vector.load %x_view[%x_row0, %xk] : view<64x72xf16> -> vector<8xf16>
|
||||
%x1 = vector.load %x_view[%x_row1, %xk] : view<64x72xf16> -> vector<8xf16>
|
||||
%lhs0 = vector.fragment<lhs> %x0 shape [%m, %m] : vector<8xf16>
|
||||
%lhs1 = vector.fragment<lhs> %x1 shape [%m, %m] : vector<8xf16>
|
||||
%rhs0 = vector.fragment.load<rhs> %w_view[%kh, %row0] shape [%m, %m] : view<64x128xf16, %w_layout> -> vector<8xf16>
|
||||
%rhs1 = vector.fragment.load<rhs> %w_view[%kh, %row1] shape [%m, %m] : view<64x128xf16, %w_layout> -> vector<8xf16>
|
||||
%n00 = vector.mma %lhs0, %rhs0, %a00 : vector<8xf16>, vector<8xf16>, vector<8xf32>
|
||||
%n01 = vector.mma %lhs0, %rhs1, %a01 : vector<8xf16>, vector<8xf16>, vector<8xf32>
|
||||
%n10 = vector.mma %lhs1, %rhs0, %a10 : vector<8xf16>, vector<8xf16>, vector<8xf32>
|
||||
%n11 = vector.mma %lhs1, %rhs1, %a11 : vector<8xf16>, vector<8xf16>, vector<8xf32>
|
||||
scf.yield %n00, %n01, %n10, %n11 : vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>
|
||||
}
|
||||
template.return %r00, %r01, %r10, %r11 : vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>
|
||||
}
|
||||
|
||||
func.def inline @ggml_mma_x(%x_stage: buffer, %x_rows: index, %col: index, %k: index) -> (f32) {
|
||||
%c72 = index.constant 72 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%zero = scalar.constant 0.0 : f32
|
||||
%x_view = buffer.view %x_stage[%c0_offset] : buffer -> view<[%x_rows]x72xf16>
|
||||
%col_in = index.cmp ult, %col, %x_rows : index
|
||||
%value = scf.if %col_in -> (f32) {
|
||||
%k_in = index.cmp ult, %k, %c72 : index
|
||||
%loaded = scf.if %k_in -> (f32) {
|
||||
%half = view.load %x_view[%col, %k] : view<[%x_rows]x72xf16> -> f16
|
||||
%wide = scalar.extf %half : f16 to f32
|
||||
scf.yield %wide : f32
|
||||
} else {
|
||||
scf.yield %zero : f32
|
||||
}
|
||||
scf.yield %loaded : f32
|
||||
} else {
|
||||
scf.yield %zero : f32
|
||||
}
|
||||
func.return %value : f32
|
||||
}
|
||||
|
||||
func.def inline @ggml_mma_w(%w_stage: buffer, %k: index, %row: index) -> (f32) {
|
||||
%c64 = index.constant 64 : index
|
||||
%c128 = index.constant 128 : index
|
||||
%c0_offset = index.constant 0 : offset
|
||||
%zero = scalar.constant 0.0 : f32
|
||||
%w_layout = encoding.layout.strided [1, 72] : encoding<layout>
|
||||
%w_view = buffer.view %w_stage[%c0_offset] : buffer -> view<64x128xf16, %w_layout>
|
||||
%row_in = index.cmp ult, %row, %c128 : index
|
||||
%value = scf.if %row_in -> (f32) {
|
||||
%k_in = index.cmp ult, %k, %c64 : index
|
||||
%loaded = scf.if %k_in -> (f32) {
|
||||
%half = view.load %w_view[%k, %row] : view<64x128xf16, %w_layout> -> f16
|
||||
%wide = scalar.extf %half : f16 to f32
|
||||
scf.yield %wide : f32
|
||||
} else {
|
||||
scf.yield %zero : f32
|
||||
}
|
||||
scf.yield %loaded : f32
|
||||
} else {
|
||||
scf.yield %zero : f32
|
||||
}
|
||||
func.return %value : f32
|
||||
}
|
||||
|
||||
func.def inline @ggml_mma_tile16(%x_stage: buffer, %x_rows: index, %w_stage: buffer, %col: index, %row: index, %acc: vector<8xf32>) -> (vector<8xf32>) {
|
||||
%c0 = index.constant 0 : index
|
||||
%c1 = index.constant 1 : index
|
||||
%c2 = index.constant 2 : index
|
||||
%c4 = index.constant 4 : index
|
||||
%c6 = index.constant 6 : index
|
||||
%c8 = index.constant 8 : index
|
||||
%c10 = index.constant 10 : index
|
||||
%c12 = index.constant 12 : index
|
||||
%c14 = index.constant 14 : index
|
||||
%c16 = index.constant 16 : index
|
||||
%c64 = index.constant 64 : index
|
||||
%lane0 = kernel.subgroup.lane.id : index
|
||||
%lane = index.assume %lane0 [range(%lane0, 0, 31)] : index
|
||||
%lane_col = index.div %lane, %c16 : index
|
||||
%lane_row = index.rem %lane, %c16 : index
|
||||
%r = index.add %row, %lane_row : index
|
||||
%col_e0 = index.add %col, %lane_col : index
|
||||
%col_e1 = index.add %col_e0, %c2 : index
|
||||
%col_e2 = index.add %col_e0, %c4 : index
|
||||
%col_e3 = index.add %col_e0, %c6 : index
|
||||
%col_e4 = index.add %col_e0, %c8 : index
|
||||
%col_e5 = index.add %col_e0, %c10 : index
|
||||
%col_e6 = index.add %col_e0, %c12 : index
|
||||
%col_e7 = index.add %col_e0, %c14 : index
|
||||
%result = scf.for %k = [%c0 to %c64 step %c1](%a = %acc : vector<8xf32>) -> (vector<8xf32>) {
|
||||
%w = func.call @ggml_mma_w(%w_stage, %k, %r) : (buffer, index, index) -> (f32)
|
||||
%x0 = func.call @ggml_mma_x(%x_stage, %x_rows, %col_e0, %k) : (buffer, index, index, index) -> (f32)
|
||||
%x1 = func.call @ggml_mma_x(%x_stage, %x_rows, %col_e1, %k) : (buffer, index, index, index) -> (f32)
|
||||
%x2 = func.call @ggml_mma_x(%x_stage, %x_rows, %col_e2, %k) : (buffer, index, index, index) -> (f32)
|
||||
%x3 = func.call @ggml_mma_x(%x_stage, %x_rows, %col_e3, %k) : (buffer, index, index, index) -> (f32)
|
||||
%x4 = func.call @ggml_mma_x(%x_stage, %x_rows, %col_e4, %k) : (buffer, index, index, index) -> (f32)
|
||||
%x5 = func.call @ggml_mma_x(%x_stage, %x_rows, %col_e5, %k) : (buffer, index, index, index) -> (f32)
|
||||
%x6 = func.call @ggml_mma_x(%x_stage, %x_rows, %col_e6, %k) : (buffer, index, index, index) -> (f32)
|
||||
%x7 = func.call @ggml_mma_x(%x_stage, %x_rows, %col_e7, %k) : (buffer, index, index, index) -> (f32)
|
||||
%xv = vector.from_elements %x0, %x1, %x2, %x3, %x4, %x5, %x6, %x7 : vector<8xf32>
|
||||
%wv = vector.splat %w : vector<8xf32>
|
||||
%next = vector.fmaf %xv, %wv, %a : vector<8xf32>
|
||||
scf.yield %next : vector<8xf32>
|
||||
}
|
||||
func.return %result : vector<8xf32>
|
||||
}
|
||||
|
||||
template.def<@ggml.mma.k64_2x2> device requires [#target.subgroup.size<32>] priority(1) @ggml_mma_k64_2x2(%x_stage: buffer, %w_stage: buffer, %col0: index, %row0: index, %acc00: vector<8xf32>, %acc01: vector<8xf32>, %acc10: vector<8xf32>, %acc11: vector<8xf32>) -> (vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>) {
|
||||
%c16 = index.constant 16 : index
|
||||
%x_rows = index.constant 64 : index
|
||||
%col1 = index.add %col0, %c16 : index
|
||||
%row1 = index.add %row0, %c16 : index
|
||||
%t00 = func.call @ggml_mma_tile16(%x_stage, %x_rows, %w_stage, %col0, %row0, %acc00) : (buffer, index, buffer, index, index, vector<8xf32>) -> (vector<8xf32>)
|
||||
%t01 = func.call @ggml_mma_tile16(%x_stage, %x_rows, %w_stage, %col0, %row1, %acc01) : (buffer, index, buffer, index, index, vector<8xf32>) -> (vector<8xf32>)
|
||||
%t10 = func.call @ggml_mma_tile16(%x_stage, %x_rows, %w_stage, %col1, %row0, %acc10) : (buffer, index, buffer, index, index, vector<8xf32>) -> (vector<8xf32>)
|
||||
%t11 = func.call @ggml_mma_tile16(%x_stage, %x_rows, %w_stage, %col1, %row1, %acc11) : (buffer, index, buffer, index, index, vector<8xf32>) -> (vector<8xf32>)
|
||||
template.return %t00, %t01, %t10, %t11 : vector<8xf32>, vector<8xf32>, vector<8xf32>, vector<8xf32>
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
// Row ids are i64. Strides are in elements. A row id out of range is skipped.
|
||||
|
||||
config.decl @ggml.set_rows.dst_type : %value: index where [range(%value, 0, 1)]
|
||||
|
||||
config.decl @ggml.elementwise.wg_size : %value: index where [range(%value, 64, 1024), multiple_of(%value, 64)]
|
||||
|
||||
target.decl @ggml_wave64
|
||||
|
||||
kernel.def target(@ggml_wave64) export("ggml_set_rows_f32") @ggml_set_rows_f32(%n: index) {
|
||||
%one = index.constant 1 : index
|
||||
%wg_size = config.get @ggml.elementwise.wg_size : index
|
||||
%round = index.sub %wg_size, %one : index
|
||||
%n_round = index.add %n, %round : index
|
||||
%groups = index.div %n_round, %wg_size : index
|
||||
kernel.launch.config workgroups(%groups, %one, %one) workgroup_size(%wg_size, %one, %one) : index
|
||||
} launch(%n_in: index, %ne0_in: index, %ne1_in: index, %ne2_in: index, %s0_in: index, %s1_in: index, %s2_in: index, %s3_in: index, %src_span_in: index, %ids_ne1_in: index, %ids_ne2_in: index, %ids_s0_in: index, %ids_s1_in: index, %ids_s2_in: index, %ids_span_in: index, %dst_rows_in: index, %d0_in: index, %d1_in: index, %d2_in: index, %d3_in: index, %dst_span_in: index, %src: buffer, %ids: buffer, %dst: buffer) {
|
||||
// supports_set_rows checks these ranges.
|
||||
%n = index.assume %n_in [range(%n_in, 1, 2147483647)] : index
|
||||
%ne0 = index.assume %ne0_in [range(%ne0_in, 1, 2147483647)] : index
|
||||
%ne1 = index.assume %ne1_in [range(%ne1_in, 1, 2147483647)] : index
|
||||
%ne2 = index.assume %ne2_in [range(%ne2_in, 1, 2147483647)] : index
|
||||
%s0 = index.assume %s0_in [range(%s0_in, 0, 2147483647)] : index
|
||||
%s1 = index.assume %s1_in [range(%s1_in, 0, 2147483647)] : index
|
||||
%s2 = index.assume %s2_in [range(%s2_in, 0, 2147483647)] : index
|
||||
%s3 = index.assume %s3_in [range(%s3_in, 0, 2147483647)] : index
|
||||
%src_span = index.assume %src_span_in [range(%src_span_in, 1, 2147483647)] : index
|
||||
%ids_ne1 = index.assume %ids_ne1_in [range(%ids_ne1_in, 1, 2147483647)] : index
|
||||
%ids_ne2 = index.assume %ids_ne2_in [range(%ids_ne2_in, 1, 2147483647)] : index
|
||||
%ids_s0 = index.assume %ids_s0_in [range(%ids_s0_in, 0, 2147483647)] : index
|
||||
%ids_s1 = index.assume %ids_s1_in [range(%ids_s1_in, 0, 2147483647)] : index
|
||||
%ids_s2 = index.assume %ids_s2_in [range(%ids_s2_in, 0, 2147483647)] : index
|
||||
%ids_span = index.assume %ids_span_in [range(%ids_span_in, 1, 2147483647)] : index
|
||||
%dst_rows = index.assume %dst_rows_in [range(%dst_rows_in, 1, 2147483647)] : index
|
||||
%d0 = index.assume %d0_in [range(%d0_in, 0, 2147483647)] : index
|
||||
%d1 = index.assume %d1_in [range(%d1_in, 0, 2147483647)] : index
|
||||
%d2 = index.assume %d2_in [range(%d2_in, 0, 2147483647)] : index
|
||||
%d3 = index.assume %d3_in [range(%d3_in, 0, 2147483647)] : index
|
||||
%dst_span = index.assume %dst_span_in [range(%dst_span_in, 1, 2147483647)] : index
|
||||
// dst_type: 0 is f32, 1 is f16.
|
||||
%dst_type = config.get @ggml.set_rows.dst_type : index
|
||||
%c0 = index.constant 0 : index
|
||||
%c1 = index.constant 1 : index
|
||||
%wg_size = config.get @ggml.elementwise.wg_size : index
|
||||
%group = kernel.workgroup.id<x> : index
|
||||
%item = kernel.workitem.id<x> : index
|
||||
%base = index.mul %group, %wg_size : index
|
||||
%i = index.add %base, %item : index
|
||||
%in_bounds = index.cmp ult, %i, %n : index
|
||||
%zero = index.constant 0 : offset
|
||||
%src_view = buffer.view %src[%zero] : buffer -> view<[%src_span]xf32>
|
||||
scf.if %in_bounds {
|
||||
%i0 = index.rem %i, %ne0 : index
|
||||
%t0 = index.div %i, %ne0 : index
|
||||
%i1 = index.rem %t0, %ne1 : index
|
||||
%t1 = index.div %t0, %ne1 : index
|
||||
%i2 = index.rem %t1, %ne2 : index
|
||||
%i3 = index.div %t1, %ne2 : index
|
||||
|
||||
%j1 = index.rem %i2, %ids_ne1 : index
|
||||
%j2 = index.rem %i3, %ids_ne2 : index
|
||||
%io0 = index.mul %i1, %ids_s0 : index
|
||||
%io1 = index.mul %j1, %ids_s1 : index
|
||||
%io2 = index.mul %j2, %ids_s2 : index
|
||||
%io01 = index.add %io0, %io1 : index
|
||||
%ids_idx = index.add %io01, %io2 : index
|
||||
%ids_off = index.assume %ids_idx [range(%ids_idx, 0, 2147483646)] : index
|
||||
%ids_ok = index.cmp ult, %ids_off, %ids_span : index
|
||||
scf.if %ids_ok {
|
||||
// An i64 id out of range becomes -1. The check below skips it.
|
||||
%ids_view = buffer.view %ids[%zero] : buffer -> view<[%ids_span]xi64>
|
||||
%v = view.load %ids_view[%ids_off] : view<[%ids_span]xi64> -> i64
|
||||
%c0_i64 = scalar.constant 0 : i64
|
||||
%cm1_i32 = scalar.constant -1 : i32
|
||||
%limit = index.cast %dst_rows : index to i64
|
||||
%nonneg = scalar.cmpi sge, %v, %c0_i64 : i64
|
||||
%below = scalar.cmpi slt, %v, %limit : i64
|
||||
%ok = scalar.andi %nonneg, %below : i1
|
||||
%safe = scf.select %ok, %v, %c0_i64 : i64
|
||||
%narrow = scalar.trunci %safe : i64 to i32
|
||||
%row_i32 = scf.select %ok, %narrow, %cm1_i32 : i32
|
||||
%row = index.cast %row_i32 : i32 to index
|
||||
%row_nonneg = index.cmp sge, %row, %c0 : index
|
||||
scf.if %row_nonneg {
|
||||
%row_below = index.cmp ult, %row, %dst_rows : index
|
||||
scf.if %row_below {
|
||||
%so0 = index.mul %i0, %s0 : index
|
||||
%so1 = index.mul %i1, %s1 : index
|
||||
%so2 = index.mul %i2, %s2 : index
|
||||
%so3 = index.mul %i3, %s3 : index
|
||||
%so01 = index.add %so0, %so1 : index
|
||||
%so23 = index.add %so2, %so3 : index
|
||||
%src_idx = index.add %so01, %so23 : index
|
||||
%src_off = index.assume %src_idx [range(%src_idx, 0, 2147483646)] : index
|
||||
|
||||
%do0 = index.mul %i0, %d0 : index
|
||||
%do1 = index.mul %row, %d1 : index
|
||||
%do2 = index.mul %i2, %d2 : index
|
||||
%do3 = index.mul %i3, %d3 : index
|
||||
%do01 = index.add %do0, %do1 : index
|
||||
%do23 = index.add %do2, %do3 : index
|
||||
%dst_idx = index.add %do01, %do23 : index
|
||||
%dst_off = index.assume %dst_idx [range(%dst_idx, 0, 2147483646)] : index
|
||||
|
||||
%src_ok = index.cmp ult, %src_off, %src_span : index
|
||||
scf.if %src_ok {
|
||||
%dst_ok = index.cmp ult, %dst_off, %dst_span : index
|
||||
scf.if %dst_ok {
|
||||
%x = view.load %src_view[%src_off] : view<[%src_span]xf32> -> f32
|
||||
%is_f16 = index.cmp eq, %dst_type, %c1 : index
|
||||
scf.if %is_f16 {
|
||||
%dst_view = buffer.view %dst[%zero] : buffer -> view<[%dst_span]xf16>
|
||||
%h = scalar.fptrunc %x : f32 to f16
|
||||
view.store %h, %dst_view[%dst_off] : f16, view<[%dst_span]xf16>
|
||||
} else {
|
||||
%dst_view = buffer.view %dst[%zero] : buffer -> view<[%dst_span]xf32>
|
||||
view.store %x, %dst_view[%dst_off] : f32, view<[%dst_span]xf32>
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
kernel.return
|
||||
}
|
||||
@@ -0,0 +1,545 @@
|
||||
#include "loom-jit.h"
|
||||
|
||||
#include "loomc/launch_config.h"
|
||||
#include "loomc/loomc.h"
|
||||
#include "loomc/target/amdgpu.h"
|
||||
|
||||
#include <cstring>
|
||||
#include <map>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <new>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
static constexpr size_t GGML_HRX_LOOM_MAX_LAUNCH_RESULTS = 1024;
|
||||
|
||||
struct ggml_hrx_loom_launch_program {
|
||||
loomc_launch_config_program_t * program = nullptr;
|
||||
loomc_launch_config_function_t function = loomc_launch_config_function_invalid();
|
||||
std::mutex mutex;
|
||||
// The result depends only on the workload. The program call is slow.
|
||||
std::map<std::vector<uint64_t>, ggml_hrx_loom_launch_config> results;
|
||||
|
||||
~ggml_hrx_loom_launch_program() {
|
||||
if (program != nullptr) {
|
||||
loomc_launch_config_program_release(program);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct ggml_hrx_loom_jit {
|
||||
loomc_target_environment_t * target_environment = nullptr;
|
||||
loomc_context_t * context = nullptr;
|
||||
loomc_target_profile_t * target_profile = nullptr;
|
||||
loomc_compiler_t * compiler = nullptr;
|
||||
loomc_pass_program_t * pass_program = nullptr;
|
||||
std::string targets; // Loom source that defines the kernel targets.
|
||||
|
||||
~ggml_hrx_loom_jit() {
|
||||
loomc_pass_program_release(pass_program);
|
||||
loomc_compiler_release(compiler);
|
||||
loomc_target_profile_release(target_profile);
|
||||
loomc_context_release(context);
|
||||
loomc_target_environment_release(target_environment);
|
||||
}
|
||||
};
|
||||
|
||||
namespace {
|
||||
|
||||
template <typename T, void (*Release)(T *)> class loom_handle {
|
||||
public:
|
||||
loom_handle() = default;
|
||||
loom_handle(const loom_handle &) = delete;
|
||||
loom_handle & operator=(const loom_handle &) = delete;
|
||||
~loom_handle() { reset(); }
|
||||
|
||||
T * get() const { return value; }
|
||||
|
||||
T ** out() {
|
||||
reset();
|
||||
return &value;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
if (value != nullptr) {
|
||||
Release(value);
|
||||
}
|
||||
value = nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
T * value = nullptr;
|
||||
};
|
||||
|
||||
using loom_workspace = loom_handle<loomc_workspace_t, loomc_workspace_release>;
|
||||
using loom_source = loom_handle<loomc_source_t, loomc_source_release>;
|
||||
using loom_module = loom_handle<loomc_module_t, loomc_module_release>;
|
||||
using loom_result = loom_handle<loomc_result_t, loomc_result_release>;
|
||||
using loom_link_index_builder = loom_handle<loomc_link_index_builder_t, loomc_link_index_builder_free>;
|
||||
using loom_link_index = loom_handle<loomc_link_index_t, loomc_link_index_release>;
|
||||
using loom_linker = loom_handle<loomc_linker_t, loomc_linker_release>;
|
||||
|
||||
#if defined(LOOMC_ARTIFACT_ROLE_COMPILE_REPORT)
|
||||
using artifact_selector = loomc_string_view_t;
|
||||
#define LOOM_ARTIFACT_LAUNCH_CONFIG loomc_make_cstring_view(LOOMC_ARTIFACT_ROLE_LAUNCH_CONFIG)
|
||||
#define LOOM_ARTIFACT_KERNEL loomc_make_cstring_view(LOOMC_ARTIFACT_ROLE_KERNEL)
|
||||
static bool artifact_matches(const loomc_artifact_t * artifact, artifact_selector selector) {
|
||||
return loomc_string_view_equal(artifact->role, selector);
|
||||
}
|
||||
#else // defined(LOOMC_ARTIFACT_ROLE_COMPILE_REPORT)
|
||||
using artifact_selector = loomc_artifact_kind_t;
|
||||
#define LOOM_ARTIFACT_LAUNCH_CONFIG LOOMC_ARTIFACT_KIND_LAUNCH_CONFIG
|
||||
#define LOOM_ARTIFACT_KERNEL LOOMC_ARTIFACT_KIND_EXECUTABLE
|
||||
static bool artifact_matches(const loomc_artifact_t * artifact, artifact_selector selector) {
|
||||
return artifact->kind == selector;
|
||||
}
|
||||
#endif // defined(LOOMC_ARTIFACT_ROLE_COMPILE_REPORT)
|
||||
|
||||
static hrx_status_code_t status_code_from_loom(loomc_status_code_t code) {
|
||||
switch (code) {
|
||||
case LOOMC_STATUS_OK: return HRX_STATUS_OK;
|
||||
case LOOMC_STATUS_CANCELLED: return HRX_STATUS_CANCELLED;
|
||||
case LOOMC_STATUS_INVALID_ARGUMENT: return HRX_STATUS_INVALID_ARGUMENT;
|
||||
case LOOMC_STATUS_DEADLINE_EXCEEDED: return HRX_STATUS_DEADLINE_EXCEEDED;
|
||||
case LOOMC_STATUS_NOT_FOUND: return HRX_STATUS_NOT_FOUND;
|
||||
case LOOMC_STATUS_ALREADY_EXISTS: return HRX_STATUS_ALREADY_EXISTS;
|
||||
case LOOMC_STATUS_PERMISSION_DENIED: return HRX_STATUS_PERMISSION_DENIED;
|
||||
case LOOMC_STATUS_RESOURCE_EXHAUSTED: return HRX_STATUS_OUT_OF_MEMORY;
|
||||
case LOOMC_STATUS_FAILED_PRECONDITION: return HRX_STATUS_FAILED_PRECONDITION;
|
||||
case LOOMC_STATUS_ABORTED: return HRX_STATUS_ABORTED;
|
||||
case LOOMC_STATUS_OUT_OF_RANGE: return HRX_STATUS_OUT_OF_RANGE;
|
||||
case LOOMC_STATUS_UNIMPLEMENTED: return HRX_STATUS_UNIMPLEMENTED;
|
||||
case LOOMC_STATUS_UNAVAILABLE: return HRX_STATUS_UNAVAILABLE;
|
||||
case LOOMC_STATUS_DATA_LOSS: return HRX_STATUS_DATA_LOSS;
|
||||
default: return HRX_STATUS_INTERNAL;
|
||||
}
|
||||
}
|
||||
|
||||
static std::string format_loom_status(loomc_status_t status) {
|
||||
loomc_host_size_t length = 0;
|
||||
loomc_status_format(status, 0, nullptr, &length);
|
||||
std::string text(length + 1, '\0');
|
||||
loomc_host_size_t actual = 0;
|
||||
loomc_status_format(status, text.size(), text.data(), &actual);
|
||||
text.resize(actual);
|
||||
return text;
|
||||
}
|
||||
|
||||
static hrx_status_t make_status(hrx_status_code_t code, const std::string & message) {
|
||||
return hrx_make_status(code, message.c_str());
|
||||
}
|
||||
|
||||
// Takes ownership of the status.
|
||||
static hrx_status_t status_from_loom(loomc_status_t status, const char * what) {
|
||||
if (loomc_status_is_ok(status)) {
|
||||
return hrx_ok_status();
|
||||
}
|
||||
const hrx_status_code_t code = status_code_from_loom(loomc_status_code(status));
|
||||
const std::string message = std::string(what) + ": " + format_loom_status(status);
|
||||
loomc_status_free(status);
|
||||
return make_status(code, message);
|
||||
}
|
||||
|
||||
static hrx_status_t status_from_result(const loomc_result_t * result, const char * what) {
|
||||
if (result != nullptr && loomc_result_succeeded(result)) {
|
||||
return hrx_ok_status();
|
||||
}
|
||||
std::string message = what;
|
||||
if (result != nullptr) {
|
||||
for (loomc_host_size_t i = 0; i < loomc_result_diagnostic_count(result); ++i) {
|
||||
const loomc_diagnostic_t * diag = loomc_result_diagnostic_at(result, i);
|
||||
if (diag == nullptr) {
|
||||
continue;
|
||||
}
|
||||
message += "\n ";
|
||||
message.append(diag->code.data, diag->code.size);
|
||||
message += ": ";
|
||||
message.append(diag->message.data, diag->message.size);
|
||||
if (diag->range.start_line || diag->range.start_column) {
|
||||
message += " @ " + std::to_string(diag->range.start_line) + ":" + std::to_string(diag->range.start_column);
|
||||
}
|
||||
}
|
||||
}
|
||||
return make_status(HRX_STATUS_FAILED_PRECONDITION, message);
|
||||
}
|
||||
|
||||
static const loomc_artifact_t * find_artifact(const loomc_result_t * result, artifact_selector selector, const char * format) {
|
||||
const loomc_string_view_t fmt = loomc_make_cstring_view(format);
|
||||
for (loomc_host_size_t i = 0; i < loomc_result_artifact_count(result); ++i) {
|
||||
const loomc_artifact_t * artifact = loomc_result_artifact_at(result, i);
|
||||
if (artifact != nullptr && artifact_matches(artifact, selector) && loomc_string_view_equal(artifact->format, fmt)) {
|
||||
return artifact;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static hrx_status_t copy_artifact(const loomc_artifact_t * artifact, std::vector<uint8_t> & out) {
|
||||
loomc_byte_span_t contents = loomc_byte_span_empty();
|
||||
const bool borrowed = loomc_byte_sequence_try_get_contiguous_span(artifact->contents, &contents);
|
||||
if (!borrowed) {
|
||||
loomc_status_t status = loomc_byte_sequence_clone(artifact->contents, loomc_allocator_system(), &contents);
|
||||
if (!loomc_status_is_ok(status)) {
|
||||
return status_from_loom(status, "copy Loom artifact");
|
||||
}
|
||||
}
|
||||
out.assign(contents.data, contents.data + contents.data_length);
|
||||
if (!borrowed) {
|
||||
loomc_allocator_free(loomc_allocator_system(), const_cast<uint8_t *>(contents.data));
|
||||
}
|
||||
return hrx_ok_status();
|
||||
}
|
||||
|
||||
static hrx_status_t create_source(const ggml_hrx_loom_source & src, loomc_source_t ** out) {
|
||||
loomc_source_options_t options = {};
|
||||
options.type = LOOMC_STRUCTURE_TYPE_SOURCE_OPTIONS;
|
||||
options.structure_size = sizeof(options);
|
||||
options.format = LOOMC_SOURCE_FORMAT_TEXT;
|
||||
options.identifier = loomc_make_cstring_view(src.identifier);
|
||||
options.contents = loomc_make_byte_span(src.data, src.size);
|
||||
options.storage = LOOMC_SOURCE_STORAGE_BORROWED;
|
||||
return status_from_loom(loomc_source_create(&options, loomc_allocator_system(), out), "create Loom source");
|
||||
}
|
||||
|
||||
static hrx_status_t index_source(loomc_link_index_builder_t * builder, loomc_source_t * source, const char * name) {
|
||||
loomc_link_index_source_options_t options = {};
|
||||
options.provider_name = loomc_make_cstring_view(name);
|
||||
options.role = LOOMC_LINK_PROVIDER_ROLE_INPUT;
|
||||
return status_from_loom(loomc_link_index_builder_add_source(builder, source, &options, nullptr), "index Loom source");
|
||||
}
|
||||
|
||||
static hrx_status_t finish_index(loomc_link_index_builder_t * builder, loom_link_index & index) {
|
||||
loom_result result;
|
||||
hrx_status_t status = status_from_loom(loomc_link_index_builder_finish(builder, index.out(), result.out()), "finish Loom link index");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
return status_from_result(result.get(), "Loom source indexing failed");
|
||||
}
|
||||
|
||||
// config.decl ops are not call edges. A selective link drops them. Thus link all library sources into one archive first, then write it back as text.
|
||||
static hrx_status_t archive_sources(ggml_hrx_loom_jit * jit, loomc_linker_t * linker, loomc_workspace_t * workspace,
|
||||
const char * name, loom_link_index & index, loom_source & archived) {
|
||||
loom_module module;
|
||||
loom_result result;
|
||||
loomc_link_options_t options = {};
|
||||
options.type = LOOMC_STRUCTURE_TYPE_LINK_OPTIONS;
|
||||
options.structure_size = sizeof(options);
|
||||
options.link_index = index.get();
|
||||
options.module_name = loomc_make_cstring_view(name);
|
||||
options.flags = LOOMC_LINK_FLAG_STRIP_TEST_SYMBOLS;
|
||||
hrx_status_t status = status_from_loom(loomc_link_module(linker, workspace, &options, module.out(), result.out()), "archive Loom module");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = status_from_result(result.get(), "Loom archive link failed");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loomc_module_serialize_options_t serialize = {};
|
||||
serialize.type = LOOMC_STRUCTURE_TYPE_MODULE_SERIALIZE_OPTIONS;
|
||||
serialize.structure_size = sizeof(serialize);
|
||||
serialize.format = LOOMC_SOURCE_FORMAT_TEXT;
|
||||
serialize.identifier = loomc_make_cstring_view(name);
|
||||
status = status_from_loom(loomc_module_serialize_to_source(module.get(), &serialize, loomc_allocator_system(), archived.out()),
|
||||
"serialize Loom archive");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loom_link_index_builder builder;
|
||||
status = status_from_loom(loomc_link_index_builder_allocate(jit->context, nullptr, loomc_allocator_system(), builder.out()),
|
||||
"allocate Loom archive index");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = index_source(builder.get(), archived.get(), name);
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
return finish_index(builder.get(), index);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
hrx_status_t ggml_hrx_loom_jit_create(const char * processor, const char * kernel_target, ggml_hrx_loom_jit ** out_jit) {
|
||||
*out_jit = nullptr;
|
||||
if (processor == nullptr || processor[0] == '\0' || kernel_target == nullptr || kernel_target[0] == '\0') {
|
||||
return make_status(HRX_STATUS_INVALID_ARGUMENT, "Loom JIT needs a target processor");
|
||||
}
|
||||
std::unique_ptr<ggml_hrx_loom_jit> jit(new (std::nothrow) ggml_hrx_loom_jit());
|
||||
if (!jit) {
|
||||
return make_status(HRX_STATUS_OUT_OF_MEMORY, "allocate Loom JIT");
|
||||
}
|
||||
// Kernels and library providers use target.decl. The family records are requirements and do not follow the device.
|
||||
jit->targets = std::string("amdgpu.target<") + kernel_target + "> @ggml_wave32 {subgroup_size = 32}\n" +
|
||||
"amdgpu.target<" + kernel_target + "> @ggml_wave64 {subgroup_size = 64}\n" +
|
||||
"amdgpu.target<gfx11-generic> @ggml_gfx11\n" +
|
||||
"amdgpu.target<gfx12-generic> @ggml_gfx12\n";
|
||||
|
||||
hrx_status_t status = status_from_loom(loomc_target_environment_create_amdgpu(loomc_allocator_system(), &jit->target_environment),
|
||||
"create AMDGPU target environment");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loomc_context_target_options_t target_options = {};
|
||||
target_options.type = LOOMC_STRUCTURE_TYPE_CONTEXT_TARGET_OPTIONS;
|
||||
target_options.structure_size = sizeof(target_options);
|
||||
target_options.target_environment = jit->target_environment;
|
||||
loomc_context_options_t context_options = {};
|
||||
context_options.type = LOOMC_STRUCTURE_TYPE_CONTEXT_OPTIONS;
|
||||
context_options.structure_size = sizeof(context_options);
|
||||
context_options.next = &target_options;
|
||||
status = status_from_loom(loomc_context_create(&context_options, loomc_allocator_system(), &jit->context), "create Loom context");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loomc_amdgpu_profile_options_t profile = {};
|
||||
profile.type = LOOMC_STRUCTURE_TYPE_AMDGPU_PROFILE_OPTIONS;
|
||||
profile.structure_size = sizeof(profile);
|
||||
profile.identifier = loomc_make_cstring_view(processor);
|
||||
profile.identity.target = loomc_make_cstring_view(processor);
|
||||
status = status_from_loom(loomc_target_profile_create_amdgpu(jit->target_environment, &profile, loomc_allocator_system(), &jit->target_profile),
|
||||
"create AMDGPU target profile");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = status_from_loom(loomc_compiler_create(jit->context, nullptr, loomc_allocator_system(), &jit->compiler), "create Loom compiler");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loomc_target_pipeline_options_t pipeline = {};
|
||||
pipeline.type = LOOMC_STRUCTURE_TYPE_TARGET_PIPELINE_OPTIONS;
|
||||
pipeline.structure_size = sizeof(pipeline);
|
||||
pipeline.identifier = loomc_make_cstring_view("ggml-hrx-amdgpu");
|
||||
pipeline.kind = LOOMC_TARGET_PIPELINE_KIND_PREPARED_LOW;
|
||||
pipeline.control_flow_lowering = LOOMC_TARGET_CONTROL_FLOW_LOWERING_CFG;
|
||||
pipeline.source_to_low_max_errors = 20;
|
||||
loom_result result;
|
||||
status = status_from_loom(loomc_pass_program_create_from_target_pipeline(jit->context, &pipeline, loomc_allocator_system(),
|
||||
&jit->pass_program, result.out()),
|
||||
"create target pass program");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = status_from_result(result.get(), "target pass program failed");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
*out_jit = jit.release();
|
||||
return hrx_ok_status();
|
||||
}
|
||||
|
||||
void ggml_hrx_loom_jit_free(ggml_hrx_loom_jit * jit) {
|
||||
delete jit;
|
||||
}
|
||||
|
||||
hrx_status_t ggml_hrx_loom_compile(ggml_hrx_loom_jit * jit, const ggml_hrx_loom_compile_options * options,
|
||||
ggml_hrx_loom_compile_result * out_result) {
|
||||
out_result->hsaco.clear();
|
||||
out_result->launch = nullptr;
|
||||
if (options->source.data == nullptr || options->source.size == 0 || options->symbol == nullptr) {
|
||||
return make_status(HRX_STATUS_INVALID_ARGUMENT, "Loom compile needs a source and a symbol");
|
||||
}
|
||||
const char * symbol = options->symbol;
|
||||
|
||||
loom_workspace workspace;
|
||||
hrx_status_t status = status_from_loom(loomc_workspace_create(nullptr, loomc_allocator_system(), workspace.out()),
|
||||
"create Loom workspace");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loom_link_index_builder builder;
|
||||
status = status_from_loom(loomc_link_index_builder_allocate(jit->context, nullptr, loomc_allocator_system(), builder.out()),
|
||||
"allocate Loom link index");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
std::vector<ggml_hrx_loom_source> inputs = { options->source };
|
||||
inputs.insert(inputs.end(), options->deps, options->deps + options->n_deps);
|
||||
inputs.push_back({ jit->targets.data(), jit->targets.size(), "ggml-hrx-targets.loom" });
|
||||
|
||||
// The sources must stay alive until the index is complete.
|
||||
std::vector<std::unique_ptr<loom_source>> sources;
|
||||
for (const ggml_hrx_loom_source & src : inputs) {
|
||||
sources.emplace_back(new loom_source());
|
||||
status = create_source(src, sources.back()->out());
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = index_source(builder.get(), sources.back()->get(), src.identifier);
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
}
|
||||
loom_link_index index;
|
||||
status = finish_index(builder.get(), index);
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loom_linker linker;
|
||||
status = status_from_loom(loomc_linker_create(jit->context, nullptr, loomc_allocator_system(), linker.out()), "create Loom linker");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loom_source archived;
|
||||
status = archive_sources(jit, linker.get(), workspace.get(), options->source.identifier, index, archived);
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
std::vector<loomc_config_binding_t> config(options->n_config);
|
||||
for (size_t i = 0; i < options->n_config; ++i) {
|
||||
config[i].key = loomc_make_cstring_view(options->config[i].key);
|
||||
config[i].value = loomc_make_cstring_view(options->config[i].value);
|
||||
}
|
||||
|
||||
const loomc_target_specialization_t specialization = { loomc_make_cstring_view(symbol), jit->target_profile };
|
||||
loomc_target_specialization_options_t target_options = {};
|
||||
target_options.type = LOOMC_STRUCTURE_TYPE_TARGET_SPECIALIZATION_OPTIONS;
|
||||
target_options.structure_size = sizeof(target_options);
|
||||
target_options.specializations = &specialization;
|
||||
target_options.specialization_count = 1;
|
||||
|
||||
const loomc_string_view_t roots[] = { loomc_make_cstring_view(symbol) };
|
||||
loomc_link_options_t link = {};
|
||||
link.type = LOOMC_STRUCTURE_TYPE_LINK_OPTIONS;
|
||||
link.structure_size = sizeof(link);
|
||||
link.next = &target_options;
|
||||
link.mode = LOOMC_LINK_MODE_LINK;
|
||||
link.link_index = index.get();
|
||||
link.module_name = loomc_make_cstring_view(symbol);
|
||||
link.root_symbols = roots;
|
||||
link.root_symbol_count = 1;
|
||||
link.flags = LOOMC_LINK_FLAG_STRIP_TEST_SYMBOLS;
|
||||
link.config.bindings = config.empty() ? nullptr : config.data();
|
||||
link.config.binding_count = config.size();
|
||||
|
||||
loom_module module;
|
||||
loom_result result;
|
||||
status = status_from_loom(loomc_link_module(linker.get(), workspace.get(), &link, module.out(), result.out()), "link Loom root");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = status_from_result(result.get(), "Loom root link failed");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loomc_compile_options_t compile = {};
|
||||
compile.type = LOOMC_STRUCTURE_TYPE_COMPILE_OPTIONS;
|
||||
compile.structure_size = sizeof(compile);
|
||||
compile.next = &target_options;
|
||||
compile.module_name = loomc_make_cstring_view(symbol);
|
||||
compile.artifact_flags = LOOMC_COMPILE_ARTIFACT_FLAG_LAUNCH_CONFIG;
|
||||
compile.config_flags = LOOMC_CONFIG_POLICY_FLAG_REQUIRE_RESOLVED;
|
||||
status = status_from_loom(loomc_compile_module(jit->compiler, workspace.get(), jit->pass_program, module.get(), &compile,
|
||||
loomc_allocator_system(), result.out()),
|
||||
"compile Loom module");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = status_from_result(result.get(), "Loom compilation failed");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
const loomc_artifact_t * launch_artifact = find_artifact(result.get(), LOOM_ARTIFACT_LAUNCH_CONFIG, LOOMC_ARTIFACT_FORMAT_LOOM_BYTECODE);
|
||||
if (launch_artifact == nullptr) {
|
||||
return make_status(HRX_STATUS_NOT_FOUND, "Loom did not return a launch config");
|
||||
}
|
||||
std::unique_ptr<ggml_hrx_loom_launch_program> launch(new (std::nothrow) ggml_hrx_loom_launch_program());
|
||||
if (!launch) {
|
||||
return make_status(HRX_STATUS_OUT_OF_MEMORY, "allocate Loom launch program");
|
||||
}
|
||||
status = status_from_loom(loomc_launch_config_program_load(launch_artifact, loomc_allocator_system(), &launch->program),
|
||||
"load Loom launch config");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = status_from_loom(loomc_launch_config_program_lookup_function(launch->program, loomc_make_cstring_view(symbol), &launch->function),
|
||||
"find Loom launch config function");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
loomc_emit_options_t emit = {};
|
||||
emit.type = LOOMC_STRUCTURE_TYPE_EMIT_OPTIONS;
|
||||
emit.structure_size = sizeof(emit);
|
||||
emit.artifact_format = loomc_make_cstring_view(LOOMC_ARTIFACT_FORMAT_AMDGPU_HSACO);
|
||||
emit.identifier = loomc_make_cstring_view(symbol);
|
||||
emit.artifact_flags = LOOMC_EMIT_ARTIFACT_FLAG_PRIMARY;
|
||||
status = status_from_loom(loomc_emit_module(jit->target_environment, workspace.get(), module.get(), &emit,
|
||||
loomc_allocator_system(), result.out()),
|
||||
"emit AMDGPU code object");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
status = status_from_result(result.get(), "AMDGPU code object emission failed");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
const loomc_artifact_t * hsaco = find_artifact(result.get(), LOOM_ARTIFACT_KERNEL, LOOMC_ARTIFACT_FORMAT_AMDGPU_HSACO);
|
||||
if (hsaco == nullptr) {
|
||||
return make_status(HRX_STATUS_NOT_FOUND, "Loom did not return an AMDGPU code object");
|
||||
}
|
||||
status = copy_artifact(hsaco, out_result->hsaco);
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
|
||||
out_result->launch = launch.release();
|
||||
return hrx_ok_status();
|
||||
}
|
||||
|
||||
void ggml_hrx_loom_launch_program_free(ggml_hrx_loom_launch_program * program) {
|
||||
delete program;
|
||||
}
|
||||
|
||||
hrx_status_t ggml_hrx_loom_launch_program_eval(ggml_hrx_loom_launch_program * program, const int64_t * workload,
|
||||
size_t n_workload, ggml_hrx_loom_launch_config * out_config) {
|
||||
std::vector<uint64_t> bits(workload, workload + n_workload);
|
||||
|
||||
loomc_launch_config_t config = {};
|
||||
config.type = LOOMC_STRUCTURE_TYPE_LAUNCH_CONFIG;
|
||||
config.structure_size = sizeof(config);
|
||||
|
||||
std::lock_guard<std::mutex> lock(program->mutex);
|
||||
auto it = program->results.find(bits);
|
||||
if (it != program->results.end()) {
|
||||
*out_config = it->second;
|
||||
return hrx_ok_status();
|
||||
}
|
||||
hrx_status_t status = status_from_loom(loomc_launch_config_program_invoke(program->program, program->function,
|
||||
bits.empty() ? nullptr : bits.data(), bits.size(), &config),
|
||||
"evaluate Loom launch config");
|
||||
if (!hrx_status_is_ok(status)) {
|
||||
return status;
|
||||
}
|
||||
if (!config.workgroup_count.x || !config.workgroup_count.y || !config.workgroup_count.z ||
|
||||
!config.workgroup_size.x || !config.workgroup_size.y || !config.workgroup_size.z) {
|
||||
return make_status(HRX_STATUS_FAILED_PRECONDITION, "Loom launch config has an empty workgroup count or size");
|
||||
}
|
||||
out_config->workgroup_count[0] = config.workgroup_count.x;
|
||||
out_config->workgroup_count[1] = config.workgroup_count.y;
|
||||
out_config->workgroup_count[2] = config.workgroup_count.z;
|
||||
out_config->workgroup_size[0] = config.workgroup_size.x;
|
||||
out_config->workgroup_size[1] = config.workgroup_size.y;
|
||||
out_config->workgroup_size[2] = config.workgroup_size.z;
|
||||
out_config->subgroup_size = config.subgroup_size;
|
||||
if (program->results.size() >= GGML_HRX_LOOM_MAX_LAUNCH_RESULTS) {
|
||||
program->results.clear();
|
||||
}
|
||||
program->results.emplace(std::move(bits), *out_config);
|
||||
return hrx_ok_status();
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include "hrx_runtime.h"
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
// Shapes go to kernels as launch scalars. Thus each kernel and config pair compiles only one time.
|
||||
|
||||
struct ggml_hrx_loom_jit;
|
||||
struct ggml_hrx_loom_launch_program;
|
||||
|
||||
struct ggml_hrx_loom_source {
|
||||
const void * data = nullptr;
|
||||
size_t size = 0;
|
||||
const char * identifier = nullptr;
|
||||
};
|
||||
|
||||
struct ggml_hrx_loom_config_binding {
|
||||
const char * key = nullptr;
|
||||
const char * value = nullptr;
|
||||
};
|
||||
|
||||
struct ggml_hrx_loom_compile_options {
|
||||
ggml_hrx_loom_source source;
|
||||
const ggml_hrx_loom_source * deps = nullptr;
|
||||
size_t n_deps = 0;
|
||||
const ggml_hrx_loom_config_binding * config = nullptr;
|
||||
size_t n_config = 0;
|
||||
const char * symbol = nullptr;
|
||||
};
|
||||
|
||||
struct ggml_hrx_loom_launch_config {
|
||||
uint32_t workgroup_count[3] = { 0, 0, 0 };
|
||||
uint32_t workgroup_size[3] = { 0, 0, 0 };
|
||||
uint32_t subgroup_size = 0;
|
||||
};
|
||||
|
||||
struct ggml_hrx_loom_compile_result {
|
||||
std::vector<uint8_t> hsaco;
|
||||
ggml_hrx_loom_launch_program * launch = nullptr; // On success, the caller owns this.
|
||||
};
|
||||
|
||||
// processor: the device architecture. kernel_target: the AMDGPU target of @ggml_wave32 and @ggml_wave64.
|
||||
hrx_status_t ggml_hrx_loom_jit_create(const char * processor, const char * kernel_target, ggml_hrx_loom_jit ** out_jit);
|
||||
void ggml_hrx_loom_jit_free(ggml_hrx_loom_jit * jit);
|
||||
|
||||
// Not thread safe. Callers must lock each jit.
|
||||
hrx_status_t ggml_hrx_loom_compile(ggml_hrx_loom_jit * jit,
|
||||
const ggml_hrx_loom_compile_options * options,
|
||||
ggml_hrx_loom_compile_result * out_result);
|
||||
|
||||
void ggml_hrx_loom_launch_program_free(ggml_hrx_loom_launch_program * program);
|
||||
hrx_status_t ggml_hrx_loom_launch_program_eval(ggml_hrx_loom_launch_program * program,
|
||||
const int64_t * workload,
|
||||
size_t n_workload,
|
||||
ggml_hrx_loom_launch_config * out_config);
|
||||
@@ -0,0 +1,136 @@
|
||||
#include "ggml-hrx-ops.h"
|
||||
|
||||
#include <climits>
|
||||
#include <string>
|
||||
|
||||
// Must match the dst type codes in copy/cpy_f32.loom and rows/set_rows_f32.loom.
|
||||
static int ggml_hrx_cpy_dst_code(ggml_type type) {
|
||||
switch (type) {
|
||||
case GGML_TYPE_F32: return 0;
|
||||
case GGML_TYPE_F16: return 1;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
static int64_t ggml_hrx_span(const ggml_tensor * t) {
|
||||
return (int64_t) (ggml_nbytes(t) / ggml_type_size(t->type));
|
||||
}
|
||||
|
||||
// Indices and spans are 32-bit launch scalars.
|
||||
static bool ggml_hrx_fits_i32(const ggml_tensor * t) {
|
||||
return ggml_nelements(t) < INT_MAX && ggml_hrx_span(t) < INT_MAX;
|
||||
}
|
||||
|
||||
// The kernel does not use the stride of a size-1 dim. Set it to 0.
|
||||
static bool ggml_hrx_launch_strides(const ggml_tensor * t, int64_t s[GGML_MAX_DIMS]) {
|
||||
if (!ggml_hrx_elem_strides(t, s)) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < GGML_MAX_DIMS; ++i) {
|
||||
if (t->ne[i] == 1) {
|
||||
s[i] = 0;
|
||||
}
|
||||
if (s[i] >= INT_MAX) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ggml_hrx_supports_cpy(const ggml_hrx_device_context * dev, const ggml_tensor * op) {
|
||||
GGML_UNUSED(dev);
|
||||
const ggml_tensor * src = op->src[0];
|
||||
if (src == nullptr || src->type != GGML_TYPE_F32 || ggml_hrx_cpy_dst_code(op->type) < 0 ||
|
||||
ggml_nelements(src) != ggml_nelements(op)) {
|
||||
return false;
|
||||
}
|
||||
int64_t s[GGML_MAX_DIMS];
|
||||
if (!ggml_hrx_launch_strides(src, s) || !ggml_hrx_launch_strides(op, s)) {
|
||||
return false;
|
||||
}
|
||||
return ggml_hrx_fits_i32(src) && ggml_hrx_fits_i32(op);
|
||||
}
|
||||
|
||||
bool ggml_hrx_op_cpy(ggml_backend_hrx_context * ctx, const ggml_tensor * node) {
|
||||
const ggml_tensor * src = node->src[0];
|
||||
const ggml_tensor * dst = node;
|
||||
const int64_t n = ggml_nelements(dst);
|
||||
const bool stream = dst->type == GGML_TYPE_F32 && n % 4 == 0 && ggml_is_contiguous(src) && ggml_is_contiguous(dst);
|
||||
const int64_t groups = stream ? ggml_hrx_stream_groups(ctx->device, n) : 0;
|
||||
if (groups > 0) {
|
||||
ggml_hrx_kernel_desc desc;
|
||||
desc.file = "copy/cpy_f32.loom";
|
||||
desc.symbol = "ggml_cpy_f32_stream";
|
||||
desc.config.push_back(ggml_hrx_elementwise_wg_config(ctx->device));
|
||||
return ggml_hrx_dispatch(ctx, ggml_hrx_get_kernel(ctx->device, desc), { groups }, { n, groups }, { src, dst });
|
||||
}
|
||||
|
||||
int64_t ss[GGML_MAX_DIMS];
|
||||
int64_t ts[GGML_MAX_DIMS];
|
||||
ggml_hrx_launch_strides(src, ss);
|
||||
ggml_hrx_launch_strides(dst, ts);
|
||||
|
||||
ggml_hrx_kernel_desc desc;
|
||||
desc.file = "copy/cpy_f32.loom";
|
||||
desc.symbol = "ggml_cpy_f32";
|
||||
desc.config = { { "ggml.cpy.dst_type", std::to_string(ggml_hrx_cpy_dst_code(dst->type)) } };
|
||||
desc.config.push_back(ggml_hrx_elementwise_wg_config(ctx->device));
|
||||
ggml_hrx_kernel * kernel = ggml_hrx_get_kernel(ctx->device, desc);
|
||||
|
||||
// src and dst can have different shapes. Both use logical element order.
|
||||
return ggml_hrx_dispatch(ctx, kernel, { n },
|
||||
{
|
||||
n,
|
||||
src->ne[0], src->ne[1], src->ne[2], ss[0], ss[1], ss[2], ss[3], ggml_hrx_span(src),
|
||||
dst->ne[0], dst->ne[1], dst->ne[2], ts[0], ts[1], ts[2], ts[3], ggml_hrx_span(dst),
|
||||
},
|
||||
{ src, dst });
|
||||
}
|
||||
|
||||
bool ggml_hrx_supports_set_rows(const ggml_hrx_device_context * dev, const ggml_tensor * op) {
|
||||
GGML_UNUSED(dev);
|
||||
const ggml_tensor * src = op->src[0];
|
||||
const ggml_tensor * ids = op->src[1];
|
||||
if (src->type != GGML_TYPE_F32 || ggml_hrx_cpy_dst_code(op->type) < 0 || ids->type != GGML_TYPE_I64) {
|
||||
return false;
|
||||
}
|
||||
int64_t s[GGML_MAX_DIMS];
|
||||
if (!ggml_hrx_elem_strides(src, s) || !ggml_hrx_elem_strides(ids, s) || !ggml_hrx_elem_strides(op, s)) {
|
||||
return false;
|
||||
}
|
||||
return ggml_hrx_fits_i32(op) && ggml_hrx_fits_i32(src) && ggml_hrx_fits_i32(ids);
|
||||
}
|
||||
|
||||
bool ggml_hrx_op_set_rows(ggml_backend_hrx_context * ctx, const ggml_tensor * node) {
|
||||
const ggml_tensor * src = node->src[0];
|
||||
const ggml_tensor * ids = node->src[1];
|
||||
|
||||
const int64_t n = ggml_nelements(src);
|
||||
if (n == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
int64_t ss[GGML_MAX_DIMS];
|
||||
int64_t is[GGML_MAX_DIMS];
|
||||
int64_t ds[GGML_MAX_DIMS];
|
||||
ggml_hrx_elem_strides(src, ss);
|
||||
ggml_hrx_elem_strides(ids, is);
|
||||
ggml_hrx_elem_strides(node, ds);
|
||||
|
||||
ggml_hrx_kernel_desc desc;
|
||||
desc.file = "rows/set_rows_f32.loom";
|
||||
desc.symbol = "ggml_set_rows_f32";
|
||||
desc.config = { { "ggml.set_rows.dst_type", std::to_string(ggml_hrx_cpy_dst_code(node->type)) } };
|
||||
desc.config.push_back(ggml_hrx_elementwise_wg_config(ctx->device));
|
||||
ggml_hrx_kernel * kernel = ggml_hrx_get_kernel(ctx->device, desc);
|
||||
|
||||
// node is the dst view. Its binding covers only the rows that the kernel can write.
|
||||
return ggml_hrx_dispatch(ctx, kernel, { n },
|
||||
{
|
||||
n, src->ne[0], src->ne[1], src->ne[2],
|
||||
ss[0], ss[1], ss[2], ss[3], ggml_hrx_span(src),
|
||||
ids->ne[1], ids->ne[2], is[0], is[1], is[2], ggml_hrx_span(ids),
|
||||
node->ne[1], ds[0], ds[1], ds[2], ds[3], ggml_hrx_span(node),
|
||||
},
|
||||
{ src, ids, node });
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
#include "ggml-hrx-ops.h"
|
||||
|
||||
#include <climits>
|
||||
#include <string>
|
||||
|
||||
// The matrix-op kernel (kernels/matmul/mul_mat_wmma.loom) gets wave32 providers for gfx11 and gfx12 from motifs/wmma.loom.
|
||||
// Other archs use the tiled kernel without matrix ops until their layout is validated.
|
||||
static bool ggml_hrx_mul_mat_wmma_arch(const ggml_hrx_device_context * dev) {
|
||||
const ggml_hrx_matrix_op op = dev->arch->matrix_op;
|
||||
return (op == GGML_HRX_MATRIX_OP_WMMA_GFX11 || op == GGML_HRX_MATRIX_OP_WMMA_GFX12) && dev->arch->wave32;
|
||||
}
|
||||
|
||||
// Weight type config value of kernels/matmul/lib/mm_core.loom. The value is -1 if the type is not supported.
|
||||
static int ggml_hrx_mul_mat_weight_type(ggml_type type) {
|
||||
switch (type) {
|
||||
case GGML_TYPE_Q4_0: return 2;
|
||||
default: return -1;
|
||||
}
|
||||
}
|
||||
|
||||
// Weight strides and spans are in halves. Q4_0 blocks have only 2-byte alignment.
|
||||
static bool ggml_hrx_mul_mat_weight_strides(const ggml_tensor * w, int64_t s[GGML_MAX_DIMS]) {
|
||||
if (w->view_offs % 2 != 0) {
|
||||
return false;
|
||||
}
|
||||
for (int i = 0; i < GGML_MAX_DIMS; ++i) {
|
||||
if (w->nb[i] % 2 != 0) {
|
||||
return false;
|
||||
}
|
||||
s[i] = (int64_t) (w->nb[i] / 2);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ggml_hrx_supports_mul_mat(const ggml_hrx_device_context * dev, const ggml_tensor * op) {
|
||||
const ggml_tensor * w = op->src[0];
|
||||
const ggml_tensor * x = op->src[1];
|
||||
if (ggml_hrx_mul_mat_weight_type(w->type) < 0 || x->type != GGML_TYPE_F32 || op->type != GGML_TYPE_F32) {
|
||||
return false;
|
||||
}
|
||||
// graph_compute skips an empty dst (for example no output rows).
|
||||
if (ggml_is_empty(op)) {
|
||||
return true;
|
||||
}
|
||||
int64_t s[GGML_MAX_DIMS];
|
||||
if (!ggml_hrx_mul_mat_weight_strides(w, s) || !ggml_hrx_elem_strides(x, s) || !ggml_hrx_elem_strides(op, s)) {
|
||||
return false;
|
||||
}
|
||||
if (x->view_offs % sizeof(float) != 0 || op->nb[0] != sizeof(float)) {
|
||||
return false;
|
||||
}
|
||||
// An empty tensor cannot be a buffer binding.
|
||||
if (ggml_is_empty(w) || ggml_is_empty(x)) {
|
||||
return false;
|
||||
}
|
||||
// The tiled kernels use one workgroup in y for each 32 rows or columns.
|
||||
const int64_t max_yz = dev->arch->max_workgroups_yz;
|
||||
if ((w->ne[1] + 31) / 32 > max_yz || (x->ne[1] + 31) / 32 > max_yz || x->ne[2] * x->ne[3] > max_yz) {
|
||||
return false;
|
||||
}
|
||||
// Indices, strides and spans are 32-bit launch scalars.
|
||||
return ggml_nbytes(w) <= INT_MAX && ggml_nbytes(x) <= INT_MAX && ggml_nbytes(op) <= INT_MAX;
|
||||
}
|
||||
|
||||
// The matrix-op kernel needs contiguous input rows.
|
||||
// It converts src1 to F16. The src1 precision request must allow this.
|
||||
static bool ggml_hrx_mul_mat_use_wmma(const ggml_tensor * node, const int64_t xs[GGML_MAX_DIMS]) {
|
||||
const ggml_prec prec_src1 = ggml_prec_get_src(node, 1);
|
||||
if (prec_src1 != GGML_PREC_UNDEFINED && prec_src1 < GGML_PREC_F16) {
|
||||
return false;
|
||||
}
|
||||
return xs[0] == 1;
|
||||
}
|
||||
|
||||
bool ggml_hrx_op_mul_mat(ggml_backend_hrx_context * ctx, const ggml_tensor * node) {
|
||||
const ggml_tensor * w = node->src[0];
|
||||
const ggml_tensor * x = node->src[1];
|
||||
|
||||
int64_t ws[GGML_MAX_DIMS];
|
||||
int64_t xs[GGML_MAX_DIMS];
|
||||
int64_t ds[GGML_MAX_DIMS];
|
||||
ggml_hrx_mul_mat_weight_strides(w, ws);
|
||||
ggml_hrx_elem_strides(x, xs);
|
||||
ggml_hrx_elem_strides(node, ds);
|
||||
|
||||
const ggml_hrx_mul_mat_vec_tune & mv = ctx->device->tune->mul_mat_vec[w->type];
|
||||
// The vector kernel reads K in 256-value superblocks with 4-wide activation loads.
|
||||
// The choice does not depend on the column count. Thus a column gets the same result for each batch size.
|
||||
const bool k_tail = w->ne[0] % 256 != 0;
|
||||
const bool vec = x->ne[1] <= mv.max_cols && w->ne[0] <= mv.xs_max_k && xs[0] == 1;
|
||||
const bool wmma = x->ne[1] > mv.max_cols && ggml_hrx_mul_mat_wmma_arch(ctx->device) &&
|
||||
ggml_hrx_mul_mat_use_wmma(node, xs);
|
||||
|
||||
const int64_t n_batch = x->ne[2] * x->ne[3];
|
||||
|
||||
ggml_hrx_kernel_desc desc;
|
||||
desc.file = wmma ? "matmul/mul_mat_wmma.loom" : "matmul/mul_mat.loom";
|
||||
desc.symbol = wmma ? "ggml_mul_mat_wmma" : vec ? "ggml_mul_mat_vec_xs" : "ggml_mul_mat_tiled";
|
||||
desc.libs = { "motifs/common.loom", "motifs/q4_0.loom", "matmul/lib/mm_core.loom", "matmul/lib/mm_vec.loom" };
|
||||
if (wmma) {
|
||||
desc.libs.push_back("matmul/lib/mm_wmma.loom");
|
||||
desc.libs.push_back("motifs/wmma.loom");
|
||||
}
|
||||
desc.config = { { "ggml.mul_mat.weight_type", std::to_string(ggml_hrx_mul_mat_weight_type(w->type)) } };
|
||||
if (vec) {
|
||||
desc.config.push_back({ "ggml.mul_mat.vec_cols", std::to_string(x->ne[1]) });
|
||||
desc.config.push_back({ "ggml.mul_mat.vec_xs_workgroups", std::to_string(mv.xs_wg_per_cu * ctx->device->n_cu) });
|
||||
desc.config.push_back({ "ggml.mul_mat.vec_xs_depth", std::to_string(mv.xs_depth) });
|
||||
desc.config.push_back({ "ggml.mul_mat.vec_k_tail", k_tail ? "1" : "0" });
|
||||
}
|
||||
ggml_hrx_kernel * kernel = ggml_hrx_get_kernel(ctx->device, desc);
|
||||
|
||||
std::vector<int64_t> workload;
|
||||
if (vec) {
|
||||
workload = { w->ne[1], w->ne[0], n_batch };
|
||||
} else {
|
||||
workload = { w->ne[1], x->ne[1], n_batch };
|
||||
}
|
||||
|
||||
return ggml_hrx_dispatch(ctx, kernel, workload,
|
||||
{
|
||||
w->ne[0], w->ne[1], x->ne[1], x->ne[2], x->ne[2] / w->ne[2], x->ne[3] / w->ne[3],
|
||||
ws[1], ws[2], ws[3], (int64_t) (ggml_nbytes(w) / 2),
|
||||
xs[0], xs[1], xs[2], xs[3], (int64_t) (ggml_nbytes(x) / sizeof(float)),
|
||||
ds[1], ds[2], ds[3], (int64_t) (ggml_nbytes(node) / sizeof(float)),
|
||||
},
|
||||
{ w, x, node });
|
||||
}
|
||||
@@ -865,6 +865,7 @@ struct ggml_backend_opencl_context {
|
||||
|
||||
cl_kernel kernel_add, kernel_add_row, kernel_add_f16, kernel_add_row_f16;
|
||||
cl_kernel kernel_mul, kernel_mul_row, kernel_mul_f16, kernel_mul_row_f16;
|
||||
cl_kernel kernel_mul_mat_scale = nullptr;
|
||||
cl_kernel kernel_div, kernel_div_row, kernel_div_f16, kernel_div_row_f16;
|
||||
cl_kernel kernel_sub, kernel_sub_row, kernel_sub_f16, kernel_sub_row_f16;
|
||||
cl_kernel kernel_add_id;
|
||||
@@ -1573,6 +1574,7 @@ struct ggml_backend_opencl_context {
|
||||
#endif
|
||||
for (cl_kernel kernel : {
|
||||
kernel_gemv_f32_f32_mcr,
|
||||
kernel_mul_mat_scale,
|
||||
kernel_xielu_f32,
|
||||
kernel_xielu_f16,
|
||||
kernel_mul_mm_f16_f32_kq_p8,
|
||||
@@ -4584,6 +4586,7 @@ static void load_cl_kernels(ggml_backend_opencl_context *backend_ctx) {
|
||||
CL_CHECK((backend_ctx->kernel_mul_row = clCreateKernel(backend_ctx->program_mul, "kernel_mul_row", &err), err));
|
||||
CL_CHECK((backend_ctx->kernel_mul_f16 = clCreateKernel(backend_ctx->program_mul, "kernel_mul_f16", &err), err));
|
||||
CL_CHECK((backend_ctx->kernel_mul_row_f16 = clCreateKernel(backend_ctx->program_mul, "kernel_mul_row_f16", &err), err));
|
||||
CL_CHECK((backend_ctx->kernel_mul_mat_scale = clCreateKernel(backend_ctx->program_mul, "kernel_mul_mat_scale", &err), err));
|
||||
GGML_LOG_CONT(".");
|
||||
}
|
||||
|
||||
@@ -11380,7 +11383,7 @@ static void ggml_cl_moe_gemm_coopmat(
|
||||
clReleaseMemObject(buf_dst_image);
|
||||
}
|
||||
|
||||
static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
|
||||
static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
|
||||
|
||||
// Runs the gate and up matmuls unchanged, then one kernel in place of
|
||||
// add_id(gate) + add_id(up) + swiglu_oai. See ggml_opencl_can_fuse_moe_bias_glu.
|
||||
@@ -11388,8 +11391,8 @@ static void ggml_cl_moe_bias_glu_fused(ggml_backend_t backend, ggml_tensor * gat
|
||||
ggml_tensor * up_mm, const ggml_tensor * up_add, const ggml_tensor * glu) {
|
||||
ggml_backend_opencl_context * backend_ctx = (ggml_backend_opencl_context *)backend->context;
|
||||
|
||||
ggml_cl_mul_mat_id(backend, gate_mm->src[0], gate_mm->src[1], gate_mm);
|
||||
ggml_cl_mul_mat_id(backend, up_mm->src[0], up_mm->src[1], up_mm);
|
||||
ggml_cl_mul_mat_ext(backend, gate_mm->src[0], gate_mm->src[1], gate_mm);
|
||||
ggml_cl_mul_mat_ext(backend, up_mm->src[0], up_mm->src[1], up_mm);
|
||||
|
||||
const ggml_tensor * gbias = gate_add->src[1];
|
||||
const ggml_tensor * ubias = up_add->src[1];
|
||||
@@ -11678,6 +11681,10 @@ static bool ggml_opencl_can_fuse(const ggml_backend_opencl_context * backend_ctx
|
||||
const ggml_tensor *up = cgraph->nodes[node_idx+1];
|
||||
const ggml_tensor *glu = cgraph->nodes[node_idx+2];
|
||||
|
||||
if (ggml_get_src_scale(gate, 0) || ggml_get_src_scale(up, 0)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// decode GEMV path only (single token); prefill GEMM is separate
|
||||
if (gate->ne[1] != 1 || up->ne[1] != 1) {
|
||||
return false;
|
||||
@@ -12746,10 +12753,6 @@ 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;
|
||||
@@ -39795,6 +39798,70 @@ static void ggml_cl_mul_mat_id(ggml_backend_t backend, const ggml_tensor * src0,
|
||||
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst);
|
||||
}
|
||||
|
||||
static void ggml_cl_mul_mat_ext(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
const ggml_tensor * ids = dst->op == GGML_OP_MUL_MAT_ID ? dst->src[2] : nullptr;
|
||||
if (ids) {
|
||||
ggml_cl_mul_mat_id(backend, src0, src1, dst);
|
||||
} else {
|
||||
ggml_cl_mul_mat(backend, src0, src1, dst);
|
||||
}
|
||||
|
||||
const ggml_tensor * scale = ggml_get_src_scale(dst, 0);
|
||||
if (!scale) {
|
||||
return;
|
||||
}
|
||||
GGML_ASSERT(ggml_is_contiguous(dst) && dst->type == GGML_TYPE_F32 && scale->type == GGML_TYPE_F32);
|
||||
|
||||
cl_ulong channel_stride = 0;
|
||||
cl_ulong expert_stride = 0;
|
||||
if (!ggml_is_scalar(scale)) {
|
||||
if (ids && ggml_is_vector(scale) && scale->ne[0] == src0->ne[2]) {
|
||||
expert_stride = scale->nb[0];
|
||||
} else {
|
||||
channel_stride = scale->nb[0];
|
||||
expert_stride = ids ? scale->nb[1] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
auto * backend_ctx = (ggml_backend_opencl_context *) backend->context;
|
||||
auto * ed = (ggml_tensor_extra_cl *) dst->extra;
|
||||
auto * es = (ggml_tensor_extra_cl *) scale->extra;
|
||||
auto * ei = ids ? (ggml_tensor_extra_cl *) ids->extra : nullptr;
|
||||
const cl_ulong offsetd = ed->offset + dst->view_offs;
|
||||
const cl_ulong offsets = es->offset + scale->view_offs;
|
||||
const cl_mem ids_buf = ids ? ei->data_device : nullptr;
|
||||
const cl_ulong offseti = ids ? ei->offset + ids->view_offs : 0;
|
||||
const cl_ulong ids_nb0 = ids ? ids->nb[0] : 0;
|
||||
const cl_ulong ids_nb1 = ids ? ids->nb[1] : 0;
|
||||
const cl_long n_expert = src0->ne[2];
|
||||
const int ne0 = dst->ne[0];
|
||||
const int ne1 = dst->ne[1];
|
||||
|
||||
cl_kernel kernel = backend_ctx->kernel_mul_mat_scale;
|
||||
CL_CHECK(clSetKernelArg(kernel, 0, sizeof(cl_mem), &ed->data_device));
|
||||
CL_CHECK(clSetKernelArg(kernel, 1, sizeof(cl_ulong), &offsetd));
|
||||
CL_CHECK(clSetKernelArg(kernel, 2, sizeof(cl_mem), &es->data_device));
|
||||
CL_CHECK(clSetKernelArg(kernel, 3, sizeof(cl_ulong), &offsets));
|
||||
CL_CHECK(clSetKernelArg(kernel, 4, sizeof(cl_ulong), &channel_stride));
|
||||
CL_CHECK(clSetKernelArg(kernel, 5, sizeof(cl_ulong), &expert_stride));
|
||||
CL_CHECK(clSetKernelArg(kernel, 6, sizeof(cl_mem), &ids_buf));
|
||||
CL_CHECK(clSetKernelArg(kernel, 7, sizeof(cl_ulong), &offseti));
|
||||
CL_CHECK(clSetKernelArg(kernel, 8, sizeof(cl_ulong), &ids_nb0));
|
||||
CL_CHECK(clSetKernelArg(kernel, 9, sizeof(cl_ulong), &ids_nb1));
|
||||
CL_CHECK(clSetKernelArg(kernel, 10, sizeof(cl_long), &n_expert));
|
||||
CL_CHECK(clSetKernelArg(kernel, 11, sizeof(int), &ne0));
|
||||
CL_CHECK(clSetKernelArg(kernel, 12, sizeof(int), &ne1));
|
||||
|
||||
// few rows (decode): 1 element per work-item to keep enough work-items, else 8
|
||||
const size_t nth = 128;
|
||||
const size_t nrows = (size_t) ne1*dst->ne[2]*dst->ne[3];
|
||||
const size_t elems_per_item = nrows < 32 ? 1 : 8;
|
||||
const size_t nwg = CEIL_DIV((size_t) ne0, nth*elems_per_item);
|
||||
size_t global_work_size[] = { nwg*nth, (size_t) ne1, (size_t) (dst->ne[2]*dst->ne[3]) };
|
||||
size_t local_work_size[] = { nth, 1, 1 };
|
||||
backend_ctx->enqueue_ndrange_kernel(kernel, 3, global_work_size, local_work_size, dst);
|
||||
}
|
||||
|
||||
static void ggml_cl_scale(ggml_backend_t backend, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst) {
|
||||
GGML_ASSERT(src0);
|
||||
GGML_ASSERT(src0->extra);
|
||||
@@ -42049,13 +42116,13 @@ bool ggml_cl_compute_forward(ggml_backend_t backend, struct ggml_tensor * tensor
|
||||
if (!any_on_device && !ggml_cl_can_mul_mat(tensor->src[0], tensor->src[1], tensor)) {
|
||||
return false;
|
||||
}
|
||||
func = ggml_cl_mul_mat;
|
||||
func = ggml_cl_mul_mat_ext;
|
||||
break;
|
||||
case GGML_OP_MUL_MAT_ID:
|
||||
if (!any_on_device) {
|
||||
return false;
|
||||
}
|
||||
func = ggml_cl_mul_mat_id;
|
||||
func = ggml_cl_mul_mat_ext;
|
||||
break;
|
||||
case GGML_OP_SCALE:
|
||||
if (!any_on_device) {
|
||||
|
||||
@@ -150,3 +150,41 @@ kernel void kernel_mul_row_f16(
|
||||
uint idx1 = gid - (gid/ne)*ne; // get_global_id(0) % ne
|
||||
dst[gid] = src0[gid] * src1[idx1];
|
||||
}
|
||||
|
||||
kernel void kernel_mul_mat_scale(
|
||||
global char * dst,
|
||||
ulong offsetd,
|
||||
global const char * scale,
|
||||
ulong offsets,
|
||||
ulong channel_stride,
|
||||
ulong expert_stride,
|
||||
global const char * ids,
|
||||
ulong offseti,
|
||||
ulong ids_nb0,
|
||||
ulong ids_nb1,
|
||||
long n_expert,
|
||||
int ne0,
|
||||
int ne1
|
||||
) {
|
||||
const int slot = get_group_id(1);
|
||||
const int batch = get_group_id(2);
|
||||
int expert = 0;
|
||||
if (ids) {
|
||||
expert = *(global const int *)(ids + offseti + slot*ids_nb0 + batch*ids_nb1);
|
||||
if (expert < 0 || expert >= n_expert) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
global float * d = (global float *)(dst + offsetd) + (ulong)ne0*(slot + (ulong)ne1*batch);
|
||||
global const char * s = scale + offsets + expert*expert_stride;
|
||||
if (channel_stride == 0) {
|
||||
const float v = *(global const float *) s;
|
||||
for (int i = get_global_id(0); i < ne0; i += get_global_size(0)) {
|
||||
d[i] *= v;
|
||||
}
|
||||
} else {
|
||||
for (int i = get_global_id(0); i < ne0; i += get_global_size(0)) {
|
||||
d[i] *= *(global const float *)(s + i*channel_stride);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,9 @@ static void launch_gated_delta_net_esimd(const float * q,
|
||||
int64_t sq1,
|
||||
int64_t sq2,
|
||||
int64_t sq3,
|
||||
int64_t sk1,
|
||||
int64_t sk2,
|
||||
int64_t sk3,
|
||||
int64_t sv1,
|
||||
int64_t sv2,
|
||||
int64_t sv3,
|
||||
@@ -52,7 +55,7 @@ static void launch_gated_delta_net_esimd(const float * q,
|
||||
|
||||
for (int t = 0; t < n_tokens; ++t) {
|
||||
const simd<float, S_v> q_t = block_load<float, S_v>(q + iq3 * sq3 + t * sq2 + iq1 * sq1);
|
||||
const simd<float, S_v> k_t = block_load<float, S_v>(k + iq3 * sq3 + t * sq2 + iq1 * sq1);
|
||||
const simd<float, S_v> k_t = block_load<float, S_v>(k + iq3 * sk3 + t * sk2 + iq1 * sk1);
|
||||
const float v_val = v[sequence * sv3 + t * sv2 + h_idx * sv1 + col];
|
||||
const int64_t gb = sequence * sb3 + t * sb2 + h_idx * sb1;
|
||||
const float g_val = exp(g[gb]);
|
||||
@@ -78,8 +81,26 @@ static constexpr int gdn_warps = 2;
|
||||
// State columns per warp when there are enough heads, see launch_gated_delta_net.
|
||||
static constexpr int gdn_cols_wide = 4;
|
||||
|
||||
// replay: pending tokens to run before the new ones (see ggml_gated_delta_net_ext)
|
||||
struct gdn_replay_args {
|
||||
const float * pk; // [S_v, H_k, n_pend, n_seqs]
|
||||
const float * pv; // [S_v, H, n_pend, n_seqs]
|
||||
const float * pgb; // [g0, H, 2*n_pend, n_seqs], gates then betas
|
||||
const int32_t * n_rep; // [n_seqs]
|
||||
int64_t sk1, sk2, sk3; // head, token and seq strides in floats
|
||||
int64_t sv1, sv2, sv3;
|
||||
int64_t sg1, sg2, sg3;
|
||||
int n_pend;
|
||||
bool keep; // write the state after the replay, not the final one
|
||||
|
||||
// optional (not KDA): store the k, v, g, beta inputs of the new tokens as pending (fused cpys)
|
||||
float * st[4];
|
||||
int64_t st2[4]; // token stride in floats
|
||||
int64_t st3[4]; // seq stride in floats
|
||||
};
|
||||
|
||||
// C is the number of state columns per warp: a token's q/k shard is loaded once and shared by these columns.
|
||||
template <int S_v, int C, bool KDA, bool keep_rs_t>
|
||||
template <int S_v, int C, bool KDA, bool keep_rs_t, bool replay>
|
||||
void gated_delta_net_sycl(const float * q,
|
||||
const float * k,
|
||||
const float * v,
|
||||
@@ -93,6 +114,9 @@ void gated_delta_net_sycl(const float * q,
|
||||
int64_t sq1,
|
||||
int64_t sq2,
|
||||
int64_t sq3,
|
||||
int64_t sk1,
|
||||
int64_t sk2,
|
||||
int64_t sk3,
|
||||
int64_t sv1,
|
||||
int64_t sv2,
|
||||
int64_t sv3,
|
||||
@@ -103,7 +127,8 @@ void gated_delta_net_sycl(const float * q,
|
||||
const sycl::uint3 rq3_magic,
|
||||
float scale,
|
||||
int64_t state_slot_stride,
|
||||
int K) {
|
||||
int K,
|
||||
const gdn_replay_args rep) {
|
||||
auto item_ct1 = sycl::ext::oneapi::this_work_item::get_nd_item<3>();
|
||||
const uint32_t h_idx = item_ct1.get_group(2);
|
||||
const uint32_t sequence = item_ct1.get_group(1);
|
||||
@@ -140,11 +165,79 @@ void gated_delta_net_sycl(const float * q,
|
||||
}
|
||||
}
|
||||
|
||||
if constexpr (replay) {
|
||||
// the same state update as the main loop below, without the attention output
|
||||
const int n_r = rep.n_rep[sequence];
|
||||
const float * pk = rep.pk + sequence * rep.sk3 + iq1 * rep.sk1 + lane;
|
||||
const float * pv = rep.pv + sequence * rep.sv3 + h_idx * rep.sv1 + col0;
|
||||
const float * pgb = rep.pgb + sequence * rep.sg3 + h_idx * rep.sg1;
|
||||
|
||||
for (int t = 0; t < n_r; t++) {
|
||||
const float * g_t = pgb + t * rep.sg2;
|
||||
const float beta_val = pgb[(rep.n_pend + t) * rep.sg2];
|
||||
|
||||
float k_reg[rows_per_lane];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
k_reg[r] = pk[t * rep.sk2 + r * warp_size];
|
||||
}
|
||||
|
||||
if constexpr (!KDA) {
|
||||
const float g_val = sycl::native::exp(*g_t);
|
||||
#pragma unroll
|
||||
for (int c = 0; c < C; c++) {
|
||||
float kv_shard = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
kv_shard += s_shard[c][r] * k_reg[r];
|
||||
}
|
||||
const float kv_col = warp_reduce_sum<warp_size>(kv_shard);
|
||||
const float delta_col = (pv[t * rep.sv2 + c] - g_val * kv_col) * beta_val;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
s_shard[c][r] = g_val * s_shard[c][r] + k_reg[r] * delta_col;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
float g_reg[rows_per_lane];
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
g_reg[r] = sycl::native::exp(g_t[r * warp_size + lane]);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int c = 0; c < C; c++) {
|
||||
float kv_shard = 0.0f;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
kv_shard += g_reg[r] * s_shard[c][r] * k_reg[r];
|
||||
}
|
||||
const float kv_col = warp_reduce_sum<warp_size>(kv_shard);
|
||||
const float delta_col = (pv[t * rep.sv2 + c] - kv_col) * beta_val;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
s_shard[c][r] = g_reg[r] * s_shard[c][r] + k_reg[r] * delta_col;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (rep.keep) {
|
||||
float * out_col = state + col0 * S_v + lane;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < C; c++) {
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
out_col[c * S_v + r * warp_size] = s_shard[c][r];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// snapshot slot mapping: slot 0 = most recent state, slot s = s tokens back.
|
||||
// When n_tokens < K only slots 0..n_tokens-1 are written; older slots are caller-owned.
|
||||
|
||||
const float * qp = q + iq3 * sq3 + iq1 * sq1 + lane;
|
||||
const float * kp = k + iq3 * sq3 + iq1 * sq1 + lane;
|
||||
const float * kp = k + iq3 * sk3 + iq1 * sk1 + lane;
|
||||
const float * vp = v + sequence * sv3 + h_idx * sv1 + col0;
|
||||
const float * bp = beta + sequence * sb3 + h_idx * sb1;
|
||||
const float * gp = g + (sequence * sb3 + h_idx * sb1) * (KDA ? S_v : 1);
|
||||
@@ -173,7 +266,7 @@ void gated_delta_net_sycl(const float * q,
|
||||
}
|
||||
if (t + 1 < n_tokens) {
|
||||
qp += sq2;
|
||||
kp += sq2;
|
||||
kp += sk2;
|
||||
}
|
||||
// Load outside the branch: the last token reads its own row again.
|
||||
// A guarded load is 20% slower at 32 heads on Arc Pro B70.
|
||||
@@ -190,6 +283,31 @@ void gated_delta_net_sycl(const float * q,
|
||||
}
|
||||
vp += sv2;
|
||||
|
||||
if constexpr (replay && !KDA) {
|
||||
if (rep.st[0] != nullptr) {
|
||||
// keep the inputs of this token pending: one work-group per k head writes k, each warp its v columns
|
||||
const bool first_wg = item_ct1.get_group(0) == 0 && item_ct1.get_local_id(1) == 0;
|
||||
if (first_wg && h_idx < neqk1_magic.z()) {
|
||||
float * dk = rep.st[0] + sequence * rep.st3[0] + t * rep.st2[0] + h_idx * S_v + lane;
|
||||
#pragma unroll
|
||||
for (int r = 0; r < rows_per_lane; r++) {
|
||||
dk[r * warp_size] = k_reg[r];
|
||||
}
|
||||
}
|
||||
if (lane == 0) {
|
||||
float * dv = rep.st[1] + sequence * rep.st3[1] + t * rep.st2[1] + h_idx * S_v + col0;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < C; c++) {
|
||||
dv[c] = v_reg[c];
|
||||
}
|
||||
if (first_wg) {
|
||||
rep.st[2][sequence * rep.st3[2] + t * rep.st2[2] + h_idx] = *g_t;
|
||||
rep.st[3][sequence * rep.st3[3] + t * rep.st2[3] + h_idx] = beta_val;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// attn[col] = g * (S^T q)[col] + delta[col] * (k . q), so no reduction waits for delta
|
||||
float kq_shard = 0.0f;
|
||||
#pragma unroll
|
||||
@@ -281,6 +399,9 @@ void gated_delta_net_sycl(const float * q,
|
||||
}
|
||||
|
||||
if constexpr (!keep_rs_t) {
|
||||
if (replay && rep.keep) {
|
||||
return;
|
||||
}
|
||||
float * out_col = state + col0 * S_v + lane;
|
||||
#pragma unroll
|
||||
for (int c = 0; c < C; c++) {
|
||||
@@ -292,7 +413,7 @@ void gated_delta_net_sycl(const float * q,
|
||||
}
|
||||
}
|
||||
|
||||
template <bool KDA, bool keep_rs_t>
|
||||
template <bool KDA, bool keep_rs_t, bool replay>
|
||||
static void launch_gated_delta_net(const float * q_d,
|
||||
const float * k_d,
|
||||
const float * v_d,
|
||||
@@ -308,6 +429,9 @@ static void launch_gated_delta_net(const float * q_d,
|
||||
int64_t sq1,
|
||||
int64_t sq2,
|
||||
int64_t sq3,
|
||||
int64_t sk1,
|
||||
int64_t sk2,
|
||||
int64_t sk3,
|
||||
int64_t sv1,
|
||||
int64_t sv2,
|
||||
int64_t sv3,
|
||||
@@ -319,6 +443,7 @@ static void launch_gated_delta_net(const float * q_d,
|
||||
float scale,
|
||||
int64_t state_slot_stride,
|
||||
int K,
|
||||
const gdn_replay_args & rep,
|
||||
dpct::queue_ptr stream) {
|
||||
//TODO: Add chunked kernel for even faster pre-fill
|
||||
const int warp_size = ggml_sycl_info().devices[ggml_sycl_get_device()].warp_size;
|
||||
@@ -333,9 +458,9 @@ static void launch_gated_delta_net(const float * q_d,
|
||||
dpct::dim3 block_dims(warp_size <= sv ? warp_size : sv, gdn_warps, 1);
|
||||
stream->parallel_for(sycl::nd_range<3>(grid_dims * block_dims, block_dims),
|
||||
[=](sycl::nd_item<3> /*item_ct1*/) [[sycl::reqd_sub_group_size(WARP_SIZE)]] {
|
||||
gated_delta_net_sycl<sv, C, KDA, keep_rs_t>(
|
||||
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sv1, sv2,
|
||||
sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K);
|
||||
gated_delta_net_sycl<sv, C, KDA, keep_rs_t, replay>(
|
||||
q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, sq1, sq2, sq3, sk1, sk2, sk3, sv1, sv2,
|
||||
sv3, sb1, sb2, sb3, neqk1_magic, rq3_magic, scale, state_slot_stride, K, rep);
|
||||
});
|
||||
};
|
||||
// gdn_cols_wide columns per warp cut the q/k loads but launch fewer warps, so with few heads 1 column is faster.
|
||||
@@ -400,7 +525,6 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
|
||||
GGML_ASSERT(ggml_is_contiguous_rows(src_q));
|
||||
GGML_ASSERT(ggml_is_contiguous_rows(src_k));
|
||||
GGML_ASSERT(ggml_is_contiguous_rows(src_v));
|
||||
GGML_ASSERT(ggml_are_same_stride(src_q, src_k));
|
||||
GGML_ASSERT(src_g->ne[0] == 1 || kda);
|
||||
GGML_ASSERT(ggml_is_contiguous(src_g));
|
||||
GGML_ASSERT(ggml_is_contiguous(src_beta));
|
||||
@@ -410,6 +534,10 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
|
||||
const int64_t sq1 = nbq1 / sizeof(float);
|
||||
const int64_t sq2 = nbq2 / sizeof(float);
|
||||
const int64_t sq3 = nbq3 / sizeof(float);
|
||||
// k can have its own layout (a permuted or padded view), only its rows must be contiguous
|
||||
const int64_t sk1 = nbk1 / sizeof(float);
|
||||
const int64_t sk2 = nbk2 / sizeof(float);
|
||||
const int64_t sk3 = nbk3 / sizeof(float);
|
||||
const int64_t sv1 = nbv1 / sizeof(float);
|
||||
const int64_t sv2 = nbv2 / sizeof(float);
|
||||
const int64_t sv3 = nbv3 / sizeof(float);
|
||||
@@ -433,35 +561,73 @@ static void ggml_sycl_op_gated_delta_net_impl(ggml_backend_sycl_context & ctx, g
|
||||
state_slot_stride = cache->slot_stride;
|
||||
}
|
||||
|
||||
const ggml_tensor * src_pk = dst->src[6];
|
||||
gdn_replay_args rep = {};
|
||||
if (src_pk != nullptr) {
|
||||
const ggml_tensor * src_pv = dst->src[7];
|
||||
const ggml_tensor * src_pgb = dst->src[8];
|
||||
const ggml_tensor * src_nr = dst->src[9];
|
||||
|
||||
GGML_ASSERT(K == 1);
|
||||
GGML_ASSERT(src_pv != nullptr && src_pgb != nullptr && src_nr != nullptr);
|
||||
GGML_ASSERT(src_pk->type == GGML_TYPE_F32 && src_pv->type == GGML_TYPE_F32 && src_pgb->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(src_nr->type == GGML_TYPE_I32 && ggml_is_contiguous(src_nr) && ggml_nelements(src_nr) == n_seqs);
|
||||
GGML_ASSERT(src_pk->nb[0] == sizeof(float) && src_pv->nb[0] == sizeof(float) && src_pgb->nb[0] == sizeof(float));
|
||||
|
||||
rep.pk = (const float *) src_pk->data;
|
||||
rep.pv = (const float *) src_pv->data;
|
||||
rep.pgb = (const float *) src_pgb->data;
|
||||
rep.n_rep = (const int32_t *) src_nr->data;
|
||||
rep.sk1 = src_pk->nb[1] / sizeof(float);
|
||||
rep.sk2 = src_pk->nb[2] / sizeof(float);
|
||||
rep.sk3 = src_pk->nb[3] / sizeof(float);
|
||||
rep.sv1 = src_pv->nb[1] / sizeof(float);
|
||||
rep.sv2 = src_pv->nb[2] / sizeof(float);
|
||||
rep.sv3 = src_pv->nb[3] / sizeof(float);
|
||||
rep.sg1 = src_pgb->nb[1] / sizeof(float);
|
||||
rep.sg2 = src_pgb->nb[2] / sizeof(float);
|
||||
rep.sg3 = src_pgb->nb[3] / sizeof(float);
|
||||
rep.n_pend = ggml_get_op_params_i32(dst, 1);
|
||||
rep.keep = ggml_get_op_params_i32(dst, 2) != 0;
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
rep.st[i] = cache != nullptr ? cache->in_dst[i] : nullptr;
|
||||
rep.st2[i] = cache != nullptr ? cache->in_nb2[i] : 0;
|
||||
rep.st3[i] = cache != nullptr ? cache->in_nb3[i] : 0;
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef GGML_SYCL_DMMV_HAS_ESIMD
|
||||
if (!kda && S_v == 128 && g_ggml_sycl_enable_esimd && state_slot_stride % 4 == 0 && (uintptr_t) state_d % 16 == 0) {
|
||||
if (src_pk == nullptr && !kda && S_v == 128 && g_ggml_sycl_enable_esimd && state_slot_stride % 4 == 0 && (uintptr_t) state_d % 16 == 0) {
|
||||
launch_gated_delta_net_esimd(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, H, n_tokens, n_seqs, sq1, sq2, sq3,
|
||||
sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
|
||||
sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
|
||||
#define GDN_LAUNCH(KDA, KEEP, REPLAY) \
|
||||
launch_gated_delta_net<KDA, KEEP, REPLAY>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d, S_v, H, n_tokens, \
|
||||
n_seqs, sq1, sq2, sq3, sk1, sk2, sk3, sv1, sv2, sv3, sb1, sb2, sb3, neqk1, rq3, \
|
||||
scale, state_slot_stride, K, rep, stream)
|
||||
|
||||
if (kda) {
|
||||
if (keep_rs) {
|
||||
launch_gated_delta_net<true, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
|
||||
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
|
||||
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
|
||||
GDN_LAUNCH(true, true, false);
|
||||
} else if (src_pk != nullptr) {
|
||||
GDN_LAUNCH(true, false, true);
|
||||
} else {
|
||||
launch_gated_delta_net<true, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
|
||||
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
|
||||
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
|
||||
GDN_LAUNCH(true, false, false);
|
||||
}
|
||||
} else {
|
||||
if (keep_rs) {
|
||||
launch_gated_delta_net<false, true>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
|
||||
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
|
||||
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
|
||||
GDN_LAUNCH(false, true, false);
|
||||
} else if (src_pk != nullptr) {
|
||||
GDN_LAUNCH(false, false, true);
|
||||
} else {
|
||||
launch_gated_delta_net<false, false>(q_d, k_d, v_d, g_d, b_d, s_d, dst_d, state_d,
|
||||
S_v, H, n_tokens, n_seqs, sq1, sq2, sq3, sv1, sv2, sv3,
|
||||
sb1, sb2, sb3, neqk1, rq3, scale, state_slot_stride, K, stream);
|
||||
GDN_LAUNCH(false, false, false);
|
||||
}
|
||||
}
|
||||
|
||||
#undef GDN_LAUNCH
|
||||
}
|
||||
|
||||
void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
|
||||
@@ -469,12 +635,12 @@ void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor *
|
||||
}
|
||||
|
||||
void ggml_sycl_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
|
||||
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/6);
|
||||
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/dst->src[6] != nullptr ? 10 : 6);
|
||||
ggml_sycl_op_gated_delta_net(ctx, dst);
|
||||
}
|
||||
|
||||
void ggml_sycl_op_gated_delta_net_fused_cache(ggml_backend_sycl_context & ctx, ggml_tensor * dst,
|
||||
ggml_sycl_gated_delta_net_fused_cache cache) {
|
||||
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/6);
|
||||
scope_op_debug_print scope_dbg_print(__func__, dst, /*num_src=*/dst->src[6] != nullptr ? 10 : 6);
|
||||
ggml_sycl_op_gated_delta_net_impl(ctx, dst, &cache);
|
||||
}
|
||||
|
||||
@@ -9,6 +9,11 @@
|
||||
struct ggml_sycl_gated_delta_net_fused_cache {
|
||||
float * data; // rollback slot 0
|
||||
int64_t slot_stride; // between rollback slots (0 when K==1)
|
||||
|
||||
// replay: the cpys of the k, v, g, beta inputs into the pending rows, null when not fused
|
||||
float * in_dst[4] = {};
|
||||
int64_t in_nb2[4] = {}; // token stride in elements
|
||||
int64_t in_nb3[4] = {}; // seq stride in elements
|
||||
};
|
||||
|
||||
void ggml_sycl_op_gated_delta_net(ggml_backend_sycl_context & ctx, ggml_tensor * dst);
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
#include <array>
|
||||
#include <assert.h>
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
#include <cctype>
|
||||
#include <cinttypes>
|
||||
#include <cstddef>
|
||||
@@ -747,6 +748,8 @@ struct ggml_backend_sycl_buffer_context {
|
||||
optimize_feature opt_feature;
|
||||
std::vector<ggml_tensor_extra_gpu *> tensor_extras;
|
||||
host_staging staging;
|
||||
// pinned block for get_tensor, one slot per download worker
|
||||
char * download_staging = nullptr;
|
||||
bool is_usm_system;
|
||||
|
||||
ggml_backend_sycl_buffer_context(int device, void * dev_ptr, queue_ptr stream, bool is_usm_system) :
|
||||
@@ -772,6 +775,10 @@ struct ggml_backend_sycl_buffer_context {
|
||||
|
||||
~ggml_backend_sycl_buffer_context() {
|
||||
drop_host_staging();
|
||||
if (download_staging != nullptr) {
|
||||
sycl::free(download_staging, *stream);
|
||||
download_staging = nullptr;
|
||||
}
|
||||
if (dev_ptr != nullptr) {
|
||||
ggml_sycl_set_device(device);
|
||||
if (is_usm_system)
|
||||
@@ -980,6 +987,54 @@ catch (sycl::exception const &exc) {
|
||||
std::exit(1);
|
||||
}
|
||||
|
||||
// Reads go through a pinned block, as a copy into pageable memory is slow, and the caller often hands over fresh
|
||||
// memory, where the first write to each 4 KiB page takes a page fault. Each worker owns one slot and loops over the
|
||||
// chunks: queue the device copy, touch the destination pages while it is in flight, wait, copy out. So the faults
|
||||
// overlap the transfer and run on several threads. Returns false when the pinned block is not available.
|
||||
static bool ggml_sycl_buffer_download_staged(ggml_backend_sycl_buffer_context * ctx, char * dst, const char * src,
|
||||
size_t size) {
|
||||
constexpr size_t min_size = 64*1024;
|
||||
constexpr size_t chunk = 1*1024*1024;
|
||||
constexpr size_t n_max = 4;
|
||||
constexpr size_t page = 4096;
|
||||
if (size < min_size) {
|
||||
return false;
|
||||
}
|
||||
sycl::queue & q = *ctx->stream;
|
||||
if (ctx->download_staging == nullptr) {
|
||||
ctx->download_staging = (char *) sycl::malloc_host(n_max * chunk, q);
|
||||
if (ctx->download_staging == nullptr) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const size_t n_chnk = (size + chunk - 1) / chunk;
|
||||
const size_t n_work = std::min(n_max, n_chnk);
|
||||
|
||||
std::atomic<size_t> next{ 0 };
|
||||
auto work = [&](size_t w) {
|
||||
char * stage = ctx->download_staging + w * chunk;
|
||||
for (size_t i = next++; i < n_chnk; i = next++) {
|
||||
const size_t off = i * chunk;
|
||||
const size_t n = std::min(chunk, size - off);
|
||||
sycl::event ev = q.memcpy(stage, src + off, n);
|
||||
for (size_t j = 0; j < n; j += page) {
|
||||
((volatile char *) dst)[off + j] = 0;
|
||||
}
|
||||
ev.wait_and_throw();
|
||||
memcpy(dst + off, stage, n);
|
||||
}
|
||||
};
|
||||
std::vector<std::thread> workers;
|
||||
for (size_t w = 1; w < n_work; ++w) {
|
||||
workers.emplace_back(work, w);
|
||||
}
|
||||
work(0);
|
||||
for (auto & t : workers) {
|
||||
t.join();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void ggml_backend_sycl_buffer_get_tensor(ggml_backend_buffer_t buffer,
|
||||
const ggml_tensor *tensor,
|
||||
void *data, size_t offset,
|
||||
@@ -992,9 +1047,11 @@ static void ggml_backend_sycl_buffer_get_tensor(ggml_backend_buffer_t buffer,
|
||||
ggml_sycl_set_device(ctx->device);
|
||||
auto stream = dpct::dev_mgr::instance().get_device(ctx->device).default_queue();
|
||||
|
||||
SYCL_CHECK(CHECK_TRY_ERROR(
|
||||
stream.memcpy(data, (const char *)tensor->data + offset, size)
|
||||
.wait()));
|
||||
if (!ggml_sycl_buffer_download_staged(ctx, (char *) data, (const char *) tensor->data + offset, size)) {
|
||||
SYCL_CHECK(CHECK_TRY_ERROR(
|
||||
stream.memcpy(data, (const char *)tensor->data + offset, size)
|
||||
.wait()));
|
||||
}
|
||||
}
|
||||
catch (sycl::exception const &exc) {
|
||||
std::cerr << exc.what() << "Exception caught at file:" << __FILE__
|
||||
@@ -6657,8 +6714,62 @@ static int ggml_sycl_try_gdn_cache_fusion(const ggml_cgraph * cgraph, int node_i
|
||||
return 0;
|
||||
}
|
||||
|
||||
// replay: the kernel reads the pending inputs (src[6..8]) while it writes the cache, so they must not share memory
|
||||
const auto overlaps = [](const ggml_tensor * x, const ggml_tensor * y) {
|
||||
const char * x0 = (const char *) x->data;
|
||||
const char * y0 = (const char *) y->data;
|
||||
return x0 < y0 + ggml_nbytes(y) && y0 < x0 + ggml_nbytes(x);
|
||||
};
|
||||
for (int s = 6; s <= 8; ++s) {
|
||||
if (gdn->src[s] != nullptr && overlaps(gdn->src[s], dst)) {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
fused_state_cpy.data = (float *) dst->data; // rollback group 0 (newest)
|
||||
fused_state_cpy.slot_stride = K > 1 ? (int64_t) (dst->nb[2] / sizeof(float)) : 0;
|
||||
|
||||
// replay (not KDA): the next 4 real nodes may store the k, v, g, beta inputs into the pending rows
|
||||
if (gdn->src[6] != nullptr && gdn->src[3]->ne[0] == 1) {
|
||||
float * in_dst[4];
|
||||
int64_t in_nb2[4];
|
||||
int64_t in_nb3[4];
|
||||
int skip_in = skip;
|
||||
int n_in = 0;
|
||||
for (int j = node_idx + skip + 1; n_in < 4 && j < cgraph->n_nodes; ++j) {
|
||||
const ggml_tensor * n = cgraph->nodes[j];
|
||||
if (ggml_sycl_is_view_or_noop(n) || (n->flags & GGML_TENSOR_FLAG_COMPUTE) == 0) {
|
||||
continue;
|
||||
}
|
||||
const ggml_tensor * in = gdn->src[1 + n_in];
|
||||
const ggml_tensor * s0 = n->src[0];
|
||||
const ggml_tensor * d = n->src[1];
|
||||
// the cpy reads the whole input, directly or through a view of the same data
|
||||
const bool whole_in = s0 == in || (s0 != nullptr && s0->data == in->data && ggml_are_same_shape(s0, in) &&
|
||||
ggml_are_same_stride(s0, in));
|
||||
if (n->op != GGML_OP_CPY || (n->flags & GGML_TENSOR_FLAG_OUTPUT) || !whole_in ||
|
||||
d->type != GGML_TYPE_F32 || d->data == nullptr || !ggml_are_same_shape(d, in) ||
|
||||
d->nb[0] != sizeof(float) || d->nb[1] != d->ne[0]*sizeof(float) ||
|
||||
d->nb[2] != d->ne[0]*d->ne[1]*sizeof(float) ||
|
||||
overlaps(d, gdn->src[6]) || overlaps(d, gdn->src[7]) || overlaps(d, gdn->src[8])) {
|
||||
break;
|
||||
}
|
||||
in_dst[n_in] = (float *) d->data;
|
||||
in_nb2[n_in] = d->nb[2] / sizeof(float);
|
||||
in_nb3[n_in] = d->nb[3] / sizeof(float);
|
||||
skip_in = j - node_idx;
|
||||
++n_in;
|
||||
}
|
||||
if (n_in == 4) {
|
||||
for (int c = 0; c < 4; ++c) {
|
||||
fused_state_cpy.in_dst[c] = in_dst[c];
|
||||
fused_state_cpy.in_nb2[c] = in_nb2[c];
|
||||
fused_state_cpy.in_nb3[c] = in_nb3[c];
|
||||
}
|
||||
skip = skip_in;
|
||||
}
|
||||
}
|
||||
|
||||
return skip;
|
||||
}
|
||||
|
||||
@@ -7718,8 +7829,8 @@ static bool do_ggml_backend_sycl_device_supports_op(ggml_backend_dev_t dev, cons
|
||||
case GGML_OP_OPT_STEP_SGD:
|
||||
return true;
|
||||
case GGML_OP_GATED_DELTA_NET:
|
||||
// replay of pending tokens (op param 1) is not implemented
|
||||
return ggml_get_op_params_i32(op, 1) == 0;
|
||||
// replay of pending tokens (src[6..9]) always has a single state slot
|
||||
return op->src[6] == nullptr || ggml_get_op_params_i32(op, 0) == 1;
|
||||
case GGML_OP_SSM_CONV:
|
||||
return op->type == GGML_TYPE_F32 &&
|
||||
op->src[0]->type == GGML_TYPE_F32 &&
|
||||
|
||||
@@ -1019,9 +1019,11 @@ void ggml_vk_check_results_0(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph
|
||||
ggml_flash_attn_ext_set_sinks(tensor_clone, src_clone[4]);
|
||||
}
|
||||
} else if (tensor->op == GGML_OP_MUL_MAT) {
|
||||
tensor_clone = ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
|
||||
tensor_clone = src_clone[2] ? ggml_mul_mat_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], nullptr)
|
||||
: ggml_mul_mat(ggml_ctx, src_clone[0], src_clone[1]);
|
||||
} else if (tensor->op == GGML_OP_MUL_MAT_ID) {
|
||||
tensor_clone = ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
|
||||
tensor_clone = src_clone[3] ? ggml_mul_mat_id_ext(ggml_ctx, src_clone[0], src_clone[1], src_clone[2], src_clone[3], nullptr)
|
||||
: ggml_mul_mat_id(ggml_ctx, src_clone[0], src_clone[1], src_clone[2]);
|
||||
} else if (tensor->op == GGML_OP_SUB) {
|
||||
tensor_clone = ggml_sub(ggml_ctx, src_clone[0], src_clone[1]);
|
||||
} else if (tensor->op == GGML_OP_MUL) {
|
||||
@@ -1612,4 +1614,3 @@ void ggml_vk_check_results_1(ggml_backend_vk_context * ctx, ggml_cgraph * cgraph
|
||||
VK_LOG_DEBUG("END ggml_vk_check_results_1(" << tensor->name << ")");
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
@@ -45,6 +45,18 @@ struct vk_mat_mat_stream_k_fixup_push_constants {
|
||||
|
||||
static_assert(sizeof(vk_mat_mat_push_constants) <= 128);
|
||||
|
||||
struct vk_op_mul_mat_scale_push_constants {
|
||||
uint32_t ne0; uint32_t ne1; uint32_t ne2; uint32_t ne3;
|
||||
uint32_t sne0; uint32_t sne1; uint32_t sne2; uint32_t sne3;
|
||||
uint32_t snb0; uint32_t snb1; uint32_t snb2; uint32_t snb3;
|
||||
uint32_t per_expert;
|
||||
uint32_t has_ids;
|
||||
uint32_t ids_s0; uint32_t ids_s1; uint32_t ids_offset;
|
||||
uint32_t ne_012mp; uint32_t ne_012L;
|
||||
uint32_t ne_01mp; uint32_t ne_01L;
|
||||
uint32_t ne_0mp; uint32_t ne_0L;
|
||||
};
|
||||
|
||||
struct vk_mat_vec_push_constants {
|
||||
uint32_t ncols;
|
||||
uint32_t stride_a;
|
||||
@@ -1255,4 +1267,3 @@ static vk_op_binary_push_constants ggml_vk_rms_norm_push_constants(
|
||||
eps, 0.0f, (int32_t)num_partials,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -864,6 +864,7 @@ struct vk_device_struct {
|
||||
|
||||
vk_pipeline pipeline_matmul_split_k_reduce;
|
||||
vk_pipeline pipeline_matmul_stream_k_fixup;
|
||||
vk_pipeline pipeline_mul_mat_scale_f32;
|
||||
vk_pipeline pipeline_quantize_q8_1_x4;
|
||||
|
||||
vk_pipeline pipeline_dequant[GGML_TYPE_COUNT];
|
||||
@@ -921,8 +922,8 @@ struct vk_device_struct {
|
||||
vk_pipeline pipeline_roll_f32;
|
||||
vk_pipeline pipeline_repeat_i32, pipeline_repeat_back_f32;
|
||||
vk_pipeline pipeline_repeat_i16;
|
||||
vk_pipeline pipeline_cpy_32, pipeline_cpy_f32_f16, pipeline_cpy_16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_bf16_f32, pipeline_cpy_bf16_f16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
|
||||
vk_pipeline pipeline_contig_cpy_32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_bf16_f32, pipeline_contig_cpy_bf16_f16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
|
||||
vk_pipeline pipeline_cpy_32, pipeline_cpy_f32_f16, pipeline_cpy_16, pipeline_cpy_f16_f32, pipeline_cpy_f32_bf16, pipeline_cpy_bf16_f32, pipeline_cpy_bf16_f16, pipeline_cpy_8, pipeline_cpy_f8_e4m3_f16, pipeline_cpy_f32_i32, pipeline_cpy_i32_f32;
|
||||
vk_pipeline pipeline_contig_cpy_32, pipeline_contig_cpy_f32_f16, pipeline_contig_cpy_16, pipeline_contig_cpy_f16_f32, pipeline_contig_cpy_f32_bf16, pipeline_contig_cpy_bf16_f32, pipeline_contig_cpy_bf16_f16, pipeline_contig_cpy_8, pipeline_contig_cpy_f8_e4m3_f16, pipeline_contig_cpy_f32_i32, pipeline_contig_cpy_i32_f32;
|
||||
vk_pipeline pipeline_cpy_f32_quant[GGML_TYPE_COUNT];
|
||||
vk_pipeline pipeline_cpy_quant_f32[GGML_TYPE_COUNT];
|
||||
vk_pipeline pipeline_cpy_transpose_16, pipeline_cpy_transpose_32;
|
||||
@@ -1175,6 +1176,10 @@ typedef std::vector<vk_submission> vk_sequence;
|
||||
|
||||
#define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
|
||||
|
||||
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE 0x10
|
||||
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC 0x20
|
||||
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_2D 0x40
|
||||
|
||||
struct vk_staging_memcpy {
|
||||
vk_staging_memcpy(void * _dst, const void * _src, size_t _n) : dst(_dst), src(_src), n(_n) {}
|
||||
|
||||
|
||||
@@ -2776,6 +2776,9 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
}
|
||||
#undef X_CM2
|
||||
|
||||
create_mm_pipelines({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_f8_e4m3_f16_f16acc", matmul_f8_e4m3_f16_f16acc_cm2_len, matmul_f8_e4m3_f16_f16acc_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true);
|
||||
create_mm_pipelines({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_f8_e4m3_f16", matmul_f8_e4m3_f16_cm2_len, matmul_f8_e4m3_f16_cm2_data, sizeof(vk_mat_mat_push_constants), 3, cm2_spec, true);
|
||||
|
||||
GGML_ASSERT(device->subgroup_ballot);
|
||||
|
||||
create_mm_pipelines({GGML_TYPE_F16, GGML_TYPE_F16, true, true}, tc_mm, "matmul_id_subgroup_f16_f16acc", matmul_id_subgroup_f16_f16acc_cm2_len, matmul_id_subgroup_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true);
|
||||
@@ -2820,6 +2823,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
FOR_EACH_LUT_FP4_TYPE(X_CM2_ID)
|
||||
}
|
||||
#undef X_CM2_ID
|
||||
create_mm_pipelines({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, true, true}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f16_f16acc", matmul_id_subgroup_f8_e4m3_f16_f16acc_cm2_len, matmul_id_subgroup_f8_e4m3_f16_f16acc_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true);
|
||||
create_mm_pipelines({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, true, false}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f16", matmul_id_subgroup_f8_e4m3_f16_cm2_len, matmul_id_subgroup_f8_e4m3_f16_cm2_data, sizeof(vk_mat_mat_id_push_constants), 5, cm2_spec, true);
|
||||
} else
|
||||
#endif // defined(VK_NV_cooperative_matrix2) && defined(GGML_VULKAN_COOPMAT2_GLSLC_SUPPORT)
|
||||
#if defined(VK_KHR_cooperative_matrix) && defined(GGML_VULKAN_COOPMAT_GLSLC_SUPPORT)
|
||||
@@ -2943,6 +2948,14 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
cm1_create_mmq({GGML_TYPE_Q6_K, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int_k, "matmul_q6_k_q8_1", matmul_q6_k_q8_1_cm1_len, matmul_q6_k_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
|
||||
if (!rdna4) { cm1_create_mmq({GGML_TYPE_NVFP4, GGML_TYPE_Q8_1, false, false}, tc_mmq_cm1_int_k, "matmul_nvfp4_q8_1", matmul_nvfp4_q8_1_cm1_len, matmul_nvfp4_q8_1_cm1_data, sizeof(vk_mat_mat_push_constants), 3); }
|
||||
}
|
||||
if (device->coopmat_acc_f16_support) {
|
||||
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_f8_e4m3_f32_f16acc", matmul_f8_e4m3_f32_f16acc_cm1_len, matmul_f8_e4m3_f32_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
|
||||
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, false, true}, tc_mmq, "matmul_f8_e4m3_f16_f16acc", matmul_f8_e4m3_f16_f16acc_cm1_len, matmul_f8_e4m3_f16_f16acc_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
|
||||
}
|
||||
if (device->coopmat_acc_f32_support) {
|
||||
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_f8_e4m3_f32", matmul_f8_e4m3_f32_cm1_len, matmul_f8_e4m3_f32_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
|
||||
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, false, false}, tc_mmq, "matmul_f8_e4m3_f16", matmul_f8_e4m3_f16_cm1_len, matmul_f8_e4m3_f16_cm1_data, sizeof(vk_mat_mat_push_constants), 3);
|
||||
}
|
||||
|
||||
GGML_ASSERT(device->subgroup_ballot);
|
||||
|
||||
@@ -3000,6 +3013,14 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
FOR_EACH_LUT_FP4_TYPE(X_CM1_ID)
|
||||
}
|
||||
#undef X_CM1_ID
|
||||
if (device->coopmat_acc_f16_support) {
|
||||
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, true}, tc_mmq_id, "matmul_id_subgroup_f8_e4m3_f32_f16acc", matmul_id_subgroup_f8_e4m3_f32_f16acc_cm1_len, matmul_id_subgroup_f8_e4m3_f32_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, true, true}, tc_mmq_id, "matmul_id_subgroup_f8_e4m3_f16_f16acc", matmul_id_subgroup_f8_e4m3_f16_f16acc_cm1_len, matmul_id_subgroup_f8_e4m3_f16_f16acc_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
}
|
||||
if (device->coopmat_acc_f32_support) {
|
||||
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmq_id, "matmul_id_subgroup_f8_e4m3_f32", matmul_id_subgroup_f8_e4m3_f32_cm1_len, matmul_id_subgroup_f8_e4m3_f32_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
cm1_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F16, true, false}, tc_mmq_id, "matmul_id_subgroup_f8_e4m3_f16", matmul_id_subgroup_f8_e4m3_f16_cm1_len, matmul_id_subgroup_f8_e4m3_f16_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
}
|
||||
|
||||
if (device->coopmat_int_support && (rdna3 || rdna4)) {
|
||||
cm1_create_mmq({GGML_TYPE_Q4_0, GGML_TYPE_Q8_1, true, false}, tc_mmq_cm1_int, "matmul_id_subgroup_q4_0_q8_1", matmul_id_subgroup_q4_0_q8_1_cm1_len, matmul_id_subgroup_q4_0_q8_1_cm1_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
@@ -3080,6 +3101,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
sg_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32", SPV_DOT2(matmul_##tstr##_f32), sizeof(vk_mat_mat_push_constants), 3);
|
||||
FOR_EACH_LUT_TYPE(X_SG)
|
||||
#undef X_SG
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, true}, tc_mmq, "matmul_f8_e4m3_f32_f16acc", SPV_DOT2_F16ACC(matmul_f8_e4m3_f32), sizeof(vk_mat_mat_push_constants), 3);
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_f8_e4m3_f32", SPV_DOT2(matmul_f8_e4m3_f32), sizeof(vk_mat_mat_push_constants), 3);
|
||||
|
||||
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
|
||||
if (device->integer_dot_product) {
|
||||
@@ -3119,6 +3142,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_" #tstr "_f32", SPV_DOT2(matmul_id_subgroup_##tstr##_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
|
||||
FOR_EACH_LUT_TYPE(X_SG_ID_SUB)
|
||||
#undef X_SG_ID_SUB
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, true}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_subgroup_f8_e4m3_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f32", SPV_DOT2(matmul_id_subgroup_f8_e4m3_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
|
||||
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
|
||||
if (device->integer_dot_product) {
|
||||
std::vector<vk_tile_config> tc_mmqid_int = {{s_warptile_mmqid_int, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid_int, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid_int, l_mmq_wg_denoms, l_align}};
|
||||
@@ -3156,6 +3181,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_" #tstr "_f32", SPV_DOT2(matmul_id_##tstr##_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
FOR_EACH_LUT_TYPE(X_SG_ID)
|
||||
#undef X_SG_ID
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, true}, tc_mmqid, "matmul_id_f8_e4m3_f32_f16acc", SPV_DOT2_F16ACC(matmul_id_f8_e4m3_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_f8_e4m3_f32", SPV_DOT2(matmul_id_f8_e4m3_f32), sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
|
||||
if (device->integer_dot_product) {
|
||||
std::vector<vk_tile_config> tc_mmqid_int = {{s_warptile_mmqid_int, s_mmq_wg_denoms, s_align}, {m_warptile_mmqid_int, m_mmq_wg_denoms, m_align}, {l_warptile_mmqid_int, l_mmq_wg_denoms, l_align}};
|
||||
@@ -3194,6 +3221,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
sg_create({TYPE, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_" #tstr "_f32", matmul_##tstr##_f32_fp32_len, matmul_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_push_constants), 3);
|
||||
FOR_EACH_LUT_TYPE(X_SG_FP32)
|
||||
#undef X_SG_FP32
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, false, false}, tc_mmq, "matmul_f8_e4m3_f32", matmul_f8_e4m3_f32_fp32_len, matmul_f8_e4m3_f32_fp32_data, sizeof(vk_mat_mat_push_constants), 3);
|
||||
|
||||
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
|
||||
if (device->integer_dot_product) {
|
||||
@@ -3227,6 +3255,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_" #tstr "_f32", matmul_id_subgroup_##tstr##_f32_fp32_len, matmul_id_subgroup_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
|
||||
FOR_EACH_LUT_TYPE(X_SG_ID_SUB_FP32)
|
||||
#undef X_SG_ID_SUB_FP32
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_subgroup_f8_e4m3_f32", matmul_id_subgroup_f8_e4m3_f32_fp32_len, matmul_id_subgroup_f8_e4m3_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count, mul_mat_subgroup_size);
|
||||
} else {
|
||||
sg_create({GGML_TYPE_F32, GGML_TYPE_F32, true, false}, tc_mm, "matmul_id_f32_f32", matmul_id_f32_f32_fp32_len, matmul_id_f32_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
sg_create({GGML_TYPE_F16, GGML_TYPE_F16, true, false}, tc_mm, "matmul_id_f16", matmul_id_f16_fp32_len, matmul_id_f16_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
@@ -3239,6 +3268,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
sg_create({TYPE, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_" #tstr "_f32", matmul_id_##tstr##_f32_fp32_len, matmul_id_##tstr##_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
FOR_EACH_LUT_TYPE(X_SG_ID_FP32)
|
||||
#undef X_SG_ID_FP32
|
||||
sg_create({GGML_TYPE_F8_E4M3, GGML_TYPE_F32, true, false}, tc_mmqid, "matmul_id_f8_e4m3_f32", matmul_id_f8_e4m3_f32_fp32_len, matmul_id_f8_e4m3_f32_fp32_data, sizeof(vk_mat_mat_id_push_constants), mul_mat_id_param_count);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3419,6 +3449,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f32_f32", arr_dmmv_iq4_nl_f32_f32_len[reduc16], arr_dmmv_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_mxfp4_f32_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f32_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_nvfp4_f32_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f32_f32[w][GGML_TYPE_F8_E4M3][i], "mul_mat_vec_f8_e4m3_f32_f32", arr_dmmv_f8_e4m3_f32_f32_len[reduc16], arr_dmmv_f8_e4m3_f32_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F32 ][i], "mul_mat_vec_f32_f16_f32", arr_dmmv_f32_f16_f32_len[reduc], arr_dmmv_f32_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {1, 1, 1}, {wg_size_subgroup, 1, i+1}, 1, false, use_subgroups, force_subgroup_size);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F16 ][i], "mul_mat_vec_f16_f16_f32", arr_dmmv_f16_f16_f32_len[reduc], arr_dmmv_f16_f16_f32_data[reduc], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {2, 1, 1}, {wg_size_subgroup, 2, i+1}, 1, false, use_subgroups, force_subgroup_size);
|
||||
@@ -3448,6 +3479,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_IQ4_NL][i], "mul_mat_vec_iq4_nl_f16_f32", arr_dmmv_iq4_nl_f16_f32_len[reduc16], arr_dmmv_iq4_nl_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_MXFP4][i], "mul_mat_vec_mxfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_mxfp4_f16_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_mxfp4_f16_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_NVFP4][i], "mul_mat_vec_nvfp4_f16_f32", OCP_DMMV_LEN(arr_dmmv_nvfp4_f16_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_nvfp4_f16_f32, reduc16), "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_f16_f32[w][GGML_TYPE_F8_E4M3][i], "mul_mat_vec_f8_e4m3_f16_f32", arr_dmmv_f8_e4m3_f16_f32_len[reduc16], arr_dmmv_f8_e4m3_f16_f32_data[reduc16], "main", mul_mat_vec_num_bindings, sizeof(vk_mat_vec_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq, i+1}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
|
||||
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
|
||||
if (device->integer_dot_product) {
|
||||
@@ -3523,6 +3555,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_IQ4_NL], "mul_mat_vec_id_iq4_nl_f32", arr_dmmv_id_iq4_nl_f32_f32_len[reduc16], arr_dmmv_id_iq4_nl_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_MXFP4], "mul_mat_vec_id_mxfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_mxfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_id_mxfp4_f32_f32, reduc16), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_NVFP4], "mul_mat_vec_id_nvfp4_f32", OCP_DMMV_LEN(arr_dmmv_id_nvfp4_f32_f32, reduc16), OCP_DMMV_DATA(arr_dmmv_id_nvfp4_f32_f32, reduc16), "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant_mul_mat_vec_id_f32[w][GGML_TYPE_F8_E4M3], "mul_mat_vec_id_f8_e4m3_f32", arr_dmmv_id_f8_e4m3_f32_f32_len[reduc16], arr_dmmv_id_f8_e4m3_f32_f32_data[reduc16], "main", mul_mat_vec_id_num_bindings, sizeof(vk_mat_vec_id_push_constants), {rm_iq, 1, 1}, {wg_size_subgroup16, rm_iq}, 1, true, use_subgroups16, force_subgroup_size16);
|
||||
|
||||
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
|
||||
if (device->integer_dot_product) {
|
||||
@@ -3590,6 +3623,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_IQ4_NL], "dequant_iq4_nl", dequant_iq4_nl_len, dequant_iq4_nl_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_MXFP4], "dequant_mxfp4", dequant_mxfp4_len, dequant_mxfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_NVFP4], "dequant_nvfp4", dequant_nvfp4_len, dequant_nvfp4_data, "main", 2, 5 * sizeof(uint32_t), {256 * 16, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_dequant[GGML_TYPE_F8_E4M3], "dequant_f8_e4m3", dequant_f8_e4m3_len, dequant_f8_e4m3_data, "main", 2, 5 * sizeof(uint32_t), {256, 1, 1}, {}, 1);
|
||||
|
||||
// get_rows
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F32 ], "get_rows_f32", get_rows_f32_len, get_rows_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
|
||||
@@ -3620,6 +3654,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl", get_rows_iq4_nl_len, get_rows_iq4_nl_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_MXFP4], "get_rows_mxfp4", get_rows_mxfp4_len, get_rows_mxfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_NVFP4], "get_rows_nvfp4", get_rows_nvfp4_len, get_rows_nvfp4_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_F8_E4M3], "get_rows_f8_e4m3", get_rows_f8_e4m3_len, get_rows_f8_e4m3_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows[GGML_TYPE_I32], "get_rows_i32", get_rows_i32_len, get_rows_i32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F32 ], "get_rows_f32_f32", get_rows_f32_f32_len, get_rows_f32_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
|
||||
@@ -3650,6 +3685,7 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_IQ4_NL], "get_rows_iq4_nl_f32", get_rows_iq4_nl_f32_len, get_rows_iq4_nl_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_MXFP4], "get_rows_mxfp4_f32", get_rows_mxfp4_f32_len, get_rows_mxfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_NVFP4], "get_rows_nvfp4_f32", get_rows_nvfp4_f32_len, get_rows_nvfp4_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {1024, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows_f32[GGML_TYPE_F8_E4M3], "get_rows_f8_e4m3_f32", get_rows_f8_e4m3_f32_len, get_rows_f8_e4m3_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), { 512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_get_rows_back_f32, "get_rows_back_f32", get_rows_back_f32_len, get_rows_back_f32_data, "main", 3, sizeof(vk_op_binary_push_constants), {256, 1, 1}, {}, 1, true);
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_matmul_split_k_reduce, "split_k_reduce", split_k_reduce_len, split_k_reduce_data, "main", 2, 2 * sizeof(uint32_t), {256 * 4, 1, 1}, {}, 1);
|
||||
@@ -3778,6 +3814,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_bf16,"cpy_f32_bf16",cpy_f32_bf16_len,cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f32,"cpy_bf16_f32",cpy_bf16_f32_len,cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_cpy_bf16_f16,"cpy_bf16_f16",cpy_bf16_f16_len,cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_cpy_8, "cpy_8", cpy_8_len, cpy_8_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_cpy_f8_e4m3_f16, "cpy_f8_e4m3_f16", cpy_f8_e4m3_f16_len, cpy_f8_e4m3_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_cpy_i32_f32, "cpy_i32_f32", cpy_i32_f32_len, cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_cpy_f32_i32, "cpy_f32_i32", cpy_f32_i32_len, cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
|
||||
@@ -3788,6 +3826,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_bf16,"contig_cpy_f32_bf16",contig_cpy_f32_bf16_len,contig_cpy_f32_bf16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f32,"contig_cpy_bf16_f32",contig_cpy_bf16_f32_len,contig_cpy_bf16_f32_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_bf16_f16,"contig_cpy_bf16_f16",contig_cpy_bf16_f16_len,contig_cpy_bf16_f16_data,"main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_8, "contig_cpy_8", contig_cpy_8_len, contig_cpy_8_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f8_e4m3_f16, "contig_cpy_f8_e4m3_f16", contig_cpy_f8_e4m3_f16_len, contig_cpy_f8_e4m3_f16_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_i32_f32, "contig_cpy_i32_f32", contig_cpy_i32_f32_len, contig_cpy_i32_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_contig_cpy_f32_i32, "contig_cpy_f32_i32", contig_cpy_f32_i32_len, contig_cpy_f32_i32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
|
||||
@@ -3902,6 +3942,8 @@ void ggml_vk_load_shaders(vk_device& device, vk_pipeline requested) {
|
||||
ggml_vk_create_pipeline(device, device->pipeline_upscale_bicubic_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BICUBIC}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_upscale_bilinear_antialias_f32, "upscale_f32", upscale_f32_len, upscale_f32_data, "main", 2, sizeof(vk_op_upscale_push_constants), {512, 1, 1}, {GGML_SCALE_MODE_BILINEAR | GGML_SCALE_FLAG_ANTIALIAS}, 1);
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_mul_mat_scale_f32, "mul_mat_scale_f32", mul_mat_scale_f32_len, mul_mat_scale_f32_data, "main", 3, sizeof(vk_op_mul_mat_scale_push_constants), {256, 1, 1}, {}, 1);
|
||||
|
||||
ggml_vk_create_pipeline(device, device->pipeline_pad_f32, "pad_f32", pad_f32_len, pad_f32_data, "main", 2, sizeof(vk_op_pad_push_constants), {512, 1, 1}, {}, 1);
|
||||
ggml_vk_create_pipeline(device, device->pipeline_pad_reflect_1d_f32, "pad_reflect_1d_f32", pad_reflect_1d_f32_len, pad_reflect_1d_f32_data, "main", 2, sizeof(vk_op_unary_push_constants), {512, 1, 1}, {}, 1);
|
||||
|
||||
@@ -6340,6 +6382,7 @@ vk_pipeline ggml_vk_get_to_fp16(ggml_backend_vk_context * ctx, ggml_type type) {
|
||||
case GGML_TYPE_NVFP4:
|
||||
case GGML_TYPE_TQ1_0:
|
||||
case GGML_TYPE_TQ2_0:
|
||||
case GGML_TYPE_F8_E4M3:
|
||||
break;
|
||||
default:
|
||||
return nullptr;
|
||||
@@ -6405,6 +6448,7 @@ static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec(ggml_backend_vk_context *
|
||||
case GGML_TYPE_NVFP4:
|
||||
case GGML_TYPE_TQ1_0:
|
||||
case GGML_TYPE_TQ2_0:
|
||||
case GGML_TYPE_F8_E4M3:
|
||||
break;
|
||||
default:
|
||||
return nullptr;
|
||||
@@ -6493,6 +6537,7 @@ static vk_pipeline ggml_vk_get_dequantize_mul_mat_vec_id(ggml_backend_vk_context
|
||||
case GGML_TYPE_NVFP4:
|
||||
case GGML_TYPE_TQ1_0:
|
||||
case GGML_TYPE_TQ2_0:
|
||||
case GGML_TYPE_F8_E4M3:
|
||||
break;
|
||||
default:
|
||||
return nullptr;
|
||||
@@ -7094,6 +7139,13 @@ vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_t
|
||||
return ctx->device->pipeline_cpy_bf16_f16;
|
||||
}
|
||||
}
|
||||
if (src->type == GGML_TYPE_F8_E4M3 && to == GGML_TYPE_F16) {
|
||||
if (contig) {
|
||||
return ctx->device->pipeline_contig_cpy_f8_e4m3_f16;
|
||||
} else {
|
||||
return ctx->device->pipeline_cpy_f8_e4m3_f16;
|
||||
}
|
||||
}
|
||||
if (src->type == GGML_TYPE_F32 && to == GGML_TYPE_I32) {
|
||||
if (contig) {
|
||||
return ctx->device->pipeline_contig_cpy_f32_i32;
|
||||
@@ -7140,6 +7192,9 @@ vk_pipeline ggml_vk_get_cpy_pipeline(ggml_backend_vk_context * ctx, const ggml_t
|
||||
}
|
||||
}
|
||||
|
||||
if (src->type == to && !ggml_is_quantized(to) && ggml_type_size(to) == 1) {
|
||||
return contig ? ctx->device->pipeline_contig_cpy_8 : ctx->device->pipeline_cpy_8;
|
||||
}
|
||||
if (src->type == to) {
|
||||
// Copy two or four bytes at a time, depending on block size.
|
||||
// For quantized types, we scale by block size/type size. But
|
||||
@@ -7280,7 +7335,7 @@ static void ggml_vk_mul_mat_q_f16(ggml_backend_vk_context * ctx, vk_context& sub
|
||||
std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << ggml_type_name(src1->type) << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
|
||||
std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << ggml_type_name(dst->type) << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
|
||||
std::cerr << "))");
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3); // NOLINT
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
|
||||
|
||||
const uint64_t ne00 = src0->ne[0];
|
||||
@@ -7657,6 +7712,10 @@ static bool ggml_vk_should_use_mmvq(const vk_device& device, uint32_t m, uint32_
|
||||
GGML_UNUSED(m);
|
||||
}
|
||||
|
||||
static bool ggml_vk_mat_vec_folds_weight_scale(const ggml_tensor * scale, bool swap_inputs = false) {
|
||||
return scale != nullptr && !swap_inputs && ggml_is_contiguous(scale);
|
||||
}
|
||||
|
||||
static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const struct ggml_cgraph * cgraph, int node_idx, bool swap_inputs = false) {
|
||||
ggml_tensor * dst = cgraph->nodes[node_idx];
|
||||
const ggml_tensor * src0 = dst->src[swap_inputs ? 1 : 0];
|
||||
@@ -7666,7 +7725,7 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context&
|
||||
std::cerr << "), (" << src1 << ", name=" << src1->name << ", type=" << src1->type << ", ne0=" << src1->ne[0] << ", ne1=" << src1->ne[1] << ", ne2=" << src1->ne[2] << ", ne3=" << src1->ne[3] << ", nb0=" << src1->nb[0] << ", nb1=" << src1->nb[1] << ", nb2=" << src1->nb[2] << ", nb3=" << src1->nb[3];
|
||||
std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
|
||||
std::cerr << ")),)");
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3); // NOLINT
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
|
||||
|
||||
const uint64_t ne00 = src0->ne[0];
|
||||
@@ -7872,6 +7931,15 @@ static void ggml_vk_mul_mat_vec_q_f16(ggml_backend_vk_context * ctx, vk_context&
|
||||
fusion_flags |= MAT_VEC_FUSION_FLAGS_BIAS1;
|
||||
}
|
||||
|
||||
// fold weight scale (src[2]) via the F0 slot, free since scaled matmuls don't fuse
|
||||
if (ggml_vk_mat_vec_folds_weight_scale(dst->src[2], swap_inputs)) {
|
||||
d_F0 = ggml_vk_tensor_subbuffer(ctx, dst->src[2]);
|
||||
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE;
|
||||
if (ggml_nelements(dst->src[2]) > 1) {
|
||||
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC;
|
||||
}
|
||||
}
|
||||
|
||||
ggml_pipeline_request_descriptor_sets(ctx, dmmv, CEIL_DIV(ne12 * ne13, ctx->device->properties.limits.maxComputeWorkGroupCount[1]));
|
||||
|
||||
uint32_t base_work_group_y = 0;
|
||||
@@ -8167,6 +8235,48 @@ static uint32_t ggml_vk_nb_elem(const ggml_tensor * t, int i) {
|
||||
return (uint32_t)(t->nb[i] / ggml_type_size(t->type));
|
||||
}
|
||||
|
||||
static void ggml_vk_mul_mat_scale(ggml_backend_vk_context * ctx, vk_context& subctx, ggml_tensor * dst) {
|
||||
const bool is_id = dst->op == GGML_OP_MUL_MAT_ID;
|
||||
const ggml_tensor * scale = is_id ? dst->src[3] : dst->src[2];
|
||||
const ggml_tensor * ids = is_id ? dst->src[2] : nullptr;
|
||||
|
||||
GGML_ASSERT(scale != nullptr && scale->type == GGML_TYPE_F32);
|
||||
GGML_ASSERT(dst->type == GGML_TYPE_F32 && ggml_is_contiguous(dst));
|
||||
|
||||
const bool per_channel_expert = is_id && scale->ne[0] == dst->ne[0] && 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);
|
||||
|
||||
vk_pipeline pipeline = ctx->device->pipeline_mul_mat_scale_f32;
|
||||
ggml_pipeline_request_descriptor_sets(ctx, pipeline, 1);
|
||||
|
||||
ggml_vk_sync_buffers(ctx, subctx);
|
||||
|
||||
vk_subbuffer d_D = ggml_vk_tensor_subbuffer(ctx, dst);
|
||||
vk_subbuffer d_S = ggml_vk_tensor_subbuffer(ctx, scale);
|
||||
vk_subbuffer d_I = is_id ? ggml_vk_tensor_subbuffer(ctx, ids, true) : d_S;
|
||||
|
||||
vk_op_mul_mat_scale_push_constants pc = {
|
||||
(uint32_t)dst->ne[0], (uint32_t)dst->ne[1], (uint32_t)dst->ne[2], (uint32_t)dst->ne[3],
|
||||
(uint32_t)scale->ne[0], (uint32_t)scale->ne[1], (uint32_t)scale->ne[2], (uint32_t)scale->ne[3],
|
||||
ggml_vk_nb_elem(scale, 0), ggml_vk_nb_elem(scale, 1), ggml_vk_nb_elem(scale, 2), ggml_vk_nb_elem(scale, 3),
|
||||
per_channel_expert ? 2u : per_expert ? 1u : 0u,
|
||||
is_id ? 1u : 0u,
|
||||
is_id ? (uint32_t)(ids->nb[0] / sizeof(int32_t)) : 0u,
|
||||
is_id ? (uint32_t)(ids->nb[1] / sizeof(int32_t)) : 0u,
|
||||
is_id ? get_misalign_bytes(ctx, ids) / (uint32_t)sizeof(int32_t) : 0u,
|
||||
0, 0, 0, 0, 0, 0,
|
||||
};
|
||||
init_fastdiv_values(pc.ne0 * pc.ne1 * pc.ne2, pc.ne_012mp, pc.ne_012L);
|
||||
init_fastdiv_values(pc.ne0 * pc.ne1, pc.ne_01mp, pc.ne_01L);
|
||||
init_fastdiv_values(pc.ne0, pc.ne_0mp, pc.ne_0L);
|
||||
|
||||
const uint64_t total = (uint64_t)ggml_nelements(dst);
|
||||
const uint64_t max_elems = (uint64_t)ctx->device->properties.limits.maxComputeWorkGroupCount[0] * 256;
|
||||
const uint32_t elements0 = (uint32_t)std::min(total, max_elems);
|
||||
|
||||
ggml_vk_dispatch_pipeline(ctx, subctx, pipeline, { d_D, d_S, d_I }, pc, { elements0, 1, 1 });
|
||||
}
|
||||
|
||||
void ggml_vk_dsv4_hc_comb(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * mixes, const ggml_tensor * scale, const ggml_tensor * base, ggml_tensor * dst) {
|
||||
VK_LOG_DEBUG("ggml_vk_dsv4_hc_comb(" << mixes << ", " << scale << ", " << base << ", " << dst << ")");
|
||||
|
||||
@@ -8310,6 +8420,8 @@ void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const st
|
||||
ggml_tensor * src1 = dst->src[1];
|
||||
VK_LOG_DEBUG("ggml_vk_mul_mat(" << src0 << ", " << src1 << ", " << dst << ")");
|
||||
|
||||
bool folded = false;
|
||||
|
||||
// Handle huge A matrix by splitting the M dimensions. This works well for convolution use cases
|
||||
// where the M dimension is very large.
|
||||
// Split_k doesn't work with M splitting.
|
||||
@@ -8371,11 +8483,16 @@ void ggml_vk_mul_mat(ggml_backend_vk_context * ctx, vk_context& subctx, const st
|
||||
// mul_mat_vec supports batching ne12*ne13 when ne11==1, or treating ne11 as the batch size (up to four)
|
||||
// when ne12 and ne13 are one.
|
||||
} else if ((dst->ne[1] == 1 || (dst->ne[1] <= ggml_vk_mul_mat_vec_max_cols(ctx->device) && src1->ne[2] * src1->ne[3] == 1)) &&
|
||||
(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || ggml_is_quantized(src0->type))) {
|
||||
(src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3 || ggml_is_quantized(src0->type))) {
|
||||
ggml_vk_mul_mat_vec_q_f16(ctx, subctx, cgraph, node_idx);
|
||||
folded = ggml_vk_mat_vec_folds_weight_scale(dst->src[2]);
|
||||
} else {
|
||||
ggml_vk_mul_mat_q_f16(ctx, subctx, src0, src1, dst, false);
|
||||
}
|
||||
|
||||
if (dst->src[2] != nullptr && !folded) {
|
||||
ggml_vk_mul_mat_scale(ctx, subctx, dst);
|
||||
}
|
||||
}
|
||||
|
||||
static void ggml_vk_mul_mat_id_q_f16(ggml_backend_vk_context * ctx, vk_context& subctx, const ggml_tensor * src0, const ggml_tensor * src1, const ggml_tensor * ids, ggml_tensor * dst) {
|
||||
@@ -8741,7 +8858,7 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte
|
||||
std::cerr << "), (" << ids << ", name=" << ids->name << ", type=" << ids->type << ", ne0=" << ids->ne[0] << ", ne1=" << ids->ne[1] << ", ne2=" << ids->ne[2] << ", ne3=" << ids->ne[3] << ", nb0=" << ids->nb[0] << ", nb1=" << ids->nb[1] << ", nb2=" << ids->nb[2] << ", nb3=" << ids->nb[3];
|
||||
std::cerr << "), (" << dst << ", name=" << dst->name << ", type=" << dst->type << ", ne0=" << dst->ne[0] << ", ne1=" << dst->ne[1] << ", ne2=" << dst->ne[2] << ", ne3=" << dst->ne[3] << ", nb0=" << dst->nb[0] << ", nb1=" << dst->nb[1] << ", nb2=" << dst->nb[2] << ", nb3=" << dst->nb[3];
|
||||
std::cerr << "))");
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16); // NOLINT
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src0) || src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_BF16 || src0->type == GGML_TYPE_F8_E4M3); // NOLINT
|
||||
GGML_ASSERT(ggml_vk_dim01_contiguous(src1) || src1->type == GGML_TYPE_F32 || src1->type == GGML_TYPE_F16); // NOLINT
|
||||
GGML_ASSERT(ids->type == GGML_TYPE_I32);
|
||||
|
||||
@@ -8940,6 +9057,18 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte
|
||||
fusion_flags |= MAT_VEC_FUSION_FLAGS_SCALE1;
|
||||
}
|
||||
|
||||
// fold weight scale (src[3]) via the F0 slot, free since scaled matmuls don't fuse
|
||||
if (ggml_vk_mat_vec_folds_weight_scale(dst->src[3])) {
|
||||
d_F0 = ggml_vk_tensor_subbuffer(ctx, dst->src[3]);
|
||||
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE;
|
||||
if (ggml_nelements(dst->src[3]) > 1) {
|
||||
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC;
|
||||
}
|
||||
if (dst->src[3]->ne[0] == dst->ne[0] && dst->src[3]->ne[1] == src0->ne[2]) {
|
||||
fusion_flags |= MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_2D;
|
||||
}
|
||||
}
|
||||
|
||||
// Loop over the batch dimension
|
||||
for (uint32_t expert_i1 = 0; expert_i1 < nei1; ++expert_i1) {
|
||||
const vk_mat_vec_id_push_constants pc = {
|
||||
@@ -8971,7 +9100,7 @@ static void ggml_vk_mul_mat_vec_id_q_f16(ggml_backend_vk_context * ctx, vk_conte
|
||||
static bool ggml_vk_use_mul_mat_vec_id(const ggml_tensor * dst) {
|
||||
const ggml_tensor * src0 = dst->src[0];
|
||||
const ggml_tensor * ids = dst->src[2];
|
||||
return ids->ne[1] <= 8 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || ggml_is_quantized(src0->type));
|
||||
return ids->ne[1] <= 8 && (src0->type == GGML_TYPE_F32 || src0->type == GGML_TYPE_F16 || src0->type == GGML_TYPE_F8_E4M3 || ggml_is_quantized(src0->type));
|
||||
}
|
||||
|
||||
bool ggml_vk_use_mul_mat_vec_id(const struct ggml_cgraph * cgraph, int node_idx) {
|
||||
@@ -8984,11 +9113,17 @@ void ggml_vk_mul_mat_id(ggml_backend_vk_context * ctx, vk_context& subctx, const
|
||||
ggml_tensor * src1 = dst->src[1];
|
||||
ggml_tensor * src2 = dst->src[2];
|
||||
VK_LOG_DEBUG("ggml_vk_mul_mat_id(" << src0 << ", " << src1 << ", " << src2 << ", " << dst << ")");
|
||||
bool folded = false;
|
||||
if (ggml_vk_use_mul_mat_vec_id(cgraph, node_idx)) {
|
||||
ggml_vk_mul_mat_vec_id_q_f16(ctx, subctx, cgraph, node_idx);
|
||||
folded = ggml_vk_mat_vec_folds_weight_scale(dst->src[3]);
|
||||
} else {
|
||||
ggml_vk_mul_mat_id_q_f16(ctx, subctx, src0, src1, src2, dst);
|
||||
}
|
||||
|
||||
if (dst->src[3] != nullptr && !folded) {
|
||||
ggml_vk_mul_mat_scale(ctx, subctx, dst);
|
||||
}
|
||||
}
|
||||
|
||||
bool ggml_vk_flash_attn_scalar_shmem_support(const vk_device& device, const vk_fa_tuning_params& params, uint32_t hsk, uint32_t hsv, bool f32acc, ggml_type k_type, ggml_type v_type) {
|
||||
@@ -15280,6 +15415,12 @@ bool ggml_vk_can_fuse(const ggml_backend_vk_context * ctx, const struct ggml_cgr
|
||||
return false;
|
||||
}
|
||||
|
||||
const ggml_tensor * base = cgraph->nodes[node_idx];
|
||||
if ((base->op == GGML_OP_MUL_MAT && base->src[2] != nullptr) ||
|
||||
(base->op == GGML_OP_MUL_MAT_ID && base->src[3] != nullptr)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if ((ops.size() == 2 || ops.size() == 3 || ops.size() == 4) &&
|
||||
ops.begin()[0] == GGML_OP_RMS_NORM && ops.begin()[1] == GGML_OP_MUL) {
|
||||
// additional constraints specific to this fusion
|
||||
@@ -17158,10 +17299,6 @@ 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;
|
||||
|
||||
@@ -17235,6 +17372,12 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
|
||||
case GGML_OP_MUL_MAT_ID:
|
||||
{
|
||||
ggml_type src0_type = op->src[0]->type;
|
||||
// matmul paths bind these at their raw offset
|
||||
for (const ggml_tensor * t : std::initializer_list<const ggml_tensor *>{op->src[0], op->src[1], ggml_get_src_scale(op, 0)}) {
|
||||
if (t && (vk_tensor_offset(t) + t->view_offs) % device->properties.limits.minStorageBufferOffsetAlignment != 0) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (op->op == GGML_OP_MUL_MAT_ID) {
|
||||
if (!ggml_vk_use_mul_mat_vec_id(op)) {
|
||||
const ggml_tensor * ids = op->src[2];
|
||||
@@ -17280,6 +17423,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
|
||||
case GGML_TYPE_NVFP4:
|
||||
case GGML_TYPE_TQ1_0:
|
||||
case GGML_TYPE_TQ2_0:
|
||||
case GGML_TYPE_F8_E4M3:
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
@@ -17288,7 +17432,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
|
||||
if (op->op == GGML_OP_MUL_MAT_ID && op->src[2]->ne[3] != op->src[1]->ne[3]) {
|
||||
return false;
|
||||
}
|
||||
if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16) ||
|
||||
if (!(ggml_vk_dim01_contiguous(op->src[0]) || op->src[0]->type == GGML_TYPE_F32 || op->src[0]->type == GGML_TYPE_F16 || op->src[0]->type == GGML_TYPE_BF16 || op->src[0]->type == GGML_TYPE_F8_E4M3) ||
|
||||
!(ggml_vk_dim01_contiguous(op->src[1]) || op->src[1]->type == GGML_TYPE_F32 || op->src[1]->type == GGML_TYPE_F16)) {
|
||||
return false;
|
||||
}
|
||||
@@ -17393,6 +17537,7 @@ static bool ggml_backend_vk_device_supports_op(ggml_backend_dev_t dev, const ggm
|
||||
case GGML_TYPE_NVFP4:
|
||||
case GGML_TYPE_TQ1_0:
|
||||
case GGML_TYPE_TQ2_0:
|
||||
case GGML_TYPE_F8_E4M3:
|
||||
case GGML_TYPE_I32:
|
||||
return true;
|
||||
default:
|
||||
@@ -18477,4 +18622,3 @@ void ggml_vk_debug_label::begin(vk_context & ctx, const std::string & name) {
|
||||
subctx->debug_labels.push_back(name);
|
||||
ggml_vk_cmd_label_begin(subctx->s->buffer->buf, subctx->debug_labels.back().c_str());
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#version 450
|
||||
|
||||
#extension GL_EXT_shader_8bit_storage : require
|
||||
|
||||
#include "types.glsl"
|
||||
#include "generic_unary_head.glsl"
|
||||
|
||||
@@ -19,7 +21,9 @@ void main() {
|
||||
if (idx + (num_iter-1)*num_threads < p.ne) {
|
||||
[[unroll]] for (uint i = 0; i < num_iter; ++i) {
|
||||
|
||||
#if defined(DATA_A_BF16)
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
data_d[get_doffset() + idx] = D_TYPE(e4m3_to_fp32(data_a[get_aoffset() + idx]));
|
||||
#elif defined(DATA_A_BF16)
|
||||
data_d[get_doffset() + idx] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + idx])));
|
||||
#elif defined(DATA_D_BF16)
|
||||
float f = float(data_a[get_aoffset() + idx]);
|
||||
@@ -37,7 +41,9 @@ void main() {
|
||||
continue;
|
||||
}
|
||||
|
||||
#if defined(DATA_A_BF16)
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
data_d[get_doffset() + idx] = D_TYPE(e4m3_to_fp32(data_a[get_aoffset() + idx]));
|
||||
#elif defined(DATA_A_BF16)
|
||||
data_d[get_doffset() + idx] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + idx])));
|
||||
#elif defined(DATA_D_BF16)
|
||||
float f = float(data_a[get_aoffset() + idx]);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#version 450
|
||||
|
||||
#extension GL_EXT_shader_8bit_storage : require
|
||||
|
||||
#include "types.glsl"
|
||||
#include "generic_unary_head.glsl"
|
||||
|
||||
@@ -12,7 +14,9 @@ void main() {
|
||||
return;
|
||||
}
|
||||
|
||||
#if defined(DATA_A_BF16)
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
data_d[get_doffset() + dst_idx(idx)] = D_TYPE(e4m3_to_fp32(data_a[get_aoffset() + src0_idx(idx)]));
|
||||
#elif defined(DATA_A_BF16)
|
||||
data_d[get_doffset() + dst_idx(idx)] = D_TYPE(bf16_to_fp32(uint32_t(data_a[get_aoffset() + src0_idx(idx)])));
|
||||
#elif defined(DATA_D_BF16)
|
||||
float f = float(data_a[get_aoffset() + src0_idx(idx)]);
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
#version 450
|
||||
|
||||
#include "dequant_head.glsl"
|
||||
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
|
||||
layout (binding = 0) readonly buffer A {uint8_t data_a[];};
|
||||
layout (binding = 1) writeonly buffer D {D_TYPE data_b[];};
|
||||
|
||||
void main() {
|
||||
const uint i = gl_GlobalInvocationID.x;
|
||||
|
||||
if (i >= p.nel) {
|
||||
return;
|
||||
}
|
||||
|
||||
data_b[i] = D_TYPE(e4m3_to_fp32(data_a[i]));
|
||||
}
|
||||
@@ -544,12 +544,38 @@ vec4 dequantize4(uint ib, uint iqs, uint a_offset) {
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
FLOAT_TYPE dequantize1(uint ib, uint iqs, uint a_offset) {
|
||||
return FLOAT_TYPE(e4m3_to_fp32(data_a[a_offset + ib + iqs]));
|
||||
}
|
||||
vec2 dequantize(uint ib, uint iqs, uint a_offset) {
|
||||
const uint idx = a_offset + ib + iqs;
|
||||
return vec2(e4m3_to_fp32(data_a[idx]), e4m3_to_fp32(data_a[idx + 1]));
|
||||
}
|
||||
vec4 dequantize4(uint ib, uint iqs, uint a_offset) {
|
||||
const uint idx = a_offset + ib + iqs;
|
||||
return vec4(e4m3_to_fp32(data_a[idx ]), e4m3_to_fp32(data_a[idx + 1]),
|
||||
e4m3_to_fp32(data_a[idx + 2]), e4m3_to_fp32(data_a[idx + 3]));
|
||||
}
|
||||
vec4 dequantize4_2aligned(uint ib, uint iqs, uint a_offset) {
|
||||
const uint idx = a_offset + ib + iqs;
|
||||
return vec4(e4m3_to_fp32(data_a[idx ]), e4m3_to_fp32(data_a[idx + 1]),
|
||||
e4m3_to_fp32(data_a[idx + 2]), e4m3_to_fp32(data_a[idx + 3]));
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16)
|
||||
vec2 get_dm(uint ib, uint a_offset) {
|
||||
return vec2(0, 0);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
vec2 get_dm(uint ib, uint a_offset) {
|
||||
return vec2(1.0, 0.0);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_IQ1_M)
|
||||
vec2 get_dm(uint ib, uint a_offset) {
|
||||
const uint16_t[4] scales = data_a[a_offset + ib].scales;
|
||||
|
||||
@@ -1412,6 +1412,17 @@ f16vec4 dequantFuncNVFP4_v(const in decodeBufNVFP4 bl, const in uint blockCoords
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
layout(buffer_reference, std430, buffer_reference_align = 1) buffer decodeBufF8_E4M3 {
|
||||
uint8_t block;
|
||||
};
|
||||
|
||||
float16_t dequantFuncF8_E4M3(const in decodeBufF8_E4M3 bl, const in uint blockCoords[2], const in uint coordInBlock[2])
|
||||
{
|
||||
return float16_t(e4m3_to_fp32(bl.block));
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_Q1_0)
|
||||
#define dequantFuncA dequantFuncQ1_0
|
||||
#define dequantFuncA_v dequantFuncQ1_0_v
|
||||
@@ -1492,4 +1503,6 @@ f16vec4 dequantFuncNVFP4_v(const in decodeBufNVFP4 bl, const in uint blockCoords
|
||||
#define dequantFuncA_v dequantFuncNVFP4_v
|
||||
#elif defined(DATA_A_F32)
|
||||
#define dequantFuncA dequantFuncF32
|
||||
#elif defined(DATA_A_F8_E4M3)
|
||||
#define dequantFuncA dequantFuncF8_E4M3
|
||||
#endif
|
||||
|
||||
@@ -27,6 +27,8 @@ void main() {
|
||||
|
||||
#if defined(DATA_A_BF16)
|
||||
TEMP_TYPE v = TEMP_TYPE(bf16_to_fp32(data_a[a_offset + i00]));
|
||||
#elif defined(DATA_A_F8_E4M3)
|
||||
TEMP_TYPE v = TEMP_TYPE(e4m3_to_fp32(data_a[a_offset + i00]));
|
||||
#else
|
||||
TEMP_TYPE v = TEMP_TYPE(data_a[a_offset + i00]);
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
#version 450
|
||||
|
||||
#extension GL_EXT_shader_explicit_arithmetic_types_int32 : require
|
||||
|
||||
#include "utils.glsl"
|
||||
|
||||
layout(local_size_x = 256, local_size_y = 1, local_size_z = 1) in;
|
||||
|
||||
layout(binding = 0) buffer D { float data_d[]; };
|
||||
layout(binding = 1) readonly buffer S { float data_s[]; };
|
||||
layout(binding = 2) readonly buffer I { int32_t data_ids[]; };
|
||||
|
||||
layout(push_constant) uniform parameter {
|
||||
uint ne0; uint ne1; uint ne2; uint ne3;
|
||||
uint sne0; uint sne1; uint sne2; uint sne3;
|
||||
uint snb0; uint snb1; uint snb2; uint snb3;
|
||||
uint per_expert;
|
||||
uint has_ids;
|
||||
uint ids_s0; uint ids_s1; uint ids_offset;
|
||||
uint ne_012mp; uint ne_012L;
|
||||
uint ne_01mp; uint ne_01L;
|
||||
uint ne_0mp; uint ne_0L;
|
||||
} p;
|
||||
|
||||
void main() {
|
||||
const uint total = p.ne0 * p.ne1 * p.ne2 * p.ne3;
|
||||
const uint stride = gl_NumWorkGroups.x * gl_WorkGroupSize.x;
|
||||
|
||||
for (uint i = gl_GlobalInvocationID.x; i < total; i += stride) {
|
||||
const uint i3 = fastdiv(i, p.ne_012mp, p.ne_012L);
|
||||
const uint r3 = i - i3 * p.ne0 * p.ne1 * p.ne2;
|
||||
const uint i2 = fastdiv(r3, p.ne_01mp, p.ne_01L);
|
||||
const uint r2 = r3 - i2 * p.ne0 * p.ne1;
|
||||
const uint i1 = fastdiv(r2, p.ne_0mp, p.ne_0L);
|
||||
const uint i0 = r2 - i1 * p.ne0;
|
||||
|
||||
int32_t expert = 0;
|
||||
if (p.has_ids != 0) {
|
||||
expert = data_ids[p.ids_offset + i1 * p.ids_s0 + i2 * p.ids_s1];
|
||||
if (expert < 0) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
uint si;
|
||||
if (p.per_expert != 0) {
|
||||
si = (p.per_expert == 2) ? i0 * p.snb0 + uint(expert) * p.snb1 : uint(expert) * p.snb0;
|
||||
} else {
|
||||
si = (i0 % p.sne0) * p.snb0
|
||||
+ (i1 % p.sne1) * p.snb1
|
||||
+ (i2 % p.sne2) * p.snb2
|
||||
+ (i3 % p.sne3) * p.snb3;
|
||||
}
|
||||
|
||||
data_d[i] *= data_s[si];
|
||||
}
|
||||
}
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
layout(local_size_x_id = 0, local_size_y = 1, local_size_z = 1) in;
|
||||
|
||||
#if !defined(DATA_A_F32) && !defined(DATA_A_F16) && !defined(DATA_A_BF16)
|
||||
#if !defined(DATA_A_F32) && !defined(DATA_A_F16) && !defined(DATA_A_BF16) && !defined(DATA_A_F8_E4M3)
|
||||
#define K_PER_ITER 8
|
||||
#else
|
||||
#define K_PER_ITER 4
|
||||
@@ -114,7 +114,7 @@ void iter(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16)
|
||||
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16) || defined(DATA_A_F8_E4M3)
|
||||
void iter_aligned_nonquant(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const uint first_row, const uint num_rows, const uint tid, const uint i)
|
||||
{
|
||||
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
|
||||
|
||||
@@ -93,6 +93,16 @@ layout (constant_id = 0) const uint BLOCK_SIZE = 32;
|
||||
layout (constant_id = 1) const uint NUM_ROWS = 1;
|
||||
layout (constant_id = 2) const uint NUM_COLS = 1;
|
||||
|
||||
#ifdef MUL_MAT_ID
|
||||
#define WEIGHT_SCALE_INDEX(row) (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_2D) != 0) ? (expert_id * p.stride_d + (row)) : (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC) != 0) ? expert_id : 0u))
|
||||
#else
|
||||
#define WEIGHT_SCALE_INDEX(row) (((p.fusion_flags & MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC) != 0) ? (row) : 0u)
|
||||
#endif
|
||||
#define APPLY_WEIGHT_SCALE(acc, row) \
|
||||
if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE) != 0) { \
|
||||
(acc) *= FLOAT_TYPE(data_fuse0[WEIGHT_SCALE_INDEX(row)]); \
|
||||
}
|
||||
|
||||
#ifdef USE_SUBGROUP_ADD_NO_SHMEM
|
||||
void reduce_result(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offset, const in uint32_t first_row, const in uint32_t num_rows, const in uint32_t tid) {
|
||||
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
|
||||
@@ -104,6 +114,7 @@ void reduce_result(inout FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t
|
||||
if (tid == 0) {
|
||||
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
|
||||
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
|
||||
APPLY_WEIGHT_SCALE(temp[j][n], first_row + n);
|
||||
#ifdef MUL_MAT_ID
|
||||
if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) {
|
||||
temp[j][n] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]);
|
||||
@@ -162,6 +173,7 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs
|
||||
[[unroll]] for (uint s = 0; s < gl_NumSubgroups; ++s) {
|
||||
temp[j][n] += tmpsh[j][n][s];
|
||||
}
|
||||
APPLY_WEIGHT_SCALE(temp[j][n], first_row + n);
|
||||
#ifdef MUL_MAT_ID
|
||||
if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) {
|
||||
temp[j][n] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]);
|
||||
@@ -210,6 +222,7 @@ void reduce_result(FLOAT_TYPE temp[NUM_COLS][NUM_ROWS], const in uint32_t d_offs
|
||||
if (tid == 0) {
|
||||
[[unroll]] for (uint j = 0; j < NUM_COLS; ++j) {
|
||||
[[unroll]] for (uint n = 0; n < num_rows; ++n) {
|
||||
APPLY_WEIGHT_SCALE(tmpsh[j][n][0], first_row + n);
|
||||
#ifdef MUL_MAT_ID
|
||||
if ((p.fusion_flags & MAT_VEC_FUSION_FLAGS_BIAS0) != 0) {
|
||||
tmpsh[j][n][0] += FLOAT_TYPE(data_fuse0[expert_id*p.stride_d + first_row + n]);
|
||||
|
||||
@@ -4,6 +4,11 @@
|
||||
#define MAT_VEC_FUSION_FLAGS_BIAS1 0x2
|
||||
#define MAT_VEC_FUSION_FLAGS_SCALE0 0x4
|
||||
#define MAT_VEC_FUSION_FLAGS_SCALE1 0x8
|
||||
// weight scale in data_fuse0; _VEC: per-output (dense) / per-expert (id), else scalar;
|
||||
// _2D (id only): per-channel-per-expert [n_out, n_expert]
|
||||
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE 0x10
|
||||
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_VEC 0x20
|
||||
#define MAT_VEC_FUSION_FLAGS_WEIGHT_SCALE_2D 0x40
|
||||
|
||||
layout (binding = 0) readonly buffer A {A_TYPE data_a[];};
|
||||
#if defined(A_TYPEV4)
|
||||
|
||||
@@ -87,6 +87,8 @@ layout (binding = 0) readonly buffer A_SCALAR {float data_a_scalar[];};
|
||||
layout (binding = 0) readonly buffer A_SCALAR {float16_t data_a_scalar[];};
|
||||
#elif defined(DATA_A_BF16)
|
||||
layout (binding = 0) readonly buffer A_SCALAR {uint16_t data_a_scalar[];};
|
||||
#elif defined(DATA_A_F8_E4M3)
|
||||
layout (binding = 0) readonly buffer A_SCALAR {uint8_t data_a_scalar[];};
|
||||
#endif
|
||||
#if defined(A_TYPE_PACKED16)
|
||||
layout (binding = 0) readonly buffer A_PACKED16 {A_TYPE_PACKED16 data_a_packed16[];};
|
||||
@@ -283,7 +285,7 @@ void main() {
|
||||
const uint warp_r = warp_i % (BM / WM);
|
||||
const uint warp_c = warp_i / (BM / WM);
|
||||
|
||||
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16)
|
||||
#if defined(DATA_A_F32) || defined(DATA_A_F16) || defined(DATA_A_BF16) || defined(DATA_A_F8_E4M3)
|
||||
const uint LOAD_VEC_A_EFF = (ALIGNED != 0) ? LOAD_VEC_A : 1;
|
||||
const uint LOAD_VEC_BATCH_A = (ALIGNED != 0) ? 1 : 2;
|
||||
#elif !defined(MULMAT_QUANT)
|
||||
|
||||
@@ -124,7 +124,7 @@ layout (binding = 3) writeonly buffer S {D_TYPE data_s[];};
|
||||
layout (binding = 1) readonly buffer B4 {B_TYPEV4 data_b_v4[];};
|
||||
#endif
|
||||
|
||||
#if defined(MULMAT_QUANT) || QUANT_K > 1
|
||||
#if defined(MULMAT_QUANT) || QUANT_K > 1 || defined(DATA_A_F8_E4M3)
|
||||
#include "dequant_funcs_cm2.glsl"
|
||||
#ifndef MULMAT_QUANT
|
||||
// Per-type path: use the alias set by dequant_funcs_cm2.glsl
|
||||
|
||||
@@ -345,6 +345,26 @@ void load_a_to_shmem(const uint pos_a, const uint row, const uint col, const uin
|
||||
store_a(col, eff_row + 4, FLOAT_TYPEV2(kvalues_mxfp4[vui >> 4] * d,
|
||||
kvalues_mxfp4[vui2 >> 4] * d));
|
||||
#endif
|
||||
#elif defined(DATA_A_F8_E4M3)
|
||||
#if LOAD_VEC_A == 4
|
||||
if (ALIGNED != 0) {
|
||||
const uint idx = pos_a + col * p.stride_a / LOAD_VEC_A + row;
|
||||
const uint k_pair = row * LOAD_VEC_A / 2;
|
||||
FLOAT_TYPEV4 aa = FLOAT_TYPEV4(e4m3_to_fp32(data_a[idx]));
|
||||
store_a(col, k_pair, aa.xy);
|
||||
store_a(col, k_pair + 1, aa.zw);
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
const uint idx = pos_a + col * p.stride_a + row * 2;
|
||||
if (idx_m < p.M && block + row * 2 + 1 < end_k) {
|
||||
store_a(col, row, FLOAT_TYPEV2(e4m3_to_fp32(data_a_scalar[idx]),
|
||||
e4m3_to_fp32(data_a_scalar[idx + 1])));
|
||||
} else if (idx_m < p.M && block + row * 2 < end_k) {
|
||||
store_a(col, row, FLOAT_TYPEV2(e4m3_to_fp32(data_a_scalar[idx]), 0.0f));
|
||||
} else {
|
||||
store_a(col, row, FLOAT_TYPEV2(0.0f));
|
||||
}
|
||||
#else
|
||||
if (MmTypeA == GGML_TYPE_Q4_0) {
|
||||
const uint idx = pos_a + col * p.stride_a / mm_load_vec_a() + row;
|
||||
|
||||
@@ -12,6 +12,10 @@
|
||||
#extension GL_EXT_float_e4m3 : require
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
#extension GL_EXT_shader_8bit_storage : require
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_F32)
|
||||
#define QUANT_K 1
|
||||
#define QUANT_R 1
|
||||
@@ -54,6 +58,18 @@
|
||||
#define A_TYPE_PACKED32 uint32_t
|
||||
#endif
|
||||
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
#define QUANT_K 1
|
||||
#define QUANT_R 1
|
||||
|
||||
#if LOAD_VEC_A == 4
|
||||
#define A_TYPE u8vec4
|
||||
#else
|
||||
#define A_TYPE uint8_t
|
||||
#endif
|
||||
#define A_TYPE_PACKED32 uint32_t
|
||||
#endif
|
||||
|
||||
#define QUANT_K_Q4_0 32
|
||||
#define QUANT_R_Q4_0 2
|
||||
|
||||
@@ -1971,6 +1987,33 @@ float bf16_to_fp32(uint32_t u)
|
||||
return uintBitsToFloat(u << 16);
|
||||
}
|
||||
|
||||
// OCP E4M3: 1 sign, 4 exponent (bias 7), 3 mantissa. No infinities; S.1111.111 is NaN.
|
||||
float e4m3_to_fp32(uint x) {
|
||||
const uint s = (x >> 7) & 1u;
|
||||
const uint e = (x >> 3) & 0xFu;
|
||||
const uint m = x & 0x7u;
|
||||
float val;
|
||||
if (e == 0xFu && m == 0x7u) {
|
||||
return uintBitsToFloat(0x7FC00000u | (s << 31)); // NaN
|
||||
} else if (e == 0u) {
|
||||
val = float(m) * (1.0 / 512.0); // 2^-6 * m/8
|
||||
} else {
|
||||
val = uintBitsToFloat(((e + 120u) << 23) | (m << 20));
|
||||
}
|
||||
return s == 1u ? -val : val;
|
||||
}
|
||||
|
||||
#if defined(DATA_A_F8_E4M3)
|
||||
float e4m3_to_fp32(uint8_t x) {
|
||||
return e4m3_to_fp32(uint(x));
|
||||
}
|
||||
|
||||
vec4 e4m3_to_fp32(u8vec4 x) {
|
||||
return vec4(e4m3_to_fp32(uint(x.x)), e4m3_to_fp32(uint(x.y)),
|
||||
e4m3_to_fp32(uint(x.z)), e4m3_to_fp32(uint(x.w)));
|
||||
}
|
||||
#endif
|
||||
|
||||
vec4 bf16_to_fp32(uvec4 u)
|
||||
{
|
||||
return vec4(bf16_to_fp32(u.x), bf16_to_fp32(u.y), bf16_to_fp32(u.z), bf16_to_fp32(u.w));
|
||||
|
||||
@@ -75,6 +75,7 @@ const std::vector<std::string> type_names = {
|
||||
"tq1_0",
|
||||
"tq2_0",
|
||||
"bf16",
|
||||
"f8_e4m3",
|
||||
};
|
||||
|
||||
enum MatMulIdType {
|
||||
@@ -628,6 +629,15 @@ void matmul_shaders(bool fp16, MatMulIdType matmul_id_type, bool coopmat, bool c
|
||||
{"FLOAT_TYPEV8", FLOAT_TYPE(8, tname)},
|
||||
};
|
||||
|
||||
if (tname == "f8_e4m3") {
|
||||
const std::string load_vec_a = coopmat2 ? "1" : "4";
|
||||
if (!coopmat2) {
|
||||
string_to_spv(shader_name + "_f8_e4m3_f32" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec_a}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f32}, {"B_TYPE_SCALAR", "float"}, {"B_TYPEV4", "vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc);
|
||||
}
|
||||
string_to_spv(shader_name + "_f8_e4m3_f16" + dot2_sfx, source_name, merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"LOAD_VEC_A", load_vec_a}, {"LOAD_VEC_B", load_vec}, {"B_TYPE", aligned_b_type_f16}, {"B_TYPE_SCALAR", "float16_t"}, {"B_TYPEV4", "f16vec4"}, {"D_TYPE", "float"}}), fp16, coopmat, coopmat2, f16acc);
|
||||
continue;
|
||||
}
|
||||
|
||||
#if defined(GGML_VULKAN_INTEGER_DOT_GLSLC_SUPPORT)
|
||||
if (!f16acc && !coopmat && !coopmat2 && !dot2 && (is_legacy_quant(tname) || is_k_quant(tname) || tname == "mxfp4" || tname == "iq3_s" || tname == "iq4_xs")) {
|
||||
string_to_spv(shader_name + "_" + tname + "_q8_1", "mul_mmq.comp", merge_maps(merge_maps(base_dict, float_type_dict), {{data_a_key, "1"}, {"D_TYPE", "float"},}), fp16, coopmat, coopmat2, f16acc);
|
||||
@@ -850,7 +860,7 @@ void process_shaders() {
|
||||
string_to_spv("dequant_" + tname + "_transpose", "dequant_" + tname + ".comp", merge_maps(base_dict, {{data_a_key, "1"}, {"D_TYPE", "float16_t"}, {"DEQUANT_TRANSPOSE", "1"}}));
|
||||
}
|
||||
|
||||
shader = (tname == "f32" || tname == "f16" || tname == "bf16") ? "get_rows.comp" : "get_rows_quant.comp";
|
||||
shader = (tname == "f32" || tname == "f16" || tname == "bf16" || tname == "f8_e4m3") ? "get_rows.comp" : "get_rows_quant.comp";
|
||||
|
||||
if (tname == "f16") {
|
||||
string_to_spv("get_rows_" + tname, shader, merge_maps(base_dict, {{"TEMP_TYPE", "FLOAT_TYPE"}, {data_a_key, "1"}, {"B_TYPE", "int"}, {"D_TYPE", "float16_t"}, {"OPTIMIZATION_ERROR_WORKAROUND", "1"}}));
|
||||
@@ -895,6 +905,8 @@ void process_shaders() {
|
||||
string_to_spv("cpy_f32_bf16","copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "uint16_t"}, {"DATA_D_BF16", "1"}});
|
||||
string_to_spv("cpy_bf16_f32","copy.comp", {{"A_TYPE", "uint16_t"}, {"D_TYPE", "float"}, {"DATA_A_BF16", "1"}});
|
||||
string_to_spv("cpy_bf16_f16","copy.comp", {{"A_TYPE", "uint16_t"}, {"D_TYPE", "float16_t"}, {"DATA_A_BF16", "1"}});
|
||||
string_to_spv("cpy_8", "copy.comp", {{"A_TYPE", "uint8_t"}, {"D_TYPE", "uint8_t"}});
|
||||
string_to_spv("cpy_f8_e4m3_f16", "copy.comp", {{"A_TYPE", "uint8_t"}, {"D_TYPE", "float16_t"}, {"DATA_A_F8_E4M3", "1"}});
|
||||
string_to_spv("contig_cpy_32", "contig_copy.comp", {{"A_TYPE", "uint"}, {"D_TYPE", "uint"}});
|
||||
string_to_spv("contig_cpy_f32_i32", "contig_copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "int"}});
|
||||
string_to_spv("contig_cpy_i32_f32", "contig_copy.comp", {{"A_TYPE", "int"}, {"D_TYPE", "float"}});
|
||||
@@ -904,6 +916,8 @@ void process_shaders() {
|
||||
string_to_spv("contig_cpy_f32_bf16","contig_copy.comp",{{"A_TYPE", "float"}, {"D_TYPE", "uint16_t"}, {"DATA_D_BF16", "1"}});
|
||||
string_to_spv("contig_cpy_bf16_f32","contig_copy.comp",{{"A_TYPE", "uint16_t"}, {"D_TYPE", "float"}, {"DATA_A_BF16", "1"}});
|
||||
string_to_spv("contig_cpy_bf16_f16","contig_copy.comp",{{"A_TYPE", "uint16_t"}, {"D_TYPE", "float16_t"}, {"DATA_A_BF16", "1"}});
|
||||
string_to_spv("contig_cpy_8", "contig_copy.comp", {{"A_TYPE", "uint8_t"}, {"D_TYPE", "uint8_t"}});
|
||||
string_to_spv("contig_cpy_f8_e4m3_f16", "contig_copy.comp", {{"A_TYPE", "uint8_t"}, {"D_TYPE", "float16_t"}, {"DATA_A_F8_E4M3", "1"}});
|
||||
string_to_spv("cpy_f32_i32", "copy.comp", {{"A_TYPE", "float"}, {"D_TYPE", "int"}});
|
||||
string_to_spv("cpy_i32_f32", "copy.comp", {{"A_TYPE", "int"}, {"D_TYPE", "float"}});
|
||||
|
||||
@@ -987,6 +1001,8 @@ void process_shaders() {
|
||||
|
||||
string_to_spv("repeat_i16", "repeat.comp", {{"A_TYPE", "int16_t"}, {"D_TYPE", "int16_t"}});
|
||||
|
||||
string_to_spv("mul_mat_scale_f32", "mul_mat_scale.comp", {});
|
||||
|
||||
string_to_spv("pad_f32", "pad.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
|
||||
string_to_spv("pad_reflect_1d_f32", "pad_reflect_1d.comp", {{"A_TYPE", "float"}, {"D_TYPE", "float"}});
|
||||
|
||||
|
||||
@@ -554,6 +554,10 @@ static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr
|
||||
GGML_LOG_ERROR("%s: key %" PRIi64 " is empty\n", __func__, i);
|
||||
ok = false;
|
||||
}
|
||||
if (ok && key.find('\0') != std::string::npos) {
|
||||
GGML_LOG_ERROR("%s: key %" PRIi64 " contains a NUL byte\n", __func__, i);
|
||||
ok = false;
|
||||
}
|
||||
if (ok && !seen_keys.insert(key).second) {
|
||||
GGML_LOG_ERROR("%s: duplicate key '%s' for KV pair %" PRIi64 "\n", __func__, key.c_str(), i);
|
||||
ok = false;
|
||||
@@ -636,6 +640,11 @@ static struct gguf_context * gguf_init_from_reader(const struct gguf_reader & gr
|
||||
GGML_LOG_ERROR("%s: encountered bad_alloc error while reading tensor name %" PRIi64 "\n", __func__, i);
|
||||
ok = false;
|
||||
}
|
||||
if (ok && name.find('\0') != std::string::npos) {
|
||||
GGML_LOG_ERROR("%s: tensor name %" PRIi64 " contains a NUL byte\n", __func__, i);
|
||||
ok = false;
|
||||
break;
|
||||
}
|
||||
if (name.length() >= GGML_MAX_NAME) {
|
||||
GGML_LOG_ERROR("%s: tensor name %" PRIi64 " is too long: %zu >= %d\n", __func__, i, name.length(), GGML_MAX_NAME);
|
||||
ok = false;
|
||||
|
||||
@@ -187,6 +187,8 @@ class GGUFReader:
|
||||
# Ensure alignment is a non-zero power of two
|
||||
if self.alignment == 0 or (self.alignment & (self.alignment - 1)) != 0:
|
||||
raise ValueError('Invalid alignment: must be a non-zero power of two')
|
||||
if self.alignment > self.data.nbytes:
|
||||
raise ValueError(f'Declared general.alignment ({self.alignment}) exceeds the size of the input file ({self.data.nbytes} bytes)')
|
||||
padding = offs % self.alignment
|
||||
if padding != 0:
|
||||
offs += int(self.alignment - padding)
|
||||
@@ -296,9 +298,13 @@ class GGUFReader:
|
||||
offset_tensor = self._get(offs, np.uint64)
|
||||
offs += int(offset_tensor.nbytes)
|
||||
|
||||
name = str(bytes(name_data), encoding = 'utf-8')
|
||||
if '\0' in name:
|
||||
raise ValueError(f'Tensor name {name!r} contains a NUL byte')
|
||||
|
||||
return ReaderField(
|
||||
orig_offs,
|
||||
str(bytes(name_data), encoding = 'utf-8'),
|
||||
name,
|
||||
[name_len, name_data, n_dims, dims, raw_dtype, offset_tensor],
|
||||
[1, 3, 4, 5],
|
||||
)
|
||||
@@ -308,6 +314,9 @@ class GGUFReader:
|
||||
orig_offs = offs
|
||||
kv_klen, kv_kdata = self._get_str(offs)
|
||||
offs += int(kv_klen.nbytes + kv_kdata.nbytes)
|
||||
key = str(bytes(kv_kdata), encoding = 'utf-8')
|
||||
if '\0' in key:
|
||||
raise ValueError(f'Key {key!r} contains a NUL byte')
|
||||
raw_kv_type = self._get(offs, np.uint32)
|
||||
offs += int(raw_kv_type.nbytes)
|
||||
parts: list[npt.NDArray[Any]] = [kv_klen, kv_kdata, raw_kv_type]
|
||||
@@ -316,7 +325,7 @@ class GGUFReader:
|
||||
parts += field_parts
|
||||
self._push_field(ReaderField(
|
||||
orig_offs,
|
||||
str(bytes(kv_kdata), encoding = 'utf-8'),
|
||||
key,
|
||||
parts,
|
||||
[idx + idxs_offs for idx in field_idxs],
|
||||
field_types,
|
||||
|
||||
@@ -412,7 +412,11 @@ class GGUFWriter:
|
||||
def write_padding(self, fp: IO[bytes], n: int, align: int | None = None) -> None:
|
||||
pad = GGUFWriter.ggml_pad(n, align if align is not None else self.data_alignment) - n
|
||||
if pad != 0:
|
||||
fp.write(bytes([0] * pad))
|
||||
zeros = bytes(8 * 1024)
|
||||
while pad > 0:
|
||||
chunk = zeros[:pad]
|
||||
fp.write(chunk)
|
||||
pad -= len(chunk)
|
||||
|
||||
def write_tensor_data(self, tensor: np.ndarray[Any, Any], tensor_endianess: GGUFEndian | None = None) -> None:
|
||||
if self.state is not WriterState.TI_DATA and self.state is not WriterState.WEIGHTS:
|
||||
|
||||
@@ -98,6 +98,8 @@ CODEPOINT_FLAG_MARK = 0x0010 # \p{M}
|
||||
CODEPOINT_FLAG_PUNCTUATION = 0x0020 # \p{P}
|
||||
CODEPOINT_FLAG_SYMBOL = 0x0040 # \p{S}
|
||||
CODEPOINT_FLAG_CONTROL = 0x0080 # \p{C}
|
||||
CODEPOINT_FLAG_LOWERCASE = 0x0200 # \p{Ll}
|
||||
CODEPOINT_FLAG_UPPERCASE = 0x0400 # \p{Lu}
|
||||
|
||||
UNICODE_CATEGORY_TO_FLAG = {
|
||||
"Cn": CODEPOINT_FLAG_UNDEFINED, # Undefined
|
||||
@@ -146,6 +148,10 @@ for (cpt, cpt_lower, cpt_upper, categ, bidir) in unicode_data_iter():
|
||||
|
||||
# codepoint category flags
|
||||
codepoint_flags[cpt] = UNICODE_CATEGORY_TO_FLAG[categ]
|
||||
if categ == "Lu":
|
||||
codepoint_flags[cpt] |= CODEPOINT_FLAG_UPPERCASE
|
||||
elif categ == "Ll":
|
||||
codepoint_flags[cpt] |= CODEPOINT_FLAG_LOWERCASE
|
||||
|
||||
# lowercase conversion
|
||||
if cpt_lower:
|
||||
|
||||
@@ -966,6 +966,7 @@ static const std::map<llm_tensor, const char *> LLM_TENSOR_NAMES = {
|
||||
{ LLM_TENSOR_ROUTER_OUT, "blk.%d.ffn_router_out" },
|
||||
{ LLM_TENSOR_ATTN_V_GATE, "blk.%d.attn_v_gate" },
|
||||
{ LLM_TENSOR_ATTN_V_EXPS, "blk.%d.attn_v_exps" },
|
||||
{ LLM_TENSOR_OUTPUT_LEXICAL, "output" },
|
||||
};
|
||||
|
||||
// declare information about the model weight tensors:
|
||||
@@ -1408,6 +1409,7 @@ static const std::map<llm_tensor, llm_tensor_info> LLM_TENSOR_INFOS = {
|
||||
|
||||
{LLM_TENSOR_ATTN_V_GATE, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT}},
|
||||
{LLM_TENSOR_ATTN_V_EXPS, {LLM_TENSOR_LAYER_REPEATING, GGML_OP_MUL_MAT_ID}},
|
||||
{LLM_TENSOR_OUTPUT_LEXICAL, {LLM_TENSOR_LAYER_OUTPUT, GGML_OP_GET_ROWS}},
|
||||
};
|
||||
|
||||
LLM_KV::LLM_KV(llm_arch arch, const char * suffix) : arch(arch), suffix(suffix) {}
|
||||
|
||||
@@ -969,6 +969,7 @@ enum llm_tensor {
|
||||
LLM_TENSOR_ROUTER_OUT,
|
||||
LLM_TENSOR_ATTN_V_GATE,
|
||||
LLM_TENSOR_ATTN_V_EXPS,
|
||||
LLM_TENSOR_OUTPUT_LEXICAL, // Clef: Maps to the same tensor as LLM_TENSOR_OUTPUT but uses GET_ROWS operation
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -345,6 +345,7 @@ llama_context::llama_context(
|
||||
|
||||
cparams.op_offload = params.op_offload;
|
||||
cparams.kv_unified = params.kv_unified;
|
||||
cparams.kv_quantized = ggml_is_quantized(params.type_k) || ggml_is_quantized(params.type_v);
|
||||
|
||||
// the Hy4 flash pools gather their members from a single KV stream
|
||||
if (model.arch == LLM_ARCH_HY_V4_FLASH && !cparams.kv_unified && cparams.n_seq_max > 1) {
|
||||
@@ -2886,6 +2887,13 @@ uint32_t llama_context::graph_max_nodes() const {
|
||||
res += 32u*model.hparams.n_layer_all;
|
||||
}
|
||||
|
||||
// a quantized KV cache may rotate Q and K (K cache) and V and the attention output (V cache) of each layer,
|
||||
// 3 nodes per rotation plus the rotation matrices, which the per-tensor estimate above does not cover for
|
||||
// models with few tensors per layer (e.g. fused QKV)
|
||||
if (cparams.kv_quantized) {
|
||||
res += 16u*model.hparams.n_layer_all;
|
||||
}
|
||||
|
||||
// every sampler builds n_outputs_max_per_seq chains, see llm_graph_context::build_sampling
|
||||
for (const auto & [seq_id, sampler] : sampling.samplers) {
|
||||
res += llama_sampler_backend_n_nodes(sampler) * cparams.n_outputs_max_per_seq;
|
||||
|
||||
@@ -51,6 +51,7 @@ struct llama_cparams {
|
||||
bool no_perf;
|
||||
bool op_offload;
|
||||
bool kv_unified;
|
||||
bool kv_quantized; // quantized K or V cache: the cache may rotate Q/K/V and the attention output
|
||||
bool pipeline_parallel;
|
||||
bool training; // set by llama_opt_init()
|
||||
bool moe_random_routing; // benchmark only: random expert ids in the MoE GEMMs
|
||||
|
||||
@@ -2249,6 +2249,7 @@ void llama_model_base::load_hparams_hadamard(llama_model_loader & ml) {
|
||||
|
||||
// only build_lora_mm/build_lora_mm_id apply the transform: refuse archs and tensor kinds that can skip them
|
||||
switch (arch) {
|
||||
case LLM_ARCH_LFM3:
|
||||
case LLM_ARCH_LLAMA:
|
||||
case LLM_ARCH_QWEN3:
|
||||
case LLM_ARCH_QWEN3MOE:
|
||||
@@ -2271,6 +2272,7 @@ void llama_model_base::load_hparams_hadamard(llama_model_loader & ml) {
|
||||
"ffn_gate_exps", "ffn_up_exps", "ffn_down_exps", "ffn_gate_up_exps",
|
||||
"ffn_gate_shexp", "ffn_up_shexp", "ffn_down_shexp",
|
||||
"ssm_out",
|
||||
"shortconv.in_proj", "shortconv.out_proj",
|
||||
};
|
||||
if (name == "output.weight") {
|
||||
return true; // the output head is built through build_lora_mm in every arch
|
||||
|
||||
+7
-1
@@ -82,6 +82,12 @@ void llama_model_clef::load_arch_tensors(llama_model_loader & ml) {
|
||||
load_norm(field_norm, LLM_TENSOR_DECISION_FIELD_NORM, n_embd_h);
|
||||
load_norm(option_norm, LLM_TENSOR_DECISION_OPTION_NORM, n_embd_h);
|
||||
|
||||
output_lexical = create_tensor(tn(LLM_TENSOR_OUTPUT_LEXICAL, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);
|
||||
|
||||
if (output_lexical == nullptr) {
|
||||
output_lexical = tok_embd;
|
||||
}
|
||||
|
||||
proj_memory = create_tensor(tn(LLM_TENSOR_DECISION_PROJ_MEMORY, "weight"), {n_embd, n_embd_h}, 0);
|
||||
proj_question = create_tensor(tn(LLM_TENSOR_DECISION_PROJ_QUESTION, "weight"), {n_embd, n_embd_h}, 0);
|
||||
proj_option_question = create_tensor(tn(LLM_TENSOR_DECISION_PROJ_OPTION_QUESTION, "weight"), {n_embd, n_embd_h}, 0);
|
||||
@@ -559,7 +565,7 @@ ggml_tensor * llama_model_clef::graph::build_head(ggml_tensor * hidden, input_de
|
||||
ggml_tensor * opt_ctx = ggml_mul_mat(ctx0, hidden_t, inp->pool_o); // [n_embd, n_options]
|
||||
|
||||
// mean of the output embeddings of the tokens of each option
|
||||
ggml_tensor * lexical = ggml_get_rows(ctx0, model.output, inp->tokens);
|
||||
ggml_tensor * lexical = ggml_get_rows(ctx0, model.output_lexical, inp->tokens);
|
||||
lexical = ggml_mul_mat(ctx0, ggml_cont(ctx0, ggml_transpose(ctx0, lexical)), inp->pool_o); // [n_embd, n_options]
|
||||
|
||||
// one query per option
|
||||
|
||||
@@ -2999,6 +2999,8 @@ struct llama_model_qwen35 : public llama_model_base {
|
||||
graph_mtp(const llm_graph_params & params);
|
||||
};
|
||||
|
||||
// if false, the derived model does not use the LM head and builds its own output
|
||||
virtual bool has_lm_head() const { return true; }
|
||||
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
|
||||
};
|
||||
|
||||
@@ -3060,6 +3062,7 @@ struct llama_model_clef : public llama_model_qwen35 {
|
||||
ggml_tensor * scorer_b = nullptr;
|
||||
ggml_tensor * scorer_out = nullptr;
|
||||
ggml_tensor * scorer_out_b = nullptr;
|
||||
ggml_tensor * output_lexical = nullptr;
|
||||
|
||||
class input_decision;
|
||||
|
||||
@@ -3090,6 +3093,7 @@ struct llama_model_clef : public llama_model_qwen35 {
|
||||
const llama_model_clef & model;
|
||||
};
|
||||
|
||||
bool has_lm_head() const override { return false; }
|
||||
std::unique_ptr<llm_graph_context> build_arch_graph(const llm_graph_params & params) const override;
|
||||
};
|
||||
|
||||
|
||||
@@ -41,17 +41,20 @@ void llama_model_qwen35::load_arch_tensors(llama_model_loader & ml) {
|
||||
|
||||
// output
|
||||
output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), { n_embd }, 0);
|
||||
output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED);
|
||||
|
||||
if (has_lm_head()) {
|
||||
output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), { n_embd, n_vocab }, TENSOR_NOT_REQUIRED);
|
||||
|
||||
// if output is NULL, init from the input tok embed
|
||||
if (output == NULL) {
|
||||
output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, TENSOR_DUPLICATED);
|
||||
}
|
||||
}
|
||||
|
||||
// optional projection of the embeddings output
|
||||
cls_out = create_tensor(tn(LLM_TENSOR_CLS_OUT, "weight"), { n_embd, hparams.n_embd_out() }, TENSOR_NOT_REQUIRED);
|
||||
cls_out_b = create_tensor(tn(LLM_TENSOR_CLS_OUT, "bias"), { hparams.n_embd_out() }, TENSOR_NOT_REQUIRED);
|
||||
|
||||
// if output is NULL, init from the input tok embed
|
||||
if (output == NULL) {
|
||||
output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), { n_embd, n_vocab }, TENSOR_DUPLICATED);
|
||||
}
|
||||
|
||||
auto load_block_trunk = [&](int il, int flags) {
|
||||
auto & layer = layers[il];
|
||||
|
||||
|
||||
+1336
-127
File diff suppressed because it is too large
Load Diff
+30
-25
@@ -145,14 +145,6 @@ static std::vector<unicode_cpt_flags> unicode_cpt_flags_array() {
|
||||
cpt_flags[cpt].is_whitespace = true;
|
||||
}
|
||||
|
||||
for (auto p : unicode_map_lowercase) {
|
||||
cpt_flags[p.second].is_lowercase = true;
|
||||
}
|
||||
|
||||
for (auto p : unicode_map_uppercase) {
|
||||
cpt_flags[p.second].is_uppercase = true;
|
||||
}
|
||||
|
||||
for (auto &range : unicode_ranges_nfd) { // start, last, nfd
|
||||
cpt_flags[range.nfd].is_nfd = true;
|
||||
}
|
||||
@@ -1653,31 +1645,41 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
|
||||
return {};
|
||||
}
|
||||
|
||||
// collapsed categories: LETTER alone means a letter that is not Lu or Ll
|
||||
static constexpr int UCAT_LU = unicode_cpt_flags::LETTER | unicode_cpt_flags::UPPERCASE;
|
||||
static constexpr int UCAT_LL = unicode_cpt_flags::LETTER | unicode_cpt_flags::LOWERCASE;
|
||||
static constexpr int UCAT_LX = unicode_cpt_flags::LETTER;
|
||||
|
||||
// unicode categories
|
||||
static const std::map<std::string, int> k_ucat_enum = {
|
||||
{ "\\p{N}", unicode_cpt_flags::NUMBER },
|
||||
{ "\\p{L}", unicode_cpt_flags::LETTER },
|
||||
{ "\\p{P}", unicode_cpt_flags::PUNCTUATION },
|
||||
{ "\\p{M}", unicode_cpt_flags::ACCENT_MARK },
|
||||
{ "\\p{S}", unicode_cpt_flags::SYMBOL },
|
||||
{ "\\p{Lu}", unicode_cpt_flags::LETTER }, // Uppercase letter
|
||||
{ "\\p{Ll}", unicode_cpt_flags::LETTER }, // Lowercase letter
|
||||
{ "\\p{Lt}", unicode_cpt_flags::LETTER }, // Titlecase letter
|
||||
{ "\\p{Lm}", unicode_cpt_flags::LETTER }, // Modifier letter
|
||||
{ "\\p{Lo}", unicode_cpt_flags::LETTER }, // Other letter
|
||||
// Lt, Lm and Lo share one collapsed category, so \p{Lt} also matches Lm and Lo letters
|
||||
static const std::map<std::string, std::vector<int>> k_ucat_enum = {
|
||||
{ "\\p{N}", { unicode_cpt_flags::NUMBER } },
|
||||
{ "\\p{L}", { UCAT_LU, UCAT_LL, UCAT_LX } },
|
||||
{ "\\p{P}", { unicode_cpt_flags::PUNCTUATION } },
|
||||
{ "\\p{M}", { unicode_cpt_flags::ACCENT_MARK } },
|
||||
{ "\\p{S}", { unicode_cpt_flags::SYMBOL } },
|
||||
{ "\\p{Lu}", { UCAT_LU } }, // Uppercase letter
|
||||
{ "\\p{Ll}", { UCAT_LL } }, // Lowercase letter
|
||||
{ "\\p{Lt}", { UCAT_LX } }, // Titlecase letter
|
||||
{ "\\p{Lm}", { UCAT_LX } }, // Modifier letter
|
||||
{ "\\p{Lo}", { UCAT_LX } }, // Other letter
|
||||
};
|
||||
|
||||
static const std::map<int, int> k_ucat_cpt = {
|
||||
{ unicode_cpt_flags::NUMBER, 0xD1 },
|
||||
{ unicode_cpt_flags::LETTER, 0xD2 },
|
||||
{ UCAT_LX, 0xD2 },
|
||||
{ unicode_cpt_flags::PUNCTUATION, 0xD3 },
|
||||
{ unicode_cpt_flags::ACCENT_MARK, 0xD4 },
|
||||
{ unicode_cpt_flags::SYMBOL, 0xD5 },
|
||||
{ UCAT_LU, 0xD6 },
|
||||
{ UCAT_LL, 0xD7 },
|
||||
};
|
||||
|
||||
static const std::map<int, std::string> k_ucat_map = {
|
||||
{ unicode_cpt_flags::NUMBER, "\x30-\x39" }, // 0-9
|
||||
{ unicode_cpt_flags::LETTER, "\x41-\x5A\x61-\x7A" }, // A-Za-z
|
||||
{ UCAT_LX, "" }, // no sub-128 codepoints
|
||||
{ UCAT_LU, "\x41-\x5A" }, // A-Z
|
||||
{ UCAT_LL, "\x61-\x7A" }, // a-z
|
||||
{ unicode_cpt_flags::PUNCTUATION, "\x21-\x23\x25-\x2A\x2C-\x2F\x3A-\x3B\x3F-\x40\\\x5B-\\\x5D\x5F\\\x7B\\\x7D" }, // !-#%-*,-/:-;?-@\[-\]_\{\}
|
||||
{ unicode_cpt_flags::ACCENT_MARK, "" }, // no sub-128 codepoints
|
||||
{ unicode_cpt_flags::SYMBOL, "\\\x24\\\x2B\x3C-\x3E\x5E\x60\\\x7C\\\x7E" }, // $+<=>^`|~
|
||||
@@ -1712,13 +1714,14 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
|
||||
}
|
||||
|
||||
const auto flags = unicode_cpt_flags_from_cpt(cpts[i]);
|
||||
const int ucat = flags.as_uint() & (unicode_cpt_flags::MASK_CATEGORIES | unicode_cpt_flags::UPPERCASE | unicode_cpt_flags::LOWERCASE);
|
||||
|
||||
if (flags.is_whitespace) {
|
||||
//NOTE: C++ std::regex \s does not mach 0x85, Rust and Python regex does.
|
||||
//text_collapsed[i] = (char) 0x85; // <Next Line> as whitespace fallback
|
||||
text_collapsed[i] = (char) 0x0B; // <vertical tab> as whitespace fallback
|
||||
} else if (k_ucat_cpt.find(flags.category_flag()) != k_ucat_cpt.end()) {
|
||||
text_collapsed[i] = k_ucat_cpt.at(flags.category_flag());
|
||||
} else if (k_ucat_cpt.find(ucat) != k_ucat_cpt.end()) {
|
||||
text_collapsed[i] = k_ucat_cpt.at(ucat);
|
||||
} else {
|
||||
text_collapsed[i] = (char) 0xD0; // fallback
|
||||
}
|
||||
@@ -1787,8 +1790,10 @@ std::vector<std::string> unicode_regex_split(const std::string & text, const std
|
||||
if (!inside) {
|
||||
regex_expr_collapsed += '[';
|
||||
}
|
||||
regex_expr_collapsed += k_ucat_cpt.at(k_ucat_enum.at(pat));
|
||||
regex_expr_collapsed += k_ucat_map.at(k_ucat_enum.at(pat));
|
||||
for (const int ucat : k_ucat_enum.at(pat)) {
|
||||
regex_expr_collapsed += k_ucat_cpt.at(ucat);
|
||||
regex_expr_collapsed += k_ucat_map.at(ucat);
|
||||
}
|
||||
if (!inside) {
|
||||
regex_expr_collapsed += ']';
|
||||
}
|
||||
|
||||
+4
-4
@@ -17,8 +17,8 @@ struct unicode_cpt_flags {
|
||||
CONTROL = 0x0080, // regex: \p{C}
|
||||
MASK_CATEGORIES = 0x00FF,
|
||||
WHITESPACE = 0x0100,
|
||||
LOWERCASE = 0x0200,
|
||||
UPPERCASE = 0x0400,
|
||||
LOWERCASE = 0x0200, // regex: \p{Ll}
|
||||
UPPERCASE = 0x0400, // regex: \p{Lu}
|
||||
NFD = 0x0800,
|
||||
};
|
||||
|
||||
@@ -33,8 +33,8 @@ struct unicode_cpt_flags {
|
||||
uint16_t is_control : 1; // regex: \p{C}
|
||||
// helper flags
|
||||
uint16_t is_whitespace : 1; // regex: \s
|
||||
uint16_t is_lowercase : 1;
|
||||
uint16_t is_uppercase : 1;
|
||||
uint16_t is_lowercase : 1; // regex: \p{Ll}
|
||||
uint16_t is_uppercase : 1; // regex: \p{Lu}
|
||||
uint16_t is_nfd : 1;
|
||||
|
||||
// decode from uint16
|
||||
|
||||
@@ -6850,7 +6850,7 @@ struct test_mul_mat_id : public test_case {
|
||||
const int64_t m_v; // rows of as in memory, the experts of as are strided for m_v > m, no view for m_v == 0
|
||||
const bool ids_offset;
|
||||
const bool skip; // set some ids to a negative value
|
||||
const int scale_gran; // weight scale granularity: 0=default, 1=per-expert scalar, 2=per-channel-per-expert
|
||||
const int scale_gran; // weight scale granularity: 0=default, 1=per-expert scalar, 2=per-channel-per-expert, 3=per-tensor +inf
|
||||
const bool scale_view;
|
||||
|
||||
std::string vars() override {
|
||||
@@ -6908,12 +6908,14 @@ struct test_mul_mat_id : public test_case {
|
||||
ggml_set_name(b, "b");
|
||||
|
||||
ggml_tensor * s = nullptr;
|
||||
if (scale_gran == 2) {
|
||||
if (scale_gran == 3) {
|
||||
s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
|
||||
} else if (scale_gran == 2) {
|
||||
s = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, m, n_mats);
|
||||
} else if (scale_gran == 1 || ggml_needs_scale(type_a)) {
|
||||
s = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_mats);
|
||||
}
|
||||
if (s && skip && !scale_view) {
|
||||
if (s && skip && !scale_view && scale_gran != 3) {
|
||||
const int64_t n_channels = scale_gran == 2 ? m : 1;
|
||||
ggml_tensor * storage = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_channels, n_mats + 1);
|
||||
ggml_set_name(storage, "scale_storage");
|
||||
@@ -6942,6 +6944,14 @@ struct test_mul_mat_id : public test_case {
|
||||
std::vector<float> prefix(storage->ne[0], NAN);
|
||||
ggml_backend_tensor_set(storage, prefix.data(), 0, prefix.size()*sizeof(float));
|
||||
}
|
||||
if (scale_gran == 3) {
|
||||
// skipped slots stay zero with an infinite scale, positive inputs keep the other slots at +inf
|
||||
for (const char * name : {"as", "b"}) {
|
||||
init_tensor_uniform(ggml_get_tensor(ctx, name), 0.1f, 1.0f);
|
||||
}
|
||||
const float inf = INFINITY;
|
||||
ggml_backend_tensor_set(ggml_get_tensor(ctx, "s"), &inf, 0, sizeof(float));
|
||||
}
|
||||
}
|
||||
|
||||
void reinit_perf_iter(ggml_context * ctx) override {
|
||||
@@ -13601,6 +13611,13 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
}
|
||||
}
|
||||
|
||||
for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F8_E4M3}) {
|
||||
for (int64_t n : {1, 9}) {
|
||||
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 4, 2, false, 32, n, 32, 0, false, true, 3));
|
||||
}
|
||||
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 4, 2, false, 32, 9, 32, 0, true, true, 3));
|
||||
}
|
||||
|
||||
for (int scale_gran : {1, 2}) {
|
||||
for (ggml_type type : {GGML_TYPE_F32, GGML_TYPE_F8_E4M3}) {
|
||||
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 1, 1, false, 32, 4, 32, 0, false, false, scale_gran));
|
||||
@@ -13609,6 +13626,8 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
}
|
||||
test_cases.emplace_back(new test_mul_mat(type, GGML_TYPE_F32, 32, 4, 32, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, false, scale_gran, true));
|
||||
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 4, 2, false, 32, 4, 32, 0, false, false, scale_gran, true));
|
||||
// misaligned ids view
|
||||
test_cases.emplace_back(new test_mul_mat_id(type, GGML_TYPE_F32, 4, 2, false, 32, 9, 32, 0, true, true, scale_gran));
|
||||
}
|
||||
for (int64_t n : {1, 8}) {
|
||||
test_cases.emplace_back(new test_mul_mat(GGML_TYPE_Q4_K, GGML_TYPE_F32, 32, n, 256, {1, 1}, {1, 1}, {0, 1, 2, 3}, 0, 1, false, 0, 0, 0, false, scale_gran));
|
||||
@@ -14330,6 +14349,18 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
exponent <<= 1;
|
||||
}
|
||||
#endif
|
||||
for (int64_t ne0 : {1, 3, 4, 8}) {
|
||||
for (bool mask : {false, true}) {
|
||||
for (bool sinks : {false, true}) {
|
||||
for (float max_bias : {0.0f, 8.0f}) {
|
||||
if (!mask && max_bias > 0.0f) continue;
|
||||
test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {ne0, 37, 2, 3}, mask, sinks, GGML_TYPE_F16, {1, 1}, 0.1f, max_bias));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {4, 37, 2, 3}, true, true, GGML_TYPE_F16, {2, 3}, 0.1f, 8.0f));
|
||||
test_cases.emplace_back(new test_soft_max(GGML_TYPE_F32, {4, 300000, 1, 1}, false, false, GGML_TYPE_F32, {1, 1}, 1.0f, 0.0f));
|
||||
for (bool mask : {false, true}) {
|
||||
for (bool sinks : {false, true}) {
|
||||
for (float max_bias : {0.0f, 8.0f}) {
|
||||
@@ -14722,6 +14753,10 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_sum_rows(GGML_TYPE_F32, { 33, 1, 1, 1 }));
|
||||
test_cases.emplace_back(new test_sum_rows(GGML_TYPE_F32, { 33, 1024, 1, 1 }));
|
||||
test_cases.emplace_back(new test_sum_rows(GGML_TYPE_F32, { 33, 256, 1, 1 }));
|
||||
test_cases.emplace_back(new test_sum_rows(GGML_TYPE_F32, { 1, 37, 2, 3 }));
|
||||
test_cases.emplace_back(new test_sum_rows(GGML_TYPE_F32, { 4, 37, 2, 3 }));
|
||||
test_cases.emplace_back(new test_sum_rows(GGML_TYPE_F32, { 8, 37, 2, 3 }));
|
||||
test_cases.emplace_back(new test_sum_rows(GGML_TYPE_F32, { 4, 300000, 1, 1 }));
|
||||
test_cases.emplace_back(new test_sum_rows(GGML_TYPE_F32, { 17, 65537, 1, 1 }));
|
||||
test_cases.emplace_back(new test_group_norm(GGML_TYPE_F32, {64, 64, 320, 1}));
|
||||
test_cases.emplace_back(new test_group_norm(GGML_TYPE_F32, {9, 9, 1280, 1}));
|
||||
@@ -15039,6 +15074,13 @@ static std::vector<std::unique_ptr<test_case>> make_test_cases_eval() {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 8, 2, 4096, 1280, nb, n_slices));
|
||||
}
|
||||
}
|
||||
// decode: one token per slice, non-f16 K/V take the vec kernel
|
||||
for (ggml_type type_KV : {GGML_TYPE_F16, GGML_TYPE_BF16, GGML_TYPE_Q8_0, GGML_TYPE_Q4_0}) {
|
||||
for (int64_t n_slices : {1, 3, 8}) {
|
||||
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(256, 2, 12, 8192, 2304, 1, n_slices, type_KV));
|
||||
test_cases.emplace_back(new test_flash_attn_ext_kv_rows(128, 4, 4, 5000, 512, 2, n_slices, type_KV));
|
||||
}
|
||||
}
|
||||
|
||||
// flash attention with an indexed bias (Inkling 2 relative-position bias)
|
||||
for (bool kv_rows : {false, true}) {
|
||||
|
||||
@@ -706,6 +706,18 @@ static void test_expressions(testing & t) {
|
||||
"3,-4,-4,3.0,3"
|
||||
);
|
||||
|
||||
test_template(t, "modulo",
|
||||
"{{ 7 % 3 }},{{ a % 3 }},{{ 7 % b }},{{ a % b }},{{ (a // 2) * 2 + a % 2 }},{{ 9007199254740993 % 2 }}",
|
||||
{{"a", -7}, {"b", -3}},
|
||||
"1,2,-2,-1,-7,1"
|
||||
);
|
||||
|
||||
test_template(t, "float modulo",
|
||||
"{{ 7.5 % 2 }},{{ c % 2 }},{{ 7.5 % b }},{{ c % 3 }},{{ 6.0 % b }}",
|
||||
{{"b", -2}, {"c", -7.5}},
|
||||
"1.5,0.5,-0.5,1.5,-0.0"
|
||||
);
|
||||
|
||||
test_template(t, "string comparison",
|
||||
"{{ 'b' > 'a' }},{{ 'VBD' > 'VB' }},{{ 'a' <= 'a' }},{{ 'Z' < 'a' }},{{ 'ab' >= 'b' }}",
|
||||
json::object(),
|
||||
|
||||
@@ -82,6 +82,24 @@ int main() {
|
||||
success = false;
|
||||
}
|
||||
|
||||
// \p{Lu} and \p{Ll} must split on case, expected output from HF tokenizers
|
||||
const std::vector<std::string> regex_exprs_case = {
|
||||
"[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]*[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]+(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|[^\\r\\n\\p{L}\\p{N}]?[\\p{Lu}\\p{Lt}\\p{Lm}\\p{Lo}\\p{M}]+[\\p{Ll}\\p{Lm}\\p{Lo}\\p{M}]*(?:'[sS]|'[tT]|'[rR][eE]|'[vV][eE]|'[mM]|'[lL][lL]|'[dD])?|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n/]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
|
||||
};
|
||||
const std::vector<std::string> expected_case = {
|
||||
"get", "User", "By", "ID", " HTTPServer", " \xc3\x80" "bc", "D\xc3\x89" "f", " stra\xc3\x9f" "e", "\xc3\x96" "l",
|
||||
};
|
||||
const auto actual_case = unicode_regex_split("getUserByID HTTPServer \xc3\x80" "bcD\xc3\x89" "f stra\xc3\x9f" "e\xc3\x96" "l", regex_exprs_case, false);
|
||||
|
||||
if (actual_case != expected_case) {
|
||||
fprintf(stderr, "unexpected case split:");
|
||||
for (const auto & piece : actual_case) {
|
||||
fprintf(stderr, " [%s]", piece.c_str());
|
||||
}
|
||||
fprintf(stderr, "\n");
|
||||
success = false;
|
||||
}
|
||||
|
||||
const std::vector<std::string> regex_exprs_bytes = { "\\p{L}+", "\\p{N}+", "\\s+" };
|
||||
const std::string byte_encode_text = "\xc4\x80\xc4\xb1\xe0\xa4\x95\xf0\x9f\x98\x80";
|
||||
const auto actual_byte_encode = unicode_regex_split(byte_encode_text, regex_exprs_bytes, true);
|
||||
|
||||
+473
-92
@@ -30,6 +30,11 @@
|
||||
# include <io.h>
|
||||
#else
|
||||
# include <cerrno>
|
||||
# include <csignal>
|
||||
# include <fcntl.h>
|
||||
# include <poll.h>
|
||||
# include <spawn.h>
|
||||
# include <sys/wait.h>
|
||||
# include <unistd.h>
|
||||
#endif
|
||||
|
||||
@@ -176,15 +181,51 @@ public:
|
||||
virtual list_result list_entries(const std::string & base, int max_depth, list_kind kind) const = 0;
|
||||
// on_chunk, if set, is called with each chunk of output as it is read (before truncation cuts in);
|
||||
// returning false terminates the process early (e.g. the client disconnected)
|
||||
// should_stop, if set, is checked while the process runs, even when it writes nothing; true terminates it
|
||||
virtual exec_result run(
|
||||
const std::vector<std::string> & args,
|
||||
size_t max_output,
|
||||
int timeout_secs,
|
||||
const std::function<bool(const std::string &)> & on_chunk = nullptr) const = 0;
|
||||
const std::function<bool(const std::string &)> & on_chunk = nullptr,
|
||||
const std::function<bool()> & should_stop = nullptr) const = 0;
|
||||
};
|
||||
|
||||
#if defined(LLAMA_SUBPROCESS)
|
||||
// time the output gets to close once the job is killed, and between two checks of exit, deadline and stop
|
||||
static constexpr int SERVER_TOOL_SUBPROCESS_DRAIN_MS = 2000;
|
||||
static constexpr int SERVER_TOOL_SUBPROCESS_POLL_MS = 100;
|
||||
#endif
|
||||
|
||||
// output of a job, capped at max_output, handed to on_chunk as it arrives until on_chunk returns false
|
||||
struct subprocess_output {
|
||||
size_t max_output;
|
||||
const std::function<bool(const std::string &)> & on_chunk;
|
||||
std::string text;
|
||||
bool truncated = false;
|
||||
bool stopped = false;
|
||||
|
||||
subprocess_output(size_t max_output, const std::function<bool(const std::string &)> & on_chunk)
|
||||
: max_output(max_output), on_chunk(on_chunk) {}
|
||||
|
||||
void add(const char * buf, size_t len) {
|
||||
if (truncated) {
|
||||
return;
|
||||
}
|
||||
if (text.size() + len > max_output) {
|
||||
len = max_output - text.size();
|
||||
truncated = true;
|
||||
}
|
||||
text.append(buf, len);
|
||||
if (on_chunk && !stopped && len > 0) {
|
||||
stopped = !on_chunk(console_output_to_utf8(std::string(buf, len)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// shared subprocess execution helper, used by both the local and the isolate-backed tools_io implementations.
|
||||
// combine_stderr=false when the raw stdout bytes must not be tainted by stderr, e.g. reading file contents.
|
||||
// the command runs as a job, a process group on POSIX and a Job Object on Windows, killed with everything it started
|
||||
// once the command exits, times out, or the caller stops it, so a call leaves nothing running
|
||||
static tools_io::exec_result run_subprocess(
|
||||
const std::vector<std::string> & args,
|
||||
size_t max_output,
|
||||
@@ -192,110 +233,445 @@ static tools_io::exec_result run_subprocess(
|
||||
const std::function<bool(const std::string &)> & on_chunk,
|
||||
bool combine_stderr,
|
||||
const std::string & cwd = "",
|
||||
const std::string * stdin_data = nullptr) {
|
||||
const std::string * stdin_data = nullptr,
|
||||
const std::function<bool()> & should_stop = nullptr);
|
||||
|
||||
#if !defined(LLAMA_SUBPROCESS)
|
||||
|
||||
static tools_io::exec_result run_subprocess(
|
||||
const std::vector<std::string> &, size_t, int, const std::function<bool(const std::string &)> &,
|
||||
bool, const std::string &, const std::string *, const std::function<bool()> &) {
|
||||
tools_io::exec_result res;
|
||||
res.output = "failed to spawn process";
|
||||
return res;
|
||||
}
|
||||
|
||||
common_subproc proc;
|
||||
#elif defined(_WIN32)
|
||||
|
||||
int options = subprocess_option_no_window
|
||||
| subprocess_option_inherit_environment
|
||||
| subprocess_option_search_user_path;
|
||||
if (combine_stderr) {
|
||||
options |= subprocess_option_combined_stdout_stderr;
|
||||
struct subprocess_handle {
|
||||
HANDLE h = nullptr;
|
||||
|
||||
subprocess_handle() = default;
|
||||
explicit subprocess_handle(HANDLE h) : h(h == INVALID_HANDLE_VALUE ? nullptr : h) {}
|
||||
subprocess_handle(const subprocess_handle &) = delete;
|
||||
subprocess_handle & operator=(const subprocess_handle &) = delete;
|
||||
~subprocess_handle() { reset(); }
|
||||
|
||||
void reset() {
|
||||
if (h) {
|
||||
CloseHandle(h);
|
||||
h = nullptr;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static std::wstring subprocess_wide(const std::string & s) {
|
||||
const int len = MultiByteToWideChar(CP_UTF8, 0, s.data(), (int) s.size(), nullptr, 0);
|
||||
std::wstring w(len, L'\0');
|
||||
MultiByteToWideChar(CP_UTF8, 0, s.data(), (int) s.size(), w.data(), len);
|
||||
return w;
|
||||
}
|
||||
|
||||
// the command line the MSVC runtime of the child parses back into args
|
||||
// cmd.exe parses its own command line without the C runtime rules, so its args go as written
|
||||
static std::wstring subprocess_command_line(const std::vector<std::string> & args) {
|
||||
const bool verbatim = !args.empty() && _stricmp(args[0].c_str(), "cmd") == 0;
|
||||
std::string line;
|
||||
for (const auto & arg : args) {
|
||||
if (!line.empty()) {
|
||||
line += ' ';
|
||||
}
|
||||
if (verbatim) {
|
||||
line += arg;
|
||||
continue;
|
||||
}
|
||||
const bool quote = arg.empty() || arg.find_first_of(" \t\v") != std::string::npos;
|
||||
if (quote) {
|
||||
line += '"';
|
||||
}
|
||||
size_t backslashes = 0;
|
||||
for (const char c : arg) {
|
||||
if (c == '\\') {
|
||||
backslashes++;
|
||||
continue;
|
||||
}
|
||||
line.append(c == '"' ? backslashes * 2 + 1 : backslashes, '\\');
|
||||
line += c;
|
||||
backslashes = 0;
|
||||
}
|
||||
line.append(quote ? backslashes * 2 : backslashes, '\\');
|
||||
if (quote) {
|
||||
line += '"';
|
||||
}
|
||||
}
|
||||
return subprocess_wide(line);
|
||||
}
|
||||
|
||||
// reads the output of the job until every writer closed its end
|
||||
struct subprocess_reader {
|
||||
HANDLE pipe;
|
||||
std::mutex mutex;
|
||||
std::string pending;
|
||||
|
||||
std::string take() {
|
||||
std::string chunk;
|
||||
std::lock_guard<std::mutex> lock(mutex);
|
||||
chunk.swap(pending);
|
||||
return chunk;
|
||||
}
|
||||
|
||||
if (!proc.create(args, options, {}, cwd.empty() ? nullptr : cwd.c_str())) {
|
||||
res.output = "failed to spawn process";
|
||||
static DWORD WINAPI run(void * p) {
|
||||
auto * r = (subprocess_reader *) p;
|
||||
char buf[4096];
|
||||
DWORD got = 0;
|
||||
while (ReadFile(r->pipe, buf, sizeof(buf), &got, nullptr) && got > 0) {
|
||||
std::lock_guard<std::mutex> lock(r->mutex);
|
||||
r->pending.append(buf, got);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
// writes the stdin data of the job, then closes it
|
||||
struct subprocess_writer {
|
||||
HANDLE pipe;
|
||||
const std::string * data;
|
||||
|
||||
static DWORD WINAPI run(void * p) {
|
||||
auto * w = (subprocess_writer *) p;
|
||||
size_t done = 0;
|
||||
DWORD put = 0;
|
||||
while (done < w->data->size() &&
|
||||
WriteFile(w->pipe, w->data->data() + done, (DWORD) std::min<size_t>(w->data->size() - done, 65536), &put, nullptr)) {
|
||||
done += put;
|
||||
}
|
||||
CloseHandle(w->pipe);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
static tools_io::exec_result run_subprocess(
|
||||
const std::vector<std::string> & args,
|
||||
size_t max_output,
|
||||
int timeout_secs,
|
||||
const std::function<bool(const std::string &)> & on_chunk,
|
||||
bool combine_stderr,
|
||||
const std::string & cwd,
|
||||
const std::string * stdin_data,
|
||||
const std::function<bool()> & should_stop) {
|
||||
tools_io::exec_result res;
|
||||
res.output = "failed to spawn process";
|
||||
|
||||
// only the child ends are inheritable, and only by this child (handle list below)
|
||||
SECURITY_ATTRIBUTES sa = { sizeof(sa), nullptr, TRUE };
|
||||
HANDLE in_r = nullptr, in_w = nullptr, out_r = nullptr, out_w = nullptr;
|
||||
if (!CreatePipe(&in_r, &in_w, &sa, 0)) {
|
||||
return res;
|
||||
}
|
||||
subprocess_handle in_child(in_r), in_parent(in_w);
|
||||
if (!CreatePipe(&out_r, &out_w, &sa, 0)) {
|
||||
return res;
|
||||
}
|
||||
subprocess_handle out_parent(out_r), out_child(out_w);
|
||||
subprocess_handle err_child(combine_stderr ? nullptr :
|
||||
CreateFileW(L"NUL", GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, &sa, OPEN_EXISTING, 0, nullptr));
|
||||
SetHandleInformation(in_parent.h, HANDLE_FLAG_INHERIT, 0);
|
||||
SetHandleInformation(out_parent.h, HANDLE_FLAG_INHERIT, 0);
|
||||
HANDLE err = combine_stderr ? out_child.h : err_child.h;
|
||||
if (!err) {
|
||||
return res;
|
||||
}
|
||||
|
||||
std::atomic<bool> done{false};
|
||||
std::atomic<bool> timed_out{false};
|
||||
|
||||
std::thread timeout_thread([&]() {
|
||||
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_secs);
|
||||
while (!done.load()) {
|
||||
if (std::chrono::steady_clock::now() >= deadline) {
|
||||
timed_out.store(true);
|
||||
proc.terminate();
|
||||
return;
|
||||
}
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(100));
|
||||
}
|
||||
});
|
||||
|
||||
// write stdin before reading stdout, the child drains stdin as it goes
|
||||
// always close stdin, a transport client waits forever if its stdin pipe stays open
|
||||
if (FILE * in = proc.stdin_file()) {
|
||||
if (stdin_data != nullptr && !stdin_data->empty()) {
|
||||
#if defined(_WIN32)
|
||||
// pipe fds default to CRT text mode: binary keeps the bytes untranslated
|
||||
_setmode(_fileno(in), _O_BINARY);
|
||||
#endif
|
||||
// a short write is not an error by itself, the exit code below decides
|
||||
fwrite(stdin_data->data(), 1, stdin_data->size(), in);
|
||||
}
|
||||
fflush(in);
|
||||
subprocess_handle job(CreateJobObjectW(nullptr, nullptr));
|
||||
if (!job.h) {
|
||||
return res;
|
||||
}
|
||||
proc.close_stdin();
|
||||
JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = {};
|
||||
limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
SetInformationJobObject(job.h, JobObjectExtendedLimitInformation, &limits, sizeof(limits));
|
||||
|
||||
FILE * f = proc.stdout_file();
|
||||
std::string output;
|
||||
bool truncated = false;
|
||||
if (f) {
|
||||
#if defined(_WIN32)
|
||||
// pipe fds default to CRT text mode: binary keeps the bytes untranslated
|
||||
_setmode(_fileno(f), _O_BINARY);
|
||||
#endif
|
||||
// read raw bytes, not lines: the output can hold NUL and must arrive as soon as it is ready
|
||||
// keep draining past the size cap, else the child blocks on a full pipe
|
||||
char buf[4096];
|
||||
for (;;) {
|
||||
#if defined(_WIN32)
|
||||
const int n = _read(_fileno(f), buf, (unsigned) sizeof(buf));
|
||||
#else
|
||||
ssize_t n = read(fileno(f), buf, sizeof(buf));
|
||||
while (n < 0 && errno == EINTR) {
|
||||
n = read(fileno(f), buf, sizeof(buf));
|
||||
}
|
||||
#endif
|
||||
if (n <= 0) {
|
||||
break;
|
||||
}
|
||||
if (truncated) {
|
||||
continue;
|
||||
}
|
||||
const size_t len = (size_t) n;
|
||||
if (output.size() + len <= max_output) {
|
||||
output.append(buf, len);
|
||||
if (on_chunk && !on_chunk(console_output_to_utf8(std::string(buf, len)))) {
|
||||
proc.terminate();
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
size_t remaining = max_output - output.size();
|
||||
output.append(buf, remaining);
|
||||
if (on_chunk && remaining > 0) on_chunk(console_output_to_utf8(std::string(buf, remaining)));
|
||||
truncated = true;
|
||||
}
|
||||
HANDLE inherited[3] = { in_child.h, out_child.h, err };
|
||||
const DWORD n_inherited = combine_stderr ? 2 : 3;
|
||||
SIZE_T attrs_size = 0;
|
||||
InitializeProcThreadAttributeList(nullptr, 1, 0, &attrs_size);
|
||||
std::vector<char> attrs_buf(attrs_size);
|
||||
auto attrs = (LPPROC_THREAD_ATTRIBUTE_LIST) attrs_buf.data();
|
||||
if (!InitializeProcThreadAttributeList(attrs, 1, 0, &attrs_size)) {
|
||||
return res;
|
||||
}
|
||||
UpdateProcThreadAttribute(attrs, 0, PROC_THREAD_ATTRIBUTE_HANDLE_LIST, inherited, n_inherited * sizeof(HANDLE), nullptr, nullptr);
|
||||
|
||||
STARTUPINFOEXW si = {};
|
||||
si.StartupInfo.cb = sizeof(si);
|
||||
si.StartupInfo.dwFlags = STARTF_USESTDHANDLES;
|
||||
si.StartupInfo.hStdInput = in_child.h;
|
||||
si.StartupInfo.hStdOutput = out_child.h;
|
||||
si.StartupInfo.hStdError = err;
|
||||
si.lpAttributeList = attrs;
|
||||
|
||||
// suspended until it belongs to the job, so nothing it starts escapes the job
|
||||
std::wstring command = subprocess_command_line(args);
|
||||
const std::wstring directory = subprocess_wide(cwd);
|
||||
PROCESS_INFORMATION pi = {};
|
||||
const BOOL spawned = CreateProcessW(nullptr, command.data(), nullptr, nullptr, TRUE,
|
||||
CREATE_SUSPENDED | CREATE_NO_WINDOW | EXTENDED_STARTUPINFO_PRESENT, nullptr,
|
||||
cwd.empty() ? nullptr : directory.c_str(), &si.StartupInfo, &pi);
|
||||
DeleteProcThreadAttributeList(attrs);
|
||||
in_child.reset();
|
||||
out_child.reset();
|
||||
err_child.reset();
|
||||
if (!spawned) {
|
||||
return res;
|
||||
}
|
||||
subprocess_handle process(pi.hProcess), thread(pi.hThread);
|
||||
if (!AssignProcessToJobObject(job.h, process.h)) {
|
||||
TerminateProcess(process.h, 1);
|
||||
return res;
|
||||
}
|
||||
ResumeThread(thread.h);
|
||||
|
||||
subprocess_reader reader;
|
||||
reader.pipe = out_parent.h;
|
||||
subprocess_handle reading(CreateThread(nullptr, 0, subprocess_reader::run, &reader, 0, nullptr));
|
||||
|
||||
subprocess_writer writer = { in_parent.h, stdin_data };
|
||||
subprocess_handle writing;
|
||||
if (stdin_data != nullptr && !stdin_data->empty()) {
|
||||
// the writer closes the pipe once done
|
||||
in_parent.h = nullptr;
|
||||
writing.h = CreateThread(nullptr, 0, subprocess_writer::run, &writer, 0, nullptr);
|
||||
if (!writing.h) {
|
||||
CloseHandle(writer.pipe);
|
||||
}
|
||||
} else {
|
||||
in_parent.reset();
|
||||
}
|
||||
|
||||
subprocess_output out(max_output, on_chunk);
|
||||
const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(timeout_secs);
|
||||
while (WaitForSingleObject(process.h, SERVER_TOOL_SUBPROCESS_POLL_MS) == WAIT_TIMEOUT) {
|
||||
const std::string chunk = reader.take();
|
||||
out.add(chunk.data(), chunk.size());
|
||||
if (std::chrono::steady_clock::now() >= deadline) {
|
||||
res.timed_out = true;
|
||||
break;
|
||||
}
|
||||
if (out.stopped || (should_stop && should_stop())) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
done.store(true);
|
||||
if (timeout_thread.joinable()) {
|
||||
timeout_thread.join();
|
||||
TerminateJobObject(job.h, 1);
|
||||
WaitForSingleObject(process.h, INFINITE);
|
||||
if (WaitForSingleObject(reading.h, SERVER_TOOL_SUBPROCESS_DRAIN_MS) == WAIT_TIMEOUT) {
|
||||
CancelSynchronousIo(reading.h);
|
||||
WaitForSingleObject(reading.h, INFINITE);
|
||||
}
|
||||
const std::string rest = reader.take();
|
||||
out.add(rest.data(), rest.size());
|
||||
if (writing.h) {
|
||||
CancelSynchronousIo(writing.h);
|
||||
WaitForSingleObject(writing.h, INFINITE);
|
||||
}
|
||||
|
||||
res.exit_code = proc.join();
|
||||
|
||||
res.output = console_output_to_utf8(output);
|
||||
res.timed_out = timed_out.load();
|
||||
if (truncated) {
|
||||
DWORD code = 1;
|
||||
GetExitCodeProcess(process.h, &code);
|
||||
res.exit_code = (int) code;
|
||||
res.output = console_output_to_utf8(out.text);
|
||||
if (out.truncated) {
|
||||
res.output += "\n[output truncated]";
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
#else
|
||||
|
||||
extern char ** environ;
|
||||
|
||||
// a pipe no concurrent spawn inherits
|
||||
static bool subprocess_pipe(int fd[2]) {
|
||||
#if defined(__APPLE__)
|
||||
if (pipe(fd) != 0) {
|
||||
return false;
|
||||
}
|
||||
fcntl(fd[0], F_SETFD, FD_CLOEXEC);
|
||||
fcntl(fd[1], F_SETFD, FD_CLOEXEC);
|
||||
return true;
|
||||
#else
|
||||
return pipe2(fd, O_CLOEXEC) == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
// the spelling of the chdir file action follows the detection of the vendored subprocess.h
|
||||
static int subprocess_addchdir(posix_spawn_file_actions_t * actions, const char * cwd) {
|
||||
#if SUBPROCESS_ADDCHDIR_IS_POSIX
|
||||
return posix_spawn_file_actions_addchdir(actions, cwd);
|
||||
#elif SUBPROCESS_HAVE_CWD && !SUBPROCESS_SPAWN_VIA_FORK
|
||||
#if defined(__APPLE__) && defined(__clang__)
|
||||
#pragma clang diagnostic push
|
||||
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
|
||||
#endif
|
||||
return posix_spawn_file_actions_addchdir_np(actions, cwd);
|
||||
#if defined(__APPLE__) && defined(__clang__)
|
||||
#pragma clang diagnostic pop
|
||||
#endif
|
||||
#else
|
||||
(void) actions;
|
||||
(void) cwd;
|
||||
return ENOSYS;
|
||||
#endif
|
||||
}
|
||||
|
||||
static tools_io::exec_result run_subprocess(
|
||||
const std::vector<std::string> & args,
|
||||
size_t max_output,
|
||||
int timeout_secs,
|
||||
const std::function<bool(const std::string &)> & on_chunk,
|
||||
bool combine_stderr,
|
||||
const std::string & cwd,
|
||||
const std::string * stdin_data,
|
||||
const std::function<bool()> & should_stop) {
|
||||
tools_io::exec_result res;
|
||||
res.output = "failed to spawn process";
|
||||
|
||||
int in[2], out_pipe[2];
|
||||
if (!subprocess_pipe(in)) {
|
||||
return res;
|
||||
}
|
||||
if (!subprocess_pipe(out_pipe)) {
|
||||
close(in[0]);
|
||||
close(in[1]);
|
||||
return res;
|
||||
}
|
||||
|
||||
posix_spawn_file_actions_t actions;
|
||||
posix_spawn_file_actions_init(&actions);
|
||||
posix_spawn_file_actions_adddup2(&actions, in[0], 0);
|
||||
posix_spawn_file_actions_adddup2(&actions, out_pipe[1], 1);
|
||||
if (combine_stderr) {
|
||||
posix_spawn_file_actions_adddup2(&actions, out_pipe[1], 2);
|
||||
} else {
|
||||
posix_spawn_file_actions_addopen(&actions, 2, "/dev/null", O_WRONLY, 0);
|
||||
}
|
||||
int err = cwd.empty() ? 0 : subprocess_addchdir(&actions, cwd.c_str());
|
||||
|
||||
// a group of its own, with the signals the server ignores back to their default, so a pipeline dies of SIGPIPE as usual
|
||||
posix_spawnattr_t attr;
|
||||
posix_spawnattr_init(&attr);
|
||||
sigset_t none, defaults;
|
||||
sigemptyset(&none);
|
||||
sigemptyset(&defaults);
|
||||
sigaddset(&defaults, SIGPIPE);
|
||||
posix_spawnattr_setsigmask(&attr, &none);
|
||||
posix_spawnattr_setsigdefault(&attr, &defaults);
|
||||
posix_spawnattr_setpgroup(&attr, 0);
|
||||
posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETPGROUP | POSIX_SPAWN_SETSIGMASK | POSIX_SPAWN_SETSIGDEF);
|
||||
|
||||
std::vector<char *> argv;
|
||||
for (const auto & a : args) {
|
||||
argv.push_back(const_cast<char *>(a.c_str()));
|
||||
}
|
||||
argv.push_back(nullptr);
|
||||
|
||||
pid_t pid = 0;
|
||||
if (err == 0) {
|
||||
err = posix_spawnp(&pid, argv[0], &actions, &attr, argv.data(), environ);
|
||||
}
|
||||
posix_spawn_file_actions_destroy(&actions);
|
||||
posix_spawnattr_destroy(&attr);
|
||||
close(in[0]);
|
||||
close(out_pipe[1]);
|
||||
if (err != 0) {
|
||||
close(in[1]);
|
||||
close(out_pipe[0]);
|
||||
return res;
|
||||
}
|
||||
|
||||
int in_fd = in[1];
|
||||
int out_fd = out_pipe[0];
|
||||
size_t written = 0;
|
||||
if (stdin_data == nullptr || stdin_data->empty()) {
|
||||
close(in_fd);
|
||||
in_fd = -1;
|
||||
} else {
|
||||
fcntl(in_fd, F_SETFL, fcntl(in_fd, F_GETFL) | O_NONBLOCK);
|
||||
}
|
||||
|
||||
subprocess_output out(max_output, on_chunk);
|
||||
using clock = std::chrono::steady_clock;
|
||||
const auto deadline = clock::now() + std::chrono::seconds(timeout_secs);
|
||||
auto drain_end = clock::time_point::max();
|
||||
bool exited = false;
|
||||
bool killed = false;
|
||||
int status = 0;
|
||||
|
||||
for (;;) {
|
||||
pollfd fds[2] = {
|
||||
{ out_fd, POLLIN, 0 },
|
||||
{ in_fd, POLLOUT, 0 },
|
||||
};
|
||||
if (poll(fds, 2, SERVER_TOOL_SUBPROCESS_POLL_MS) < 0 && errno != EINTR) {
|
||||
break;
|
||||
}
|
||||
if (out_fd >= 0 && (fds[0].revents & (POLLIN | POLLHUP | POLLERR))) {
|
||||
char buf[4096];
|
||||
const ssize_t got = read(out_fd, buf, sizeof(buf));
|
||||
if (got > 0) {
|
||||
out.add(buf, (size_t) got);
|
||||
} else if (got == 0 || errno != EINTR) {
|
||||
close(out_fd);
|
||||
out_fd = -1;
|
||||
}
|
||||
}
|
||||
if (in_fd >= 0 && (fds[1].revents & (POLLOUT | POLLHUP | POLLERR))) {
|
||||
const ssize_t put = write(in_fd, stdin_data->data() + written, stdin_data->size() - written);
|
||||
if (put > 0) {
|
||||
written += (size_t) put;
|
||||
}
|
||||
if ((put < 0 && errno != EAGAIN && errno != EINTR) || written == stdin_data->size()) {
|
||||
close(in_fd);
|
||||
in_fd = -1;
|
||||
}
|
||||
}
|
||||
if (!exited && waitpid(pid, &status, WNOHANG) == pid) {
|
||||
exited = true;
|
||||
}
|
||||
const auto now = clock::now();
|
||||
if (!killed && !exited && now >= deadline) {
|
||||
res.timed_out = true;
|
||||
}
|
||||
// the command exits or is ended: what it left running dies with it
|
||||
if (!killed && (exited || res.timed_out || out.stopped || (should_stop && should_stop()))) {
|
||||
killed = true;
|
||||
kill(-pid, SIGKILL);
|
||||
drain_end = now + std::chrono::milliseconds(SERVER_TOOL_SUBPROCESS_DRAIN_MS);
|
||||
}
|
||||
if ((exited && out_fd < 0) || now >= drain_end) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (in_fd >= 0) {
|
||||
close(in_fd);
|
||||
}
|
||||
if (out_fd >= 0) {
|
||||
close(out_fd);
|
||||
}
|
||||
if (!exited) {
|
||||
kill(-pid, SIGKILL);
|
||||
waitpid(pid, &status, 0);
|
||||
}
|
||||
|
||||
res.exit_code = WIFEXITED(status) ? WEXITSTATUS(status) : 128 + WTERMSIG(status);
|
||||
res.output = console_output_to_utf8(out.text);
|
||||
if (out.truncated) {
|
||||
res.output += "\n[output truncated]";
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
class tools_io_basic : public tools_io {
|
||||
public:
|
||||
// cwd, if non-empty, is used to resolve relative paths and as the working directory for run()
|
||||
@@ -406,8 +782,9 @@ public:
|
||||
const std::vector<std::string> & args,
|
||||
size_t max_output,
|
||||
int timeout_secs,
|
||||
const std::function<bool(const std::string &)> & on_chunk = nullptr) const override {
|
||||
return run_subprocess(args, max_output, timeout_secs, on_chunk, /*combine_stderr=*/true, cwd);
|
||||
const std::function<bool(const std::string &)> & on_chunk = nullptr,
|
||||
const std::function<bool()> & should_stop = nullptr) const override {
|
||||
return run_subprocess(args, max_output, timeout_secs, on_chunk, /*combine_stderr=*/true, cwd, nullptr, should_stop);
|
||||
}
|
||||
|
||||
private:
|
||||
@@ -617,14 +994,15 @@ public:
|
||||
const std::vector<std::string> & args,
|
||||
size_t max_output,
|
||||
int timeout_secs,
|
||||
const std::function<bool(const std::string &)> & on_chunk = nullptr) const override {
|
||||
const std::function<bool(const std::string &)> & on_chunk = nullptr,
|
||||
const std::function<bool()> & should_stop = nullptr) const override {
|
||||
std::vector<std::string> inner = {"timeout", std::to_string(timeout_secs) + "s"};
|
||||
inner.insert(inner.end(), args.begin(), args.end());
|
||||
// small buffer over timeout_secs so the in-isolate `timeout` has a chance to exit cleanly
|
||||
// before the host-side supervisory timeout forcibly kills the client
|
||||
return run_subprocess(
|
||||
build_argv(with_cwd(inner), /*needs_stdin=*/true),
|
||||
max_output, timeout_secs + 5, on_chunk, true);
|
||||
max_output, timeout_secs + 5, on_chunk, true, "", nullptr, should_stop);
|
||||
}
|
||||
|
||||
protected:
|
||||
@@ -1286,7 +1664,7 @@ struct server_tool_exec_shell_command : server_tool {
|
||||
};
|
||||
}
|
||||
|
||||
json invoke(json params, server_tool::stream * st, const std::function<bool()> &) const override {
|
||||
json invoke(json params, server_tool::stream * st, const std::function<bool()> & should_stop) const override {
|
||||
std::string command = params.at("command").get<std::string>();
|
||||
int timeout = json_value(params, "timeout", 10);
|
||||
size_t max_output = (size_t) json_value(params, "max_output_size", (int) SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE);
|
||||
@@ -1295,10 +1673,11 @@ struct server_tool_exec_shell_command : server_tool {
|
||||
max_output = std::min(max_output, SERVER_TOOL_EXEC_SHELL_COMMAND_MAX_OUTPUT_SIZE);
|
||||
|
||||
// an isolate is always POSIX regardless of host OS, so it always gets `sh -c`
|
||||
// cmd gets the command as written: /d skips AutoRun, /s removes only the outer quotes
|
||||
#ifdef _WIN32
|
||||
std::vector<std::string> args = !json_value(params, "runtime", std::string()).empty()
|
||||
? std::vector<std::string>{"sh", "-c", command}
|
||||
: std::vector<std::string>{"cmd", "/c", command};
|
||||
: std::vector<std::string>{"cmd", "/d", "/s", "/c", "\"" + command + "\""};
|
||||
#else
|
||||
std::vector<std::string> args = {"sh", "-c", command};
|
||||
#endif
|
||||
@@ -1309,6 +1688,8 @@ struct server_tool_exec_shell_command : server_tool {
|
||||
auto res = io->run(args, max_output, timeout, [st](const std::string & chunk) {
|
||||
st->push(chunk);
|
||||
return !st->alive || st->alive();
|
||||
}, [st]() {
|
||||
return st->alive && !st->alive();
|
||||
});
|
||||
if (st->alive && !st->alive()) {
|
||||
return json();
|
||||
@@ -1321,7 +1702,7 @@ struct server_tool_exec_shell_command : server_tool {
|
||||
return json();
|
||||
}
|
||||
|
||||
auto res = io->run(args, max_output, timeout);
|
||||
auto res = io->run(args, max_output, timeout, nullptr, should_stop);
|
||||
|
||||
std::string text_output = res.output;
|
||||
text_output += string_format("\n[exit code: %d]", res.exit_code);
|
||||
|
||||
@@ -2,6 +2,8 @@ import os
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import pytest
|
||||
from utils import *
|
||||
@@ -17,6 +19,9 @@ GREP_MARKER = "llama_cpp_test_tools_builtin_marker_grep_search"
|
||||
# image the container runtime tests run their shell in
|
||||
CONTAINER_IMAGE = "busybox"
|
||||
|
||||
COMMAND_LEAVING_A_PROCESS = "start /b ping -n 30 127.0.0.1 & echo started" if os.name == "nt" else "sleep 30 & echo started"
|
||||
COMMAND_OUTLIVING_THE_TIMEOUT = "ping -n 30 127.0.0.1 & echo done" if os.name == "nt" else "sleep 30; echo done"
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def create_server():
|
||||
@@ -226,6 +231,37 @@ def test_tools_builtin_exec_shell_command_stream():
|
||||
assert "[exit code: 0]" in chunks
|
||||
|
||||
|
||||
def test_tools_builtin_exec_shell_command_double_quotes():
|
||||
global server
|
||||
server.start()
|
||||
|
||||
res = call_tool("exec_shell_command", {"command": f"\"{sys.executable}\" -c \"print('quoted arg')\""})
|
||||
assert "quoted arg" in res["plain_text_response"]
|
||||
assert "[exit code: 0]" in res["plain_text_response"]
|
||||
|
||||
|
||||
def test_tools_builtin_exec_shell_command_returns_when_the_shell_exits():
|
||||
global server
|
||||
server.start()
|
||||
|
||||
start = time.monotonic()
|
||||
res = call_tool("exec_shell_command", {"command": COMMAND_LEAVING_A_PROCESS, "timeout": 20})
|
||||
assert time.monotonic() - start < 10
|
||||
assert "started" in res["plain_text_response"]
|
||||
assert "[exit code: 0]" in res["plain_text_response"]
|
||||
|
||||
|
||||
def test_tools_builtin_exec_shell_command_timeout_ends_the_command():
|
||||
global server
|
||||
server.start()
|
||||
|
||||
start = time.monotonic()
|
||||
res = call_tool("exec_shell_command", {"command": COMMAND_OUTLIVING_THE_TIMEOUT, "timeout": 2})
|
||||
assert time.monotonic() - start < 10
|
||||
assert "[exit due to timed out]" in res["plain_text_response"]
|
||||
assert "done" not in res["plain_text_response"]
|
||||
|
||||
|
||||
def test_tools_builtin_cwd_header(tmp_path):
|
||||
global server
|
||||
server.start()
|
||||
|
||||
@@ -6,7 +6,7 @@ These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/ap
|
||||
- **Demos, checks and docs media:** [skills/ui-demo](../../../skills/ui-demo/SKILL.md) records a PR's demo video, turns its flow into an e2e check and captures docs videos and screenshots, for Llama Chat and Llama UI alike.
|
||||
- **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/<area>`, one folder per `src/lib/components/app/<area>` (`chat/` has one per Chat folder), titled `Llama Chat/<Area>/<Component>`. How the app works on a phone (the sidebar's keys, the sheets and the pages each pushes) is written up in `tests/stories/mobile`, titled `Llama Chat/Mobile/Flows`: update it when a sheet gains or loses a page. An accessibility story sits next to its component's, as `<Component>.a11y.stories.svelte`, titled `.../<Component>/Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here.
|
||||
- **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together.
|
||||
- **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions.
|
||||
- **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions. A component whose machinery is hard to read keeps its own `AGENTS.md` beside it, such as [the Markdown editor's](src/lib/components/app/content/MarkdownEditor/AGENTS.md).
|
||||
|
||||
## Content is Markdown, custom pieces are Svelte: .svx
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
# Instructions for ui/apps/chat/src/lib/components/app/content/MarkdownEditor
|
||||
|
||||
These add to the repository's [AGENTS.md](../../../../../../../../../AGENTS.md) for Chat's rich content editor: a CodeMirror 6 editor whose document is always the markdown source itself. `../../chat/ChatForm/ChatFormInput/ChatFormInput.svelte` writes a message with it, and `../MarkdownContent` renders that same source in a chat message, reusing its pipeline and stylesheet, so the two must keep agreeing on what a block is.
|
||||
|
||||
- **The document is the prompt.** The live preview only decorates: `markdown-live-preview.ts` replaces every top-level block the cursor is not in with the HTML `MarkdownContent` renders for it and shows the block being edited as raw text, and none of it touches the text. What reaches `onChange` is what gets sent, byte for byte. An extension that inserts text (fence auto-close) enlarges the user's keystroke rather than correcting them: one transaction with `userEvent: 'input.type'`, which reports like typing and undoes in one step.
|
||||
- **Edits come in two directions.** Editor edits reach `onChange` and so back into `value`; the edits that bring the editor in line with `value` (streamed tokens, a cleared form) go through `syncValue` as the single differing middle of the two texts, annotated `valueSync` to keep them out of `onChange` and out of the undo history.
|
||||
- **Extension order decides who sees a key.** The `extensions` prop sits ahead of the editor's own keymaps, so the chat form's handlers keep their keys first (submit, pickers); the editor's own behaviour is added after `markdownSupport`. A `keymap` `run` handler returns `false` when it does not handle the event, otherwise the handlers below it never run.
|
||||
- **Typed text arrives through `EditorView.inputHandler`, not a keymap.** The editor takes text through contenteditable on every browser (`ContentEditableView`, because Chrome on Android opens no virtual keyboard for EditContext), where soft keyboards and input methods give no reliable key events but do report the text they inserted. `markdown-code-fence.ts` is that for ``` fences: the last backtick of an opening fence writes the closing one and moves the cursor between them.
|
||||
- **What is code is asked of the syntax tree, never of a regex.** `markdown-syntax.ts` (`codeRanges`) and `markdown-blocks.ts` (`collectBlocks`, `CODE_BLOCK_NAMES`) answer the way the preview renders. A code block that is still open runs to the end of the document while a closed one stops before its newline, so resolving the start of a line with side `-1` and walking up tells you whether a block is open there.
|
||||
- **Block gaps are computed, not measured.** CodeMirror cannot read the margins of a block widget, so `BLOCK_MARGINS_REM` holds them per block kind, and `markdown-editor-margins.svelte.test.ts` checks them against `../MarkdownContent/markdown-content.css`.
|
||||
- **Its tests** are `markdown-editor.svelte.test.ts` and `markdown-editor-margins.svelte.test.ts` in `ui/apps/chat/tests/client` (vitest project `client`, real Chromium). Typing that must reach an input handler is driven with `userEvent.keyboard`; `editor.dispatch` writes the document without going through the DOM input path at all.
|
||||
@@ -13,6 +13,7 @@
|
||||
<script lang="ts">
|
||||
import '#lib/styles/katex-custom.scss';
|
||||
import MarkdownSurface from '../MarkdownContent/MarkdownSurface.svelte';
|
||||
import { autoCloseCodeFence } from './markdown-code-fence';
|
||||
import {
|
||||
markdownLivePreview,
|
||||
type MarkdownLivePreviewOptions,
|
||||
@@ -166,6 +167,8 @@
|
||||
),
|
||||
keymap.of([...markdownKeymap, ...defaultKeymap, ...historyKeymap]),
|
||||
markdownSupport,
|
||||
// the third backtick of a fence opens a code block that is already closed
|
||||
autoCloseCodeFence(),
|
||||
previewCompartment.of(previewExtension()),
|
||||
editableCompartment.of(EditorView.editable.of(!disabled)),
|
||||
EditorView.lineWrapping,
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
// Opening a code block as it is typed: the last backticks of an opening fence write the
|
||||
// closing fence too and put the cursor between them, so what comes next is code.
|
||||
|
||||
import { CODE_BLOCK_NAMES } from './markdown-blocks';
|
||||
import { syntaxTree } from '@codemirror/language';
|
||||
import { type EditorState, type Extension } from '@codemirror/state';
|
||||
import { EditorView } from '@codemirror/view';
|
||||
|
||||
/** The fence that opens and closes a fenced code block. */
|
||||
const CODE_FENCE = '```';
|
||||
/** What a single input can add to a line to complete that fence, from a key or a gesture. */
|
||||
const FENCE_COMPLETIONS = ['`', '``', '```'];
|
||||
/** Markdown lets a fence be indented by up to three spaces. */
|
||||
const MAX_FENCE_INDENT = 3;
|
||||
|
||||
/**
|
||||
* Whether the cursor sits after a line that `typed` makes an opening fence all by itself:
|
||||
* the fence's backticks, indented as markdown allows, with nothing else on the line.
|
||||
*/
|
||||
function opensFence(state: EditorState, from: number, to: number, typed: string): boolean {
|
||||
const line = state.doc.lineAt(from);
|
||||
const fence = `${line.text.slice(0, from - line.from)}${typed}`;
|
||||
// What stands before the backticks, which is the line's indentation at most.
|
||||
const indent = fence.length - CODE_FENCE.length;
|
||||
|
||||
return (
|
||||
to === from &&
|
||||
line.to === from &&
|
||||
indent >= 0 &&
|
||||
indent <= MAX_FENCE_INDENT &&
|
||||
fence.endsWith(CODE_FENCE) &&
|
||||
!fence.slice(0, indent).trim()
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether `pos` is below a code block that is still open, where a fence is only text. */
|
||||
function inCodeBlock(state: EditorState, pos: number): boolean {
|
||||
const { from } = state.doc.lineAt(pos);
|
||||
|
||||
// The start of a line falls between nodes, so ask what stands before it: a code block
|
||||
// that is still open reaches past the line, while a closed one stops before its newline.
|
||||
let node = syntaxTree(state).resolve(from, -1);
|
||||
|
||||
// Up through the parents until the top node, which has none: that ends the walk.
|
||||
for (;;) {
|
||||
if (CODE_BLOCK_NAMES.has(node.name)) return node.from < from && node.to >= from;
|
||||
|
||||
const parent = node.parent;
|
||||
|
||||
if (!parent) break;
|
||||
|
||||
node = parent;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The last backticks of an opening fence close the code block they open right away: the
|
||||
* cursor moves to the next line, which already has the closing fence below it. A fence
|
||||
* inside a code block stays the text it is, and the block is one undo step.
|
||||
*/
|
||||
export function autoCloseCodeFence(): Extension {
|
||||
return EditorView.inputHandler.of((view, from, to, typed) => {
|
||||
if (
|
||||
// an input method may commit the backticks as part of a longer composition
|
||||
view.composing ||
|
||||
!FENCE_COMPLETIONS.includes(typed) ||
|
||||
!opensFence(view.state, from, to, typed) ||
|
||||
inCodeBlock(view.state, from)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
view.dispatch({
|
||||
// the fence, the line the cursor goes to, and the one that closes the block
|
||||
changes: { from, insert: `${typed}\n\n${CODE_FENCE}`, to },
|
||||
selection: { anchor: from + typed.length + 1 },
|
||||
userEvent: 'input.type'
|
||||
});
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -15,9 +15,12 @@ export const SVG = {
|
||||
/**
|
||||
* Shadow root style for an inline svg block. Mirrors the centered, padded
|
||||
* sizing the light dom used before the svg moved behind a shadow boundary.
|
||||
* The svg box includes its padding and stays within the message width and the
|
||||
* block's max height (less the scroll container's 4rem of padding), so the
|
||||
* whole drawing shows without scrolling.
|
||||
*/
|
||||
INLINE_SHADOW_STYLE:
|
||||
':host{display:block;width:100%;text-align:center}svg{display:block;margin:0 auto;width:auto;height:auto;max-width:100%;max-height:70vh;min-height:8rem;padding:3rem 1rem}',
|
||||
':host{display:block;width:100%;text-align:center}svg{box-sizing:border-box;display:block;margin:0 auto;width:auto;height:auto;max-width:100%;max-height:min(70vh,calc(var(--max-message-height,70vh) - 4rem));min-height:8rem;padding:3rem 1rem}',
|
||||
// Languages that mark a code block as svg content.
|
||||
LANGUAGE: 'svg',
|
||||
/**
|
||||
|
||||
@@ -24,6 +24,7 @@ export enum KeyboardKey {
|
||||
PAGE_UP = 'PageUp',
|
||||
SPACE = ' ',
|
||||
TAB = 'Tab',
|
||||
W_LOWER = 'w',
|
||||
X_LOWER = 'x',
|
||||
X_UPPER = 'X'
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { NEW_CHAT_TAB_ID } from '#lib/constants/index.ts';
|
||||
import { KeyboardKey } from '#lib/enums/index.ts';
|
||||
import { conversationsStore, settingsStore, tabsStore } from '#lib/stores/index.ts';
|
||||
import { conversationsStore, deviceStore, settingsStore, tabsStore } from '#lib/stores/index.ts';
|
||||
import { resolveTabTarget, resolveWindowCloseTab } from '#lib/utils/index.ts';
|
||||
import { page } from '$app/state';
|
||||
|
||||
interface KeyboardShortcutsCallbacks {
|
||||
@@ -73,14 +73,33 @@ export function useKeyboardShortcuts(callbacks: KeyboardShortcutsCallbacks) {
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const activeId =
|
||||
page.params.id ?? (page.route.id === '/(chat)' ? NEW_CHAT_TAB_ID : undefined);
|
||||
const activeId = resolveTabTarget(page);
|
||||
|
||||
if (activeId) {
|
||||
void tabsStore.close(activeId, true);
|
||||
}
|
||||
}
|
||||
|
||||
// the browser's own close shortcut: Cmd+W on Apple platforms, where Ctrl+W
|
||||
// deletes a word in text fields, and Ctrl+W elsewhere
|
||||
const isWindowClose =
|
||||
(deviceStore.isApplePlatform ? event.metaKey && !event.ctrlKey : event.ctrlKey) &&
|
||||
!event.shiftKey &&
|
||||
!event.altKey &&
|
||||
event.key === KeyboardKey.W_LOWER;
|
||||
|
||||
// the tab strip is hidden on mobile, where the shortcut keeps closing the window
|
||||
if (isWindowClose && settingsStore.config.conversationTabs && !deviceStore.isMobile) {
|
||||
if (event.defaultPrevented) return;
|
||||
|
||||
const tabId = resolveWindowCloseTab(page, tabsStore.openTabs);
|
||||
|
||||
if (tabId) {
|
||||
event.preventDefault();
|
||||
void tabsStore.close(tabId, true);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
isCmdOrCtrl &&
|
||||
event.shiftKey &&
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* deviceStore - Browser environment signals
|
||||
*
|
||||
* Device capabilities, OS theme and viewport in one class store:
|
||||
* deviceStore.isMobile, deviceStore.isIOSDevice / isIOSSafari / isWKWebView /
|
||||
* deviceStore.isMobile, deviceStore.isApplePlatform / isIOSDevice / isIOSSafari / isWKWebView /
|
||||
* isStandalone, deviceStore.systemTheme.isDark.
|
||||
*
|
||||
* UA-derived flags are static for the session; isStandalone and systemTheme
|
||||
@@ -30,6 +30,8 @@ const UA_PATTERNS = {
|
||||
} as const;
|
||||
|
||||
class DeviceStore {
|
||||
/** macOS, iOS or iPadOS, where shortcuts take Cmd instead of Ctrl. */
|
||||
readonly isApplePlatform: boolean = false;
|
||||
/** Any iOS/iPadOS device, regardless of which app or browser embeds the page. */
|
||||
readonly isIOSDevice: boolean = false;
|
||||
/** The Safari browser app on iOS, excluding other iOS browsers and WKWebViews. */
|
||||
@@ -63,6 +65,7 @@ class DeviceStore {
|
||||
|
||||
this.isIOSDevice =
|
||||
UA_PATTERNS.IOS_PHONE.test(ua) || (UA_PATTERNS.MACINTOSH.test(ua) && isTouch);
|
||||
this.isApplePlatform = this.isIOSDevice || UA_PATTERNS.MACINTOSH.test(ua);
|
||||
// Safari keeps 'Safari/' in the UA; non-Safari iOS browsers emit their own
|
||||
// token instead. WKWebView typically omits 'Safari/' entirely.
|
||||
const hasSafariToken = UA_PATTERNS.SAFARI.test(ua) && !UA_PATTERNS.WEBVIEW_IOS.test(ua);
|
||||
|
||||
@@ -36,3 +36,13 @@ export function resolveTabView(page: TabRoute, openTabs: string[]): TabView {
|
||||
ids: openTabs
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Tab the browser's close shortcut closes in place of the window: the active
|
||||
* one, while other tabs stay open. Null leaves the shortcut to the browser.
|
||||
*/
|
||||
export function resolveWindowCloseTab(page: TabRoute, openTabs: string[]): string | null {
|
||||
const { activeId, ids } = resolveTabView(page, openTabs);
|
||||
|
||||
return activeId && ids.length > 1 && ids.includes(activeId) ? activeId : null;
|
||||
}
|
||||
|
||||
@@ -255,7 +255,7 @@ export {
|
||||
type PathQuery
|
||||
} from './working-directory';
|
||||
|
||||
export { resolveTabTarget, resolveTabView, type TabView } from './chat-tabs';
|
||||
export { resolveTabTarget, resolveTabView, resolveWindowCloseTab, type TabView } from './chat-tabs';
|
||||
|
||||
// Shared `file_glob_search` runner with a short-lived result cache
|
||||
export { runFolderSearch, runGlobSearch, runGlobSearchWithChildren } from './glob-search';
|
||||
|
||||
@@ -1,3 +1,44 @@
|
||||
const SVG_VIEWBOX_ATTR = 'viewBox';
|
||||
const SVG_CSS_DPI = 96;
|
||||
const SVG_DIMENSION_PATTERN = /^\s*(\d*\.?\d+)\s*(px|in|cm|mm|pt|pc)?\s*$/;
|
||||
// user units (css px) per absolute length unit, at the css dpi
|
||||
const SVG_ABSOLUTE_UNIT_PX: Record<string, number> = {
|
||||
'': 1,
|
||||
cm: SVG_CSS_DPI / 2.54,
|
||||
in: SVG_CSS_DPI,
|
||||
mm: SVG_CSS_DPI / 25.4,
|
||||
pc: SVG_CSS_DPI / 6,
|
||||
pt: SVG_CSS_DPI / 72,
|
||||
px: 1
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads an absolute svg width/height attribute (unitless, px, in, cm, mm, pt or pc)
|
||||
* as user units. Relative lengths such as % or em return null.
|
||||
*/
|
||||
export function readSvgDimension(value: string | null): number | null {
|
||||
const match = value?.match(SVG_DIMENSION_PATTERN);
|
||||
|
||||
if (!match) return null;
|
||||
|
||||
const size = Number(match[1]) * SVG_ABSOLUTE_UNIT_PX[match[2] ?? ''];
|
||||
|
||||
return size > 0 ? size : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gives an svg with a fixed width and height but no viewBox a matching viewBox,
|
||||
* so css max-width scales the drawing instead of clipping it.
|
||||
*/
|
||||
function ensureSvgViewBox(svg: SVGSVGElement): void {
|
||||
if (svg.hasAttribute(SVG_VIEWBOX_ATTR)) return;
|
||||
|
||||
const width = readSvgDimension(svg.getAttribute('width'));
|
||||
const height = readSvgDimension(svg.getAttribute('height'));
|
||||
|
||||
if (width && height) svg.setAttribute(SVG_VIEWBOX_ATTR, `0 0 ${width} ${height}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts svg markup inside an open shadow root on the host element.
|
||||
* The shadow boundary scopes the svg <style> and its animations to the host,
|
||||
@@ -8,4 +49,8 @@ export function mountSvgShadow(host: HTMLElement, markup: string, style: string)
|
||||
const root = host.shadowRoot ?? host.attachShadow({ mode: 'open' });
|
||||
|
||||
root.innerHTML = markup ? `<style>${style}</style>${markup}` : '';
|
||||
|
||||
const svg = root.querySelector('svg');
|
||||
|
||||
if (svg) ensureSvgViewBox(svg);
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Guards the MarkdownEditor contract beyond the chat form: which edits reach onChange,
|
||||
// undo of a programmatic replace, props changed after mount, blocks the live preview
|
||||
// keeps raw or joins, the gap after a raw block, and selecting text in rendered blocks.
|
||||
// undo of a programmatic replace, the code block a typed fence opens, props changed after
|
||||
// mount, blocks the live preview keeps raw or joins, the gap after a raw block, and
|
||||
// selecting text in rendered blocks.
|
||||
|
||||
import { undo } from '@codemirror/commands';
|
||||
import { EditorView, type WidgetType } from '@codemirror/view';
|
||||
@@ -8,6 +9,7 @@ import MarkdownEditor from '#lib/components/app/content/MarkdownEditor/MarkdownE
|
||||
import { SVG } from '#lib/constants/index.ts';
|
||||
import { tick } from 'svelte';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { userEvent } from 'vitest/browser';
|
||||
import { render } from 'vitest-browser-svelte';
|
||||
|
||||
function editorIn(container: HTMLElement): EditorView {
|
||||
@@ -63,6 +65,64 @@ describe('MarkdownEditor', () => {
|
||||
expect(editor.state.doc.toString()).toBe('see @no');
|
||||
});
|
||||
|
||||
it('closes a code block as its opening fence is typed', async () => {
|
||||
const onChange = vi.fn();
|
||||
const screen = render(MarkdownEditor, { onChange, value: 'note\n' });
|
||||
const editor = editorIn(screen.container);
|
||||
|
||||
editor.focus();
|
||||
editor.dispatch({ selection: { anchor: 'note\n'.length } });
|
||||
|
||||
await userEvent.keyboard('```');
|
||||
await settle();
|
||||
|
||||
expect(editor.state.doc.toString()).toBe('note\n```\n\n```');
|
||||
// the cursor waits on the line between the fences
|
||||
expect(editor.state.selection.main.head).toBe('note\n```\n'.length);
|
||||
expect(onChange).toHaveBeenLastCalledWith('note\n```\n\n```');
|
||||
});
|
||||
|
||||
it('undoes a typed code block in one step', async () => {
|
||||
const screen = render(MarkdownEditor, { value: '' });
|
||||
const editor = editorIn(screen.container);
|
||||
|
||||
editor.focus();
|
||||
await userEvent.keyboard('```');
|
||||
await settle();
|
||||
|
||||
expect(editor.state.doc.toString()).toBe('```\n\n```');
|
||||
|
||||
undo(editor);
|
||||
|
||||
expect(editor.state.doc.toString()).toBe('');
|
||||
});
|
||||
|
||||
it('keeps a fence that closes an open code block as text', async () => {
|
||||
const screen = render(MarkdownEditor, { value: '```\n\n' });
|
||||
const editor = editorIn(screen.container);
|
||||
|
||||
editor.focus();
|
||||
editor.dispatch({ selection: { anchor: '```\n'.length } });
|
||||
|
||||
await userEvent.keyboard('```');
|
||||
await settle();
|
||||
|
||||
expect(editor.state.doc.toString()).toBe('```\n```\n');
|
||||
});
|
||||
|
||||
it('keeps backticks after text on their line as they are', async () => {
|
||||
const screen = render(MarkdownEditor, { value: 'note' });
|
||||
const editor = editorIn(screen.container);
|
||||
|
||||
editor.focus();
|
||||
editor.dispatch({ selection: { anchor: 4 } });
|
||||
|
||||
await userEvent.keyboard('```');
|
||||
await settle();
|
||||
|
||||
expect(editor.state.doc.toString()).toBe('note```');
|
||||
});
|
||||
|
||||
it('follows placeholder and label changes after mount', async () => {
|
||||
const screen = render(MarkdownEditor, { placeholder: 'First', value: '' });
|
||||
const editor = editorIn(screen.container);
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { NEW_CHAT_TAB_ID } from '#lib/constants/index.ts';
|
||||
import { resolveWindowCloseTab } from '#lib/utils/chat-tabs.ts';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const chatPage = (id: string) => ({ params: { id }, route: { id: '/(chat)/chat/[id]' } });
|
||||
const newChatPage = { params: {}, route: { id: '/(chat)' } };
|
||||
const settingsPage = { params: {}, route: { id: '/settings' } };
|
||||
|
||||
describe('resolveWindowCloseTab', () => {
|
||||
it('closes the active tab while other tabs stay open', () => {
|
||||
expect(resolveWindowCloseTab(chatPage('a'), ['a', 'b'])).toBe('a');
|
||||
expect(resolveWindowCloseTab(newChatPage, ['a', NEW_CHAT_TAB_ID])).toBe(NEW_CHAT_TAB_ID);
|
||||
});
|
||||
|
||||
it('leaves the shortcut to the browser on the last tab', () => {
|
||||
expect(resolveWindowCloseTab(chatPage('a'), ['a'])).toBeNull();
|
||||
});
|
||||
|
||||
it('leaves the shortcut to the browser on a page without tabs', () => {
|
||||
expect(resolveWindowCloseTab(settingsPage, ['a', 'b'])).toBeNull();
|
||||
});
|
||||
|
||||
it('leaves the shortcut to the browser when the route has no tab', () => {
|
||||
expect(resolveWindowCloseTab(chatPage('c'), ['a', 'b'])).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,27 @@
|
||||
import { readSvgDimension } from '#lib/utils/svg-shadow.ts';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('svg-shadow readSvgDimension', () => {
|
||||
it('reads unitless and px lengths as user units', () => {
|
||||
expect(readSvgDimension('800')).toBe(800);
|
||||
expect(readSvgDimension('800px')).toBe(800);
|
||||
expect(readSvgDimension(' 12.5 ')).toBe(12.5);
|
||||
});
|
||||
|
||||
it('converts absolute units at 96 dpi', () => {
|
||||
expect(readSvgDimension('1in')).toBe(96);
|
||||
expect(readSvgDimension('72pt')).toBeCloseTo(96, 10);
|
||||
expect(readSvgDimension('6pc')).toBe(96);
|
||||
expect(readSvgDimension('2.54cm')).toBeCloseTo(96, 10);
|
||||
expect(readSvgDimension('25.4mm')).toBeCloseTo(96, 10);
|
||||
});
|
||||
|
||||
it('returns null for relative, missing, zero or malformed lengths', () => {
|
||||
expect(readSvgDimension(null)).toBeNull();
|
||||
expect(readSvgDimension('100%')).toBeNull();
|
||||
expect(readSvgDimension('10em')).toBeNull();
|
||||
expect(readSvgDimension('auto')).toBeNull();
|
||||
expect(readSvgDimension('0')).toBeNull();
|
||||
expect(readSvgDimension('')).toBeNull();
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user