Skip to content

vllm.models.inkling2.nvidia.attention

Inkling2 attention: relative-bias GQA with short-conv K/V, L2-clipped q/k/r, gated output and per-token attention sinks.

Classes:

Inkling2Attention

Bases: Module, AttentionLayerBase

Inkling2 attention for one decoder layer.

Local layers project all of q/k/v from one input; full layers project the query side (q, r, gate, sink) from x_q, k from x_k and v from x_v, and use dynamic K/V convolutions and log-scaled q/r.

Methods:

  • forward –

    Return this rank's bf16 (T, hidden) partial output (to be

Source code in vllm/models/inkling2/nvidia/attention.py
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
class Inkling2Attention(nn.Module, AttentionLayerBase):
    """Inkling2 attention for one decoder layer.

    Local layers project all of q/k/v from one input; full layers project the
    query side (q, r, gate, sink) from `x_q`, k from `x_k` and v from
    `x_v`, and use dynamic K/V convolutions and log-scaled q/r.
    """

    def __init__(
        self,
        config: Inkling2ModelConfig,
        is_local: bool,
        conv_state: InklingConvState,
        prefix: str,
    ) -> None:
        super().__init__()
        self.prefix = prefix
        self.is_local = is_local
        num_heads = (
            config.swa_num_attention_heads if is_local else config.num_attention_heads
        )
        num_kv_heads = (
            config.swa_num_key_value_heads if is_local else config.num_key_value_heads
        )
        self.head_dim = config.swa_head_dim if is_local else config.head_dim
        self.d_rel = config.d_rel
        tp_size = get_tensor_model_parallel_world_size()
        tp_rank = get_tensor_model_parallel_rank()
        assert num_heads % tp_size == 0 and num_kv_heads % tp_size == 0
        self.num_heads = num_heads // tp_size
        self.num_kv_heads = num_kv_heads // tp_size
        self.scaling = self.head_dim**-0.5
        self.sliding_window = config.sliding_window_size
        self.rel_extent = config.sliding_window_size if is_local else config.rel_extent
        self.window_size = (config.sliding_window_size - 1, 0) if is_local else (-1, -1)
        self.qk_clip = config.qk_l2_clip_threshold
        self.rel_clip = config.rel_l2_clip_threshold
        self.eps = config.rms_norm_eps
        assert config.use_value_norm_no_gamma

        q_size = self.num_heads * self.head_dim
        kv_size = self.num_kv_heads * self.head_dim
        # Query-side outputs first so full layers can project them in one GEMM.
        self.split_sizes = [
            q_size,
            self.num_heads * self.d_rel,
            q_size,
            self.num_heads,
            kv_size,
            kv_size,
        ]
        # Full layers project the query side alone; rounding its N up to 8
        # keeps the output rows 16-byte aligned for cuBLAS (the extra columns,
        # from the K rows, are discarded).
        q_side = sum(self.split_sizes[:4])
        self.q_side_splits = [*self.split_sizes[:4], -q_side % 8]
        pad_size = -sum(self.split_sizes) % 8
        if pad_size:
            self.split_sizes.append(pad_size)
        self.qkvr = MergedColumnParallelLinear(
            config.hidden_size,
            [size * tp_size for size in self.split_sizes],
            bias=False,
            prefix=f"{prefix}.qkvr",
        )
        self.wo_ud = RowParallelLinear(
            q_size * tp_size,
            config.hidden_size,
            bias=False,
            reduce_results=False,
            prefix=f"{prefix}.wo_ud",
        )
        self.rel_logits_proj = nn.Parameter(
            torch.empty(self.d_rel, self.rel_extent), requires_grad=False
        )
        self.q_scale = nn.Parameter(
            torch.empty(self.num_heads, self.head_dim), requires_grad=False
        )
        self.r_scale = nn.Parameter(
            torch.empty(self.num_heads, self.d_rel), requires_grad=False
        )
        for param in (self.q_scale, self.r_scale):
            set_weight_attrs(
                param,
                {
                    "weight_loader": lambda p, w: p.data.copy_(
                        w.narrow(0, tp_rank * p.shape[0], p.shape[0])
                    )
                },
            )

        self.conv_state = conv_state
        self.k_sconv, self.v_sconv = (
            Inkling2ShortConv(
                kv_size,
                config.sconv_kernel_size,
                conv_state,
                stream,
                dynamic_input_size=None if is_local else config.hidden_size,
                num_heads=self.num_kv_heads,
            )
            for stream in (K_STREAM, V_STREAM)
        )

        vllm_config = get_current_vllm_config()
        self.max_decode_query_len = max_decode_query_len(vllm_config)
        assert vllm_config.cache_config.cache_dtype in ("auto", "bfloat16")
        self.kv_cache = torch.tensor([])
        forward_context = vllm_config.compilation_config.static_forward_context
        if prefix in forward_context:
            raise ValueError(f"Duplicate layer name: {prefix}")
        forward_context[prefix] = self
        if vllm_config.kernel_config.enable_jit_warmup and use_sm100_kernels():
            _INKLING2_FA4_REL_ATTENTION_KERNEL.register_warmup()

    def process_weights_after_loading(self) -> None:
        self.rel_proj_shifted = shift_rel_proj(self.rel_logits_proj, self.is_local)

    def get_attn_backend(self) -> type[AttentionBackend]:
        return Inkling2AttentionBackend

    def get_kv_cache_config(self, vllm_config: VllmConfig) -> KVCacheLayerConfig:
        spec = AttentionSpec(
            block_size=vllm_config.cache_config.block_size,
            num_kv_heads=self.num_kv_heads,
            head_size=self.head_dim,
            dtype=vllm_config.model_config.dtype,
        )
        if self.is_local:
            return SlidingWindowManager.layer_config(
                spec, sliding_window=self.sliding_window
            )
        return FullAttentionManager.layer_config(spec)

    def _project(
        self, x_q: torch.Tensor, x_k: torch.Tensor, x_v: torch.Tensor
    ) -> list[torch.Tensor]:
        # ``linear`` on the weight bypasses the layer (and a LoRA wrapper's
        # forward), so the LoRA deltas are added here (no-op without LoRA).
        weight = self.qkvr.weight
        if self.is_local:
            projected = linear(x_q, weight)
            add_linear_lora(self.qkvr, projected, x_q, range(6))
            return list(projected.split(self.split_sizes, dim=-1)[:6])
        q_side, kv_size = sum(self.split_sizes[:4]), self.split_sizes[4]
        k_end = q_side + kv_size
        projected = linear(x_q, weight[: sum(self.q_side_splits)])
        k = linear(x_k, weight[q_side:k_end])
        v = linear(x_v, weight[k_end : k_end + kv_size])
        add_linear_lora(self.qkvr, projected, x_q, range(4))
        add_linear_lora(self.qkvr, k, x_k, [4])
        add_linear_lora(self.qkvr, v, x_v, [5])
        return [*projected.split(self.q_side_splits, dim=-1)[:4], k, v]

    def _split_kv_cache(self) -> tuple[torch.Tensor, torch.Tensor]:
        key_cache, value_cache = self.kv_cache.transpose(1, 2).split(
            self.head_dim, dim=-1
        )
        return (
            canonicalize_singleton_dim_strides(key_cache),
            canonicalize_singleton_dim_strides(value_cache),
        )

    def forward(
        self,
        positions: torch.Tensor,
        x_q: torch.Tensor,
        x_k: torch.Tensor | None = None,
        x_v: torch.Tensor | None = None,
        tau: torch.Tensor | None = None,
        out: torch.Tensor | None = None,
    ) -> torch.Tensor:
        """Return this rank's bf16 `(T, hidden)` partial output (to be
        all-reduced over TP), written to `out` if given.

        Local layers read q/k/v from `x_q`; full layers take `x_k`, `x_v` and
        the fp32 log-scaling `tau` for q/r.
        """
        if self.is_local:
            x_k = x_v = x_q
        assert x_k is not None and x_v is not None
        q, r, gate, sinks, k, v = self._project(x_q, x_k, x_v)
        output = torch.empty(gate.shape, dtype=q.dtype, device=q.device)
        self._attention(
            positions,
            q,
            r,
            gate,
            sinks,
            k,
            v,
            self.k_sconv.dynamic_taps(x_k),
            self.v_sconv.dynamic_taps(x_v),
            tau,
            output,
        )
        out = linear(output, self.wo_ud.weight, out)
        add_linear_lora(self.wo_ud, out, output)
        return out

    @eager_break_during_capture
    def _attention(
        self,
        positions: torch.Tensor,
        q: torch.Tensor,
        r: torch.Tensor,
        gate: torch.Tensor,
        sinks: torch.Tensor,
        k: torch.Tensor,
        v: torch.Tensor,
        k_dynamic: torch.Tensor | None,
        v_dynamic: torch.Tensor | None,
        tau: torch.Tensor | None,
        output: torch.Tensor,
    ) -> None:
        """Write the gated attention output to `output`.

        The kernel plan and the prologue's layout follow the batch's
        decode/prefill split, so this runs eagerly in piecewise CUDA graphs,
        which are captured on a dummy batch and replayed for any batch of the
        same token count.
        """
        num_tokens = q.shape[0]
        q = q.view(num_tokens, self.num_heads, self.head_dim)
        attn_metadata = get_forward_context().attn_metadata
        md = None
        if isinstance(attn_metadata, dict) and self.kv_cache.numel() > 0:
            md = cast(Inkling2AttentionMetadata, attn_metadata[self.prefix])
        num_decodes, num_decode_tokens, decode_splits = 0, 0, 0
        if md is not None:
            num_decodes, num_decode_tokens, decode_splits = self._plan_decode(
                md, num_tokens
            )
        clipped_q = q.new_empty(q.shape)
        # Sheared for tml_fa4 (see attention_prologue); the decode kernels
        # read the same layout.
        rel_logits = q.new_empty(
            (num_tokens + 128, self.num_heads, self.rel_extent + 256)
        )
        if md is not None:
            conv_md = conv_metadata(self.conv_state)
            assert conv_md is not None
            key_cache, value_cache = self._split_kv_cache()
            attention_prologue(
                q,
                r.view(num_tokens, self.num_heads, self.d_rel),
                k,
                v,
                self.q_scale,
                self.r_scale,
                tau,
                self.rel_proj_shifted,
                self.k_sconv.conv_weight,
                self.v_sconv.conv_weight,
                k_dynamic,
                v_dynamic,
                self.conv_state.kv_cache,
                positions,
                conv_md.block_table,
                conv_md.seq_idx,
                conv_md.slot_mapping,
                conv_md.query_start,
                key_cache,
                value_cache,
                md.slot_mapping,
                clipped_q,
                rel_logits,
                md.query_start_loc,
                md.seq_lens,
                clip_threshold=self.qk_clip,
                rel_threshold=self.rel_clip,
                norm_eps=self.eps,
            )
        if decode_splits:
            assert md is not None
            self._decode_attention(
                md,
                clipped_q[:num_decode_tokens],
                rel_logits,
                gate[:num_decode_tokens],
                sinks[:num_decode_tokens],
                output[:num_decode_tokens],
                decode_splits,
                num_decodes,
            )
        if num_decode_tokens < num_tokens:
            out = q.new_empty(
                (num_tokens - num_decode_tokens, self.num_heads, self.head_dim),
                dtype=torch.float32,
            )
            lse = q.new_empty((self.num_heads, out.shape[0]), dtype=torch.float32)
            if md is not None:
                num_splits, use_scheduler = plan_attention(
                    self.is_local,
                    md.query_lens_cpu[num_decodes:],
                    md.seq_lens_cpu[num_decodes:],
                    self.num_heads,
                    self.num_kv_heads,
                )
                self._fa4_attention(
                    md,
                    clipped_q[num_decode_tokens:],
                    rel_logits[num_decode_tokens:],
                    out,
                    lse,
                    num_splits,
                    use_scheduler,
                    num_decodes,
                )
            else:
                out.zero_()
                lse.zero_()
            gate_sink(
                out,
                gate[num_decode_tokens:],
                lse.t(),
                sinks[num_decode_tokens:],
                output[num_decode_tokens:],
            )

    def _plan_decode(
        self, md: FlashAttentionMetadata, num_tokens: int
    ) -> tuple[int, int, int]:
        """Return `(num_decodes, num_decode_tokens, num_splits)` for
        `rel_decode_attention`: the whole batch, or in a mixed batch the
        leading decode/verify requests."""
        num_reqs = md.seq_lens.shape[0]
        plan = partial(
            plan_decode_attention,
            self.is_local,
            num_heads=self.num_heads,
            num_kv_heads=self.num_kv_heads,
            rel_extent=self.rel_extent,
        )
        num_splits = plan(num_reqs=num_reqs, max_query_len=md.max_query_len)
        if num_splits:
            return num_reqs, num_tokens, num_splits
        num_decodes, num_decode_tokens = md.num_decode_reqs, md.num_decode_tokens
        if not 0 < num_decodes < num_reqs:
            return 0, 0, 0
        max_query_len = min(
            self.max_decode_query_len, num_decode_tokens - num_decodes + 1
        )
        num_splits = plan(num_reqs=num_decodes, max_query_len=max_query_len)
        if not num_splits:
            return 0, 0, 0
        return num_decodes, num_decode_tokens, num_splits

    def _decode_attention(
        self,
        md: FlashAttentionMetadata,
        q: torch.Tensor,
        rel_logits: torch.Tensor,
        gate: torch.Tensor,
        sinks: torch.Tensor,
        output: torch.Tensor,
        num_splits: int,
        num_reqs: int,
    ) -> None:
        key_cache, value_cache = self._split_kv_cache()
        mixed = num_reqs < md.seq_lens.shape[0]
        num_tokens = md.num_decode_tokens if mixed else md.num_actual_tokens
        max_query_len = md.max_query_len
        if mixed:
            max_query_len = min(self.max_decode_query_len, num_tokens - num_reqs + 1)
        rel_decode_attention(
            q,
            key_cache,
            value_cache,
            rel_logits,
            gate,
            sinks,
            output,
            block_table=md.block_table[:num_reqs],
            cache_seqlens=md.seq_lens[:num_reqs],
            cu_seqlens_q=md.query_start_loc[: num_reqs + 1],
            max_query_len=max_query_len,
            num_actual_tokens=num_tokens,
            softmax_scale=self.scaling,
            is_local=self.is_local,
            num_splits=num_splits,
        )

    def _fa4_attention(
        self,
        md: FlashAttentionMetadata,
        q: torch.Tensor,
        rel_logits: torch.Tensor,
        out: torch.Tensor,
        lse: torch.Tensor,
        num_splits: int,
        use_scheduler: bool,
        num_decodes: int,
    ) -> None:
        """FA4 for the requests after the first `num_decodes`."""
        num_decode_tokens = md.num_decode_tokens if num_decodes else 0
        nt = md.num_actual_tokens - num_decode_tokens
        cu_seqlens_q = md.query_start_loc[num_decodes:]
        if num_decodes:
            cu_seqlens_q = cu_seqlens_q - num_decode_tokens
        key_cache, value_cache = self._split_kv_cache()
        if not use_sm100_kernels():
            rel_attention(
                q[:nt],
                key_cache,
                value_cache,
                out,
                lse,
                rel_logits,
                block_table=md.block_table[num_decodes:],
                cache_seqlens=md.seq_lens[num_decodes:],
                cu_seqlens_q=cu_seqlens_q,
                max_query_len=md.max_query_len,
                softmax_scale=self.scaling,
                window=self.sliding_window if self.is_local else 0,
                num_splits=1,
                mode=MODE_OUT_LSE,
            )
            out[nt:].zero_()
            lse[:, nt:].zero_()
            return
        _INKLING2_FA4_REL_ATTENTION_KERNEL(
            q[:nt],
            key_cache,
            value_cache,
            block_table=md.block_table[num_decodes:],
            cache_seqlens=md.seq_lens[num_decodes:],
            cu_seqlens_q=cu_seqlens_q,
            max_seqlen_q=bucket_max_seqlen_q(md.max_query_len),
            softmax_scale=self.scaling,
            window_size=self.window_size,
            sheared_bias=rel_logits[: nt + 128],
            num_splits=num_splits,
            use_scheduler=use_scheduler,
            out=out[:nt],
            lse=lse[:, :nt],
        )
        out[nt:].zero_()
        lse[:, nt:].zero_()

