incin-core 0.1.0

Core tensor operations and static shape checking for incin
Documentation
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
//! Typed two-rank tensor-parallel collective plans.
//!
//! Column-parallel linear and head-parallel attention produce shards that may
//! be gathered into a replicated tensor. Row-parallel linear produces local
//! partial sums that must be all-reduced. This module fixes those three
//! semantics for exactly `TP=2`, keeps operation identity in collective
//! preflight, and gives static and [`Dyn`] callers matching validation paths.

use alloc::vec::Vec;

use half::{bf16, f16};
use typenum::{U1, U2};

use crate::dist::collective::{CollectiveError, CollectiveReductionDType, StreamId};
use crate::dist::mesh::{Data, DeviceMesh, MeshAxis, MeshSpec, Pipeline, TensorParallel};
use crate::dist::placement::{Partial, PlacementAxis, PlacementKind, Replicated, Sharded, Sum};
use crate::dist::plan::{
    CollectivePlan, CollectivePlanBuilder, CollectiveTag, PlanError, SequenceToken,
};
use crate::dist::rule::ShardDivisible;
use crate::shapes::Dyn;
use crate::tensor::dtype::{BuiltinDType, ConstDType, DTypeId};

/// Exactly two tensor-parallel ranks and no data or pipeline partitioning.
pub type TwoRankTensorParallel = MeshSpec<Data<U1>, TensorParallel<U2>, Pipeline<U1>>;

/// Floating dtypes supported by the first tensor-parallel linear/attention path.
///
/// Static integer and block-quantized dtypes intentionally have no
/// implementation. [`Dyn`] is admitted so
/// [`validate_tensor_parallel_dtype`] can enforce the same policy at runtime.
pub trait TensorParallelDType: CollectiveReductionDType<Sum> {}

impl TensorParallelDType for f32 {}
impl TensorParallelDType for f64 {}
impl TensorParallelDType for f16 {}
impl TensorParallelDType for bf16 {}
impl TensorParallelDType for Dyn {}

/// Compile-time proof that an extent divides evenly across two TP ranks.
pub trait TwoWayShard: ShardDivisible<U2> {}

impl<T> TwoWayShard for T where T: ShardDivisible<U2> {}

/// Runtime counterpart of [`TensorParallelDType`].
pub const fn validate_tensor_parallel_dtype(dtype: DTypeId) -> Result<(), TensorParallelError> {
    match dtype {
        DTypeId::BF16 | DTypeId::F16 | DTypeId::F32 | DTypeId::F64 => Ok(()),
        DTypeId::U8 | DTypeId::U32 | DTypeId::I64 | DTypeId::Q8_0 | DTypeId::Bool => {
            Err(TensorParallelError::UnsupportedTensorDType { dtype })
        }
    }
}

/// Which dimension is being statically or dynamically partitioned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TensorParallelDimension {
    /// A column-parallel linear layer's output-feature dimension.
    OutputFeatures,
    /// A row-parallel linear layer's contraction/input-feature dimension.
    InputFeatures,
    /// An attention layer's head dimension.
    AttentionHeads,
}

/// Validate and project one runtime extent onto two equal shards.
pub const fn validate_two_way_extent(
    dimension: TensorParallelDimension,
    extent: usize,
) -> Result<usize, TensorParallelError> {
    if !extent.is_multiple_of(2) {
        Err(TensorParallelError::NonDivisible {
            dimension,
            extent,
            ranks: 2,
        })
    } else {
        Ok(extent / 2)
    }
}

/// Stable identity of one tensor-parallel semantic operation.
///
/// The upper two bits are rejected because the plan tag reserves two low bits
/// for the operation kind. This makes column and attention gathers with equal
/// shapes distinguishable without relying on process-local hashes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct TensorParallelId(u64);

impl TensorParallelId {
    const MAX: u64 = u64::MAX >> 2;

