-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathManagedPagedAttention.cs
More file actions
386 lines (359 loc) · 15.7 KB
/
Copy pathManagedPagedAttention.cs
File metadata and controls
386 lines (359 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
// Copyright (c) Zhongkai Fu. All rights reserved.
// https://github.com/zhongkaifu/TensorSharp
//
// This file is part of TensorSharp.
//
// TensorSharp is licensed under the BSD-3-Clause license found in the LICENSE file in the root directory of this source tree.
using System;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace TensorSharp.Runtime.Paged
{
/// <summary>
/// Managed (pure C#) implementation of batched paged attention. Mirrors the
/// shape and semantics of vLLM's <c>flash_attn_varlen_func</c>: a single
/// kernel call handles many sequences of varying length, gathering K and V
/// from a paged block pool via a per-sequence block table and a per-token
/// slot mapping. Causal masking with an optional sliding-window bound,
/// no ALiBi - just the core building block.
///
/// This is the **reference / correctness** implementation. Per-token
/// throughput is far lower than a fused GGML/CUDA kernel; the value here
/// is that one call can drive an arbitrary mix of prefill chunks and
/// decode tokens with one shared layer of weights, which is the
/// continuous-batching win. A native paged attention kernel (the
/// long-tail item in the architecture doc) drops into this same
/// interface.
///
/// Tensor layout convention
/// ------------------------
/// q : [numTokens, numHeads, headDim] (row-major)
/// kBlocks / vBlocks: [numBlocks, blockSize, numKvHeads, headDim]
/// out : [numTokens, numHeads, headDim] (row-major)
///
/// Per-sequence metadata
/// ---------------------
/// queryStartLoc[s] : index of first token of sequence s in q
/// (length numSeqs+1, last entry = numTokens)
/// seqLens[s] : total context length (prompt + generated so far)
/// blockTables[s] : list of block ids covering positions [0..seqLens[s])
/// positions[t] : absolute position of token t within its sequence
/// (used for causal masking, NOT for K/V write
/// location)
/// slotMapping[t] : physical slot in the K/V pool where token t's
/// K and V are stored
/// (slot = blockId * blockSize + offsetInBlock)
/// </summary>
public static class ManagedPagedAttention
{
/// <summary>Multi-query / grouped-query attention. The K/V have a
/// (potentially smaller) <paramref name="numKvHeads"/>; each Q head is
/// mapped to a KV head via <paramref name="numHeads"/> / <paramref name="numKvHeads"/>.
/// Backed by <c>float[]</c> arrays so we can parallelise across
/// (sequence, head) without ref-struct capture restrictions.</summary>
public static void Forward(
float[] q,
float[] kBlocks,
float[] vBlocks,
float[] output,
int numTokens,
int numHeads,
int numKvHeads,
int headDim,
int blockSize,
int[] queryStartLoc,
int[] seqLens,
int[] positions,
int[][] blockTables,
int numSeqs,
float scale,
bool causal = true,
int slidingWindow = 0)
{
if (numHeads % numKvHeads != 0)
throw new ArgumentException("numHeads must be divisible by numKvHeads.");
int groupSize = numHeads / numKvHeads;
// Parallelise across (seq, head). Each output token's attention
// computes independently so this is embarrassingly parallel.
Parallel.For(0, numSeqs * numHeads, work =>
{
int seqIdx = work / numHeads;
int headIdx = work % numHeads;
int kvHead = headIdx / groupSize;
int qStart = queryStartLoc[seqIdx];
int qEnd = queryStartLoc[seqIdx + 1];
int seqLen = seqLens[seqIdx];
int[] table = blockTables[seqIdx];
for (int t = qStart; t < qEnd; t++)
{
int pos = positions[t];
int contextEndExclusive = causal ? pos + 1 : seqLen;
int contextStart = slidingWindow > 0
? Math.Max(0, contextEndExclusive - slidingWindow)
: 0;
ComputeSingleQueryAttention(
q, kBlocks, vBlocks, output,
tokenIdx: t,
headIdx: headIdx,
kvHead: kvHead,
numHeads: numHeads,
numKvHeads: numKvHeads,
headDim: headDim,
blockSize: blockSize,
contextEndExclusive: contextEndExclusive,
contextStart: contextStart,
blockTable: table,
scale: scale);
}
});
}
/// <summary>
/// Online-softmax single-query paged attention. Walks the sequence's
/// blocks, accumulating <c>numerator</c> = Σ exp(s_i - m) v_i and
/// <c>denominator</c> = Σ exp(s_i - m), tracking the running max <c>m</c>
/// to keep the exponents from overflowing. Final output is
/// <c>numerator / denominator</c>. This is the same pattern as
/// FlashAttention's recurrence, just unfused and unsimd'd.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ComputeSingleQueryAttention(
float[] q,
float[] kBlocks,
float[] vBlocks,
float[] output,
int tokenIdx,
int headIdx,
int kvHead,
int numHeads,
int numKvHeads,
int headDim,
int blockSize,
int contextEndExclusive,
int contextStart,
int[] blockTable,
float scale)
{
// q[token, headIdx, :]
int qOffset = (tokenIdx * numHeads + headIdx) * headDim;
// Online softmax accumulators. We can't use stackalloc here because
// this method is called from a Parallel.For lambda and headDim is
// potentially large (256+). Heap-allocate one buffer per (seq,head)
// pair - the JIT escape-analyses it away in the common path.
float maxScore = float.NegativeInfinity;
float denom = 0f;
var numerator = new float[headDim];
for (int contextPos = contextStart; contextPos < contextEndExclusive; contextPos++)
{
int blockIdx = contextPos / blockSize;
if (blockIdx >= blockTable.Length) break; // ran out of allocated blocks
int slotInBlock = contextPos % blockSize;
int blockId = blockTable[blockIdx];
// K and V at (blockId, slotInBlock, kvHead, :)
int kvBaseOffset =
blockId * blockSize * numKvHeads * headDim
+ slotInBlock * numKvHeads * headDim
+ kvHead * headDim;
// Compute Q . K
float score = 0f;
for (int d = 0; d < headDim; d++)
score += q[qOffset + d] * kBlocks[kvBaseOffset + d];
score *= scale;
if (score > maxScore)
{
// Renormalize old terms by the new max.
float renorm = MathF.Exp(maxScore - score);
denom *= renorm;
for (int d = 0; d < headDim; d++)
numerator[d] *= renorm;
maxScore = score;
}
float e = MathF.Exp(score - maxScore);
denom += e;
for (int d = 0; d < headDim; d++)
numerator[d] += e * vBlocks[kvBaseOffset + d];
}
int outOffset = (tokenIdx * numHeads + headIdx) * headDim;
if (denom == 0f)
{
// Empty context: write zeros.
for (int d = 0; d < headDim; d++)
output[outOffset + d] = 0f;
return;
}
float invDenom = 1f / denom;
for (int d = 0; d < headDim; d++)
output[outOffset + d] = numerator[d] * invDenom;
}
/// <summary>
/// Paged attention with per-head attention sinks (gpt-oss style) and
/// per-layer sliding window. Sinks are an extra "virtual" position per
/// head: a learned scalar logit that participates in the softmax
/// denominator but contributes zero to the output (sink V == 0). The
/// effect is to bleed off attention mass when no real position is
/// strongly relevant, stabilising long contexts.
///
/// Math is identical to <see cref="Forward"/>'s online softmax, with
/// two changes:
/// * <paramref name="sinks"/>[h] seeds the running max as a virtual
/// position so the first real score correctly normalises against
/// it. The denominator picks up the sink's exp(sink_logit - max);
/// the numerator does NOT (sink position has zero V).
/// * <paramref name="slidingWindow"/> > 0 truncates context to the
/// last <c>slidingWindow</c> tokens (matches the per-token-position
/// mask the gpt-oss attention layers alternate ON for even layers).
/// </summary>
public static void ForwardWithSinks(
float[] q,
float[] kBlocks,
float[] vBlocks,
float[] output,
int numTokens,
int numHeads,
int numKvHeads,
int headDim,
int blockSize,
int[] queryStartLoc,
int[] seqLens,
int[] positions,
int[][] blockTables,
int numSeqs,
float scale,
float[] sinks, // [numHeads] or null
int slidingWindow) // 0 = no SWA
{
if (numHeads % numKvHeads != 0)
throw new ArgumentException("numHeads must be divisible by numKvHeads.");
int groupSize = numHeads / numKvHeads;
Parallel.For(0, numSeqs * numHeads, work =>
{
int seqIdx = work / numHeads;
int headIdx = work % numHeads;
int kvHead = headIdx / groupSize;
int qStart = queryStartLoc[seqIdx];
int qEnd = queryStartLoc[seqIdx + 1];
int[] table = blockTables[seqIdx];
float sinkLogit = sinks != null ? sinks[headIdx] : float.NegativeInfinity;
for (int t = qStart; t < qEnd; t++)
{
int pos = positions[t];
int contextEndExclusive = pos + 1; // causal
int contextStart = slidingWindow > 0
? Math.Max(0, contextEndExclusive - slidingWindow)
: 0;
ComputeSingleQueryAttentionWithSinks(
q, kBlocks, vBlocks, output,
tokenIdx: t,
headIdx: headIdx,
kvHead: kvHead,
numHeads: numHeads,
numKvHeads: numKvHeads,
headDim: headDim,
blockSize: blockSize,
contextEndExclusive: contextEndExclusive,
contextStart: contextStart,
blockTable: table,
scale: scale,
sinkLogit: sinkLogit);
}
});
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private static void ComputeSingleQueryAttentionWithSinks(
float[] q,
float[] kBlocks,
float[] vBlocks,
float[] output,
int tokenIdx,
int headIdx,
int kvHead,
int numHeads,
int numKvHeads,
int headDim,
int blockSize,
int contextEndExclusive,
int contextStart,
int[] blockTable,
float scale,
float sinkLogit)
{
int qOffset = (tokenIdx * numHeads + headIdx) * headDim;
// Seed the online softmax with the sink as a virtual position:
// maxScore = sinkLogit, denom = exp(sinkLogit - maxScore) = 1.
// numerator stays zero because the sink has zero V contribution.
bool hasSink = !float.IsNegativeInfinity(sinkLogit);
float maxScore = hasSink ? sinkLogit : float.NegativeInfinity;
float denom = hasSink ? 1f : 0f;
var numerator = new float[headDim];
for (int contextPos = contextStart; contextPos < contextEndExclusive; contextPos++)
{
int blockIdx = contextPos / blockSize;
if (blockIdx >= blockTable.Length) break;
int slotInBlock = contextPos % blockSize;
int blockId = blockTable[blockIdx];
int kvBaseOffset =
blockId * blockSize * numKvHeads * headDim
+ slotInBlock * numKvHeads * headDim
+ kvHead * headDim;
float score = 0f;
for (int d = 0; d < headDim; d++)
score += q[qOffset + d] * kBlocks[kvBaseOffset + d];
score *= scale;
if (score > maxScore)
{
float renorm = MathF.Exp(maxScore - score);
denom *= renorm;
for (int d = 0; d < headDim; d++)
numerator[d] *= renorm;
maxScore = score;
}
float e = MathF.Exp(score - maxScore);
denom += e;
for (int d = 0; d < headDim; d++)
numerator[d] += e * vBlocks[kvBaseOffset + d];
}
int outOffset = (tokenIdx * numHeads + headIdx) * headDim;
if (denom == 0f)
{
for (int d = 0; d < headDim; d++) output[outOffset + d] = 0f;
return;
}
float invDenom = 1f / denom;
for (int d = 0; d < headDim; d++)
output[outOffset + d] = numerator[d] * invDenom;
}
/// <summary>
/// Scatter the new tokens' K and V into the paged pool at the slots
/// given by <paramref name="slotMapping"/>. K and V come in as
/// <c>[numTokens, numKvHeads, headDim]</c>. The paged buffers are
/// laid out as <c>[numBlocks, blockSize, numKvHeads, headDim]</c>.
/// </summary>
public static void WriteKvToPagedPool(
float[] k,
float[] v,
float[] kBlocks,
float[] vBlocks,
int[] slotMapping,
int numTokens,
int numKvHeads,
int headDim,
int blockSize)
{
int perTokenStride = numKvHeads * headDim;
for (int t = 0; t < numTokens; t++)
{
int slot = slotMapping[t];
int blockId = slot / blockSize;
int slotInBlock = slot % blockSize;
int dstOffset =
blockId * blockSize * perTokenStride
+ slotInBlock * perTokenStride;
int srcOffset = t * perTokenStride;
for (int i = 0; i < perTokenStride; i++)
{
kBlocks[dstOffset + i] = k[srcOffset + i];
vBlocks[dstOffset + i] = v[srcOffset + i];
}
}
}
}
}