_attention(positions, q, r, gate, sinks, k, v, k_dynamic, v_dynamic, tau, output)

Write the gated attention output to output.

The kernel plan and the prologue's layout follow the batch's decode/prefill split, so this runs eagerly in piecewise CUDA graphs, which are captured on a dummy batch and replayed for any batch of the same token count.

Source code in vllm/models/inkling2/nvidia/attention.py
@eager_break_during_capture
def _attention(
    self,
    positions: torch.Tensor,
    q: torch.Tensor,
    r: torch.Tensor,
    gate: torch.Tensor,
    sinks: torch.Tensor,
    k: torch.Tensor,
    v: torch.Tensor,
    k_dynamic: torch.Tensor | None,
    v_dynamic: torch.Tensor | None,
    tau: torch.Tensor | None,
    output: torch.Tensor,
) -> None:
    """Write the gated attention output to `output`.

    The kernel plan and the prologue's layout follow the batch's
    decode/prefill split, so this runs eagerly in piecewise CUDA graphs,
    which are captured on a dummy batch and replayed for any batch of the
    same token count.
    """
    num_tokens = q.shape[0]
    q = q.view(num_tokens, self.num_heads, self.head_dim)
    attn_metadata = get_forward_context().attn_metadata
    md = None
    if isinstance(attn_metadata, dict) and self.kv_cache.numel() > 0:
        md = cast(Inkling2AttentionMetadata, attn_metadata[self.prefix])
    num_decodes, num_decode_tokens, decode_splits = 0, 0, 0
    if md is not None:
        num_decodes, num_decode_tokens, decode_splits = self._plan_decode(
            md, num_tokens
        )
    clipped_q = q.new_empty(q.shape)
    # Sheared for tml_fa4 (see attention_prologue); the decode kernels
    # read the same layout.
    rel_logits = q.new_empty(
        (num_tokens + 128, self.num_heads, self.rel_extent + 256)
    )
    if md is not None:
        conv_md = conv_metadata(self.conv_state)
        assert conv_md is not None
        key_cache, value_cache = self._split_kv_cache()
        attention_prologue(
            q,
            r.view(num_tokens, self.num_heads, self.d_rel),
            k,
            v,
            self.q_scale,
            self.r_scale,
            tau,
            self.rel_proj_shifted,
            self.k_sconv.conv_weight,
            self.v_sconv.conv_weight,
            k_dynamic,
            v_dynamic,
            self.conv_state.kv_cache,
            positions,
            conv_md.block_table,
            conv_md.seq_idx,
            conv_md.slot_mapping,
            conv_md.query_start,
            key_cache,
            value_cache,
            md.slot_mapping,
            clipped_q,
            rel_logits,
            md.query_start_loc,
            md.seq_lens,
            clip_threshold=self.qk_clip,
            rel_threshold=self.rel_clip,
            norm_eps=self.eps,
        )
    if decode_splits:
        assert md is not None
        self._decode_attention(
            md,
            clipped_q[:num_decode_tokens],
            rel_logits,
            gate[:num_decode_tokens],
            sinks[:num_decode_tokens],
            output[:num_decode_tokens],
            decode_splits,
            num_decodes,
        )
    if num_decode_tokens < num_tokens:
        out = q.new_empty(
            (num_tokens - num_decode_tokens, self.num_heads, self.head_dim),
            dtype=torch.float32,
        )
        lse = q.new_empty((self.num_heads, out.shape[0]), dtype=torch.float32)
        if md is not None:
            num_splits, use_scheduler = plan_attention(
                self.is_local,
                md.query_lens_cpu[num_decodes:],
                md.seq_lens_cpu[num_decodes:],
                self.num_heads,
                self.num_kv_heads,
            )
            self._fa4_attention(
                md,
                clipped_q[num_decode_tokens:],
                rel_logits[num_decode_tokens:],
                out,
                lse,
                num_splits,
                use_scheduler,
                num_decodes,
            )
        else:
            out.zero_()
            lse.zero_()
        gate_sink(
            out,
            gate[num_decode_tokens:],
            lse.t(),
            sinks[num_decode_tokens:],
            output[num_decode_tokens:],
        )

