|
| 1 | +package sk.ainet.exec.kernel |
| 2 | + |
| 3 | +import java.lang.foreign.Arena |
| 4 | +import java.lang.foreign.FunctionDescriptor |
| 5 | +import java.lang.foreign.Linker |
| 6 | +import java.lang.foreign.MemorySegment |
| 7 | +import java.lang.foreign.ValueLayout |
| 8 | +import java.lang.invoke.MethodHandle |
| 9 | +import sk.ainet.backend.api.kernel.Q4KMemSegMatmulKernel |
| 10 | + |
| 11 | +/** |
| 12 | + * Zero-copy native [Q4KMemSegMatmulKernel] implementation. |
| 13 | + * |
| 14 | + * Reuses the same `skainet_q4k_matmul` C symbol as |
| 15 | + * [NativeQ4KMatmulKernel] — the C side just sees `const uint8_t*` and |
| 16 | + * doesn't care whether the Kotlin caller backed those bytes by a |
| 17 | + * staged copy of a `ByteArray` or by an mmap'd off-heap segment. The |
| 18 | + * win on this path is that the weight bytes (which dominate the |
| 19 | + * payload — typical LLM Q4_K tensor: tens to hundreds of MB per layer) |
| 20 | + * never round-trip through the heap. |
| 21 | + * |
| 22 | + * Per-call cost vs [NativeQ4KMatmulKernel]: |
| 23 | + * - skips `MemorySegment.copy(weight, ...)` of `inputDim/256 * outputDim |
| 24 | + * * 144` bytes (e.g. 9 MB at 4096² shape). |
| 25 | + * - still copies `inputDim * 4` bytes for the input vector and |
| 26 | + * `outputDim * 4` bytes for the output — the input/output are |
| 27 | + * typically heap arrays produced/consumed by the surrounding |
| 28 | + * forward pass. |
| 29 | + * |
| 30 | + * PR 3 of the staged native-FFM rollout — see the `native-ffm-plan` |
| 31 | + * asciidoc. |
| 32 | + */ |
| 33 | +internal object NativeQ4KMemSegMatmulKernel : Q4KMemSegMatmulKernel { |
| 34 | + |
| 35 | + private const val BLOCK_SIZE = 256 |
| 36 | + |
| 37 | + fun isAvailable(): Boolean = handle != null |
| 38 | + |
| 39 | + override fun matmul( |
| 40 | + input: FloatArray, inputOffset: Int, |
| 41 | + weight: MemorySegment, weightByteOffset: Long, |
| 42 | + inputDim: Int, outputDim: Int, |
| 43 | + output: FloatArray, outputOffset: Int, |
| 44 | + ) { |
| 45 | + require(inputDim % BLOCK_SIZE == 0) { |
| 46 | + "NativeQ4KMemSegMatmulKernel: inputDim must be a multiple of $BLOCK_SIZE; got $inputDim" |
| 47 | + } |
| 48 | + require(weightByteOffset >= 0) { |
| 49 | + "NativeQ4KMemSegMatmulKernel: weightByteOffset must be non-negative; got $weightByteOffset" |
| 50 | + } |
| 51 | + require(weightByteOffset <= Int.MAX_VALUE) { |
| 52 | + "NativeQ4KMemSegMatmulKernel: weightByteOffset $weightByteOffset exceeds Int range — " + |
| 53 | + "the C kernel takes int32_t today; slice the segment first or wait for the int64_t overload" |
| 54 | + } |
| 55 | + if (outputDim == 0 || inputDim == 0) return |
| 56 | + val mh = handle |
| 57 | + ?: error("NativeQ4KMemSegMatmulKernel.matmul invoked while native library unavailable") |
| 58 | + |
| 59 | + // The C kernel reads weight from offset 0..weightBytesUsed, so |
| 60 | + // require that the caller's segment is large enough. This catches |
| 61 | + // scope/aliasing bugs early; without it, an undersized segment |
| 62 | + // would crash the JVM with SIGSEGV from native code. |
| 63 | + val weightBytesUsed = ((inputDim / BLOCK_SIZE).toLong() * outputDim) * 144L |
| 64 | + require(weightByteOffset + weightBytesUsed <= weight.byteSize()) { |
| 65 | + "NativeQ4KMemSegMatmulKernel: weight segment too small — needs " + |
| 66 | + "$weightBytesUsed bytes from offset $weightByteOffset, " + |
| 67 | + "segment is ${weight.byteSize()} bytes" |
| 68 | + } |
| 69 | + |
| 70 | + Arena.ofConfined().use { arena -> |
| 71 | + val inSeg = arena.allocate( |
| 72 | + inputDim.toLong() * java.lang.Float.BYTES, |
| 73 | + ValueLayout.JAVA_FLOAT.byteAlignment(), |
| 74 | + ) |
| 75 | + val outSeg = arena.allocate( |
| 76 | + outputDim.toLong() * java.lang.Float.BYTES, |
| 77 | + ValueLayout.JAVA_FLOAT.byteAlignment(), |
| 78 | + ) |
| 79 | + MemorySegment.copy(input, inputOffset, inSeg, ValueLayout.JAVA_FLOAT, 0L, inputDim) |
| 80 | + |
| 81 | + mh.invoke( |
| 82 | + inSeg, 0, |
| 83 | + weight, weightByteOffset.toInt(), |
| 84 | + inputDim, outputDim, |
| 85 | + outSeg, 0, |
| 86 | + ) |
| 87 | + |
| 88 | + MemorySegment.copy(outSeg, ValueLayout.JAVA_FLOAT, 0L, output, outputOffset, outputDim) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + private val handle: MethodHandle? by lazy { |
| 93 | + val lookup = NativeLibraryLoader.lookup() ?: return@lazy null |
| 94 | + val symbol = lookup.find("skainet_q4k_matmul").orElse(null) ?: return@lazy null |
| 95 | + val descriptor = FunctionDescriptor.ofVoid( |
| 96 | + ValueLayout.ADDRESS, // input |
| 97 | + ValueLayout.JAVA_INT, // input_offset |
| 98 | + ValueLayout.ADDRESS, // weight (passed straight through from caller) |
| 99 | + ValueLayout.JAVA_INT, // weight_byte_offset |
| 100 | + ValueLayout.JAVA_INT, // input_dim |
| 101 | + ValueLayout.JAVA_INT, // output_dim |
| 102 | + ValueLayout.ADDRESS, // output |
| 103 | + ValueLayout.JAVA_INT, // output_offset |
| 104 | + ) |
| 105 | + runCatching { Linker.nativeLinker().downcallHandle(symbol, descriptor) }.getOrNull() |
| 106 | + } |
| 107 | +} |
0 commit comments