Repository navigation
Expand file tree
/
Copy pathspec.rs
More file actions
1846 lines (1754 loc) · 69.7 KB
/
Copy pathspec.rs
File metadata and controls
1846 lines (1754 loc) · 69.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
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-FileCopyrightText: Copyright (c) 2025-2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0
// Includes changes adapted from:
// https://github.com/ai-dynamo/aiconfigurator/blob/6290c161a354da5250c391bd43372b2e9c6f4a51/aic-core/rust/aiconfigurator-core/src/engine/spec.rs
//! `EngineSpec`: the serializable engine wire format.
//!
//! `EngineSpec` is what Python's `compile_engine` emits and what the
//! Rust `Engine` consumes. It bundles the engine identity
//! ([`EngineConfig`], needed later to load the matching [`PerfDatabase`]) with
//! the precompiled context / generation op lists. Each op is an
//! [`OpSpec`] — a public alias for the crate's [`Op`] enum — and the lists
//! round-trip through bincode, including the recursive `Overlap` / `Fallback`
//! children.
//!
//! ## Vision is never on the wire
//!
//! [`Op::Vision`] derives serde with every other variant (it remains part of
//! the shared session path), but a compiled `EngineSpec` never
//! contains a `Vision` op: `compile_engine` decomposes the vision encoder
//! into its child `Gemm` / `EncoderAttention` / `Elementwise` ops, each an
//! existing variant. The type round-trips soundly (see the test below); the
//! constraint is purely a producer-side rule, not enforced by the enum.
//!
//! [`PerfDatabase`]: crate::perf_database::PerfDatabase
use serde::{Deserialize, Serialize};
use crate::ENGINE_SPEC_SCHEMA_VERSION;
use crate::common::enums::EncoderParallel;
use crate::common::error::AicError;
use crate::perfmodel::{AfdExecutionPlan, EngineConfig};
/// Public name for the serializable op. Aliases the crate's [`Op`] enum so
/// the "OpSpec" surface exists without duplicating the definition.
pub use crate::operators::op::Op as OpSpec;
/// Serializable compiled engine.
///
/// `schema_version` guards forward/backward compatibility; `engine` carries
/// the identity used to load the matching perf database; `context_ops` and
/// `generation_ops` are the precompiled op lists the runner iterates.
///
/// `EngineSpec` derives serde so JSON / other self-describing formats work
/// directly. The **bincode** wire format, however, must go through
/// [`EngineSpec::to_bincode`] / [`EngineSpec::from_bincode`], NOT
/// `bincode::serialize(&spec)` directly: [`EngineConfig`] uses
/// `#[serde(flatten)]` (load-bearing for the flat ctypes FFI contract), and
/// bincode 1.x cannot serialize a flattened struct (it emits a map of unknown
/// length → `SequenceMustHaveLength`). The helpers sidestep this by
/// JSON-encoding the `engine` field inside the bincode payload, keeping
/// `EngineConfig` the single source of truth (no mirror struct, no drift).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EngineSpec {
pub schema_version: u32,
/// Engine identity (model / system / backend / parallelism / quant).
/// Needed to locate and load the `PerfDatabase`.
pub engine: EngineConfig,
/// Context-phase ops, in execution order. Never contains `OpSpec::Vision`
/// (decomposed into child ops at compile time).
pub context_ops: Vec<OpSpec>,
/// Generation-phase ops, in execution order.
pub generation_ops: Vec<OpSpec>,
/// The vision tower of a VL model, present when the estimator was asked to
/// price encoder calls (`ForwardPassPerfModelConfig::encoder_parallel`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub vision: Option<VisionSpec>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub afd_plan: Option<AfdExecutionPlan>,
}
/// Vision-encoder ops grouped by the token count each group runs on. Image
/// shapes arrive at query time ([`EncoderImageShape`]), so the compiled spec
/// needs no image configuration.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct VisionSpec {
pub encoder_parallel: EncoderParallel,
/// Patch embedding, on the pre-merge patch sequence.
pub patch_ops: Vec<OpSpec>,
/// The ViT blocks, on the transformer sequence (patches plus any CLS token).
pub transformer_ops: Vec<OpSpec>,
/// Projector and DP exit, on the merged output tokens.
pub output_ops: Vec<OpSpec>,
}
/// One homogeneous group of images in a vision-encoder call.
///
/// The processor turns an image into `sequences` independent encoder sequences
/// (tiles, or one for a dynamic-resolution tower); ViT attention never crosses
/// them. Token counts are per sequence.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct EncoderImageShape {
pub sequences: u32,
/// Patch-embedding tokens per sequence.
pub patch_tokens: u32,
/// Transformer tokens per sequence (patches plus any CLS token).
pub transformer_tokens: u32,
/// Merged output tokens per sequence, as the projector sees them.
pub output_tokens: u32,
/// Images of this shape in the call.
pub images: u32,
}
/// Private bincode payload. `engine` is carried as a JSON string so the
/// `#[serde(flatten)]` on [`EngineConfig`] never reaches the bincode
/// serializer (which rejects unknown-length maps). The op lists are plain
/// `Vec<OpSpec>` (no flatten) and bincode-serialize directly.
#[derive(Serialize, Deserialize)]
struct BincodeWire {
schema_version: u32,
engine_json: String,
context_ops: Vec<OpSpec>,
generation_ops: Vec<OpSpec>,
vision: Option<VisionSpec>,
afd_plan: Option<AfdExecutionPlan>,
}
/// Borrowed twin of [`BincodeWire`]; identical encoding without cloning ops.
#[derive(Serialize)]
struct BincodeWireRef<'a> {
schema_version: u32,
engine_json: String,
context_ops: &'a [OpSpec],
generation_ops: &'a [OpSpec],
vision: &'a Option<VisionSpec>,
afd_plan: &'a Option<AfdExecutionPlan>,
}
impl EngineSpec {
/// SHA-256 of this spec's bincode wire encoding with every storage
/// location cleared: `systems_path`, `fpm_parquet_path` and the copy of
/// the FPM parquet path inside the `extra["estimator_config"]` controls
/// the Python compiler embeds. Their contents are fingerprinted
/// separately, so a relocated copy of the same data compiles to the same
/// digest.
pub(crate) fn content_sha256(&self) -> Result<String, AicError> {
use sha2::{Digest, Sha256};
let mut engine = self.engine.clone();
engine.systems_path = None;
engine.fpm_parquet_path = None;
if let Some(controls) = engine.extra.get_mut("estimator_config") {
let mut value: serde_json::Value = serde_json::from_str(controls)
.map_err(|e| AicError::EngineSpec(format!("extra.estimator_config: {e}")))?;
if let Some(settings) = value
.get_mut("fpm_interpolation")
.and_then(serde_json::Value::as_object_mut)
{
settings.remove("fpm_parquet_path");
}
*controls = value.to_string();
}
let engine_json = serde_json::to_string(&engine)
.map_err(|e| AicError::EngineSpec(format!("engine JSON encode: {e}")))?;
let mut digest = Sha256::new();
bincode::serialize_into(
&mut digest,
&BincodeWireRef {
schema_version: self.schema_version,
engine_json,
context_ops: &self.context_ops,
generation_ops: &self.generation_ops,
vision: &self.vision,
afd_plan: &self.afd_plan,
},
)
.map_err(|e| AicError::EngineSpec(format!("bincode encode: {e}")))?;
Ok(format!("{:x}", digest.finalize()))
}
/// Build a spec, stamping the current [`ENGINE_SPEC_SCHEMA_VERSION`].
pub fn new(
engine: EngineConfig,
context_ops: Vec<OpSpec>,
generation_ops: Vec<OpSpec>,
) -> Self {
Self {
afd_plan: None,
schema_version: ENGINE_SPEC_SCHEMA_VERSION,
engine,
context_ops,
generation_ops,
vision: None,
}
}
/// Serialize to the bincode wire format. The `engine` field is
/// JSON-encoded inside the payload (see the struct docs) so bincode never
/// sees `EngineConfig`'s flattened layout.
pub fn to_bincode(&self) -> Result<Vec<u8>, AicError> {
let engine_json = serde_json::to_string(&self.engine)
.map_err(|e| AicError::EngineSpec(format!("engine JSON encode: {e}")))?;
let wire = BincodeWire {
schema_version: self.schema_version,
engine_json,
context_ops: self.context_ops.clone(),
generation_ops: self.generation_ops.clone(),
vision: self.vision.clone(),
afd_plan: self.afd_plan.clone(),
};
bincode::serialize(&wire).map_err(|e| AicError::EngineSpec(format!("bincode encode: {e}")))
}
/// Deserialize from the bincode wire format produced by [`Self::to_bincode`].
///
/// The `schema_version` prefix is read and validated **before** the
/// variable-layout op payloads are decoded. bincode is not self-describing,
/// so a producer/consumer op-layout skew (e.g. a newer producer that added
/// serialized fields to an `OpSpec`) would otherwise fail deep inside the
/// payload with a generic `bincode decode: io error`, masking the real
/// cause. Reading the leading version first lets a version mismatch surface
/// as a clear [`AicError::UnsupportedSchemaVersion`] instead.
pub fn from_bincode(bytes: &[u8]) -> Result<Self, AicError> {
// `schema_version` is the first field of `BincodeWire`, so it is the
// first value in the byte stream. Decode just it and gate on it before
// touching the op lists (which is where a layout skew would fail).
let mut cursor = std::io::Cursor::new(bytes);
let schema_version: u32 = bincode::deserialize_from(&mut cursor).map_err(|e| {
AicError::EngineSpec(format!(
"bincode decode of the leading schema_version prefix failed \
(payload is {} bytes; too short or not an EngineSpec wire buffer): {e}",
bytes.len()
))
})?;
if schema_version != ENGINE_SPEC_SCHEMA_VERSION {
return Err(AicError::UnsupportedSchemaVersion {
kind: "EngineSpec",
got: schema_version,
expected: ENGINE_SPEC_SCHEMA_VERSION,
});
}
let wire: BincodeWire = bincode::deserialize(bytes).map_err(|e| {
AicError::EngineSpec(format!(
"bincode decode of the op payloads failed at matching \
schema_version {schema_version} — this indicates op-layout drift \
within the same version (an OpSpec changed without a \
ENGINE_SPEC_SCHEMA_VERSION bump) or a corrupt payload, not a \
version skew: {e}"
))
})?;
let engine: EngineConfig = serde_json::from_str(&wire.engine_json).map_err(|e| {
AicError::EngineSpec(format!(
"engine JSON decode failed at schema_version {schema_version}: {e}"
))
})?;
Ok(Self {
schema_version: wire.schema_version,
engine,
context_ops: wire.context_ops,
generation_ops: wire.generation_ops,
vision: wire.vision,
afd_plan: wire.afd_plan,
})
}
}
#[cfg(test)]
pub(crate) mod tests {
use super::*;
use std::collections::BTreeMap;
use crate::common::enums::{
BackendKind, CommQuantMode, FmhaQuantMode, GemmQuantMode, KvCacheQuantMode, MoeQuantMode,
};
use crate::operators::afd_comm::AfdTransferDirection;
use crate::operators::moe_dispatch::DispatchFlavor;
use crate::operators::op::{FallbackOp, OverlapOp};
use crate::operators::{
AfdCombineOp, AfdFCollectiveOp, AfdTransferOp, ContextAttentionOp, ContextMlaOp,
CustomAllReduceOp, DsaModuleOp, Dsv4MegaMoeOp, Dsv4ModuleOp, Dsv41AttentionOp,
Dsv41EngramOp, Dsv41LinearOp, Dsv41MhcOp, Dsv41StageOp, ElementwiseOp, EmbeddingOp,
EncoderAttentionOp, GdnOp, GemmOp, GenerationAttentionOp, GenerationMlaOp, KdaOp, Mamba2Op,
MhcModuleOp, MlaBmmOp, MlaModuleOp, MoEDispatchOp, MoeAllToAllOp, MoeExpertComputeOp,
MoeOp, NcclOp, P2POp, VisionEncoderOp, WideEpContextMlaOp, WideEpGenerationMlaOp,
};
use crate::perf_database::dsv4::AttnKind;
use crate::{
DataType, ENGINE_CONFIG_SCHEMA_VERSION, ParallelMapping, QuantizationConfig,
SpeculativeConfig,
};
// ---- Representative-value builders for each Op variant ----
fn gemm() -> GemmOp {
GemmOp {
name: "qkv_gemm".into(),
scale_factor: 2.0,
n: 4096,
k: 4096,
quant_mode: GemmQuantMode::Fp8,
scale_num_tokens: 0,
low_precision_input: true,
seq_split: 1,
below_grid_sol: false,
}
}
fn embedding() -> EmbeddingOp {
EmbeddingOp {
name: "embedding".into(),
scale_factor: 1.0,
vocab_size: 128_256,
hidden_size: 4096,
quant_mode: GemmQuantMode::Bfloat16,
seq_split: 1,
}
}
fn elementwise() -> ElementwiseOp {
ElementwiseOp {
name: "rmsnorm".into(),
scale_factor: 1.5,
bytes_per_token: 8192.0,
scale_num_tokens: 1,
seq_split: 1,
}
}
fn context_attention() -> ContextAttentionOp {
ContextAttentionOp {
name: "context_attention".into(),
scale_factor: 1.0,
n: 32,
n_kv: 8,
head_size: 128,
window_size: 0,
kv_cache_dtype: KvCacheQuantMode::Fp8,
fmha_quant_mode: FmhaQuantMode::Bfloat16,
use_qk_norm: true,
cp_size: 1,
// Multi-entry so the round-trip proves the whole Vec<String>
// survives, not just a single-element degenerate case.
lane_order: vec!["trtllm_mha".into(), "flashinfer".into(), "default".into()],
apply_rope: false,
dcp_size: 3,
}
}
fn generation_attention() -> GenerationAttentionOp {
GenerationAttentionOp {
name: "generation_attention".into(),
scale_factor: 1.0,
n: 32,
n_kv: 8,
head_size: 128,
window_size: 4096,
kv_cache_dtype: KvCacheQuantMode::Int8,
lane_order: vec!["triton".into(), "trtllm_mha".into(), "default".into()],
use_qk_norm: true,
scale_num_tokens: 8,
verify_query_tokens: 7,
dcp_size: 4,
}
}
fn encoder_attention() -> EncoderAttentionOp {
EncoderAttentionOp {
name: "encoder_attention".into(),
scale_factor: 1.0,
n: 16,
head_size: 80,
fmha_quant_mode: FmhaQuantMode::Fp8,
partial_rotary_factor: 0.0,
}
}
fn context_mla() -> ContextMlaOp {
ContextMlaOp {
name: "context_mla".into(),
scale_factor: 1.0,
num_heads: 128,
kv_cache_dtype: KvCacheQuantMode::Bfloat16,
fmha_quant_mode: FmhaQuantMode::Bfloat16,
cp_size: 1,
dcp_size: 4,
}
}
fn generation_mla() -> GenerationMlaOp {
GenerationMlaOp {
name: "generation_mla".into(),
scale_factor: 1.0,
num_heads: 128,
kv_cache_dtype: KvCacheQuantMode::Fp8,
dcp_size: 8,
}
}
fn mla_module() -> MlaModuleOp {
MlaModuleOp {
name: "context_mla_module".into(),
scale_factor: 1.0,
num_heads: 128,
kv_cache_dtype: KvCacheQuantMode::Fp8,
fmha_quant_mode: FmhaQuantMode::Fp8,
gemm_quant_mode: GemmQuantMode::Fp8Block,
native_num_heads: Some(128),
dcp_size: 2,
}
}
fn mla_bmm() -> MlaBmmOp {
MlaBmmOp {
name: "mla_bmm_pre".into(),
scale_factor: 1.0,
num_heads: 128,
quant_mode: GemmQuantMode::Bfloat16,
is_pre: true,
}
}
fn moe() -> MoeOp {
MoeOp {
name: "moe".into(),
scale_factor: 1.0,
hidden_size: 7168,
inter_size: 2048,
topk: 8,
num_experts: 256,
moe_tp_size: 1,
moe_ep_size: 8,
attention_dp_size: 1,
quant_mode: MoeQuantMode::Fp8Block,
workload_distribution: "power_law_1.2".into(),
is_gated: true,
moe_backend: None,
moe_kernel_source: Some("sglang_flashinfer_trtllm_moe".into()),
enable_eplb: false,
is_context: false,
}
}
fn moe_dispatch() -> MoEDispatchOp {
MoEDispatchOp {
name: "moe_dispatch".into(),
scale_factor: 1.0,
hidden_size: 7168,
topk: 8,
num_experts: 256,
moe_tp_size: 1,
moe_ep_size: 8,
attention_dp_size: 8,
pre_dispatch: true,
backend: BackendKind::Trtllm,
flavor: DispatchFlavor::TrtllmAlltoall,
comm_quant: CommQuantMode::Half,
moe_quant: MoeQuantMode::Fp8Block,
attn_cp_size: 1,
is_context: false,
sms: 12,
scale_num_tokens: 1,
attn_ar_modeled: false,
}
}
fn custom_all_reduce() -> CustomAllReduceOp {
CustomAllReduceOp {
name: "custom_all_reduce".into(),
scale_factor: 1.0,
hidden_size: 4096,
tp_size: 8,
quant: CommQuantMode::Half,
seq_split: 1,
}
}
fn nccl() -> NcclOp {
NcclOp {
name: "nccl_all_reduce".into(),
scale_factor: 1.0,
hidden_size: 4096.0,
num_gpus: 8,
dtype: CommQuantMode::Half,
operation: "all_reduce".into(),
seq_split: 1,
}
}
fn p2p() -> P2POp {
P2POp {
name: "p2p".into(),
scale_factor: 1.0,
pp_size: 4,
hidden_size: 4096,
seq_split: 1,
span_gpus: None,
force_scale_out: false,
}
}
fn vision() -> VisionEncoderOp {
VisionEncoderOp {
name: "vision_encoder".into(),
scale_factor: 1.0,
num_layers: 24,
num_heads: 16,
head_size: 80,
hidden_size: 1280,
intermediate_size: 5120,
fmha_quant: FmhaQuantMode::Bfloat16,
gemm_quant: GemmQuantMode::Bfloat16,
}
}
fn dsa_module() -> DsaModuleOp {
DsaModuleOp {
name: "dsa_module".into(),
scale_factor: 1.0,
num_heads: 128,
kv_cache_dtype: KvCacheQuantMode::Fp8,
fmha_quant_mode: FmhaQuantMode::Fp8,
gemm_quant_mode: GemmQuantMode::Fp8Block,
architecture: "DeepseekV32ForCausalLM".into(),
index_topk: 2048,
cp_size: 1,
full_frac: 1.0,
attn_projection_quant_modes: None,
dcp_size: 2,
}
}
fn msa_module() -> crate::operators::MsaModuleOp {
crate::operators::MsaModuleOp {
name: "context_attention".into(),
scale_factor: 62.0,
num_heads: 8,
num_kv_heads: 1,
hidden_size: 7168,
head_dim: 128,
v_head_dim: 128,
index_n_heads: 64,
index_head_dim: 128,
index_topk: 2048,
block_size: 64,
kv_cache_dtype: KvCacheQuantMode::Bfloat16,
fmha_quant_mode: FmhaQuantMode::Bfloat16,
gemm_quant_mode: GemmQuantMode::Fp8Block,
dsa_architecture: "GlmMoeDsaForCausalLM".into(),
dsa_scale_k: 1.0,
}
}
fn dsv4_module() -> Dsv4ModuleOp {
Dsv4ModuleOp {
name: "dsv4_module".into(),
scale_factor: 1.0,
attn_kind: AttnKind::Hca,
num_heads: 128,
native_heads: 128,
tp_size: 1,
kv_cache_dtype: KvCacheQuantMode::Fp8,
fmha_quant_mode: FmhaQuantMode::Fp8,
gemm_quant_mode: GemmQuantMode::Fp8Block,
architecture: "DeepseekV4ForCausalLM".into(),
cp_size: 1,
window_size: None,
hidden_size: 7168,
q_lora_rank: 1536,
o_lora_rank: 1024,
head_dim: 512,
rope_head_dim: 64,
index_n_heads: 64,
index_head_dim: 128,
index_topk: 1024,
o_groups: Some(16),
}
}
fn dsv4_megamoe() -> Dsv4MegaMoeOp {
Dsv4MegaMoeOp {
name: "context_megamoe".into(),
scale_factor: 61.0,
hidden_size: 7168,
inter_size: 3072,
topk: 6,
num_experts: 384,
moe_tp_size: 1,
moe_ep_size: 8,
quant_mode: MoeQuantMode::W4a8Mxfp4Mxfp8,
workload_distribution: "balanced".into(),
is_context: true,
source_policy: "random".into(),
pre_dispatch: "sglang_jit".into(),
num_fused_shared_experts: 0,
kernel_source: "deepgemm_megamoe".into(),
kernel_dtype: "fp8_fp4".into(),
}
}
fn mhc() -> MhcModuleOp {
MhcModuleOp {
name: "mhc_module".into(),
scale_factor: 1.0,
op: "pre".into(),
hc_mult: 4,
hidden_size: 7168,
architecture: "DeepseekV4ForCausalLM".into(),
sinkhorn_iters: 20,
quant_mode: GemmQuantMode::Bfloat16,
seq_split: 1,
}
}
fn mamba2() -> Mamba2Op {
Mamba2Op {
name: "mamba2".into(),
scale_factor: 1.0,
kernel_source: "mamba_chunk_scan".into(),
phase: "context".into(),
d_model: 4096,
d_state: 128,
d_conv: 4,
nheads: 128,
head_dim: 64,
n_groups: 8,
chunk_size: 256,
}
}
fn gdn() -> GdnOp {
GdnOp {
name: "gdn".into(),
scale_factor: 1.0,
kernel_source: "gdn_kernel".into(),
phase: "generation".into(),
d_model: 4096,
d_conv: 4,
num_k_heads: 16,
head_k_dim: 128,
num_v_heads: 32,
head_v_dim: 128,
// Non-default value so the round-trip notices a
// `#[serde(default)]` swallowing the carried field.
mamba_ssm_dtype: "bfloat16".into(),
}
}
fn kda() -> KdaOp {
KdaOp {
name: "kda".into(),
scale_factor: 1.0,
kernel_source: "fused_sigmoid_gating_delta_rule_update".into(),
phase: "verify".into(),
d_model: 7168,
d_conv: 4,
num_k_heads: 16,
head_k_dim: 128,
num_v_heads: 16,
head_v_dim: 128,
draft_tokens: 4,
}
}
fn wideep_context_mla() -> WideEpContextMlaOp {
WideEpContextMlaOp {
name: "wideep_context_mla".into(),
scale_factor: 1.0,
num_heads: 128,
kv_cache_dtype: KvCacheQuantMode::Fp8,
fmha_quant_mode: FmhaQuantMode::Fp8,
attn_backend: "flashinfer".into(),
cp_size: 1,
}
}
fn wideep_generation_mla() -> WideEpGenerationMlaOp {
WideEpGenerationMlaOp {
name: "wideep_generation_mla".into(),
scale_factor: 1.0,
num_heads: 128,
kv_cache_dtype: KvCacheQuantMode::Fp8,
fmha_quant_mode: FmhaQuantMode::Fp8,
attn_backend: "flashinfer".into(),
dcp_size: 4,
}
}
/// Large-EP comm phase with every optional field set to a NON-default
/// value, so the round-trip would notice a `#[serde(default)]` swallowing
/// a carried field.
fn moe_all_to_all() -> MoeAllToAllOp {
MoeAllToAllOp {
name: "moe_dispatch".into(),
scale_factor: 61.0,
phase: "dispatch".into(),
comm_backend: "deepep_ht".into(),
comm_dtype: "fp8_block".into(),
hidden_size: 7168,
topk: 8,
num_experts: 256,
moe_ep_size: 16,
node_num: 2,
sms: 24,
attention_tp_size: 2,
workload_distribution: "power_law_1.01".into(),
enable_eplb: true,
}
}
/// Large-EP expert compute. `num_slots` / `kernel_source` are `Some(...)`
/// here on purpose — the `None` (Python-default) case is what production
/// emits, and both encodings must survive the wire.
fn moe_expert_compute() -> MoeExpertComputeOp {
MoeExpertComputeOp {
name: "moe".into(),
scale_factor: 61.0,
hidden_size: 7168,
inter_size: 2048,
topk: 8,
num_experts: 256,
moe_ep_size: 16,
quant_mode: MoeQuantMode::Fp8Block,
workload_distribution: "power_law_1.2".into(),
attention_dp_size: 8,
inference_phase: "context".into(),
num_slots: Some(288),
kernel_source: Some("deepep_moe".into()),
is_gated: true,
enable_eplb: true,
}
}
fn overlap() -> OverlapOp {
// Recursive: nested children on both groups.
OverlapOp {
name: "overlap_attn_moe".into(),
group_a: vec![OpSpec::ContextMla(context_mla()), OpSpec::Gemm(gemm())],
group_b: vec![OpSpec::Moe(moe()), OpSpec::MoeDispatch(moe_dispatch())],
}
}
fn fpm_forward() -> crate::operators::FpmForwardOp {
// Recursive like Overlap/Fallback: sol_ops carries the model's
// original granular list, so the round-trip must preserve nesting.
crate::operators::FpmForwardOp {
interpolation: Default::default(),
dcp_size: None,
name: "fpm_forward_prefill".into(),
phase: crate::operators::FpmPhase::Prefill,
model_path: "org/model-a".into(),
match_identity: vec![
"nvfp4".into(),
"nvfp4".into(),
"bfloat16".into(),
"half".into(),
"fp8".into(),
"4".into(),
"1".into(),
"1".into(),
"4".into(),
"1".into(),
"1".into(),
],
weight_bytes: 1.5e10,
// Non-default on purpose: the round-trip must preserve the field.
verify_width: 8,
original_fmha_quant_mode: Some("fp8".into()),
sol_ops: vec![
OpSpec::Gemm(gemm()),
OpSpec::ContextAttention(context_attention()),
],
}
}
fn fallback() -> FallbackOp {
// Recursive: a primary module op with a granular per-kernel fallback
// chain that itself contains a nested Overlap.
FallbackOp {
name: "mla_fallback".into(),
primary: Box::new(OpSpec::MlaModuleContext(mla_module())),
fallback: vec![
OpSpec::Gemm(gemm()),
OpSpec::ContextMla(context_mla()),
OpSpec::Overlap(overlap()),
],
}
}
/// Every `Op` variant, constructed once. The exhaustive `match` below the
/// `Vec` build forces the compiler to flag any newly added variant that
/// this round-trip suite forgot to cover.
pub(crate) fn all_op_variants() -> Vec<OpSpec> {
let ops = vec![
OpSpec::Gemm(gemm()),
OpSpec::Embedding(embedding()),
OpSpec::Elementwise(elementwise()),
OpSpec::ContextAttention(context_attention()),
OpSpec::GenerationAttention(generation_attention()),
OpSpec::EncoderAttention(encoder_attention()),
OpSpec::ContextMla(context_mla()),
OpSpec::GenerationMla(generation_mla()),
OpSpec::MlaModuleContext(mla_module()),
OpSpec::MlaModuleGeneration(mla_module()),
OpSpec::MlaBmm(mla_bmm()),
OpSpec::Moe(moe()),
OpSpec::MoeDispatch(moe_dispatch()),
OpSpec::CustomAllReduce(custom_all_reduce()),
OpSpec::Nccl(nccl()),
OpSpec::P2P(p2p()),
OpSpec::Vision(vision()),
OpSpec::DsaContext(dsa_module()),
OpSpec::DsaGeneration(dsa_module()),
OpSpec::MsaContext(msa_module()),
OpSpec::MsaGeneration(msa_module()),
OpSpec::Dsv4Context(dsv4_module()),
OpSpec::Dsv4Generation(dsv4_module()),
OpSpec::Mhc(mhc()),
OpSpec::Mamba2(mamba2()),
OpSpec::Gdn(gdn()),
OpSpec::WideEpContextMla(wideep_context_mla()),
OpSpec::WideEpGenerationMla(wideep_generation_mla()),
OpSpec::Overlap(overlap()),
OpSpec::Fallback(fallback()),
// Appended AFTER Fallback (bincode enum indices are positional;
// appending shifts nothing, so no ENGINE_SPEC_SCHEMA_VERSION bump).
OpSpec::Dsv4MegaMoe(dsv4_megamoe()),
// Appended in wire order: Kda, FpmForward, then this PR's
// large-EP pair.
OpSpec::Kda(kda()),
OpSpec::FpmForward(fpm_forward()),
OpSpec::MoeAllToAll(moe_all_to_all()),
OpSpec::MoeExpertCompute(moe_expert_compute()),
OpSpec::TokenScale(crate::operators::op::TokenScaleOp {
op: Box::new(OpSpec::Gemm(gemm())),
numerator: 5,
denominator: 6,
}),
OpSpec::Dsv41Attention(Dsv41AttentionOp {
name: "v41_attention".into(),
is_context: true,
role: "full".into(),
compress_ratio: 2,
hidden_size: 5120,
num_heads: 16,
head_dim: 512,
q_lora_rank: 1280,
o_lora_rank: 1024,
o_groups: 2,
index_n_heads: 8,
index_head_dim: 128,
index_topk: 512,
window_size: 128,
candidate_limit: 0,
is_candidate_source: false,
bounded_prefill: false,
gemm_quant_mode: GemmQuantMode::Fp8Block,
fmha_quant_mode: FmhaQuantMode::Fp8,
kv_cache_layout: crate::operators::dsv41::Dsv41KvCacheLayout::SglangFp8Bf16,
}),
OpSpec::Dsv41Mhc(Dsv41MhcOp {
name: "v41_mhc".into(),
hidden_size: 5120,
hc_mult: 4,
sinkhorn_iters: 20,
}),
OpSpec::Dsv41Engram(Dsv41EngramOp {
name: "v41_engram".into(),
num_embeddings: 384006168,
head_dim: 256,
hash_columns: 24,
hidden_size: 5120,
hc_mult: 4,
tp_size: 4,
}),
OpSpec::Dsv41Stage(Dsv41StageOp {
name: "v41_stage".into(),
is_context: true,
decoder_replay: true,
bounded: true,
window_size: 128,
children: vec![OpSpec::Gemm(gemm())],
}),
OpSpec::Dsv41Linear(Dsv41LinearOp {
name: "v41_linear".into(),
n: 1152,
k: 5120,
quant_mode: GemmQuantMode::Fp8Block,
}),
OpSpec::Glm53Attention(crate::operators::glm53flash::tests::attention("kda")),
OpSpec::Glm53Mhc(crate::operators::Glm53MhcOp {
name: "mhc_pre_attn_0".into(),
role: "pre".into(),
backend: "vllm".into(),
checkpoint_format: "nvfp4".into(),
tp_size: 2,
is_context: true,
hidden_size: 4096,
hc_mult: 4,
sinkhorn_iters: 20,
}),
OpSpec::Glm53Router(crate::operators::Glm53RouterOp {
name: "router_3".into(),
backend: "vllm".into(),
checkpoint_format: "nvfp4".into(),
hidden_size: 4096,
num_experts: 288,
topk: 8,
}),
OpSpec::Glm53Ffn(crate::operators::Glm53FfnOp {
name: "ffn_0".into(),
backend: "vllm".into(),
checkpoint_format: "nvfp4".into(),
is_context: true,
is_dense: true,
hidden_size: 4096,
intermediate_size: 12288,
num_experts: 288,
topk: 8,
tp_size: 2,
n_shared_experts: 1,
swiglu_limit: 10.0,
scoring_func: "sigmoid".into(),
routed_scaling_factor: 2.5,
n_group: 1,
topk_group: 1,
norm_topk_prob: true,
gemm_quant_mode: GemmQuantMode::Nvfp4,
shared_quant_mode: GemmQuantMode::Bfloat16,
moe_quant_mode: MoeQuantMode::Nvfp4,
children: vec![OpSpec::Gemm(gemm())],
measured: vec![],
}),
OpSpec::Glm53Primitive(crate::operators::Glm53PrimitiveOp {
name: "embedding".into(),
role: "embedding".into(),
backend: "vllm".into(),
checkpoint_format: "fp8".into(),
tp_size: 2,
is_context: true,
hidden_size: 4096,
vocab_size: 154880,
token_selection: "all_scheduled".into(),
output_dtype: "bfloat16".into(),
collective: "none".into(),
children: vec![],
measured: vec![],
}),
OpSpec::MeasuredComposite(crate::operators::measured_composite::MeasuredCompositeOp {
name: "measured".into(),
system: "testsys".into(),
backend: "vllm".into(),
version: "1.0".into(),
is_context: true,
weight_bytes: 0.0,
scale_factor: 1.0,
cells: vec![crate::operators::measured_composite::MeasuredCell {
shape: [1, 4, 0],
latency_ms: 2.0,
}],
}),
// Appended AFTER MeasuredComposite (schema 30): the four AFD comm
// variants. Tail-append keeps every earlier index stable.
OpSpec::AfdTransfer(AfdTransferOp {
f_gpus_per_node: None,
name: "afd_transfer".into(),
scale_factor: 1.0,
direction: AfdTransferDirection::A2f,
hidden_size: 5120,
a_replica_count: 4,
f_rank_count: 16,
gpus_per_node: 8,
num_experts: 8,
topk: 2,
comm_quant_mode: CommQuantMode::Half,
comm_overhead_factor: 1.0,
}),
OpSpec::AfdFAllGather(AfdFCollectiveOp {
operation: "all_gather".into(),
..AfdFCollectiveOp::all_gather("afd_f_all_gather", 1.0)
}),
OpSpec::AfdFReduceScatter(AfdFCollectiveOp {
operation: "reduce_scatter".into(),
..AfdFCollectiveOp::reduce_scatter("afd_f_reduce_scatter", 1.0)
}),
OpSpec::AfdCombine(AfdCombineOp {
name: "afd_combine".into(),
scale_factor: 1.0,
hidden_size: 5120,
a_tp_size: 8,
f_moe_ep_size: 4,
comm_quant_mode: CommQuantMode::Half,
}),
];
// Exhaustiveness guard: if a variant is added to `Op`, this match
// fails to compile until it is also added to `all_op_variants`.
for op in &ops {
match op {
OpSpec::Gemm(_)
| OpSpec::Embedding(_)
| OpSpec::Elementwise(_)
| OpSpec::ContextAttention(_)
| OpSpec::GenerationAttention(_)
| OpSpec::EncoderAttention(_)
| OpSpec::ContextMla(_)
| OpSpec::GenerationMla(_)
| OpSpec::MlaModuleContext(_)
| OpSpec::MlaModuleGeneration(_)
| OpSpec::MlaBmm(_)
| OpSpec::Moe(_)
| OpSpec::MoeDispatch(_)