_fa4_attention(md, q, rel_logits, out, lse, num_splits, use_scheduler, num_decodes)

FA4 for the requests after the first num_decodes.

Source code in vllm/models/inkling2/nvidia/attention.py
def _fa4_attention(
    self,
    md: FlashAttentionMetadata,
    q: torch.Tensor,
    rel_logits: torch.Tensor,
    out: torch.Tensor,
    lse: torch.Tensor,
    num_splits: int,
    use_scheduler: bool,
    num_decodes: int,
) -> None:
    """FA4 for the requests after the first `num_decodes`."""
    num_decode_tokens = md.num_decode_tokens if num_decodes else 0
    nt = md.num_actual_tokens - num_decode_tokens
    cu_seqlens_q = md.query_start_loc[num_decodes:]
    if num_decodes:
        cu_seqlens_q = cu_seqlens_q - num_decode_tokens
    key_cache, value_cache = self._split_kv_cache()
    if not use_sm100_kernels():
        rel_attention(
            q[:nt],
            key_cache,
            value_cache,
            out,
            lse,
            rel_logits,
            block_table=md.block_table[num_decodes:],
            cache_seqlens=md.seq_lens[num_decodes:],
            cu_seqlens_q=cu_seqlens_q,
            max_query_len=md.max_query_len,
            softmax_scale=self.scaling,
            window=self.sliding_window if self.is_local else 0,
            num_splits=1,
            mode=MODE_OUT_LSE,
        )
        out[nt:].zero_()
        lse[:, nt:].zero_()
        return
    _INKLING2_FA4_REL_ATTENTION_KERNEL(
        q[:nt],
        key_cache,
        value_cache,
        block_table=md.block_table[num_decodes:],
        cache_seqlens=md.seq_lens[num_decodes:],
        cu_seqlens_q=cu_seqlens_q,
        max_seqlen_q=bucket_max_seqlen_q(md.max_query_len),
        softmax_scale=self.scaling,
        window_size=self.window_size,
        sheared_bias=rel_logits[: nt + 128],
        num_splits=num_splits,
        use_scheduler=use_scheduler,
        out=out[:nt],
        lse=lse[:, :nt],
    )
    out[nt:].zero_()
    lse[:, nt:].zero_()