    /// Build a nonzero identity that can be encoded losslessly in a plan tag.
    pub const fn new(value: u64) -> Result<Self, TensorParallelError> {
        if value == 0 {
            Err(TensorParallelError::ReservedOperationId)
        } else if value > Self::MAX {
            Err(TensorParallelError::OperationIdTooLarge {
                maximum: Self::MAX,
                found: value,
            })
        } else {
            Ok(Self(value))
        }
    }

    /// Numeric caller-defined identity.
    #[must_use]
    pub const fn get(self) -> u64 {
        self.0
    }
}

/// Tensor-parallel communication attached to one layer operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TensorParallelCollective {
    /// Gather output-feature shards from a column-parallel linear.
    ColumnOutputGather {
        /// Tensor axis partitioned across ranks.
        tensor_axis: usize,
    },
    /// Sum row-parallel local products into a replicated output.
    RowOutputSum,
    /// Gather independently computed attention-head shards.
    AttentionHeadGather {
        /// Tensor axis containing the attention heads.
        tensor_axis: usize,
    },
}

impl TensorParallelCollective {
    const fn tag_code(self) -> u64 {
        match self {
            Self::ColumnOutputGather { .. } => 1,
            Self::RowOutputSum => 2,
            Self::AttentionHeadGather { .. } => 3,
        }
    }

    /// Stable semantic tag included in collective preflight.
    #[must_use]
    pub const fn plan_tag(self, id: TensorParallelId) -> CollectiveTag {
        CollectiveTag::new((id.get() << 2) | self.tag_code())
    }
}

/// One tensor-parallel operation in launch order.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TensorParallelDescriptor {
    id: TensorParallelId,
    collective: TensorParallelCollective,
    local_elements: usize,
    global_elements: usize,
    dtype: DTypeId,
    sequence: SequenceToken,
}

impl TensorParallelDescriptor {
    /// Stable layer/operation identity.
    #[must_use]
    pub const fn id(self) -> TensorParallelId {
        self.id
    }

    /// Tensor-parallel semantic operation.
    #[must_use]
    pub const fn collective(self) -> TensorParallelCollective {
        self.collective
    }

    /// Elements supplied by this rank.
    #[must_use]
    pub const fn local_elements(self) -> usize {
        self.local_elements
    }

    /// Elements in the replicated logical result.
    #[must_use]
    pub const fn global_elements(self) -> usize {
        self.global_elements
    }

    /// Static or runtime-resolved compute/storage dtype.
    #[must_use]
    pub const fn dtype(self) -> DTypeId {
        self.dtype
    }

    /// Position in the transport plan.
    #[must_use]
    pub const fn sequence(self) -> SequenceToken {
        self.sequence
    }
}

/// Immutable TP=2 plan and its semantic layer operations.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TensorParallelPlan {
    collective: CollectivePlan,
    operations: Vec<TensorParallelDescriptor>,
}

impl TensorParallelPlan {
    /// Transport-neutral collective plan.
    #[must_use]
    pub const fn collective_plan(&self) -> &CollectivePlan {
        &self.collective
    }

    /// Ordered tensor-parallel operations.
    #[must_use]
    pub fn operations(&self) -> &[TensorParallelDescriptor] {
        &self.operations
    }

    /// Consume the wrapper for transport bootstrap.
    #[must_use]
    pub fn into_collective_plan(self) -> CollectivePlan {
        self.collective
    }
}

/// Builder for exactly two tensor-parallel ranks.
pub struct TensorParallelPlanBuilder<'a> {
    inner: CollectivePlanBuilder<'a, TwoRankTensorParallel>,
    rank: usize,
    previous: Option<SequenceToken>,
    operations: Vec<TensorParallelDescriptor>,
}

impl<'a> TensorParallelPlanBuilder<'a> {
    /// Begin a rank-local plan on a physically bound TP=2 mesh.
    #[must_use]
    pub fn new(mesh: &'a DeviceMesh<TwoRankTensorParallel>, rank: usize) -> Self {
        Self {
            inner: CollectivePlanBuilder::new(mesh),
            rank,
            previous: None,
            operations: Vec::new(),
        }
    }

