fekan 0.6.5

A library for building and training Kolmogorov-Arnold neural networks.
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
//! Error types relating to the creation and manipulation of [`KanLayer`](crate::kan_layer::KanLayer)s

use bitvec::vec::BitVec;

use crate::kan_layer::edge::{edge_errors::EdgeError, Edge};
use std::fmt::{self, Formatter};

/// Represents any error returned from a KanLayer method or static function
#[derive(Debug, PartialEq, Clone)]
pub struct LayerError {
    error_kind: LayerErrorType,
    source: Option<EdgeError>,
    spline_idx: Option<usize>,
}

#[derive(Debug, PartialEq, Clone)]
enum LayerErrorType {
    MissizedPreacts {
        actual: usize,
        expected: usize,
    },
    NaNsInActivations {
        preacts: Vec<f64>,
        offending_spline: Edge,
    },
    MissizedGradient {
        actual: usize,
        expected: usize,
    },
    BackwardBeforeForward,
    NaNsInGradient,
    NoSamples,
    SetKnotLength,
    MergeNoLayers,
    MergeMismatchedInputDimension {
        pos: usize,
        expected: usize,
        actual: usize,
    },
    MergeMismatchedOutputDimension {
        pos: usize,
        expected: usize,
        actual: usize,
    },
    MergeUnmergableSplines,
    MergeMismatchedEmbeddingDimension {
        pos: usize,
        expected: usize,
        actual: usize,
    },
    MergeMismatchedEmbeddingVocabSize {
        pos: usize,
        expected: usize,
        actual: usize,
    },
    MergeMismatchedEmbeddingFeatures {
        pos: usize,
        expected: BitVec,
        actual: BitVec,
    },
    EmbeddingFloat {
        embedded_features: BitVec,
        input_vec: Vec<f64>,
        problem_index: usize,
        problem_value: f64,
    },
}

