Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

import java.util.ArrayList;
import java.util.List;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
import org.beehive.jitllm.backend.tornado.device.TornadoDevices;
import org.beehive.jitllm.backend.tornado.kernels.TransformerComputeKernelsLayered;
Expand Down Expand Up @@ -296,13 +297,20 @@ protected static boolean metalBackend() {

/**
* Whether split-KV decode attention runs the lane-cooperative kernel for {@code headSize}: an
* FP16 cache on the NVIDIA path, no request for the packed-half2 variant, and a head width
* {@link LaneAttentionPolicy} has a kernel for. The policy also picks that kernel and its grid.
* FP16 cache, no request for the packed-half2 variant, and a head width {@link
* LaneAttentionPolicy} has a kernel for. The policy also picks that kernel and its grid.
*/
protected boolean laneAttention(int headSize) {
return useFp16KVCache()
&& !packedHalf2Attention
&& LaneAttentionPolicy.laneCooperativeAttention(headSize);
return laneAttention(headSize, LaneAttentionPolicy::laneCooperativeAttention);
}

/**
* {@link #laneAttention(int)} with the policy question a family needs answered, e.g. {@link
* LaneAttentionPolicy#scaledLaneCooperativeAttention} for one whose scores are not scaled by
* {@code 1/sqrt(headSize)}.
*/
protected boolean laneAttention(int headSize, IntPredicate kernelFor) {
return useFp16KVCache() && !packedHalf2Attention && kernelFor.test(headSize);
}

// ── Binding a layer's weights from the batched-prefill graph that uploaded them ──────────
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ protected TaskGraph configureLayerDataTransfers(TaskGraph layer, int layerIndex)
state.workspace.wrapXbFP16);
layer.consumeFromDevice(GraphNames.DECODE_ACTIVATION, keyCache(), valueCache());
layer.consumeFromDevice(GraphNames.DECODE_ACTIVATION, state.workspace.wrapBlockTable);
if (laneAttention()) {
layer.transferToDevice(
DataTransferMode.FIRST_EXECUTION, state.workspace.wrapAttSplit);
}
} else {
String pred = layerGraphName(layerIndex - 1);
layer.consumeFromDevice(
Expand All @@ -89,6 +93,9 @@ protected TaskGraph configureLayerDataTransfers(TaskGraph layer, int layerIndex)
state.workspace.positionHolder,
state.workspace.wrapXbFP16);
layer.consumeFromDevice(pred, state.workspace.wrapBlockTable);
if (laneAttention()) {
layer.consumeFromDevice(pred, state.workspace.wrapAttSplit);
}
}
return layer;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
import org.beehive.jitllm.backend.tornado.kernels.TransformerComputeKernelsLayered;
import org.beehive.jitllm.backend.tornado.layers.AbstractTransformerLayerTaskGraphs;
import org.beehive.jitllm.backend.tornado.layers.GraphNames;
import org.beehive.jitllm.backend.tornado.scheduling.LaneAttentionPolicy;
import org.beehive.jitllm.backend.tornado.scheduling.SchedulerDetectionService;
import org.beehive.jitllm.backend.tornado.scheduling.SchedulerType;
import org.beehive.jitllm.backend.tornado.scheduling.WorkerGridFactory;
Expand Down Expand Up @@ -93,8 +94,17 @@ public GridScheduler updateGridScheduler(GridScheduler tornadoForwardScheduler)
GraphNames.layer(i) + ".qkv_projection", fusedQKVWorker);
tornadoForwardScheduler.addWorkerGrid(
GraphNames.layer(i) + ".rope_and_kv_cache", ropeWithCacheWorker);
tornadoForwardScheduler.addWorkerGrid(
GraphNames.layer(i) + ".attention", parallelAttentionWorker);
if (laneAttention()) {
tornadoForwardScheduler.addWorkerGrid(
GraphNames.layer(i) + ".attention",
LaneAttentionPolicy.worker(
config.numberOfHeads() * State.SPLIT_KV, config.headSize()));
tornadoForwardScheduler.addWorkerGrid(
GraphNames.layer(i) + ".attention_combine", parallelAttentionWorker);
} else {
tornadoForwardScheduler.addWorkerGrid(
GraphNames.layer(i) + ".attention", parallelAttentionWorker);
}
tornadoForwardScheduler.addWorkerGrid(
GraphNames.layer(i) + ".attn_output_proj", configDimRowMajorGlobalWorker);
// === FFN Block ===
Expand Down Expand Up @@ -376,7 +386,14 @@ protected TaskGraph configureLayerDataTransfers(TaskGraph unifiedLayer, int laye
// the kernels reading a mapping that no longer exists, silently.
unifiedLayer.transferToDevice(
DataTransferMode.EVERY_EXECUTION, state.workspace.wrapBlockTable);
if (laneAttention()) {
unifiedLayer.transferToDevice(
DataTransferMode.FIRST_EXECUTION, state.workspace.wrapAttSplit);
}
} else {
if (laneAttention()) {
unifiedLayer.consumeFromDevice(state.workspace.wrapAttSplit);
}
// Subsequent layers: Consume data already on device from previous layer
unifiedLayer.consumeFromDevice(
// Kernel context
Expand Down Expand Up @@ -405,6 +422,38 @@ protected TaskGraph configureLayerDataTransfers(TaskGraph unifiedLayer, int laye

private TaskGraph configureAttention(
TaskGraph unifiedLayer, int layerIndex, GraniteConfiguration config) {
if (laneAttention()) {
// Split-KV with the lane-cooperative kernel, scored by Granite's attention multiplier
// rather than 1/sqrt(headSize); the combine pass merges the partials.
unifiedLayer.task(
"attention",
LaneAttentionPolicy.scaledKernel(config.headSize()),
context,
state.workspace.wrapQ,
state.workspace.wrapKeyCacheFP16,
state.workspace.wrapValueCacheFP16,
state.workspace.wrapAttSplit,
config.numberOfHeads(),
config.headSize(),
config.kvDim(),
config.kvMul(),
state.workspace.positionHolder,
layerIndex,
state.workspace.wrapBlockTable,
state.kvBlockCfg,
state.kvBlockStride,
State.SPLIT_KV,
config.attentionScale());
return unifiedLayer.task(
"attention_combine",
TransformerComputeKernelsLayered::combineSplitKVAttention,
context,
state.workspace.wrapAttSplit,
state.workspace.wrapXb,
config.numberOfHeads(),
config.headSize(),
State.SPLIT_KV);
}
// Metal runs the flash kernel too: processHeadsParallelGranitePaged produces wrong output
// there (Granite 3.2 2B and 4.0 1B answered with punctuation in both representations).
if (schedulerType == SchedulerType.NVIDIA
Expand Down Expand Up @@ -474,6 +523,12 @@ private TaskGraph configureAttention(

// @formatter:on

/** Whether attention runs the scaled lane-cooperative split-KV kernel. */
protected boolean laneAttention() {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: this copies AbstractTransformerLayerTaskGraphs.laneAttention(int) except for the scaled policy call. That's fine for now, but the two copies can drift apart if the packed-half2 condition ever changes. A base-class variant that takes the policy predicate would keep them in one place.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 3af0283: AbstractTransformerLayerTaskGraphs.laneAttention(int headSize, IntPredicate kernelFor) holds the FP16-cache and packed-half2 conditions, and laneAttention(int) passes LaneAttentionPolicy::laneCooperativeAttention. GraniteFP16FFNLayers and GraniteQ8_0FFNLayers (which had a second copy) pass LaneAttentionPolicy::scaledLaneCooperativeAttention.

return laneAttention(
config.headSize(), LaneAttentionPolicy::scaledLaneCooperativeAttention);
}

/** The key cache every graph of this family binds: FP16 when the state holds one. */
protected Object keyCache() {
return useFp16KVCache() ? state.workspace.wrapKeyCacheFP16 : state.workspace.wrapKeyCache;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -417,9 +417,8 @@ protected TaskGraph appendFFNLayer(TaskGraph existing, int layerIndex) {

/** Whether attention runs the scaled lane-cooperative split-KV kernel. */
private boolean laneAttention() {
return useFp16KVCache()
&& !packedHalf2Attention
&& LaneAttentionPolicy.scaledLaneCooperativeAttention(config.headSize());
return laneAttention(
config.headSize(), LaneAttentionPolicy::scaledLaneCooperativeAttention);
}

/** Adjacent decode layers per graph, which removes all but one host round trip per group. */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -855,9 +855,10 @@ protected Object valueCache() {
/**
* Split-KV partitions per head for attention, or 0 for one workgroup per head. With an FP32
* cache, split only where the 32-thread split kernel runs (Metal; see {@link
* SplitKvAttentionPolicy}). With an FP16 cache, asked for with {@code
* -Djitllm.attention.splitKv=true} (and {@code .count}), or taken by default on the NVIDIA path
* where the lane-cooperative kernel runs.
* SplitKvAttentionPolicy}). With an FP16 cache, split by default wherever {@link
* #laneAttention(int)} holds for the head width, on any backend; elsewhere only on the NVIDIA
* path and only when asked for with {@code -Djitllm.attention.splitKv=true} (and {@code
* .count}).
*/
protected int attentionSplits() {
if (!useFp16KVCache()) {
Expand All @@ -866,7 +867,10 @@ protected int attentionSplits() {
: 0;
}
var partitions = state.executionPolicy().splitKvPartitions();
if (schedulerType != SchedulerType.NVIDIA) {
// Off NVIDIA, the FP16 cache splits only where the lane-cooperative kernel runs (on Metal,
// the head widths LaneAttentionPolicy admits): the per-key FP16 split kernel needs more
// threadgroup memory than Metal allows.
if (schedulerType != SchedulerType.NVIDIA && !laneAttention(config.headSize())) {
return 0;
}
if (partitions.isEmpty()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,8 @@ private LaneAttentionPolicy() {}

/**
* Whether a lane-cooperative kernel may be used for this head width on the active device: CUDA
* for every width with a kernel, and Metal for the 128-wide one, where it is the FP16 cache's
* split-KV decode attention.
* for every width with a kernel, and Metal for the 128- and 64-wide ones, where they are the
* FP16 cache's split-KV decode attention.
*
* @param headSize the model's head width; anything but 64, 96 or 128 is refused
*/
Expand All @@ -164,9 +164,9 @@ public static boolean laneCooperativeAttention(int headSize) {
return headSize == 64 || headSize == 96 || headSize == 128;
}
// Metal: the FP32-cache twin already runs there on the same shuffles, and the 64-thread
// per-key FP16 kernel needs 34052 bytes of threadgroup memory, past Metal's 32 KB. Only the
// 128-wide kernel has been verified there.
return headSize == SUPPORTED_HEAD_SIZE
// per-key FP16 kernel needs 34052 bytes of threadgroup memory, past Metal's 32 KB. The
// 128- and 64-wide kernels have been verified there; the 96-wide one has not.
return (headSize == SUPPORTED_HEAD_SIZE || headSize == NARROW_HEAD_SIZE)
Comment thread
orionpapadakis marked this conversation as resolved.
Resolved
&& capabilities.supports(DeviceCapability.SUBGROUP_SHUFFLE_32);
}

Expand Down
Loading
Loading