    /// Gather a statically proved column-parallel output.
    ///
    /// `Out` is the global output-feature extent and must divide by two.
    /// `outer_elements` is the product of every non-output axis.
    pub fn push_column_static<K, Axis, Out>(
        &mut self,
        id: TensorParallelId,
        outer_elements: usize,
        stream: StreamId,
    ) -> Result<SequenceToken, TensorParallelError>
    where
        K: ConstDType + BuiltinDType + TensorParallelDType,
        Axis: PlacementAxis,
        Out: TwoWayShard,
    {
        let local_elements = checked_product(
            TensorParallelDimension::OutputFeatures,
            outer_elements,
            <Out as ShardDivisible<U2>>::LOCAL,
        )?;
        let global_elements = checked_double(local_elements)?;
        let rank = self.rank;
        let collective = TensorParallelCollective::ColumnOutputGather {
            tensor_axis: Axis::INDEX,
        };
        self.push_common(
            id,
            collective,
            local_elements,
            global_elements,
            K::DTYPE,
            |inner, tag, dependency| {
                inner.push_static_tagged::<
                    K,
                    Sharded<TwoRankTensorParallel, Axis>,
                    Replicated<TwoRankTensorParallel>,
                >(
                    tag,
                    MeshAxis::Tensor,
                    rank,
                    local_elements,
                    stream,
                    dependency,
                )
            },
        )
    }

    /// Runtime-selected counterpart of [`push_column_static`](Self::push_column_static).
    pub fn push_column_dyn(
        &mut self,
        id: TensorParallelId,
        global_shape: &[usize],
        output_axis: usize,
        dtype: DTypeId,
        stream: StreamId,
    ) -> Result<SequenceToken, TensorParallelError> {
        validate_tensor_parallel_dtype(dtype)?;
        let (local_elements, global_elements) = dynamic_sharded_elements(
            TensorParallelDimension::OutputFeatures,
            global_shape,
            output_axis,
        )?;
        let rank = self.rank;
        let collective = TensorParallelCollective::ColumnOutputGather {
            tensor_axis: output_axis,
        };
        self.push_common(
            id,
            collective,
            local_elements,
            global_elements,
            dtype,
            |inner, tag, dependency| {
                inner.push_dyn_tagged(
                    tag,
                    MeshAxis::Tensor,
                    rank,
                    local_elements,
                    dtype,
                    PlacementKind::Sharded { axis: output_axis },
                    PlacementKind::Replicated,
                    stream,
                    dependency,
                )
            },
        )
    }

    /// Sum statically proved row-parallel local products.
    ///
    /// `In` is the global contraction extent and must divide by two.
    pub fn push_row_static<K, In>(
        &mut self,
        id: TensorParallelId,
        output_elements: usize,
        stream: StreamId,
    ) -> Result<SequenceToken, TensorParallelError>
    where
        K: ConstDType + BuiltinDType + TensorParallelDType,
        In: TwoWayShard,
    {
        let _ = <In as ShardDivisible<U2>>::LOCAL;
        let rank = self.rank;
        self.push_common(
            id,
            TensorParallelCollective::RowOutputSum,
            output_elements,
            output_elements,
            K::DTYPE,
            |inner, tag, dependency| {
                inner.push_static_tagged::<
                    K,
                    Partial<TwoRankTensorParallel, Sum>,
                    Replicated<TwoRankTensorParallel>,
                >(
                    tag,
                    MeshAxis::Tensor,
                    rank,
                    output_elements,
                    stream,
                    dependency,
                )
            },
        )
    }

