1use std::collections::{BTreeMap, BTreeSet};
2use std::num::NonZeroU32;
3
4use super::{
5 AliasPolicy, AttributeConstraint, AttributeId, AttributeSchema, AttributeSpec,
6 AttributeValueKind, CanonicalRational, CapabilityId, ContractVersion, DimensionConstraint,
7 ElementType, LayoutConstraint, OperationContract, OperationDescriptor, OperationId, OracleSpec,
8 ProfilePhase, ProviderRequirement, ResourcePresenceRequirement, ResourceRequirements,
9 TensorAccess, TensorContract, VNextError,
10};
11
12pub const TOKEN_EMBEDDING_OPERATION_ID: &str = "operation.token_embedding";
13pub const TOKEN_EMBEDDING_F16_CAPABILITY_ID: &str = "capability.operation.token_embedding.f16";
14pub const TOKEN_EMBEDDING_F32_MASTER_OPERATION_ID: &str = "operation.token_embedding.f32-master";
15pub const TOKEN_EMBEDDING_F32_MASTER_CAPABILITY_ID: &str =
16 "capability.operation.token_embedding.f32-master";
17pub const LAST_TOKEN_DENSE_LINEAR_OPERATION_ID: &str = "operation.last_token_dense_linear";
18pub const LAST_TOKEN_DENSE_LINEAR_F16_CAPABILITY_ID: &str =
19 "capability.operation.last_token_dense_linear.f16";
20pub const LAST_TOKEN_DENSE_LINEAR_F32_OPERATION_ID: &str = "operation.last_token_dense_linear.f32";
21pub const LAST_TOKEN_DENSE_LINEAR_F32_CAPABILITY_ID: &str =
22 "capability.operation.last_token_dense_linear.f32";
23pub const LAST_TOKEN_MASKED_ARGMAX_OPERATION_ID: &str = "operation.last_token_masked_argmax";
24pub const LAST_TOKEN_MASKED_ARGMAX_F16_CAPABILITY_ID: &str =
25 "capability.operation.last_token_masked_argmax.f16";
26pub const LAST_TOKEN_MASKED_ARGMAX_F32_OPERATION_ID: &str =
27 "operation.last_token_masked_argmax.f32";
28pub const LAST_TOKEN_MASKED_ARGMAX_F32_CAPABILITY_ID: &str =
29 "capability.operation.last_token_masked_argmax.f32";
30pub const RMS_NORM_OPERATION_ID: &str = "operation.rms_norm";
31pub const RMS_NORM_F16_CAPABILITY_ID: &str = "capability.operation.rms_norm.f16";
32pub const RMS_NORM_F32_TO_F16_OPERATION_ID: &str = "operation.rms_norm.f32-to-f16";
33pub const RMS_NORM_F32_TO_F16_CAPABILITY_ID: &str = "capability.operation.rms_norm.f32-to-f16";
34pub const RMS_NORM_F32_OPERATION_ID: &str = "operation.rms_norm.f32";
35pub const RMS_NORM_F32_CAPABILITY_ID: &str = "capability.operation.rms_norm.f32";
36pub const DENSE_LINEAR_OPERATION_ID: &str = "operation.dense_linear";
37pub const DENSE_LINEAR_F16_CAPABILITY_ID: &str = "capability.operation.dense_linear.f16";
38pub const DENSE_SWIGLU_OPERATION_ID: &str = "operation.dense_swiglu";
39pub const DENSE_SWIGLU_F16_CAPABILITY_ID: &str = "capability.operation.dense_swiglu.f16";
40pub const ROUTED_SWIGLU_MOE_OPERATION_ID: &str = "operation.routed_swiglu_moe";
41pub const ROUTED_SWIGLU_MOE_F16_CAPABILITY_ID: &str = "capability.operation.routed_swiglu_moe.f16";
42pub const ROUTED_SHARED_SWIGLU_MOE_OPERATION_ID: &str = "operation.routed_shared_swiglu_moe";
43pub const ROUTED_SHARED_SWIGLU_MOE_F16_CAPABILITY_ID: &str =
44 "capability.operation.routed_shared_swiglu_moe.f16";
45pub const RESIDUAL_ADD_OPERATION_ID: &str = "operation.residual_add";
46pub const RESIDUAL_ADD_F16_CAPABILITY_ID: &str = "capability.operation.residual_add.f16";
47pub const RESIDUAL_ADD_F32_F16_OPERATION_ID: &str = "operation.residual_add.f32-f16";
48pub const RESIDUAL_ADD_F32_F16_CAPABILITY_ID: &str = "capability.operation.residual_add.f32-f16";
49pub const GATED_DELTA_RECURRENT_ATTENTION_OPERATION_ID: &str =
50 "operation.gated_delta_recurrent_attention";
51pub const GATED_DELTA_RECURRENT_ATTENTION_F16_CAPABILITY_ID: &str =
52 "capability.operation.gated_delta_recurrent_attention.f16";
53pub const GATED_DELTA_RECURRENT_ATTENTION_F32_MASTER_OPERATION_ID: &str =
54 "operation.gated_delta_recurrent_attention.f32-master";
55pub const GATED_DELTA_RECURRENT_ATTENTION_F32_MASTER_CAPABILITY_ID: &str =
56 "capability.operation.gated_delta_recurrent_attention.f32-master";
57pub const GATED_DELTA_EXECUTION_FORM_SELECTOR_VERSION: &str =
58 "gated-delta-execution-form-selector-v1";
59pub const CAUSAL_PAGED_ATTENTION_OPERATION_ID: &str = "operation.causal_paged_attention";
60pub const CAUSAL_PAGED_ATTENTION_F16_CAPABILITY_ID: &str =
61 "capability.operation.causal_paged_attention.f16";
62pub const CAUSAL_PAGED_ATTENTION_F32_MASTER_OPERATION_ID: &str =
63 "operation.causal_paged_attention.f32-master";
64pub const CAUSAL_PAGED_ATTENTION_F32_MASTER_CAPABILITY_ID: &str =
65 "capability.operation.causal_paged_attention.f32-master";
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub enum GatedDeltaDecayParameterization {
69 LogRate,
70 NegativeRate,
71}
72
73impl GatedDeltaDecayParameterization {
74 pub const ALL: [Self; 2] = [Self::LogRate, Self::NegativeRate];
75
76 pub const fn as_str(self) -> &'static str {
77 match self {
78 Self::LogRate => "log_rate",
79 Self::NegativeRate => "negative_rate",
80 }
81 }
82
83 pub fn parse(value: &str) -> Option<Self> {
84 Self::ALL
85 .into_iter()
86 .find(|candidate| candidate.as_str() == value)
87 }
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
91pub enum GatedDeltaValueHeadMapping {
92 GroupedByKeyHead,
93 InterleavedByKeyHead,
94}
95
96impl GatedDeltaValueHeadMapping {
97 pub const ALL: [Self; 2] = [Self::GroupedByKeyHead, Self::InterleavedByKeyHead];
98
99 pub const fn as_str(self) -> &'static str {
100 match self {
101 Self::GroupedByKeyHead => "grouped_by_key_head",
102 Self::InterleavedByKeyHead => "interleaved_by_key_head",
103 }
104 }
105
106 pub fn parse(value: &str) -> Option<Self> {
107 Self::ALL
108 .into_iter()
109 .find(|candidate| candidate.as_str() == value)
110 }
111}
112
113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
118pub struct GatedDeltaExecutionCapabilities {
119 chunked_scan: Option<GatedDeltaChunkedScanCapability>,
120}
121
122impl GatedDeltaExecutionCapabilities {
123 pub const fn recurrent_only() -> Self {
124 Self { chunked_scan: None }
125 }
126
127 pub fn with_chunked_scan(chunk_size: u32) -> Result<Self, VNextError> {
128 Ok(Self {
129 chunked_scan: Some(GatedDeltaChunkedScanCapability::new(chunk_size)?),
130 })
131 }
132
133 pub const fn chunked_scan(self) -> Option<GatedDeltaChunkedScanCapability> {
134 self.chunked_scan
135 }
136
137 pub fn select(
140 self,
141 token_count: u64,
142 preference: GatedDeltaExecutionPreference,
143 ) -> Result<GatedDeltaExecutionForm, VNextError> {
144 if token_count == 0 {
145 return Err(VNextError::InvalidExecutionPlan {
146 reason: "gated-delta execution requires at least one token".to_owned(),
147 });
148 }
149 match (preference, self.chunked_scan, token_count) {
150 (GatedDeltaExecutionPreference::ChunkedScan, Some(capability), 2..) => {
151 Ok(GatedDeltaExecutionForm::ChunkedScan(
152 GatedDeltaChunkPlan::new(token_count, capability.chunk_size),
153 ))
154 }
155 _ => Ok(GatedDeltaExecutionForm::RecurrentScan),
156 }
157 }
158}
159
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct GatedDeltaChunkedScanCapability {
162 chunk_size: NonZeroU32,
163}
164
165impl GatedDeltaChunkedScanCapability {
166 fn new(chunk_size: u32) -> Result<Self, VNextError> {
167 let chunk_size =
168 NonZeroU32::new(chunk_size).ok_or_else(|| VNextError::InvalidExecutionPlan {
169 reason: "gated-delta chunk size must be positive".to_owned(),
170 })?;
171 Ok(Self { chunk_size })
172 }
173
174 pub const fn chunk_size(self) -> u32 {
175 self.chunk_size.get()
176 }
177}
178
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
183pub enum GatedDeltaExecutionPreference {
184 RecurrentScan,
185 ChunkedScan,
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq)]
189pub struct GatedDeltaChunkPlan {
190 token_count: u64,
191 chunk_size: NonZeroU32,
192 chunk_count: u64,
193 final_chunk_tokens: u32,
194}
195
196impl GatedDeltaChunkPlan {
197 fn new(token_count: u64, chunk_size: NonZeroU32) -> Self {
198 debug_assert!(token_count > 0);
199 let chunk_size_u64 = u64::from(chunk_size.get());
200 let chunk_count = ((token_count - 1) / chunk_size_u64) + 1;
201 let remainder = (token_count % chunk_size_u64) as u32;
202 Self {
203 token_count,
204 chunk_size,
205 chunk_count,
206 final_chunk_tokens: if remainder == 0 {
207 chunk_size.get()
208 } else {
209 remainder
210 },
211 }
212 }
213
214 pub const fn token_count(self) -> u64 {
215 self.token_count
216 }
217
218 pub const fn chunk_size(self) -> u32 {
219 self.chunk_size.get()
220 }
221
222 pub const fn chunk_count(self) -> u64 {
223 self.chunk_count
224 }
225
226 pub const fn final_chunk_tokens(self) -> u32 {
227 self.final_chunk_tokens
228 }
229}
230
231#[derive(Debug, Clone, Copy, PartialEq, Eq)]
232pub enum GatedDeltaExecutionForm {
233 RecurrentScan,
234 ChunkedScan(GatedDeltaChunkPlan),
235}
236
237impl GatedDeltaExecutionForm {
238 pub const fn as_str(self) -> &'static str {
239 match self {
240 Self::RecurrentScan => "recurrent_scan",
241 Self::ChunkedScan(_) => "chunked_scan",
242 }
243 }
244}
245
246pub struct StandardOperationContract {
250 descriptor: OperationDescriptor,
251}
252
253impl OperationContract for StandardOperationContract {
254 fn descriptor(&self) -> &OperationDescriptor {
255 &self.descriptor
256 }
257
258 fn validate_signature(
259 &self,
260 inputs: &[TensorContract],
261 outputs: &[TensorContract],
262 ) -> Result<(), VNextError> {
263 if inputs != self.descriptor.inputs || outputs != self.descriptor.outputs {
264 return Err(VNextError::InvalidExecutionPlan {
265 reason: format!(
266 "operation `{}` signature differs from its standard contract",
267 self.descriptor.id
268 ),
269 });
270 }
271 Ok(())
272 }
273}
274
275pub fn token_embedding_contract() -> Result<StandardOperationContract, VNextError> {
276 token_embedding_contract_with_output(
277 TOKEN_EMBEDDING_OPERATION_ID,
278 TOKEN_EMBEDDING_F16_CAPABILITY_ID,
279 ElementType::F16,
280 )
281}
282
283pub fn token_embedding_f32_master_contract() -> Result<StandardOperationContract, VNextError> {
284 token_embedding_contract_with_output(
285 TOKEN_EMBEDDING_F32_MASTER_OPERATION_ID,
286 TOKEN_EMBEDDING_F32_MASTER_CAPABILITY_ID,
287 ElementType::F32,
288 )
289}
290
291fn token_embedding_contract_with_output(
292 operation_id: &str,
293 capability_id: &str,
294 output_type: ElementType,
295) -> Result<StandardOperationContract, VNextError> {
296 let descriptor = OperationDescriptor {
297 id: OperationId::new(operation_id)?,
298 version: ContractVersion::new(1, 0),
299 inputs: vec![
300 contiguous_tensor(
301 vec![DimensionConstraint::Symbol("tokens".to_owned())],
302 [ElementType::U32],
303 TensorAccess::Read,
304 )?,
305 contiguous_tensor(
306 vec![
307 DimensionConstraint::Symbol("vocab_size".to_owned()),
308 DimensionConstraint::Symbol("hidden_size".to_owned()),
309 ],
310 [ElementType::F16],
311 TensorAccess::Read,
312 )?,
313 ],
314 outputs: vec![contiguous_tensor(
315 vec![
316 DimensionConstraint::Symbol("tokens".to_owned()),
317 DimensionConstraint::Symbol("hidden_size".to_owned()),
318 ],
319 [output_type],
320 TensorAccess::Write,
321 )?],
322 attributes: AttributeSchema::new(BTreeMap::from([
323 unsigned_attribute("hidden_size")?,
324 unsigned_attribute("vocab_size")?,
325 ]))?,
326 resources: ResourceRequirements {
327 minimum_value_alignment_bytes: 16,
328 scratch: ResourcePresenceRequirement::Forbidden,
329 binding: ResourcePresenceRequirement::Forbidden,
330 persistent: ResourcePresenceRequirement::Forbidden,
331 },
332 oracle: OracleSpec::Exact,
333 provider: ProviderRequirement {
334 minimum_version: ContractVersion::new(1, 0),
335 required_capabilities: BTreeSet::from([CapabilityId::new(capability_id)?]),
336 },
337 profile_phase: ProfilePhase::Forward,
338 };
339 descriptor.validate()?;
340 Ok(StandardOperationContract { descriptor })
341}
342
343pub fn last_token_dense_linear_contract() -> Result<StandardOperationContract, VNextError> {
348 last_token_dense_linear_contract_with_activation(
349 LAST_TOKEN_DENSE_LINEAR_OPERATION_ID,
350 ContractVersion::new(1, 1),
351 LAST_TOKEN_DENSE_LINEAR_F16_CAPABILITY_ID,
352 ElementType::F16,
353 )
354}
355
356pub fn last_token_dense_linear_f32_contract() -> Result<StandardOperationContract, VNextError> {
357 last_token_dense_linear_contract_with_activation(
358 LAST_TOKEN_DENSE_LINEAR_F32_OPERATION_ID,
359 ContractVersion::new(1, 0),
360 LAST_TOKEN_DENSE_LINEAR_F32_CAPABILITY_ID,
361 ElementType::F32,
362 )
363}
364
365fn last_token_dense_linear_contract_with_activation(
366 operation_id: &str,
367 version: ContractVersion,
368 capability_id: &str,
369 activation_type: ElementType,
370) -> Result<StandardOperationContract, VNextError> {
371 let descriptor = OperationDescriptor {
372 id: OperationId::new(operation_id)?,
373 version,
374 inputs: vec![
375 contiguous_tensor(
376 token_hidden_dimensions(),
377 [activation_type],
378 TensorAccess::Read,
379 )?,
380 contiguous_tensor(
381 vec![
382 DimensionConstraint::Symbol("out_features".to_owned()),
383 DimensionConstraint::Symbol("hidden_size".to_owned()),
384 ],
385 [ElementType::F16],
386 TensorAccess::Read,
387 )?,
388 ],
389 outputs: vec![contiguous_tensor(
390 vec![
391 DimensionConstraint::Exact(1),
392 DimensionConstraint::Symbol("out_features".to_owned()),
393 ],
394 [activation_type],
395 TensorAccess::Write,
396 )?],
397 attributes: AttributeSchema::new(BTreeMap::from([
398 unsigned_attribute("hidden_size")?,
399 unsigned_attribute("out_features")?,
400 ]))?,
401 resources: ResourceRequirements {
402 minimum_value_alignment_bytes: 16,
403 scratch: ResourcePresenceRequirement::Optional,
404 binding: ResourcePresenceRequirement::Forbidden,
405 persistent: ResourcePresenceRequirement::Forbidden,
406 },
407 oracle: f16_reference_tolerance()?,
408 provider: provider_requirement(capability_id, version)?,
409 profile_phase: ProfilePhase::Forward,
410 };
411 descriptor.validate()?;
412 Ok(StandardOperationContract { descriptor })
413}
414
415pub fn last_token_masked_argmax_contract() -> Result<StandardOperationContract, VNextError> {
425 last_token_masked_argmax_contract_with_logits(
426 LAST_TOKEN_MASKED_ARGMAX_OPERATION_ID,
427 ContractVersion::new(3, 0),
428 LAST_TOKEN_MASKED_ARGMAX_F16_CAPABILITY_ID,
429 ElementType::F16,
430 )
431}
432
433pub fn last_token_masked_argmax_f32_contract() -> Result<StandardOperationContract, VNextError> {
434 last_token_masked_argmax_contract_with_logits(
435 LAST_TOKEN_MASKED_ARGMAX_F32_OPERATION_ID,
436 ContractVersion::new(1, 0),
437 LAST_TOKEN_MASKED_ARGMAX_F32_CAPABILITY_ID,
438 ElementType::F32,
439 )
440}
441
442fn last_token_masked_argmax_contract_with_logits(
443 operation_id: &str,
444 version: ContractVersion,
445 capability_id: &str,
446 logits_type: ElementType,
447) -> Result<StandardOperationContract, VNextError> {
448 let descriptor = OperationDescriptor {
449 id: OperationId::new(operation_id)?,
450 version,
451 inputs: vec![
452 contiguous_tensor(
453 vec![
454 DimensionConstraint::Exact(1),
455 DimensionConstraint::Symbol("vocab_size".to_owned()),
456 ],
457 [logits_type],
458 TensorAccess::Read,
459 )?,
460 contiguous_tensor(
461 vec![DimensionConstraint::Symbol("vocab_size".to_owned())],
462 [ElementType::U8],
463 TensorAccess::Read,
464 )?,
465 contiguous_tensor(
466 vec![DimensionConstraint::Symbol(
467 "repetition_capacity".to_owned(),
468 )],
469 [ElementType::U32],
470 TensorAccess::Read,
471 )?,
472 contiguous_tensor(
473 vec![DimensionConstraint::Exact(2)],
474 [ElementType::U32],
475 TensorAccess::Read,
476 )?,
477 contiguous_tensor(
478 vec![DimensionConstraint::Exact(1)],
479 [ElementType::F32],
480 TensorAccess::Read,
481 )?,
482 ],
483 outputs: vec![contiguous_tensor(
484 vec![DimensionConstraint::Exact(1)],
485 [ElementType::U32],
486 TensorAccess::Write,
487 )?],
488 attributes: AttributeSchema::new(BTreeMap::from([unsigned_attribute("vocab_size")?]))?,
489 resources: ResourceRequirements {
490 minimum_value_alignment_bytes: 16,
491 scratch: ResourcePresenceRequirement::Required,
492 binding: ResourcePresenceRequirement::Forbidden,
493 persistent: ResourcePresenceRequirement::Forbidden,
494 },
495 oracle: OracleSpec::Exact,
496 provider: provider_requirement(capability_id, version)?,
497 profile_phase: ProfilePhase::Forward,
498 };
499 descriptor.validate()?;
500 Ok(StandardOperationContract { descriptor })
501}
502
503pub fn rms_norm_contract() -> Result<StandardOperationContract, VNextError> {
504 rms_norm_contract_with_types(
505 RMS_NORM_OPERATION_ID,
506 RMS_NORM_F16_CAPABILITY_ID,
507 ElementType::F16,
508 ElementType::F16,
509 )
510}
511
512pub fn rms_norm_f32_to_f16_contract() -> Result<StandardOperationContract, VNextError> {
513 rms_norm_contract_with_types(
514 RMS_NORM_F32_TO_F16_OPERATION_ID,
515 RMS_NORM_F32_TO_F16_CAPABILITY_ID,
516 ElementType::F32,
517 ElementType::F16,
518 )
519}
520
521pub fn rms_norm_f32_contract() -> Result<StandardOperationContract, VNextError> {
522 rms_norm_contract_with_types(
523 RMS_NORM_F32_OPERATION_ID,
524 RMS_NORM_F32_CAPABILITY_ID,
525 ElementType::F32,
526 ElementType::F32,
527 )
528}
529
530fn rms_norm_contract_with_types(
531 operation_id: &str,
532 capability_id: &str,
533 input_type: ElementType,
534 output_type: ElementType,
535) -> Result<StandardOperationContract, VNextError> {
536 let descriptor = OperationDescriptor {
537 id: OperationId::new(operation_id)?,
538 version: ContractVersion::new(1, 0),
539 inputs: vec![
540 contiguous_tensor(token_hidden_dimensions(), [input_type], TensorAccess::Read)?,
541 contiguous_tensor(
542 vec![DimensionConstraint::Symbol("hidden_size".to_owned())],
543 [ElementType::F16],
544 TensorAccess::Read,
545 )?,
546 ],
547 outputs: vec![contiguous_tensor(
548 token_hidden_dimensions(),
549 [output_type],
550 TensorAccess::Write,
551 )?],
552 attributes: AttributeSchema::new(BTreeMap::from([
553 unsigned_attribute("hidden_size")?,
554 positive_epsilon_attribute("epsilon")?,
555 ]))?,
556 resources: no_auxiliary_resources(),
557 oracle: if output_type == ElementType::F32 {
558 f32_reference_tolerance()?
559 } else {
560 f16_reference_tolerance()?
561 },
562 provider: provider_requirement(capability_id, ContractVersion::new(1, 0))?,
563 profile_phase: ProfilePhase::Forward,
564 };
565 descriptor.validate()?;
566 Ok(StandardOperationContract { descriptor })
567}
568
569pub fn dense_linear_contract() -> Result<StandardOperationContract, VNextError> {
570 let descriptor = OperationDescriptor {
571 id: OperationId::new(DENSE_LINEAR_OPERATION_ID)?,
572 version: ContractVersion::new(1, 0),
573 inputs: vec![
574 contiguous_tensor(
575 vec![
576 DimensionConstraint::Symbol("rows".to_owned()),
577 DimensionConstraint::Symbol("in_features".to_owned()),
578 ],
579 [ElementType::F16],
580 TensorAccess::Read,
581 )?,
582 contiguous_tensor(
583 vec![
584 DimensionConstraint::Symbol("out_features".to_owned()),
585 DimensionConstraint::Symbol("in_features".to_owned()),
586 ],
587 [ElementType::F16],
588 TensorAccess::Read,
589 )?,
590 ],
591 outputs: vec![contiguous_tensor(
592 vec![
593 DimensionConstraint::Symbol("rows".to_owned()),
594 DimensionConstraint::Symbol("out_features".to_owned()),
595 ],
596 [ElementType::F16],
597 TensorAccess::Write,
598 )?],
599 attributes: AttributeSchema::new(BTreeMap::from([
600 unsigned_attribute("in_features")?,
601 unsigned_attribute("out_features")?,
602 ]))?,
603 resources: no_auxiliary_resources(),
604 oracle: f16_reference_tolerance()?,
605 provider: provider_requirement(DENSE_LINEAR_F16_CAPABILITY_ID, ContractVersion::new(1, 0))?,
606 profile_phase: ProfilePhase::Forward,
607 };
608 descriptor.validate()?;
609 Ok(StandardOperationContract { descriptor })
610}
611
612pub fn dense_swiglu_contract() -> Result<StandardOperationContract, VNextError> {
613 let descriptor = OperationDescriptor {
614 id: OperationId::new(DENSE_SWIGLU_OPERATION_ID)?,
615 version: ContractVersion::new(1, 0),
616 inputs: vec![
617 contiguous_tensor(
618 token_hidden_dimensions(),
619 [ElementType::F16],
620 TensorAccess::Read,
621 )?,
622 contiguous_tensor(
623 packed_gate_up_dimensions(),
624 [ElementType::F16],
625 TensorAccess::Read,
626 )?,
627 contiguous_tensor(
628 hidden_intermediate_dimensions(),
629 [ElementType::F16],
630 TensorAccess::Read,
631 )?,
632 ],
633 outputs: vec![contiguous_tensor(
634 token_hidden_dimensions(),
635 [ElementType::F16],
636 TensorAccess::Write,
637 )?],
638 attributes: AttributeSchema::new(BTreeMap::from([
639 unsigned_attribute("hidden_size")?,
640 unsigned_attribute("intermediate_size")?,
641 ]))?,
642 resources: ResourceRequirements {
643 minimum_value_alignment_bytes: 16,
644 scratch: ResourcePresenceRequirement::Required,
645 binding: ResourcePresenceRequirement::Forbidden,
646 persistent: ResourcePresenceRequirement::Forbidden,
647 },
648 oracle: f16_reference_tolerance()?,
649 provider: provider_requirement(DENSE_SWIGLU_F16_CAPABILITY_ID, ContractVersion::new(1, 0))?,
650 profile_phase: ProfilePhase::Forward,
651 };
652 descriptor.validate()?;
653 Ok(StandardOperationContract { descriptor })
654}
655
656pub fn routed_shared_swiglu_moe_contract() -> Result<StandardOperationContract, VNextError> {
665 let descriptor = OperationDescriptor {
666 id: OperationId::new(ROUTED_SHARED_SWIGLU_MOE_OPERATION_ID)?,
667 version: ContractVersion::new(1, 0),
668 inputs: vec![
669 contiguous_tensor(
670 token_hidden_dimensions(),
671 [ElementType::F16],
672 TensorAccess::Read,
673 )?,
674 contiguous_tensor(
675 vec![symbol("expert_count"), symbol("hidden_size")],
676 [ElementType::F16],
677 TensorAccess::Read,
678 )?,
679 contiguous_tensor(
680 routed_expert_gate_up_dimensions(),
681 [ElementType::F16],
682 TensorAccess::Read,
683 )?,
684 contiguous_tensor(
685 routed_expert_down_dimensions(),
686 [ElementType::F16],
687 TensorAccess::Read,
688 )?,
689 contiguous_tensor(
690 vec![exact(1), symbol("hidden_size")],
691 [ElementType::F16],
692 TensorAccess::Read,
693 )?,
694 contiguous_tensor(
695 shared_expert_gate_up_dimensions(),
696 [ElementType::F16],
697 TensorAccess::Read,
698 )?,
699 contiguous_tensor(
700 shared_expert_down_dimensions(),
701 [ElementType::F16],
702 TensorAccess::Read,
703 )?,
704 ],
705 outputs: vec![contiguous_tensor(
706 token_hidden_dimensions(),
707 [ElementType::F16],
708 TensorAccess::Write,
709 )?],
710 attributes: AttributeSchema::new(BTreeMap::from([
711 unsigned_attribute("hidden_size")?,
712 unsigned_attribute("expert_count")?,
713 unsigned_attribute("experts_per_token")?,
714 unsigned_attribute("routed_intermediate_size")?,
715 unsigned_attribute("shared_intermediate_size")?,
716 unconstrained_bool_attribute("normalize_topk")?,
717 ]))?,
718 resources: ResourceRequirements {
719 minimum_value_alignment_bytes: 16,
720 scratch: ResourcePresenceRequirement::Required,
721 binding: ResourcePresenceRequirement::Forbidden,
722 persistent: ResourcePresenceRequirement::Forbidden,
723 },
724 oracle: f16_reference_tolerance()?,
725 provider: provider_requirement(
726 ROUTED_SHARED_SWIGLU_MOE_F16_CAPABILITY_ID,
727 ContractVersion::new(1, 0),
728 )?,
729 profile_phase: ProfilePhase::Forward,
730 };
731 descriptor.validate()?;
732 Ok(StandardOperationContract { descriptor })
733}
734
735pub fn routed_swiglu_moe_contract() -> Result<StandardOperationContract, VNextError> {
743 let descriptor = OperationDescriptor {
744 id: OperationId::new(ROUTED_SWIGLU_MOE_OPERATION_ID)?,
745 version: ContractVersion::new(1, 0),
746 inputs: vec![
747 contiguous_tensor(
748 token_hidden_dimensions(),
749 [ElementType::F16],
750 TensorAccess::Read,
751 )?,
752 contiguous_tensor(
753 vec![symbol("expert_count"), symbol("hidden_size")],
754 [ElementType::F16],
755 TensorAccess::Read,
756 )?,
757 contiguous_tensor(
758 routed_expert_gate_up_dimensions(),
759 [ElementType::F16],
760 TensorAccess::Read,
761 )?,
762 contiguous_tensor(
763 routed_expert_down_dimensions(),
764 [ElementType::F16],
765 TensorAccess::Read,
766 )?,
767 ],
768 outputs: vec![contiguous_tensor(
769 token_hidden_dimensions(),
770 [ElementType::F16],
771 TensorAccess::Write,
772 )?],
773 attributes: AttributeSchema::new(BTreeMap::from([
774 unsigned_attribute("hidden_size")?,
775 unsigned_attribute("expert_count")?,
776 unsigned_attribute("experts_per_token")?,
777 unsigned_attribute("routed_intermediate_size")?,
778 unconstrained_bool_attribute("normalize_topk")?,
779 ]))?,
780 resources: ResourceRequirements {
781 minimum_value_alignment_bytes: 16,
782 scratch: ResourcePresenceRequirement::Required,
783 binding: ResourcePresenceRequirement::Forbidden,
784 persistent: ResourcePresenceRequirement::Forbidden,
785 },
786 oracle: f16_reference_tolerance()?,
787 provider: provider_requirement(
788 ROUTED_SWIGLU_MOE_F16_CAPABILITY_ID,
789 ContractVersion::new(1, 0),
790 )?,
791 profile_phase: ProfilePhase::Forward,
792 };
793 descriptor.validate()?;
794 Ok(StandardOperationContract { descriptor })
795}
796
797pub fn residual_add_contract() -> Result<StandardOperationContract, VNextError> {
798 residual_add_contract_with_types(
799 RESIDUAL_ADD_OPERATION_ID,
800 RESIDUAL_ADD_F16_CAPABILITY_ID,
801 ElementType::F16,
802 ElementType::F16,
803 ElementType::F16,
804 )
805}
806
807pub fn residual_add_f32_f16_contract() -> Result<StandardOperationContract, VNextError> {
808 residual_add_contract_with_types(
809 RESIDUAL_ADD_F32_F16_OPERATION_ID,
810 RESIDUAL_ADD_F32_F16_CAPABILITY_ID,
811 ElementType::F32,
812 ElementType::F16,
813 ElementType::F32,
814 )
815}
816
817fn residual_add_contract_with_types(
818 operation_id: &str,
819 capability_id: &str,
820 left_type: ElementType,
821 right_type: ElementType,
822 output_type: ElementType,
823) -> Result<StandardOperationContract, VNextError> {
824 let descriptor = OperationDescriptor {
825 id: OperationId::new(operation_id)?,
826 version: ContractVersion::new(1, 0),
827 inputs: vec![
828 contiguous_tensor(token_hidden_dimensions(), [left_type], TensorAccess::Read)?,
829 contiguous_tensor(token_hidden_dimensions(), [right_type], TensorAccess::Read)?,
830 ],
831 outputs: vec![contiguous_tensor_with_alias(
832 token_hidden_dimensions(),
833 [output_type],
834 TensorAccess::Write,
835 AliasPolicy::MayAlias { tensor_index: 0 },
836 )?],
837 attributes: AttributeSchema::new(BTreeMap::from([unsigned_attribute("hidden_size")?]))?,
838 resources: no_auxiliary_resources(),
839 oracle: if output_type == ElementType::F32 {
840 OracleSpec::Exact
841 } else {
842 f16_reference_tolerance()?
843 },
844 provider: provider_requirement(capability_id, ContractVersion::new(1, 0))?,
845 profile_phase: ProfilePhase::Forward,
846 };
847 descriptor.validate()?;
848 Ok(StandardOperationContract { descriptor })
849}
850
851pub fn gated_delta_recurrent_attention_contract() -> Result<StandardOperationContract, VNextError> {
855 gated_delta_recurrent_attention_contract_with_hidden(
856 GATED_DELTA_RECURRENT_ATTENTION_OPERATION_ID,
857 ContractVersion::new(6, 0),
858 GATED_DELTA_RECURRENT_ATTENTION_F16_CAPABILITY_ID,
859 ElementType::F16,
860 )
861}
862
863pub fn gated_delta_recurrent_attention_f32_master_contract(
864) -> Result<StandardOperationContract, VNextError> {
865 gated_delta_recurrent_attention_contract_with_hidden(
866 GATED_DELTA_RECURRENT_ATTENTION_F32_MASTER_OPERATION_ID,
867 ContractVersion::new(1, 0),
868 GATED_DELTA_RECURRENT_ATTENTION_F32_MASTER_CAPABILITY_ID,
869 ElementType::F32,
870 )
871}
872
873fn gated_delta_recurrent_attention_contract_with_hidden(
874 operation_id: &str,
875 version: ContractVersion,
876 capability_id: &str,
877 hidden_type: ElementType,
878) -> Result<StandardOperationContract, VNextError> {
879 let descriptor = OperationDescriptor {
880 id: OperationId::new(operation_id)?,
881 version,
882 inputs: vec![
883 contiguous_tensor(token_hidden_dimensions(), [hidden_type], TensorAccess::Read)?,
884 contiguous_tensor(
885 vec![symbol("hidden_size")],
886 [ElementType::F16],
887 TensorAccess::Read,
888 )?,
889 contiguous_tensor(
890 vec![symbol("qkvzba_features"), symbol("hidden_size")],
891 [ElementType::F16],
892 TensorAccess::Read,
893 )?,
894 contiguous_tensor(
895 vec![symbol("qkv_features"), symbol("conv_kernel")],
896 [ElementType::F16],
897 TensorAccess::Read,
898 )?,
899 contiguous_tensor(
900 vec![symbol("value_heads")],
901 [ElementType::F32],
902 TensorAccess::Read,
903 )?,
904 contiguous_tensor(
905 vec![symbol("value_heads")],
906 [ElementType::F32],
907 TensorAccess::Read,
908 )?,
909 contiguous_tensor(
910 vec![symbol("value_head_dim")],
911 [ElementType::F32],
912 TensorAccess::Read,
913 )?,
914 contiguous_tensor(
915 vec![symbol("hidden_size"), symbol("value_features")],
916 [ElementType::F16],
917 TensorAccess::Read,
918 )?,
919 contiguous_tensor(
920 vec![symbol("qkv_features"), symbol("conv_state_width")],
921 [ElementType::F16],
922 TensorAccess::ReadWrite,
923 )?,
924 contiguous_tensor(
925 vec![
926 symbol("value_heads"),
927 symbol("value_head_dim"),
928 symbol("key_head_dim"),
929 ],
930 [ElementType::F32],
931 TensorAccess::ReadWrite,
932 )?,
933 ],
934 outputs: vec![contiguous_tensor_with_alias(
935 token_hidden_dimensions(),
936 [hidden_type],
937 TensorAccess::Write,
938 AliasPolicy::MayAlias { tensor_index: 0 },
939 )?],
940 attributes: AttributeSchema::new(BTreeMap::from([
941 unsigned_attribute("hidden_size")?,
942 unsigned_attribute("key_heads")?,
943 unsigned_attribute("value_heads")?,
944 unsigned_attribute("key_head_dim")?,
945 unsigned_attribute("value_head_dim")?,
946 unsigned_attribute("qkv_features")?,
947 unsigned_attribute("value_features")?,
948 unsigned_attribute("qkvz_features")?,
949 unsigned_attribute("ba_features")?,
950 unsigned_attribute("qkvzba_features")?,
951 unsigned_attribute("conv_kernel")?,
952 unsigned_attribute("conv_state_width")?,
953 positive_epsilon_attribute("epsilon")?,
954 nonnegative_unsigned_attribute("layer_index")?,
955 text_choices_attribute(
956 "decay_parameterization",
957 GatedDeltaDecayParameterization::ALL.map(|value| value.as_str()),
958 )?,
959 text_choices_attribute(
960 "value_head_mapping",
961 GatedDeltaValueHeadMapping::ALL.map(|value| value.as_str()),
962 )?,
963 ]))?,
964 resources: attention_resources(),
965 oracle: f16_reference_tolerance()?,
966 provider: provider_requirement(capability_id, version)?,
967 profile_phase: ProfilePhase::Forward,
968 };
969 descriptor.validate()?;
970 Ok(StandardOperationContract { descriptor })
971}
972
973pub fn causal_paged_attention_contract() -> Result<StandardOperationContract, VNextError> {
977 causal_paged_attention_contract_with_hidden(
978 CAUSAL_PAGED_ATTENTION_OPERATION_ID,
979 ContractVersion::new(2, 0),
980 CAUSAL_PAGED_ATTENTION_F16_CAPABILITY_ID,
981 ElementType::F16,
982 )
983}
984
985pub fn causal_paged_attention_f32_master_contract() -> Result<StandardOperationContract, VNextError>
986{
987 causal_paged_attention_contract_with_hidden(
988 CAUSAL_PAGED_ATTENTION_F32_MASTER_OPERATION_ID,
989 ContractVersion::new(1, 0),
990 CAUSAL_PAGED_ATTENTION_F32_MASTER_CAPABILITY_ID,
991 ElementType::F32,
992 )
993}
994
995fn causal_paged_attention_contract_with_hidden(
996 operation_id: &str,
997 version: ContractVersion,
998 capability_id: &str,
999 hidden_type: ElementType,
1000) -> Result<StandardOperationContract, VNextError> {
1001 let descriptor = OperationDescriptor {
1002 id: OperationId::new(operation_id)?,
1003 version,
1004 inputs: vec![
1005 contiguous_tensor(token_hidden_dimensions(), [hidden_type], TensorAccess::Read)?,
1006 contiguous_tensor(
1007 vec![symbol("hidden_size")],
1008 [ElementType::F16],
1009 TensorAccess::Read,
1010 )?,
1011 contiguous_tensor(
1012 vec![symbol("query_projection_features"), symbol("hidden_size")],
1013 [ElementType::F16],
1014 TensorAccess::Read,
1015 )?,
1016 contiguous_tensor(
1017 vec![symbol("kv_features"), symbol("hidden_size")],
1018 [ElementType::F16],
1019 TensorAccess::Read,
1020 )?,
1021 contiguous_tensor(
1022 vec![symbol("kv_features"), symbol("hidden_size")],
1023 [ElementType::F16],
1024 TensorAccess::Read,
1025 )?,
1026 contiguous_tensor(
1027 vec![symbol("hidden_size"), symbol("query_features")],
1028 [ElementType::F16],
1029 TensorAccess::Read,
1030 )?,
1031 contiguous_tensor(
1032 vec![symbol("head_dim")],
1033 [ElementType::F16],
1034 TensorAccess::Read,
1035 )?,
1036 contiguous_tensor(
1037 vec![symbol("head_dim")],
1038 [ElementType::F16],
1039 TensorAccess::Read,
1040 )?,
1041 contiguous_tensor(
1042 vec![exact(2), symbol("key_value_heads"), symbol("head_dim")],
1043 [ElementType::F16],
1044 TensorAccess::ReadWrite,
1045 )?,
1046 ],
1047 outputs: vec![contiguous_tensor_with_alias(
1048 token_hidden_dimensions(),
1049 [hidden_type],
1050 TensorAccess::Write,
1051 AliasPolicy::MayAlias { tensor_index: 0 },
1052 )?],
1053 attributes: AttributeSchema::new(BTreeMap::from([
1054 unsigned_attribute("hidden_size")?,
1055 unsigned_attribute("query_heads")?,
1056 unsigned_attribute("key_value_heads")?,
1057 unsigned_attribute("head_dim")?,
1058 unsigned_attribute("query_features")?,
1059 unsigned_attribute("query_projection_features")?,
1060 unsigned_attribute("kv_features")?,
1061 unsigned_attribute("rope_dim")?,
1062 unsigned_attribute("maximum_context_tokens")?,
1063 positive_rational_attribute("rope_theta")?,
1064 unconstrained_bool_attribute("rope_interleaved")?,
1065 unconstrained_bool_attribute("output_gate")?,
1066 true_bool_attribute("causal")?,
1067 positive_epsilon_attribute("epsilon")?,
1068 nonnegative_unsigned_attribute("layer_index")?,
1069 ]))?,
1070 resources: causal_attention_resources(),
1071 oracle: f16_reference_tolerance()?,
1072 provider: provider_requirement(capability_id, version)?,
1073 profile_phase: ProfilePhase::Forward,
1074 };
1075 descriptor.validate()?;
1076 Ok(StandardOperationContract { descriptor })
1077}
1078
1079fn contiguous_tensor(
1080 dimensions: Vec<DimensionConstraint>,
1081 element_types: impl IntoIterator<Item = ElementType>,
1082 access: TensorAccess,
1083) -> Result<TensorContract, VNextError> {
1084 contiguous_tensor_with_alias(dimensions, element_types, access, AliasPolicy::NoAlias)
1085}
1086
1087fn contiguous_tensor_with_alias(
1088 dimensions: Vec<DimensionConstraint>,
1089 element_types: impl IntoIterator<Item = ElementType>,
1090 access: TensorAccess,
1091 alias: AliasPolicy,
1092) -> Result<TensorContract, VNextError> {
1093 TensorContract::new(
1094 dimensions,
1095 element_types.into_iter().collect(),
1096 vec![LayoutConstraint::Contiguous],
1097 access,
1098 alias,
1099 )
1100}
1101
1102fn token_hidden_dimensions() -> Vec<DimensionConstraint> {
1103 vec![
1104 DimensionConstraint::Symbol("tokens".to_owned()),
1105 DimensionConstraint::Symbol("hidden_size".to_owned()),
1106 ]
1107}
1108
1109fn packed_gate_up_dimensions() -> Vec<DimensionConstraint> {
1110 vec![
1111 DimensionConstraint::Exact(2),
1112 DimensionConstraint::Symbol("intermediate_size".to_owned()),
1113 DimensionConstraint::Symbol("hidden_size".to_owned()),
1114 ]
1115}
1116
1117fn hidden_intermediate_dimensions() -> Vec<DimensionConstraint> {
1118 vec![
1119 DimensionConstraint::Symbol("hidden_size".to_owned()),
1120 DimensionConstraint::Symbol("intermediate_size".to_owned()),
1121 ]
1122}
1123
1124fn routed_expert_gate_up_dimensions() -> Vec<DimensionConstraint> {
1125 vec![
1126 symbol("expert_count"),
1127 exact(2),
1128 symbol("routed_intermediate_size"),
1129 symbol("hidden_size"),
1130 ]
1131}
1132
1133fn routed_expert_down_dimensions() -> Vec<DimensionConstraint> {
1134 vec![
1135 symbol("expert_count"),
1136 symbol("hidden_size"),
1137 symbol("routed_intermediate_size"),
1138 ]
1139}
1140
1141fn shared_expert_gate_up_dimensions() -> Vec<DimensionConstraint> {
1142 vec![
1143 exact(2),
1144 symbol("shared_intermediate_size"),
1145 symbol("hidden_size"),
1146 ]
1147}
1148
1149fn shared_expert_down_dimensions() -> Vec<DimensionConstraint> {
1150 vec![symbol("hidden_size"), symbol("shared_intermediate_size")]
1151}
1152
1153fn no_auxiliary_resources() -> ResourceRequirements {
1154 ResourceRequirements {
1155 minimum_value_alignment_bytes: 16,
1156 scratch: ResourcePresenceRequirement::Forbidden,
1157 binding: ResourcePresenceRequirement::Forbidden,
1158 persistent: ResourcePresenceRequirement::Forbidden,
1159 }
1160}
1161
1162fn attention_resources() -> ResourceRequirements {
1163 ResourceRequirements {
1164 minimum_value_alignment_bytes: 16,
1165 scratch: ResourcePresenceRequirement::Required,
1166 binding: ResourcePresenceRequirement::Optional,
1167 persistent: ResourcePresenceRequirement::Forbidden,
1168 }
1169}
1170
1171fn causal_attention_resources() -> ResourceRequirements {
1172 ResourceRequirements {
1173 minimum_value_alignment_bytes: 16,
1174 scratch: ResourcePresenceRequirement::Required,
1175 binding: ResourcePresenceRequirement::Required,
1176 persistent: ResourcePresenceRequirement::Forbidden,
1177 }
1178}
1179
1180fn symbol(name: &str) -> DimensionConstraint {
1181 DimensionConstraint::Symbol(name.to_owned())
1182}
1183
1184const fn exact(value: u64) -> DimensionConstraint {
1185 DimensionConstraint::Exact(value)
1186}
1187
1188fn provider_requirement(
1189 capability: &str,
1190 minimum_version: ContractVersion,
1191) -> Result<ProviderRequirement, VNextError> {
1192 Ok(ProviderRequirement {
1193 minimum_version,
1194 required_capabilities: BTreeSet::from([CapabilityId::new(capability)?]),
1195 })
1196}
1197
1198fn f16_reference_tolerance() -> Result<OracleSpec, VNextError> {
1199 Ok(OracleSpec::RelativeTolerance {
1200 tolerance: CanonicalRational::new(1, 1_000)?,
1201 })
1202}
1203
1204fn f32_reference_tolerance() -> Result<OracleSpec, VNextError> {
1205 Ok(OracleSpec::RelativeTolerance {
1206 tolerance: CanonicalRational::new(1, 100_000)?,
1207 })
1208}
1209
1210fn unsigned_attribute(name: &str) -> Result<(AttributeId, AttributeSpec), VNextError> {
1211 Ok((
1212 AttributeId::new(name)?,
1213 AttributeSpec {
1214 value_kind: AttributeValueKind::Unsigned,
1215 required: true,
1216 constraint: AttributeConstraint::UnsignedRange {
1217 minimum: 1,
1218 maximum: u32::MAX as u64,
1219 },
1220 },
1221 ))
1222}
1223
1224fn nonnegative_unsigned_attribute(name: &str) -> Result<(AttributeId, AttributeSpec), VNextError> {
1225 Ok((
1226 AttributeId::new(name)?,
1227 AttributeSpec {
1228 value_kind: AttributeValueKind::Unsigned,
1229 required: true,
1230 constraint: AttributeConstraint::UnsignedRange {
1231 minimum: 0,
1232 maximum: u32::MAX as u64,
1233 },
1234 },
1235 ))
1236}
1237
1238fn unconstrained_bool_attribute(name: &str) -> Result<(AttributeId, AttributeSpec), VNextError> {
1239 Ok((
1240 AttributeId::new(name)?,
1241 AttributeSpec {
1242 value_kind: AttributeValueKind::Bool,
1243 required: true,
1244 constraint: AttributeConstraint::None,
1245 },
1246 ))
1247}
1248
1249fn true_bool_attribute(name: &str) -> Result<(AttributeId, AttributeSpec), VNextError> {
1250 Ok((
1251 AttributeId::new(name)?,
1252 AttributeSpec {
1253 value_kind: AttributeValueKind::Bool,
1254 required: true,
1255 constraint: AttributeConstraint::BoolEquals(true),
1256 },
1257 ))
1258}
1259
1260fn positive_rational_attribute(name: &str) -> Result<(AttributeId, AttributeSpec), VNextError> {
1261 Ok((
1262 AttributeId::new(name)?,
1263 AttributeSpec {
1264 value_kind: AttributeValueKind::Rational,
1265 required: true,
1266 constraint: AttributeConstraint::RationalRange {
1267 minimum: CanonicalRational::new(1, u64::MAX)?,
1268 maximum: CanonicalRational::new(i64::MAX, 1)?,
1269 },
1270 },
1271 ))
1272}
1273
1274fn positive_epsilon_attribute(name: &str) -> Result<(AttributeId, AttributeSpec), VNextError> {
1275 Ok((
1276 AttributeId::new(name)?,
1277 AttributeSpec {
1278 value_kind: AttributeValueKind::Rational,
1279 required: true,
1280 constraint: AttributeConstraint::RationalRange {
1281 minimum: CanonicalRational::new(1, 1_000_000_000_000)?,
1282 maximum: CanonicalRational::new(1, 1)?,
1283 },
1284 },
1285 ))
1286}
1287
1288fn text_choices_attribute(
1289 name: &str,
1290 values: impl IntoIterator<Item = &'static str>,
1291) -> Result<(AttributeId, AttributeSpec), VNextError> {
1292 Ok((
1293 AttributeId::new(name)?,
1294 AttributeSpec {
1295 value_kind: AttributeValueKind::Text,
1296 required: true,
1297 constraint: AttributeConstraint::TextChoices {
1298 values: values.into_iter().map(str::to_owned).collect(),
1299 },
1300 },
1301 ))
1302}
1303
1304#[cfg(test)]
1305mod tests {
1306 use super::*;
1307
1308 #[test]
1309 fn gated_delta_recurrent_only_capability_never_claims_chunked_scan() {
1310 let capabilities = GatedDeltaExecutionCapabilities::recurrent_only();
1311 assert_eq!(
1312 capabilities
1313 .select(1, GatedDeltaExecutionPreference::ChunkedScan)
1314 .unwrap(),
1315 GatedDeltaExecutionForm::RecurrentScan
1316 );
1317 assert_eq!(
1318 capabilities
1319 .select(64, GatedDeltaExecutionPreference::ChunkedScan)
1320 .unwrap(),
1321 GatedDeltaExecutionForm::RecurrentScan
1322 );
1323 }
1324
1325 #[test]
1326 fn gated_delta_chunk_plan_preserves_exact_tail_boundaries() {
1327 let capabilities = GatedDeltaExecutionCapabilities::with_chunked_scan(64).unwrap();
1328 assert_eq!(
1329 capabilities
1330 .select(1, GatedDeltaExecutionPreference::ChunkedScan)
1331 .unwrap(),
1332 GatedDeltaExecutionForm::RecurrentScan
1333 );
1334 assert_eq!(
1335 capabilities
1336 .select(64, GatedDeltaExecutionPreference::RecurrentScan)
1337 .unwrap(),
1338 GatedDeltaExecutionForm::RecurrentScan
1339 );
1340 for (tokens, chunks, final_tokens) in [(2, 1, 2), (64, 1, 64), (65, 2, 1)] {
1341 let GatedDeltaExecutionForm::ChunkedScan(plan) = capabilities
1342 .select(tokens, GatedDeltaExecutionPreference::ChunkedScan)
1343 .unwrap()
1344 else {
1345 panic!("{tokens} tokens must select chunked scan");
1346 };
1347 assert_eq!(plan.token_count(), tokens);
1348 assert_eq!(plan.chunk_size(), 64);
1349 assert_eq!(plan.chunk_count(), chunks);
1350 assert_eq!(plan.final_chunk_tokens(), final_tokens);
1351 assert_eq!(
1352 GatedDeltaExecutionForm::ChunkedScan(plan).as_str(),
1353 "chunked_scan"
1354 );
1355 }
1356 }
1357
1358 #[test]
1359 fn gated_delta_execution_capabilities_reject_invalid_domains() {
1360 assert!(GatedDeltaExecutionCapabilities::with_chunked_scan(0).is_err());
1361 assert!(GatedDeltaExecutionCapabilities::recurrent_only()
1362 .select(0, GatedDeltaExecutionPreference::RecurrentScan)
1363 .is_err());
1364 }
1365
1366 #[test]
1367 fn token_embedding_contract_is_backend_and_model_neutral() {
1368 let contract = token_embedding_contract().unwrap();
1369 let descriptor = contract.descriptor();
1370 assert_eq!(descriptor.id.as_str(), TOKEN_EMBEDDING_OPERATION_ID);
1371 assert_eq!(descriptor.fingerprint().unwrap().len(), 64);
1372 contract
1373 .validate_signature(&descriptor.inputs, &descriptor.outputs)
1374 .unwrap();
1375 }
1376
1377 #[test]
1378 fn fp32_master_contracts_form_one_exact_mixed_precision_chain() {
1379 let contracts = [
1380 token_embedding_f32_master_contract().unwrap(),
1381 gated_delta_recurrent_attention_f32_master_contract().unwrap(),
1382 causal_paged_attention_f32_master_contract().unwrap(),
1383 rms_norm_f32_to_f16_contract().unwrap(),
1384 residual_add_f32_f16_contract().unwrap(),
1385 rms_norm_f32_contract().unwrap(),
1386 last_token_dense_linear_f32_contract().unwrap(),
1387 last_token_masked_argmax_f32_contract().unwrap(),
1388 ];
1389 let ids = contracts
1390 .iter()
1391 .map(|contract| contract.descriptor().id.as_str())
1392 .collect::<BTreeSet<_>>();
1393 assert_eq!(ids.len(), contracts.len());
1394 for contract in &contracts {
1395 let descriptor = contract.descriptor();
1396 assert_eq!(descriptor.version, ContractVersion::new(1, 0));
1397 assert_eq!(descriptor.provider.required_capabilities.len(), 1);
1398 contract
1399 .validate_signature(&descriptor.inputs, &descriptor.outputs)
1400 .unwrap();
1401 }
1402
1403 let embedding = contracts[0].descriptor();
1404 assert_eq!(
1405 embedding.outputs[0].element_types(),
1406 &BTreeSet::from([ElementType::F32])
1407 );
1408 for attention in [&contracts[1], &contracts[2]] {
1409 let descriptor = attention.descriptor();
1410 assert_eq!(
1411 descriptor.inputs[0].element_types(),
1412 &BTreeSet::from([ElementType::F32])
1413 );
1414 assert_eq!(
1415 descriptor.outputs[0].element_types(),
1416 &BTreeSet::from([ElementType::F32])
1417 );
1418 assert_eq!(
1419 descriptor.outputs[0].alias(),
1420 &AliasPolicy::MayAlias { tensor_index: 0 }
1421 );
1422 }
1423
1424 let branch_norm = contracts[3].descriptor();
1425 assert_eq!(
1426 branch_norm.inputs[0].element_types(),
1427 &BTreeSet::from([ElementType::F32])
1428 );
1429 assert_eq!(
1430 branch_norm.outputs[0].element_types(),
1431 &BTreeSet::from([ElementType::F16])
1432 );
1433 let residual = contracts[4].descriptor();
1434 assert_eq!(
1435 residual.inputs[0].element_types(),
1436 &BTreeSet::from([ElementType::F32])
1437 );
1438 assert_eq!(
1439 residual.inputs[1].element_types(),
1440 &BTreeSet::from([ElementType::F16])
1441 );
1442 assert_eq!(
1443 residual.outputs[0].element_types(),
1444 &BTreeSet::from([ElementType::F32])
1445 );
1446
1447 let final_norm = contracts[5].descriptor();
1448 let head = contracts[6].descriptor();
1449 let argmax = contracts[7].descriptor();
1450 for tensor in [
1451 &final_norm.inputs[0],
1452 &final_norm.outputs[0],
1453 &head.inputs[0],
1454 &head.outputs[0],
1455 &argmax.inputs[0],
1456 ] {
1457 assert_eq!(tensor.element_types(), &BTreeSet::from([ElementType::F32]));
1458 }
1459
1460 assert!(!ids.contains(TOKEN_EMBEDDING_OPERATION_ID));
1461 assert!(!ids.contains(RMS_NORM_OPERATION_ID));
1462 assert!(!ids.contains(RESIDUAL_ADD_OPERATION_ID));
1463 }
1464
1465 #[test]
1466 fn last_token_dense_linear_contract_is_backend_and_model_neutral() {
1467 let contract = last_token_dense_linear_contract().unwrap();
1468 let descriptor = contract.descriptor();
1469 assert_eq!(descriptor.id.as_str(), LAST_TOKEN_DENSE_LINEAR_OPERATION_ID);
1470 assert_eq!(descriptor.version, ContractVersion::new(1, 1));
1471 assert_eq!(
1472 descriptor.resources.scratch,
1473 ResourcePresenceRequirement::Optional
1474 );
1475 assert_eq!(
1476 descriptor.outputs[0].dimensions(),
1477 &[
1478 DimensionConstraint::Exact(1),
1479 DimensionConstraint::Symbol("out_features".to_owned()),
1480 ]
1481 );
1482 contract
1483 .validate_signature(&descriptor.inputs, &descriptor.outputs)
1484 .unwrap();
1485 }
1486
1487 #[test]
1488 fn last_token_masked_argmax_contract_keeps_policy_in_typed_inputs() {
1489 let contract = last_token_masked_argmax_contract().unwrap();
1490 let descriptor = contract.descriptor();
1491 assert_eq!(
1492 descriptor.id.as_str(),
1493 LAST_TOKEN_MASKED_ARGMAX_OPERATION_ID
1494 );
1495 assert_eq!(descriptor.version, ContractVersion::new(3, 0));
1496 assert_eq!(descriptor.inputs.len(), 5);
1497 assert_eq!(descriptor.inputs[0].access(), TensorAccess::Read);
1498 assert_eq!(
1499 descriptor.resources.scratch,
1500 ResourcePresenceRequirement::Required
1501 );
1502 assert_eq!(
1503 descriptor.resources.binding,
1504 ResourcePresenceRequirement::Forbidden
1505 );
1506 assert_eq!(
1507 descriptor.resources.persistent,
1508 ResourcePresenceRequirement::Forbidden
1509 );
1510 assert_eq!(
1511 descriptor.inputs[1].element_types(),
1512 &BTreeSet::from([ElementType::U8])
1513 );
1514 assert_eq!(
1515 descriptor.inputs[2].element_types(),
1516 &BTreeSet::from([ElementType::U32])
1517 );
1518 assert_eq!(
1519 descriptor.inputs[3].dimensions(),
1520 &[DimensionConstraint::Exact(2)]
1521 );
1522 assert_eq!(
1523 descriptor.inputs[4].element_types(),
1524 &BTreeSet::from([ElementType::F32])
1525 );
1526 assert_eq!(
1527 descriptor.outputs[0].element_types(),
1528 &BTreeSet::from([ElementType::U32])
1529 );
1530 assert_eq!(
1531 descriptor.outputs[0].dimensions(),
1532 &[DimensionConstraint::Exact(1)]
1533 );
1534 contract
1535 .validate_signature(&descriptor.inputs, &descriptor.outputs)
1536 .unwrap();
1537 }
1538
1539 #[test]
1540 fn transformer_primitives_have_explicit_math_and_resource_boundaries() {
1541 let contracts = [
1542 rms_norm_contract().unwrap(),
1543 dense_linear_contract().unwrap(),
1544 dense_swiglu_contract().unwrap(),
1545 residual_add_contract().unwrap(),
1546 ];
1547 for contract in &contracts {
1548 let descriptor = contract.descriptor();
1549 assert_eq!(descriptor.fingerprint().unwrap().len(), 64);
1550 contract
1551 .validate_signature(&descriptor.inputs, &descriptor.outputs)
1552 .unwrap();
1553 }
1554 assert_eq!(
1555 contracts[2].descriptor().resources.scratch,
1556 ResourcePresenceRequirement::Required
1557 );
1558 assert_eq!(
1559 contracts[3].descriptor().outputs[0].alias(),
1560 &AliasPolicy::MayAlias { tensor_index: 0 }
1561 );
1562 }
1563
1564 #[test]
1565 fn routed_shared_moe_contract_keeps_fusion_and_weight_abi_generic() {
1566 let contract = routed_shared_swiglu_moe_contract().unwrap();
1567 let descriptor = contract.descriptor();
1568
1569 assert_eq!(
1570 descriptor.id.as_str(),
1571 ROUTED_SHARED_SWIGLU_MOE_OPERATION_ID
1572 );
1573 assert_eq!(descriptor.version, ContractVersion::new(1, 0));
1574 assert_eq!(descriptor.inputs.len(), 7);
1575 assert_eq!(
1576 descriptor.inputs[2].dimensions(),
1577 &[
1578 symbol("expert_count"),
1579 exact(2),
1580 symbol("routed_intermediate_size"),
1581 symbol("hidden_size"),
1582 ]
1583 );
1584 assert_eq!(
1585 descriptor.inputs[3].dimensions(),
1586 &[
1587 symbol("expert_count"),
1588 symbol("hidden_size"),
1589 symbol("routed_intermediate_size"),
1590 ]
1591 );
1592 assert_eq!(
1593 descriptor.inputs[4].dimensions(),
1594 &[exact(1), symbol("hidden_size")]
1595 );
1596 assert_eq!(
1597 descriptor.resources.scratch,
1598 ResourcePresenceRequirement::Required
1599 );
1600 assert_eq!(
1601 descriptor.resources.persistent,
1602 ResourcePresenceRequirement::Forbidden
1603 );
1604 assert_eq!(
1605 descriptor.provider.required_capabilities,
1606 BTreeSet::from([
1607 CapabilityId::new(ROUTED_SHARED_SWIGLU_MOE_F16_CAPABILITY_ID).unwrap()
1608 ])
1609 );
1610 for attribute in [
1611 "hidden_size",
1612 "expert_count",
1613 "experts_per_token",
1614 "routed_intermediate_size",
1615 "shared_intermediate_size",
1616 "normalize_topk",
1617 ] {
1618 assert!(
1619 descriptor
1620 .attributes
1621 .entries()
1622 .contains_key(&AttributeId::new(attribute).unwrap()),
1623 "missing typed MoE attribute {attribute}"
1624 );
1625 }
1626 assert_eq!(descriptor.fingerprint().unwrap().len(), 64);
1627 contract
1628 .validate_signature(&descriptor.inputs, &descriptor.outputs)
1629 .unwrap();
1630 }
1631
1632 #[test]
1633 fn routed_only_moe_contract_has_no_shared_expert_abi() {
1634 let contract = routed_swiglu_moe_contract().unwrap();
1635 let descriptor = contract.descriptor();
1636
1637 assert_eq!(descriptor.id.as_str(), ROUTED_SWIGLU_MOE_OPERATION_ID);
1638 assert_eq!(descriptor.version, ContractVersion::new(1, 0));
1639 assert_eq!(descriptor.inputs.len(), 4);
1640 assert_eq!(
1641 descriptor.inputs[2].dimensions(),
1642 &[
1643 symbol("expert_count"),
1644 exact(2),
1645 symbol("routed_intermediate_size"),
1646 symbol("hidden_size"),
1647 ]
1648 );
1649 assert_eq!(
1650 descriptor.inputs[3].dimensions(),
1651 &[
1652 symbol("expert_count"),
1653 symbol("hidden_size"),
1654 symbol("routed_intermediate_size"),
1655 ]
1656 );
1657 assert_eq!(
1658 descriptor.resources.scratch,
1659 ResourcePresenceRequirement::Required
1660 );
1661 assert_eq!(
1662 descriptor.provider.required_capabilities,
1663 BTreeSet::from([CapabilityId::new(ROUTED_SWIGLU_MOE_F16_CAPABILITY_ID).unwrap()])
1664 );
1665 for attribute in [
1666 "hidden_size",
1667 "expert_count",
1668 "experts_per_token",
1669 "routed_intermediate_size",
1670 "normalize_topk",
1671 ] {
1672 assert!(
1673 descriptor
1674 .attributes
1675 .entries()
1676 .contains_key(&AttributeId::new(attribute).unwrap()),
1677 "missing typed routed-only MoE attribute {attribute}"
1678 );
1679 }
1680 assert!(!descriptor
1681 .attributes
1682 .entries()
1683 .contains_key(&AttributeId::new("shared_intermediate_size").unwrap()));
1684 assert_eq!(descriptor.fingerprint().unwrap().len(), 64);
1685 contract
1686 .validate_signature(&descriptor.inputs, &descriptor.outputs)
1687 .unwrap();
1688 }
1689
1690 #[test]
1691 fn attention_contracts_fix_weight_order_state_mutability_and_scratch() {
1692 let linear = gated_delta_recurrent_attention_contract().unwrap();
1693 let full = causal_paged_attention_contract().unwrap();
1694 for contract in [&linear, &full] {
1695 let descriptor = contract.descriptor();
1696 assert_eq!(
1697 descriptor.resources.scratch,
1698 ResourcePresenceRequirement::Required
1699 );
1700 assert_eq!(
1701 descriptor.outputs[0].alias(),
1702 &AliasPolicy::MayAlias { tensor_index: 0 }
1703 );
1704 assert_eq!(descriptor.fingerprint().unwrap().len(), 64);
1705 contract
1706 .validate_signature(&descriptor.inputs, &descriptor.outputs)
1707 .unwrap();
1708 }
1709 assert_eq!(linear.descriptor().inputs.len(), 10);
1710 assert_eq!(linear.descriptor().version, ContractVersion::new(6, 0));
1711 assert_eq!(
1712 linear.descriptor().resources.binding,
1713 ResourcePresenceRequirement::Optional
1714 );
1715 assert_eq!(
1716 full.descriptor().resources.binding,
1717 ResourcePresenceRequirement::Required
1718 );
1719 assert_eq!(
1720 linear.descriptor().provider.minimum_version,
1721 ContractVersion::new(6, 0)
1722 );
1723 for (name, values) in [
1724 (
1725 "decay_parameterization",
1726 GatedDeltaDecayParameterization::ALL
1727 .map(|value| value.as_str().to_owned())
1728 .into_iter()
1729 .collect(),
1730 ),
1731 (
1732 "value_head_mapping",
1733 GatedDeltaValueHeadMapping::ALL
1734 .map(|value| value.as_str().to_owned())
1735 .into_iter()
1736 .collect(),
1737 ),
1738 ] {
1739 assert_eq!(
1740 linear
1741 .descriptor()
1742 .attributes
1743 .entries()
1744 .get(&AttributeId::new(name).unwrap())
1745 .unwrap()
1746 .constraint,
1747 AttributeConstraint::TextChoices { values }
1748 );
1749 }
1750 for ordinal in [4, 5, 6, 9] {
1751 assert_eq!(
1752 linear.descriptor().inputs[ordinal].element_types(),
1753 &BTreeSet::from([ElementType::F32])
1754 );
1755 }
1756 assert_eq!(
1757 linear.descriptor().inputs[8].access(),
1758 TensorAccess::ReadWrite
1759 );
1760 assert_eq!(
1761 linear.descriptor().inputs[9].access(),
1762 TensorAccess::ReadWrite
1763 );
1764 assert_eq!(full.descriptor().inputs.len(), 9);
1765 assert_eq!(full.descriptor().version, ContractVersion::new(2, 0));
1766 assert_eq!(
1767 full.descriptor().provider.minimum_version,
1768 ContractVersion::new(2, 0)
1769 );
1770 assert_eq!(
1771 full.descriptor().resources.binding,
1772 ResourcePresenceRequirement::Required
1773 );
1774 assert_eq!(
1775 full.descriptor().inputs[8].access(),
1776 TensorAccess::ReadWrite
1777 );
1778 }
1779}