_plan_decode(md, num_tokens)

Return (num_decodes, num_decode_tokens, num_splits) for rel_decode_attention: the whole batch, or in a mixed batch the leading decode/verify requests.

Source code in vllm/models/inkling2/nvidia/attention.py
def _plan_decode(
    self, md: FlashAttentionMetadata, num_tokens: int
) -> tuple[int, int, int]:
    """Return `(num_decodes, num_decode_tokens, num_splits)` for
    `rel_decode_attention`: the whole batch, or in a mixed batch the
    leading decode/verify requests."""
    num_reqs = md.seq_lens.shape[0]
    plan = partial(
        plan_decode_attention,
        self.is_local,
        num_heads=self.num_heads,
        num_kv_heads=self.num_kv_heads,
        rel_extent=self.rel_extent,
    )
    num_splits = plan(num_reqs=num_reqs, max_query_len=md.max_query_len)
    if num_splits:
        return num_reqs, num_tokens, num_splits
    num_decodes, num_decode_tokens = md.num_decode_reqs, md.num_decode_tokens
    if not 0 < num_decodes < num_reqs:
        return 0, 0, 0
    max_query_len = min(
        self.max_decode_query_len, num_decode_tokens - num_decodes + 1
    )
    num_splits = plan(num_reqs=num_decodes, max_query_len=max_query_len)
    if not num_splits:
        return 0, 0, 0
    return num_decodes, num_decode_tokens, num_splits