impl LayerError {
    // Existing function for MissizedPreacts
    pub(crate) fn missized_preacts(actual: usize, expected: usize) -> Self {
        Self {
            error_kind: LayerErrorType::MissizedPreacts { actual, expected },
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for NaNsInActivations
    pub(crate) fn nans_in_activations(
        spline_idx: usize,
        preacts: Vec<f64>,
        offending_spline: Edge,
    ) -> Self {
        Self {
            error_kind: LayerErrorType::NaNsInActivations {
                preacts,
                offending_spline,
            },
            source: None,
            spline_idx: Some(spline_idx),
        }
    }

    // Initialization function for MissizedGradient
    pub(crate) fn missized_gradient(actual: usize, expected: usize) -> Self {
        Self {
            error_kind: LayerErrorType::MissizedGradient { actual, expected },
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for BackwardBeforeForward
    pub(crate) fn backward_before_forward(
        spline_error: Option<EdgeError>,
        spline_idx: usize,
    ) -> Self {
        Self {
            error_kind: LayerErrorType::BackwardBeforeForward,
            source: spline_error,
            spline_idx: Some(spline_idx),
        }
    }

    // Initialization function for NaNsInGradient
    pub(crate) fn nans_in_gradient() -> Self {
        Self {
            error_kind: LayerErrorType::NaNsInGradient,
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for NoSamples
    pub(crate) fn no_samples() -> Self {
        Self {
            error_kind: LayerErrorType::NoSamples,
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for SetKnotLength
    pub(crate) fn set_knot_length(spline_idx: usize, spline_error: EdgeError) -> Self {
        Self {
            error_kind: LayerErrorType::SetKnotLength,
            source: Some(spline_error),
            spline_idx: Some(spline_idx),
        }
    }

    // Initialization function for MergeNoLayers
    pub(crate) fn merge_no_layers() -> Self {
        Self {
            error_kind: LayerErrorType::MergeNoLayers,
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for MergeMismatchedInputDimension
    pub(crate) fn merge_mismatched_input_dimension(
        pos: usize,
        expected: usize,
        actual: usize,
    ) -> Self {
        Self {
            error_kind: LayerErrorType::MergeMismatchedInputDimension {
                pos,
                expected,
                actual,
            },
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for MergeMismatchedOutputDimension
    pub(crate) fn merge_mismatched_output_dimension(
        pos: usize,
        expected: usize,
        actual: usize,
    ) -> Self {
        Self {
            error_kind: LayerErrorType::MergeMismatchedOutputDimension {
                pos,
                expected,
                actual,
            },
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for SplineMerge
    pub(crate) fn spline_merge(spline_idx: usize, spline_error: EdgeError) -> Self {
        Self {
            error_kind: LayerErrorType::MergeUnmergableSplines,
            source: Some(spline_error),
            spline_idx: Some(spline_idx),
        }
    }

    // Initialization function for MergeMismatchedEmbeddingDimension
    pub(crate) fn merge_mismatched_embedding_dimension(
        pos: usize,
        expected: usize,
        actual: usize,
    ) -> Self {
        Self {
            error_kind: LayerErrorType::MergeMismatchedEmbeddingDimension {
                pos,
                expected,
                actual,
            },
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for MergeMismatchedEmbeddingVocabSize
    pub(crate) fn merge_mismatched_vocab_size(pos: usize, expected: usize, actual: usize) -> Self {
        Self {
            error_kind: LayerErrorType::MergeMismatchedEmbeddingVocabSize {
                pos,
                expected,
                actual,
            },
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for MergeMismatchedEmbeddingFeatures
    pub(crate) fn merge_mismatched_embedded_features(
        pos: usize,
        expected: BitVec,
        actual: BitVec,
    ) -> Self {
        Self {
            error_kind: LayerErrorType::MergeMismatchedEmbeddingFeatures {
                pos,
                expected,
                actual,
            },
            source: None,
            spline_idx: None,
        }
    }

    // Initialization function for EmbeddingFloat
    pub(crate) fn embedding_float(
        embedded_features: BitVec,
        input_vec: Vec<f64>,
        problem_index: usize,
        problem_value: f64,
    ) -> Self {
        Self {
            error_kind: LayerErrorType::EmbeddingFloat {
                embedded_features,
                input_vec,
                problem_index,
                problem_value,
            },
            source: None,
            spline_idx: None,
        }
    }
}

impl fmt::Display for LayerError {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        match &self.error_kind {
            LayerErrorType::MissizedPreacts { actual, expected } => {
                write!(
                    f,
                    "Bad preactivation length. Expected {}, got {}",
                    expected, actual
                )
            }
            LayerErrorType::NaNsInActivations {
                preacts,
                offending_spline,
            } => {
                write!(
                    f,
                    "NaNs in activations for spline {} - preacts: {:?} - bad knots: {:?}",
                    self.spline_idx
                        .expect("NaNsInActivations error must have a spline index"),
                    preacts,
                    offending_spline.knots()
                )
            }
            LayerErrorType::MissizedGradient { actual, expected } => {
                write!(
                    f,
                    "received error vector of length {} but required vector of length {}",
                    actual, expected
                )
            }
            LayerErrorType::BackwardBeforeForward => {
                write!(f, "backward called before forward")
            }
            LayerErrorType::NaNsInGradient => {
                write!(f, "received NaNs in gradient vector during backpropogation")
            }
            LayerErrorType::SetKnotLength => {
                write!(
                    f,
                    "setting layer knot length resulted in error at spline {} - {}",
                    self.spline_idx
                        .expect("SetKnotLength error must have a spline index"),
                    self.source
                        .as_ref()
                        .expect("SetKnotLength error must have a source spline error")
                )
            }
            LayerErrorType::NoSamples => {
                write!(f, "called an internal-cache-consuming function without first populating the cache with calls to `forward()`")
            }
            LayerErrorType::MergeNoLayers => {
                write!(f, "no layers to merge")
            }
            LayerErrorType::MergeMismatchedInputDimension {
                pos,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "while merging layers, layer {} had a different input dimension than the first layer. Expected {}, got {}",
                    pos, expected, actual
                )
            }
            LayerErrorType::MergeMismatchedOutputDimension {
                pos,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "while merging layers, layer {} had a different output dimension than the first layer. Expected {}, got {}",
                    pos, expected, actual
                )
            }

            LayerErrorType::MergeUnmergableSplines {} => {
                write!(
                    f,
                    "error merging splines at index {} - {:?}",
                    self.spline_idx
                        .expect("SplineMerge error must have a spline index"),
                    self.source
                        .as_ref()
                        .expect("SplineMerge error must have a source spline error")
                )
            }

            LayerErrorType::MergeMismatchedEmbeddingDimension {
                pos,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "while merging layers, layer {} had a different embedding dimension than the first layer. Expected {}, got {}",
                    pos, expected, actual
                )
            }

            LayerErrorType::MergeMismatchedEmbeddingVocabSize {
                pos,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "while merging layers, layer {} had a different embedding vocab size than the first layer. Expected {}, got {}",
                    pos, expected, actual
                )
            }

            LayerErrorType::MergeMismatchedEmbeddingFeatures {
                pos,
                expected,
                actual,
            } => {
                write!(
                    f,
                    "while merging layers, layer {} had different embedding features than the first layer. Expected {:?}, got {:?}",
                    pos, expected, actual
                )
            }
            LayerErrorType::EmbeddingFloat {
                embedded_features,
                input_vec,
                problem_index,
                problem_value,
            } => {
                write!(
                    f,
                    "embedding layer had a float in the input vector at index {} - embedded features: {:?} - input vector: {:?} - problem value: {}",
                    problem_index, embedded_features, input_vec, problem_value
                )
            }
        }
    }
}

impl std::error::Error for LayerError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match &self.source {
            Some(source) => Some(source),
            None => None,
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_layer_error_send() {
        fn assert_send<T: Send>() {}
        assert_send::<LayerError>();
    }

    #[test]
    fn test_layer_error_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<LayerError>();
    }
}