File size: 39,917 Bytes
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9183672
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9183672
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9183672
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9183672
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9183672
65e1c10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
"""Capture Qwen and DeepSeek operator boundaries during actual SGLang requests."""

import contextvars
import functools
import inspect
import json
import math
import os
from pathlib import Path

import torch


_CONTEXT = contextvars.ContextVar("llm_capture_context", default=None)


def _bind(function, args, kwargs):
    bound = inspect.signature(function).bind(*args, **kwargs)
    bound.apply_defaults()
    return bound.arguments


def _receipt(operation, **extra):
    context = _CONTEXT.get()
    return dict(context["request"], step=context["step"], operation=operation,
                scheduler_mode=context["mode"], scheduler_sequence_lengths=context["lengths"],
                **extra)


def _compact_pages(cache, table, lengths):
    """Copy every reachable physical page and preserve its complete contents.

    Only allocator pages outside every request's page table are omitted. The
    original page IDs are returned as provenance; no token values are changed.
    """
    page_size = cache.shape[1]
    columns = (int(lengths.max()) + page_size - 1) // page_size
    table = table[:, :columns].long()
    valid = torch.arange(columns, device=table.device)[None] < ((lengths + page_size - 1) // page_size)[:, None]
    selected = torch.unique(table[valid], sorted=True)
    if not selected.numel() or selected.min() < 0 or selected.max() >= cache.shape[0]:
        raise ValueError("Invalid live cache page table")
    mapped = torch.full_like(table, -1, dtype=torch.int32)
    mapped[valid] = torch.searchsorted(selected, table[valid]).to(torch.int32)
    return cache.index_select(0, selected), mapped, selected.to(torch.int32)


def _install_context(model_class):
    original_forward = model_class.forward
    counters = {}

    @functools.wraps(original_forward)
    def forward(self, *args, **kwargs):
        request_file = Path(os.environ["INFERENCE_CAPTURE_REQUEST"])
        if not request_file.is_file():
            return original_forward(self, *args, **kwargs)
        request = json.loads(request_file.read_text())
        bound = _bind(original_forward, (self, *args), kwargs)
        batch = bound["forward_batch"]
        mode = "decode" if batch.forward_mode.is_decode() else "prefill"
        key = (request["request_id"], mode)
        step = counters.get(key, 0)
        counters[key] = step + 1
        selected = mode == "prefill" or step in request.get("capture_decode_steps", [0, 1, 3, 15])
        if request.get("overlap_profile") and mode == "decode":
            batch_key = (request["request_id"], "decode_batch", len(batch.seq_lens))
            batch_step = counters.get(batch_key, 0)
            counters[batch_key] = batch_step + 1
            selected = batch_step < 4
        token = _CONTEXT.set({"request": request, "step": step, "mode": mode,
                              "selected": selected, "lengths": batch.seq_lens.tolist(),
                              "tokens": getattr(batch, "extend_num_tokens", None) or len(batch.seq_lens),
                              "prefix_lengths": getattr(batch, "extend_prefix_lens_cpu", None)})
        try:
            return original_forward(self, *args, **kwargs)
        finally:
            _CONTEXT.reset(token)

    model_class.forward = forward


def install_qwen(writer):
    from sglang.srt.models.qwen4_exp import Qwen4ExpForConditionalGeneration
    from sglang.kernels.ops.attention.fla import chunk
    from sglang.srt.layers.attention.linear.kernels.gdn_triton import TritonGDNKernel
    from sglang.srt.layers.attention.qsa.qsa_indexer import QSAIndexer
    from sglang.srt.layers.attention.qwen_sparse_attn_backend import QwenSparseAttnBackend

    _install_context(Qwen4ExpForConditionalGeneration)
    original_chunk = chunk.chunk_gated_delta_rule_fwd

    @functools.wraps(original_chunk)
    def prefill(*args, **kwargs):
        context = _CONTEXT.get()
        if context is None or not context["selected"]:
            return original_chunk(*args, **kwargs)
        values = _bind(original_chunk, args, kwargs)
        q, k, v = (values[key] for key in ("q", "k", "v"))
        indices = values["initial_state_indices"].long()
        state_pool = values["initial_state"]
        bounds = values["cu_seqlens"].tolist()
        pending = []
        name = "gated_delta_rule_prefill_h48_dk128_dv128"
        for sample, (start, end) in enumerate(zip(bounds, bounds[1:])):
            prefix = (context["prefix_lengths"] or [0] * len(indices))[sample]
            provenance = _receipt("chunk_gated_delta_rule_fwd after engine L2 normalization",
                                  sample_index=sample, prefix_tokens=prefix, selection_step=0,
                                  variant=f"tokens_{end-start}_cached_{bool(prefix)}",
                                  adapter="Repeat shared Q/K heads; transpose the engine state; widen BF16 beta without rounding.")
            if end == start or not writer.wants(name, provenance):
                continue
            repeats = v.shape[2] // q.shape[2]
            inputs = dict(Q=q[:, start:end].repeat_interleave(repeats, 2),
                          K=k[:, start:end].repeat_interleave(repeats, 2),
                          V=v[:, start:end].clone(), beta=values["beta"][:, start:end].float().clone(),
                          g=values["g"][:, start:end].float().clone(),
                          S0=state_pool[indices[sample:sample+1]].transpose(-1, -2).clone(),
                          q_scale=float(values["scale"]))
            pending.append((sample, start, end, inputs, provenance))
        result = original_chunk(*args, **kwargs)
        for sample, start, end, inputs, provenance in pending:
            outputs = {"O": result[1][:, start:end],
                       "S_final": state_pool[indices[sample:sample+1]].transpose(-1, -2)}
            writer.write(name, inputs, outputs, provenance)
        return result

    chunk.chunk_gated_delta_rule_fwd = prefill
    original_decode = TritonGDNKernel.packed_decode

    @functools.wraps(original_decode)
    def decode(self, *args, **kwargs):
        context = _CONTEXT.get()
        if context is None or not context["selected"]:
            return original_decode(self, *args, **kwargs)
        provenance = _receipt("TritonGDNKernel.packed_decode", layer_id=0,
                              adapter="Split actual packed QKV views; transpose the selected pre-update state.")
        name = "gated_delta_rule_decode_h48_dk128_dv128"
        if not writer.wants(name, provenance):
            return original_decode(self, *args, **kwargs)
        values = _bind(original_decode, (self, *args), kwargs)
        packed = values["mixed_qkv"]
        batch = packed.shape[0]
        q, k, v = packed.split((16*128, 16*128, 48*128), dim=-1)
        indices = values["cache_indices"].long()
        pool = values["ssm_states"]
        inputs = dict(Q=q.reshape(batch, 1, 16, 128).clone(),
                      K=k.reshape(batch, 1, 16, 128).clone(),
                      V=v.reshape(batch, 1, 48, 128).clone(),
                      a=values["a"].reshape(batch, 1, 48).clone(),
                      b=values["b"].reshape(batch, 1, 48).clone(),
                      A_log=values["A_log"].float().clone(), dt_bias=values["dt_bias"].clone(),
                      S0=pool[indices].transpose(-1, -2).clone(), q_scale=float(values["scale"]))
        result = original_decode(self, *args, **kwargs)
        writer.write(name, inputs, {"O": result.transpose(0, 1),
                                   "S_final": pool[indices].transpose(-1, -2)}, provenance)
        return result

    TritonGDNKernel.packed_decode = decode
    original_index = QSAIndexer.select_decode_tokens

    @functools.wraps(original_index)
    def index(self, *args, **kwargs):
        context = _CONTEXT.get()
        if context is None or not context["selected"]:
            return original_index(self, *args, **kwargs)
        provenance = _receipt("QSAIndexer.select_decode_tokens", layer_id=self.layer_id)
        name = "qsa_index_topk_decode_qwen38_h4_d128_topk512_c4"
        if not writer.wants(name, provenance):
            return original_index(self, *args, **kwargs)
        values = _bind(original_index, (self, *args), kwargs)
        cache = values["compressed_cache"]
        lengths = values["compressed_lengths"].to(torch.int32)
        pages, table, physical = _compact_pages(cache, values["compressed_page_table"], lengths)
        provenance.update(allocated_cache_shape=list(cache.shape), original_physical_page_ids=writer.tensor(physical, name),
                          adapter="Retain all live pages byte-for-byte and remap their page IDs; omit unreachable allocator pages.")
        query = values["q"]
        if query.shape[1] != self.index_n_heads:
            if torch.count_nonzero(query[:, self.index_n_heads:]):
                raise ValueError("QSA padded query heads are not zero")
            provenance.update(padded_query=writer.tensor(query, name),
                              query_adapter="Remove verified zero query heads inserted for the backend's eight-head tile.")
            query = query[:, :self.index_n_heads]
        inputs = dict(Q_idx=query.clone(), Kc_pages=pages, page_table=table,
                      num_complete_blocks=lengths.clone())
        result = original_index(self, *args, **kwargs)
        selected = result if values["defer_expansion"] else result[:, :2048:4] // 4
        provenance.update(engine_block_ids=writer.tensor(selected, name),
                          output_adapter="Serialize the engine's selected set in increasing logical-ID order; preserve membership and -1 suffix padding.")
        ordered = torch.full_like(selected, -1, dtype=torch.int32)
        for row in range(selected.shape[0]):
            ids = selected[row][selected[row] >= 0].long().sort().values
            ordered[row, :ids.numel()] = ids.to(torch.int32)
        writer.write(name, inputs, ordered, provenance)
        return result

    QSAIndexer.select_decode_tokens = index
    original_attention = QwenSparseAttnBackend.forward_decode

    @functools.wraps(original_attention)
    def attention(self, *args, **kwargs):
        context = _CONTEXT.get()
        if context is None or not context["selected"]:
            return original_attention(self, *args, **kwargs)
        values = _bind(original_attention, (self, *args), kwargs)
        layer, batch = values["layer"], values["forward_batch"]
        provenance = _receipt("QwenSparseAttnBackend.forward_decode", layer_id=layer.layer_id)
        name = "qsa_sparse_gqa_decode_qwen38_h24_kv2_d256_topk512_c4"
        if not writer.wants(name, provenance):
            return original_attention(self, *args, **kwargs)
        query = values["q"].reshape(-1, 24, 256).clone()
        selected = values["topk_indices"].clone()
        selected = selected if selected.shape[1] == 512 else selected[:, :2048:4] // 4
        result = original_attention(self, *args, **kwargs)
        pool = self.token_to_kv_pool
        key = pool.get_key_buffer(layer.layer_id)
        value = pool.get_value_buffer(layer.layer_id)
        page_size = pool.qsa_compressed_page_size * self.compress_ratio
        keys = key.reshape(-1, page_size, 2, 256)
        values_cache = value.reshape_as(keys)
        lengths = batch.seq_lens.to(torch.int32)
        rows = self.req_to_token_pool.req_to_token[batch.req_pool_indices.long()]
        table = rows[:, ::page_size] // page_size
        pages, table, physical = _compact_pages(keys, table, lengths)
        provenance.update(allocated_cache_shape=list(keys.shape), original_physical_page_ids=writer.tensor(physical, name),
                          adapter="Snapshot after the current-token KV write; retain every live page and remap physical IDs.")
        inputs = dict(Q=query, K_pages=pages, V_pages=values_cache.index_select(0, physical.long()),
                      page_table=table, block_ids=selected.to(torch.int32), context_lens=lengths.clone())
        writer.write(name, inputs, result.reshape(-1, 24, 256), provenance)
        return result

    QwenSparseAttnBackend.forward_decode = attention


def install_deepseek(writer):
    """Capture real EP shards and reconstruct complete logical operators."""
    import torch.distributed as dist
    from sglang.srt.models.deepseek_v4 import DeepseekV4ForCausalLM
    from sglang.srt.models import deepseek_v2
    from sglang.srt.layers import deep_gemm_wrapper
    from sglang.srt.layers.moe.moe_runner.deep_gemm import DeepGemmMoeQuantInfo
    from sgl_kernel import flash_mla

    original_recipes = DeepGemmMoeQuantInfo.scale_recipes

    @functools.wraps(original_recipes)
    def scale_recipes(self, *, activation_block_size, hidden_size, activation_scale_width):
        # The pinned engine's FP4 branch hardcodes group 128 even when its
        # standard dispatcher actually quantizes activations in groups of 32.
        # Pass the dispatcher's explicit metadata; leave all tensor bytes intact.
        if self.is_fp4_experts and not self.use_mxfp8:
            group = activation_block_size or 128
            if (hidden_size + group * 4 - 1) // (group * 4) != activation_scale_width:
                raise ValueError("FP4 expert activation metadata disagrees with packed scale width")
            return (1, group), (1, 32)
        return original_recipes(self, activation_block_size=activation_block_size,
                                hidden_size=hidden_size, activation_scale_width=activation_scale_width)

    DeepGemmMoeQuantInfo.scale_recipes = scale_recipes
    _install_context(DeepseekV4ForCausalLM)
    captured = set()
    weight_cache = {}

    def selected(name, provenance):
        return name in writer.enabled and writer._selection_key(name, provenance) not in captured

    def mark(name, provenance):
        captured.add(writer._selection_key(name, provenance))

    def gather(value, axis=0):
        value = value.contiguous()
        wire = value.view(torch.uint8) if value.dtype == torch.float8_e4m3fn else value
        lengths = [None] * dist.get_world_size()
        dist.all_gather_object(lengths, wire.shape[axis])
        shape = list(wire.shape)
        shape[axis] = max(lengths)
        padded = torch.zeros(shape, dtype=wire.dtype, device=wire.device)
        padded.narrow(axis, 0, wire.shape[axis]).copy_(wire)
        parts = [torch.empty_like(padded) for _ in lengths]
        dist.all_gather(parts, padded)
        if dist.get_rank() != 0:
            return None
        result = torch.cat([part.narrow(axis, 0, length).cpu() for part, length in zip(parts, lengths)], dim=axis)
        return result.view(value.dtype) if wire.dtype != value.dtype else result

    def scales(value, groups, source_group_size=32):
        if value.dtype == torch.int32:
            result = value.contiguous().view(torch.int8)
        elif value.dtype in (torch.uint8, torch.int8, torch.float8_e8m0fnu):
            result = value.contiguous().view(torch.int8)
        else:
            exponent = torch.log2(value.float())
            if not torch.equal(exponent, exponent.round()):
                raise ValueError("Activation scales are not exact powers of two")
            result = (exponent.to(torch.int32) + 127).to(torch.uint8).view(torch.int8)
        source_groups = groups * 32 // source_group_size
        if source_group_size % 32 or result.shape[-1] < source_groups:
            raise ValueError("Unexpected quantization scale width")
        # Packed int32 scales may include padding bytes in their final word.
        return result[..., :source_groups].repeat_interleave(source_group_size // 32, -1)

    original_gemm = deep_gemm_wrapper.grouped_gemm_nt_f8f8bf16_contig

    @functools.wraps(original_gemm)
    def gemm(lhs, rhs, out, m_indices, *args, **kwargs):
        context = _CONTEXT.get()
        if context is None or not context["selected"] or rhs[0].dtype not in (torch.uint8, torch.int8):
            return original_gemm(lhs, rhs, out, m_indices, *args, **kwargs)
        local_experts, n, packed_k = rhs[0].shape
        k = lhs[0].shape[-1]
        if local_experts * dist.get_world_size() != 384 or k != packed_k * 2:
            raise ValueError("Capture requires complete expert shards without tensor-sharded expert dimensions")
        name = f"grouped_gemm_fp8_fp4_e384_n{n}_k{k}_g32"
        provenance = _receipt("SGLang DeepGEMM grouped GEMM", selection_step=0 if context["mode"] == "prefill" else context["step"],
                              variant=f"{context['mode']}_{context['tokens']}_cached_{any(context['prefix_lengths'] or [])}",
                              adapter="Gather all expert shards; discard rows marked -1 by the engine; preserve group-32 activation scales or expand each actual group-128 scale into four identical bytes.")
        if name not in writer.definitions or not selected(name, provenance):
            return original_gemm(lhs, rhs, out, m_indices, *args, **kwargs)
        valid = (m_indices >= 0) & (m_indices < local_experts)
        a = lhs[0][valid].clone()
        recipe = kwargs.get("recipe_a", args[0] if args else None) or (1, 128)
        sa = scales(lhs[1], k // 32, recipe[1])[valid].clone()
        ids = m_indices[valid].to(torch.int32) + dist.get_rank() * local_experts
        result = original_gemm(lhs, rhs, out, m_indices, *args, **kwargs)
        y = out[valid].clone()
        a, sa, ids, y = (gather(t) for t in (a, sa, ids, y))
        weight_key = (rhs[0].data_ptr(), n, k)
        if weight_key not in weight_cache:
            weight_cache[weight_key] = (gather(rhs[0].view(torch.int8)), gather(scales(rhs[1], k // 32)))
        if dist.get_rank() == 0:
            weight, sw = weight_cache[weight_key]
            order = ids.argsort(stable=True)
            inputs = dict(Aq=a[order], Wq_packed=weight, scale_A=sa[order], scale_W=sw, expert_id=ids[order])
            writer.write(name, inputs, y[order], provenance)
            if n == 4608:
                for offset, label in ((0, "gate"),):
                    split_name = "grouped_gemm_fp8_fp4_e384_n2304_k5120_g32"
                    split = dict(inputs, Wq_packed=weight[:, offset:offset+2304], scale_W=sw[:, offset:offset+2304])
                    writer.write(split_name, split, y[order, offset:offset+2304],
                                 dict(provenance, variant=provenance["variant"] + "_" + label,
                                      output_adapter="Exact gate/up slice of the executed fused projection."))
        mark(name, provenance)
        return result

    deep_gemm_wrapper.grouped_gemm_nt_f8f8bf16_contig = gemm
    original_gate = deepseek_v2.MoEGate.forward

    @functools.wraps(original_gate)
    def gate(self, hidden_states, *args, **kwargs):
        context = _CONTEXT.get()
        if ("moe_router_gemm_topk_deepseek41_d5120_e384_topk6" in writer.enabled
                and context is not None and context["selected"] and dist.get_rank() == 0
                and self.e_score_correction_bias is not None):
            context["gate_input"] = (self, hidden_states.detach().clone())
        return original_gate(self, hidden_states, *args, **kwargs)

    deepseek_v2.MoEGate.forward = gate
    original_topk = deepseek_v2.vision_topk

    @functools.wraps(original_topk)
    def topk(moe, logits, input_ids, *args, **kwargs):
        result = original_topk(moe, logits, input_ids, *args, **kwargs)
        context = _CONTEXT.get()
        if context is None or not context["selected"] or dist.get_rank() != 0:
            return result
        name = "moe_router_gemm_topk_deepseek41_d5120_e384_topk6"
        provenance = _receipt("MoEGate.forward followed by vision_topk", layer_id=moe.layer_id,
                              selection_step=0 if context["mode"] == "prefill" else context["step"],
                              variant=f"{context['mode']}_{logits.shape[0]}")
        if not writer.wants(name, provenance):
            return result
        module, x = context.pop("gate_input")
        if module is not moe.gate:
            raise ValueError("Router input and output came from different layers")
        mask = torch.zeros(x.shape[0], dtype=torch.bool, device=x.device) if input_ids is None else input_ids == moe.config.image_token_id
        config = moe.topk.topk_config
        inputs = dict(X=x, W=module.weight, bias_text=module.e_score_correction_bias,
                      bias_image=module.e_score_correction_bias_vl, is_image_token=mask,
                      routed_scale=float(config.routed_scaling_factor))
        weights = result.topk_weights
        if not config.apply_routed_scaling_factor_on_output:
            weights = weights * config.routed_scaling_factor
            provenance["output_adapter"] = "Apply the engine's deferred routing scale to its selected weights."
        provenance["engine_expert_ids"] = writer.tensor(result.topk_ids.to(torch.int64), name)
        provenance["engine_expert_weights"] = writer.tensor(weights.float(), name)
        provenance["selection_order"] = "Serialize the unchanged selected expert set by increasing expert ID; permute the actual weights with their IDs."
        order = result.topk_ids.argsort(dim=-1)
        writer.write(name, inputs, {"expert_ids": result.topk_ids.gather(1, order).to(torch.int64),
                                   "expert_weights": weights.gather(1, order).float()}, provenance)
        return result

    deepseek_v2.vision_topk = topk
    original_mla = flash_mla.flash_mla_with_kvcache

    @functools.wraps(original_mla)
    def mla(*args, **kwargs):
        context = _CONTEXT.get()
        if context is None or not context["selected"] or context["mode"] != "decode":
            return original_mla(*args, **kwargs)
        values = _bind(original_mla, args, kwargs)
        extra = values.get("extra_k_cache")
        if extra is None or extra.shape[-1] != 288:
            return original_mla(*args, **kwargs)
        name = "mixed_mla_decode_deepseek41_h64_d512_k8128_k4512"
        provenance = _receipt("flash_mla_with_kvcache mixed FP8/FP4", adapter="Gather real query heads from all tensor-parallel ranks; preserve all referenced physical pages and remap indices.")
        if not selected(name, provenance):
            return original_mla(*args, **kwargs)
        heads = 64 // dist.get_world_size()
        query = gather(values["q"][..., :heads, :].clone(), axis=2)
        sink = gather(values["attn_sink"][:heads].clone())
        inputs = None
        if dist.get_rank() == 0:
            inputs = dict(Q=query, attn_sink=sink.float(), sm_scale=float(values["softmax_scale"]))
            for suffix, cache, indices, lengths in (("8", values["k_cache"], values["indices"], values["topk_length"]),
                                                    ("4", extra, values["extra_indices_in_kvcache"], values["extra_topk_length"])):
                indices = indices.clone().to(torch.int32)
                if lengths is not None:
                    indices.masked_fill_(torch.arange(indices.shape[-1], device=indices.device) >= lengths.reshape(-1, 1, 1), -1)
                valid = indices >= 0
                physical = torch.unique(indices[valid].long() // cache.shape[1], sorted=True)
                remapped = indices.clone()
                remapped[valid] = (torch.searchsorted(physical, indices[valid].long() // cache.shape[1]) * cache.shape[1] + indices[valid] % cache.shape[1]).to(torch.int32)
                inputs["KV" + suffix] = cache.index_select(0, physical).view(torch.int8).clone()
                inputs["indices" + suffix] = remapped
                provenance["physical_pages_" + suffix] = writer.tensor(physical, name)
                provenance["allocated_cache_" + suffix] = list(cache.shape)
        result = original_mla(*args, **kwargs)
        output = gather(result[0][..., :heads, :].clone(), axis=2)
        if dist.get_rank() == 0:
            writer.write(name, inputs, output, provenance)
        mark(name, provenance)
        return result

    flash_mla.flash_mla_with_kvcache = mla
    from sglang.srt.layers.attention.deepseek_v4_backend import DeepseekV4AttnBackend
    original_prefill = DeepseekV4AttnBackend._forward_prefill_sparse

    @functools.wraps(original_prefill)
    def prefill_context(self, *args, **kwargs):
        context = _CONTEXT.get()
        if context is None:
            return original_prefill(self, *args, **kwargs)
        values = _bind(original_prefill, (self, *args), kwargs)
        previous = context.get("mla_compress_ratio")
        context["mla_compress_ratio"] = values["compress_ratio"]
        try:
            return original_prefill(self, *args, **kwargs)
        finally:
            context["mla_compress_ratio"] = previous

    DeepseekV4AttnBackend._forward_prefill_sparse = prefill_context
    original_sparse = flash_mla.flash_mla_sparse_fwd

    @functools.wraps(original_sparse)
    def sparse_prefill(*args, **kwargs):
        context = _CONTEXT.get()
        if context is None or not context["selected"] or context["mode"] != "prefill":
            return original_sparse(*args, **kwargs)
        values = _bind(original_sparse, args, kwargs)
        q, kv, indices = (values[key] for key in ("q", "kv", "indices"))
        name = f"sparse_mla_prefill_h64_d512_k{indices.shape[-1]}"
        provenance = _receipt(
            "sgl_kernel.flash_mla.flash_mla_sparse_fwd", selection_step=0,
            variant=f"rows_{q.shape[0]}_compression_{context.get('mla_compress_ratio')}_cached_{any(context['prefix_lengths'] or [])}",
            compression_ratio=context.get("mla_compress_ratio"),
            adapter="Gather all logical query heads and outputs from tensor-parallel ranks; retain the complete BF16 workspace and original sparse indices.")
        if not selected(name, provenance):
            return original_sparse(*args, **kwargs)
        heads = 64 // dist.get_world_size()
        if q.shape[1] < heads or values["d_v"] != 512:
            raise ValueError("Unexpected DeepSeek sparse prefill dimensions")
        query = gather(q[:, :heads].clone(), axis=1)
        sink = gather(values["attn_sink"][:heads].clone())
        inputs = None
        if dist.get_rank() == 0:
            lengths = values["topk_length"]
            if lengths is None:
                lengths = torch.full((q.shape[0],), indices.shape[-1], dtype=torch.int32, device=q.device)
            inputs = dict(Q=query, KV=kv.clone(), indices=indices.clone(),
                          topk_length=lengths.clone(), attn_sink=sink.float(),
                          sm_scale=float(values["sm_scale"]))
        result = original_sparse(*args, **kwargs)
        output = gather(result[0][:, :heads].clone(), axis=1)
        if dist.get_rank() == 0:
            writer.write(name, inputs, output, provenance)
        mark(name, provenance)
        return result

    flash_mla.flash_mla_sparse_fwd = sparse_prefill


def make_input_ids(profile, tokenizer):
    """Reconstruct anonymized blocks from an explicitly authored code corpus."""
    import hashlib

    corpus = """User: Inspect a small Python service and add unit tests for its cache.
Assistant: I will read the implementation, check boundary cases, and test the change.
Tool output: class Cache: stores a mapping from keys to values and expiration times.
def lookup(cache, key, now):
    entry = cache.get(key)
    if entry is None or entry.expires_at <= now:
        return None
    return entry.value
Test cases: an absent key returns None; a valid key returns its value; expired
entries return None; replacing an entry updates its deadline. Use a controlled
clock so tests do not sleep. Keep the public interface unchanged.
Tool output: three tests passed. One test failed at the expiration boundary.
Assistant: The deadline comparison must include equality. I will fix that branch
and rerun the affected tests. The change only touches the lookup implementation.
User: Also check concurrent requests, empty strings, and repeated replacement.
"""
    tokens = tokenizer.encode(corpus, add_special_tokens=False)
    tokens = tokens * (1 + profile['block_size'] // len(tokens))
    result = []
    for block in profile['hash_ids']:
        digest = hashlib.sha256(f"20261014:{profile['session_id']}:{block}".encode()).digest()
        start = int.from_bytes(digest[:8], 'little') % len(tokens)
        result.extend(tokens[(start + offset) % len(tokens)] for offset in range(profile['block_size']))
    if len(result) != profile['input_tokens']:
        raise ValueError('Recorded hash blocks do not tile the complete input')
    return result


def main():
    import argparse
    import hashlib
    import importlib.metadata
    import signal
    import subprocess
    import time
    import requests
    import concurrent.futures
    from transformers import AutoTokenizer

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--model-path', type=Path, required=True)
    parser.add_argument('--kind', choices=['qwen-next', 'deepseek41'], default='qwen-next')
    parser.add_argument('--output-root', type=Path, required=True)
    parser.add_argument('--case', action='append', default=[])
    parser.add_argument('--max-output-tokens', type=int)
    parser.add_argument('--port', type=int, default=30000)
    args = parser.parse_args()
    root = args.output_root.resolve()
    results = root / 'results'
    results.mkdir(parents=True, exist_ok=True)
    scripts = Path(__file__).resolve().parent
    fixture = json.loads((scripts / 'agentx_shapes.json').read_text())
    tokenizer = AutoTokenizer.from_pretrained(str(args.model_path))
    selected = args.case or ['short_request', 'cold_main', '256k_context_p10',
                             '256k_context_p50', '256k_context_p90', '256k_context_p99',
                             'subagent_typical', 'auxiliary_typical', 'fully_reused', '256k_long_output']
    if args.kind == 'deepseek41' and not args.case:
        selected = ['short_request', 'cold_main', 'full_context_p10', 'full_context_p50',
                    'full_context_p90', 'full_context_p99', 'subagent_typical',
                    'auxiliary_typical', 'fully_reused', 'long_output']
    profiles = {row['label']: row for row in fixture['profiles']}
    overlaps = {row['label']: row for row in fixture['overlap_profiles']}
    request_file = results / 'active_request.json'
    request_file.unlink(missing_ok=True)
    environment = dict(os.environ, INFERENCE_CAPTURE_ROOT=str(root),
                       INFERENCE_CAPTURE_DEFINITIONS=str(scripts.parent / 'definitions'),
                       INFERENCE_CAPTURE_REQUEST=str(request_file), INFERENCE_CAPTURE_MODEL=args.kind,
                       PYTHONPATH=str(scripts) + os.pathsep + os.environ.get('PYTHONPATH', ''),
                       PYTHONDONTWRITEBYTECODE='1', OMP_NUM_THREADS='8')
    command = ['python', '-m', 'sglang.launch_server', '--model-path', str(args.model_path),
               '--host', '127.0.0.1', '--port', str(args.port), '--dtype', 'bfloat16',
               '--moe-runner-backend', 'flashinfer_cutlass', '--ple-offload-embedding',
               '--linear-attn-decode-backend', 'triton', '--linear-attn-prefill-backend', 'triton',
               '--mamba-ssm-dtype', 'float32', '--disable-cuda-graph', '--disable-overlap-schedule',
               '--chunked-prefill-size', '4096', '--mem-fraction-static', '0.8',
               '--max-running-requests', '24', '--max-mamba-cache-size', '120']
    if args.kind == 'deepseek41':
        environment['SGLANG_ENABLE_DSV41_ENGRAM_HOST_TABLE'] = '1'
        environment['SGLANG_DSV41_ENGRAM_HOST_TABLE_LAYOUT'] = 'shared'
        environment['SGLANG_DSV4_KV_LAYOUT'] = 'v41'
        environment['SGLANG_DSV4_COMPRESSED_KV_LAYOUT'] = 'auto'
        command = ['python', '-m', 'sglang.launch_server', '--model-path', str(args.model_path),
                   '--host', '127.0.0.1', '--port', str(args.port), '--dtype', 'bfloat16',
                   '--trust-remote-code', '--tp-size', '4', '--ep-size', '4',
                   '--moe-runner-backend', 'deep_gemm', '--moe-a2a-backend', 'none',
                   '--disable-shared-experts-fusion', '--disable-cuda-graph', '--disable-overlap-schedule',
                   '--cuda-graph-backend-prefill', 'disabled', '--chunked-prefill-size', '4096',
                   '--mem-fraction-static', '0.9', '--max-running-requests', '24', '--watchdog-timeout', '3600']
    model, revision = (('deepseek-ai/DeepSeek-V4.1-Flash', '5254448103b6254fc646dacbca1cbbf20e9216c1')
                       if args.kind == 'deepseek41' else
                       ('nvidia/Qwen3.8-Flash-Next-NVFP4', 'fc694b54fb0174e0913e6adf86691ef85a4ead47'))
    provenance = dict(model=model, model_revision=revision,
                      engine='SGLang', engine_version=importlib.metadata.version('sglang'),
                      server_command=command,
                      serving_environment={key: value for key, value in environment.items() if key.startswith('SGLANG_')},
                      agentx_dataset=fixture['dataset'],
                      agentx_revision=fixture['revision'],
                      prompt_reconstruction='Public AgentX hash blocks select deterministic spans of an authored code corpus; original prompt text is unavailable. Input IDs preserve exact recorded block lengths.',
                      fixture_sha256=hashlib.sha256((scripts / 'agentx_shapes.json').read_bytes()).hexdigest())
    if args.kind == 'deepseek41':
        provenance['engine_adapter'] = 'Pass actual dispatcher activation-group metadata to DeepGEMM; the pinned FP4-expert recipe otherwise hardcodes group 128 for group-32 activations. Tensor bytes and model architecture are unchanged.'
    (results / 'server.json').write_text(json.dumps(provenance, indent=2) + '\n')
    base = f'http://127.0.0.1:{args.port}'
    with (results / 'server.log').open('a') as log:
        server = subprocess.Popen(command, env=environment, stdout=log, stderr=subprocess.STDOUT,
                                  start_new_session=True)
        try:
            deadline = time.monotonic() + 1800
            while True:
                if server.poll() is not None:
                    raise RuntimeError(f'Serving exited {server.returncode}; see {results / "server.log"}')
                try:
                    if requests.get(base + '/health', timeout=5).ok:
                        break
                except requests.RequestException:
                    pass
                if time.monotonic() > deadline:
                    raise TimeoutError('Serving startup exceeded 1800 seconds')
                time.sleep(2)
            for label in selected:
                if label in overlaps:
                    group = overlaps[label]
                    requests.get(base + '/flush_cache', timeout=30).raise_for_status()
                    members = [dict(member, session_id=group['session_id']) for member in group['requests']]
                    payloads = [{'input_ids': make_input_ids(member, tokenizer),
                                 'sampling_params': {'temperature': 0, 'max_new_tokens': min(member['output_tokens'], args.max_output_tokens or member['output_tokens']), 'ignore_eos': True}}
                                for member in members]
                    receipt = dict(provenance, request_id=args.kind.replace('-', '_') + '_' + label,
                                   overlap_profile={key: value for key, value in group.items() if key != 'requests'},
                                   members=[{key: value for key, value in member.items() if key not in ('hash_ids', 'cache_predecessor')} for member in members],
                                   scheduling='Submit the observed overlapping requests together; record the actual engine batch, without claiming to reproduce their original timing.')
                    temporary = request_file.with_suffix('.tmp')
                    temporary.write_text(json.dumps(receipt)); temporary.replace(request_file)
                    (results / (label + '.request.json')).write_text(json.dumps(payloads) + '\n')
                    print('REQUEST', label, len(payloads), 'concurrent requests', flush=True)
                    def submit(payload):
                        started = time.time()
                        response = requests.post(base + '/generate', json=payload, timeout=5400)
                        response.raise_for_status()
                        return dict(started_at=started, finished_at=time.time(), response=response.json())
                    with concurrent.futures.ThreadPoolExecutor(max_workers=len(payloads)) as pool:
                        receipt['responses'] = list(pool.map(submit, payloads))
                    (results / (label + '.json')).write_text(json.dumps(receipt, indent=2) + '\n')
                    request_file.unlink(missing_ok=True)
                    print('COMPLETE', label, flush=True)
                    continue
                profile = profiles[label]
                requests.get(base + '/flush_cache', timeout=30).raise_for_status()
                predecessor = profile.get('cache_predecessor')
                if predecessor:
                    warm = dict(profile, **predecessor)
                    response = requests.post(base + '/generate', json={
                        'input_ids': make_input_ids(warm, tokenizer),
                        'sampling_params': {'temperature': 0, 'max_new_tokens': 1, 'ignore_eos': True},
                    }, timeout=3600)
                    response.raise_for_status()
                    (results / (label + '.warmup.json')).write_text(json.dumps(response.json()) + '\n')
                output_tokens = min(profile['output_tokens'], args.max_output_tokens or profile['output_tokens'])
                payload = {'input_ids': make_input_ids(profile, tokenizer),
                           'sampling_params': {'temperature': 0, 'max_new_tokens': output_tokens, 'ignore_eos': True}}
                receipt = dict(provenance, request_id=args.kind.replace('-', '_') + '_' + label,
                               agentx_profile={k: v for k, v in profile.items() if k not in ('hash_ids', 'cache_predecessor')},
                               actual_requested_output_tokens=output_tokens,
                               capture_decode_steps=sorted({0, 1, 2, 3, max(0, output_tokens//2-1), max(0, output_tokens-2)}),
                               input_ids_sha256=hashlib.sha256(json.dumps(payload['input_ids']).encode()).hexdigest(),
                               cache_predecessor_locator=predecessor['locator'] if predecessor else None)
                temporary = request_file.with_suffix('.tmp')
                temporary.write_text(json.dumps(receipt)); temporary.replace(request_file)
                (results / (label + '.request.json')).write_text(json.dumps(payload) + '\n')
                print('REQUEST', label, len(payload['input_ids']), output_tokens, flush=True)
                response = requests.post(base + '/generate', json=payload, timeout=5400)
                receipt.update(status_code=response.status_code, response=response.json() if response.ok else response.text)
                (results / (label + '.json')).write_text(json.dumps(receipt, indent=2) + '\n')
                response.raise_for_status()
                request_file.unlink(missing_ok=True)
                print('COMPLETE', label, flush=True)
        finally:
            request_file.unlink(missing_ok=True)
            if server.poll() is None:
                os.killpg(server.pid, signal.SIGTERM)
                try:
                    server.wait(timeout=30)
                except subprocess.TimeoutExpired:
                    os.killpg(server.pid, signal.SIGKILL)
                    server.wait()


if __name__ == '__main__':
    main()