forward(positions, x_q, x_k=None, x_v=None, tau=None, out=None)

Return this rank's bf16 (T, hidden) partial output (to be all-reduced over TP), written to out if given.

Local layers read q/k/v from x_q; full layers take x_k, x_v and the fp32 log-scaling tau for q/r.

Source code in vllm/models/inkling2/nvidia/attention.py
def forward(
    self,
    positions: torch.Tensor,
    x_q: torch.Tensor,
    x_k: torch.Tensor | None = None,
    x_v: torch.Tensor | None = None,
    tau: torch.Tensor | None = None,
    out: torch.Tensor | None = None,
) -> torch.Tensor:
    """Return this rank's bf16 `(T, hidden)` partial output (to be
    all-reduced over TP), written to `out` if given.

    Local layers read q/k/v from `x_q`; full layers take `x_k`, `x_v` and
    the fp32 log-scaling `tau` for q/r.
    """
    if self.is_local:
        x_k = x_v = x_q
    assert x_k is not None and x_v is not None
    q, r, gate, sinks, k, v = self._project(x_q, x_k, x_v)
    output = torch.empty(gate.shape, dtype=q.dtype, device=q.device)
    self._attention(
        positions,
        q,
        r,
        gate,
        sinks,
        k,
        v,
        self.k_sconv.dynamic_taps(x_k),
        self.v_sconv.dynamic_taps(x_v),
        tau,
        output,
    )
    out = linear(output, self.wo_ud.weight, out)
    add_linear_lora(self.wo_ud, out, output)
    return out