    /// Runtime-selected counterpart of [`push_row_static`](Self::push_row_static).
    pub fn push_row_dyn(
        &mut self,
        id: TensorParallelId,
        global_input_features: usize,
        output_elements: usize,
        dtype: DTypeId,
        stream: StreamId,
    ) -> Result<SequenceToken, TensorParallelError> {
        validate_tensor_parallel_dtype(dtype)?;
        validate_two_way_extent(
            TensorParallelDimension::InputFeatures,
            global_input_features,
        )?;
        let rank = self.rank;
        self.push_common(
            id,
            TensorParallelCollective::RowOutputSum,
            output_elements,
            output_elements,
            dtype,
            |inner, tag, dependency| {
                inner.push_dyn_tagged(
                    tag,
                    MeshAxis::Tensor,
                    rank,
                    output_elements,
                    dtype,
                    PlacementKind::Partial {
                        reduction: crate::exec::ReduceOp::Sum,
                    },
                    PlacementKind::Replicated,
                    stream,
                    dependency,
                )
            },
        )
    }

    /// Gather statically proved attention-head shards.
    ///
    /// `Heads` is the global head count. `elements_per_head` includes batch,
    /// sequence, and head-width factors.
    pub fn push_attention_static<K, Axis, Heads>(
        &mut self,
        id: TensorParallelId,
        elements_per_head: usize,
        stream: StreamId,
    ) -> Result<SequenceToken, TensorParallelError>
    where
        K: ConstDType + BuiltinDType + TensorParallelDType,
        Axis: PlacementAxis,
        Heads: TwoWayShard,
    {
        let local_elements = checked_product(
            TensorParallelDimension::AttentionHeads,
            elements_per_head,
            <Heads as ShardDivisible<U2>>::LOCAL,
        )?;
        let global_elements = checked_double(local_elements)?;
        let rank = self.rank;
        let collective = TensorParallelCollective::AttentionHeadGather {
            tensor_axis: Axis::INDEX,
        };
        self.push_common(
            id,
            collective,
            local_elements,
            global_elements,
            K::DTYPE,
            |inner, tag, dependency| {
                inner.push_static_tagged::<
                    K,
                    Sharded<TwoRankTensorParallel, Axis>,
                    Replicated<TwoRankTensorParallel>,
                >(
                    tag,
                    MeshAxis::Tensor,
                    rank,
                    local_elements,
                    stream,
                    dependency,
                )
            },
        )
    }