Inkling2AttentionMetadataBuilder

Bases: FlashAttentionMetadataBuilder

Orders decode/verify requests first and records the split, so that a mixed batch runs its decode part on rel_decode_attention.

Source code in vllm/models/inkling2/nvidia/attention.py
class Inkling2AttentionMetadataBuilder(FlashAttentionMetadataBuilder):
    """Orders decode/verify requests first and records the split, so that a
    mixed batch runs its decode part on `rel_decode_attention`."""

    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)
        self._init_reorder_batch_threshold(1, supports_spec_as_decode=True)

    def build(
        self,
        common_prefix_len: int,
        common_attn_metadata: CommonAttentionMetadata,
        fast_build: bool = False,
    ) -> Inkling2AttentionMetadata:
        cm = common_attn_metadata
        assert cm.seq_lens_cpu_upper_bound is not None
        md = Inkling2AttentionMetadata(
            **vars(super().build(common_prefix_len, cm, fast_build)),
            query_lens_cpu=cm.query_start_loc_cpu.diff().numpy(),
            seq_lens_cpu=cm.seq_lens_cpu_upper_bound.numpy(),
        )
        assert self.reorder_batch_threshold is not None
        (
            md.num_decode_reqs,
            md.num_prefill_reqs,
            md.num_decode_tokens,
            md.num_prefill_tokens,
        ) = split_decodes_and_prefills(
            common_attn_metadata, decode_threshold=self.reorder_batch_threshold
        )
        return md