    /// Runtime-selected counterpart of
    /// [`push_attention_static`](Self::push_attention_static).
    pub fn push_attention_dyn(
        &mut self,
        id: TensorParallelId,
        global_shape: &[usize],
        head_axis: usize,
        dtype: DTypeId,
        stream: StreamId,
    ) -> Result<SequenceToken, TensorParallelError> {
        validate_tensor_parallel_dtype(dtype)?;
        let (local_elements, global_elements) = dynamic_sharded_elements(
            TensorParallelDimension::AttentionHeads,
            global_shape,
            head_axis,
        )?;
        let rank = self.rank;
        let collective = TensorParallelCollective::AttentionHeadGather {
            tensor_axis: head_axis,
        };
        self.push_common(
            id,
            collective,
            local_elements,
            global_elements,
            dtype,
            |inner, tag, dependency| {
                inner.push_dyn_tagged(
                    tag,
                    MeshAxis::Tensor,
                    rank,
                    local_elements,
                    dtype,
                    PlacementKind::Sharded { axis: head_axis },
                    PlacementKind::Replicated,
                    stream,
                    dependency,
                )
            },
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn push_common(
        &mut self,
        id: TensorParallelId,
        collective: TensorParallelCollective,
        local_elements: usize,
        global_elements: usize,
        dtype: DTypeId,
        append: impl FnOnce(
            &mut CollectivePlanBuilder<'a, TwoRankTensorParallel>,
            CollectiveTag,
            Option<SequenceToken>,
        ) -> Result<SequenceToken, PlanError>,
    ) -> Result<SequenceToken, TensorParallelError> {
        if self.operations.iter().any(|operation| operation.id == id) {
            return Err(TensorParallelError::DuplicateOperation { id });
        }
        let tag = collective.plan_tag(id);
        let sequence = append(&mut self.inner, tag, self.previous)?;
        self.operations.push(TensorParallelDescriptor {
            id,
            collective,
            local_elements,
            global_elements,
            dtype,
            sequence,
        });
        self.previous = Some(sequence);
        Ok(sequence)
    }

    /// Freeze the plan. An empty TP plan is rejected rather than reported as a
    /// successful distributed execution.
    pub fn finish(self) -> Result<TensorParallelPlan, TensorParallelError> {
        if self.operations.is_empty() {
            return Err(TensorParallelError::NoOperations);
        }
        Ok(TensorParallelPlan {
            collective: self.inner.finish(),
            operations: self.operations,
        })
    }
}

fn dynamic_sharded_elements(
    dimension: TensorParallelDimension,
    global_shape: &[usize],
    axis: usize,
) -> Result<(usize, usize), TensorParallelError> {
    let Some(&extent) = global_shape.get(axis) else {
        return Err(TensorParallelError::AxisOutOfBounds {
            axis,
            rank: global_shape.len(),
        });
    };
    validate_two_way_extent(dimension, extent)?;
    let global_elements = checked_numel(global_shape)?;
    Ok((global_elements / 2, global_elements))
}

fn checked_numel(shape: &[usize]) -> Result<usize, TensorParallelError> {
    shape.iter().copied().try_fold(1usize, |elements, extent| {
        elements
            .checked_mul(extent)
            .ok_or(TensorParallelError::ElementCountOverflow)
    })
}

fn checked_product(
    _dimension: TensorParallelDimension,
    lhs: usize,
    rhs: usize,
) -> Result<usize, TensorParallelError> {
    lhs.checked_mul(rhs)
        .ok_or(TensorParallelError::ElementCountOverflow)
}

fn checked_double(elements: usize) -> Result<usize, TensorParallelError> {
    elements
        .checked_mul(2)
        .ok_or(TensorParallelError::ElementCountOverflow)
}

/// Failure while building a TP=2 linear/attention plan.
#[non_exhaustive]
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum TensorParallelError {
    /// Zero is reserved for generic unlabelled collectives.
    #[error("tensor-parallel operation identity zero is reserved")]
    ReservedOperationId,
    /// Operation identities must leave room for the semantic tag bits.
    #[error("tensor-parallel operation identity {found} exceeds maximum {maximum}")]
    OperationIdTooLarge {
        /// Largest losslessly encodable identity.
        maximum: u64,
        /// Rejected identity.
        found: u64,
    },
    /// The same semantic operation appeared twice in one plan.
    #[error("tensor-parallel operation identity {id:?} appears more than once")]
    DuplicateOperation {
        /// Repeated operation identity.
        id: TensorParallelId,
    },
    /// A tensor-parallel plan described no communication.
    #[error("a tensor-parallel plan must contain at least one operation")]
    NoOperations,
    /// Runtime `Dyn` selected a non-floating linear/attention dtype.
    #[error("dtype {dtype:?} cannot represent tensor-parallel linear or attention values")]
    UnsupportedTensorDType {
        /// Rejected runtime dtype.
        dtype: DTypeId,
    },
    /// A required TP=2 dimension did not divide evenly.
    #[error("{dimension:?} extent {extent} is not divisible by {ranks} tensor-parallel ranks")]
    NonDivisible {
        /// Semantic dimension that failed.
        dimension: TensorParallelDimension,
        /// Runtime extent.
        extent: usize,
        /// Required rank count.
        ranks: usize,
    },
    /// Runtime tensor axis was outside the supplied shape.
    #[error("tensor axis {axis} is outside rank {rank}")]
    AxisOutOfBounds {
        /// Rejected axis.
        axis: usize,
        /// Runtime tensor rank.
        rank: usize,
    },
    /// Shape cardinality could not be represented by `usize`.
    #[error("tensor-parallel element count overflows usize")]
    ElementCountOverflow,
    /// The underlying collective plan was invalid.
    #[error(transparent)]
    Plan(#[from] PlanError),
    /// Shared collective validation failed.
    #[error(transparent)]
    Collective(#[from] CollectiveError),
}