candle-graph 0.1.0

Static structure and dataflow analysis for candle-rs models
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
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Unified, agent-oriented representation of a Candle model crate.
//!
//! The structure and expression analyzers intentionally keep their own compact arenas while
//! running. `ModelIr` is the durable interchange layer that joins those arenas with Cargo,
//! pipeline, optimizer, artifact, tensor-contract, and runtime evidence.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

/// Versioned schema emitted by scans and consumed by the query/runtime layers.
pub const MODEL_IR_SCHEMA: &str = "candle-graph/model/1";

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct StableId(pub String);

impl StableId {
    pub fn new(kind: &str, parts: impl IntoIterator<Item = impl AsRef<str>>) -> Self {
        let mut value = String::from(kind);
        for part in parts {
            value.push(':');
            escape_id_part(part.as_ref(), &mut value);
        }
        Self(value)
    }
}

impl std::fmt::Display for StableId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EvidenceKind {
    Source,
    Cargo,
    Checkpoint,
    Runtime,
    Inferred,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Confidence {
    Proven,
    Conditional,
    Heuristic,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Evidence {
    pub kind: EvidenceKind,
    pub confidence: Confidence,
    pub source: Option<String>,
    pub detail: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Visibility {
    Public,
    Crate,
    Restricted,
    Private,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BuilderRole {
    Trainable,
    Frozen,
    State,
    Conditional,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ParameterRole {
    Optimized,
    Frozen,
    RunningState,
    Excluded,
    Conditional,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TensorRole {
    Input,
    Output,
    Parameter,
    Activation,
    Target,
    Mask,
    Loss,
    Cache,
    State,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DeviceFact {
    Cpu,
    Cuda { ordinal: Option<u32> },
    Metal,
    SameAs(String),
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum LayoutFact {
    Contiguous,
    NonContiguous,
    Strided,
    SameAs(String),
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Dimension {
    /// Stable semantic label when one is known (`batch`, `tokens`, `hidden`, ...).
    pub name: Option<String>,
    /// Literal or symbolic Rust expression.
    pub expr: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ShapeFact {
    pub rank: Option<usize>,
    pub dimensions: Vec<Dimension>,
    pub source_expr: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TensorContract {
    pub id: StableId,
    pub name: String,
    pub role: TensorRole,
    pub owner_function: StableId,
    pub parameter: Option<StableId>,
    pub shape: ShapeFact,
    pub dtype: String,
    pub device: DeviceFact,
    pub layout: LayoutFact,
    pub requires_grad: Option<bool>,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BuilderNamespace {
    pub name: String,
    pub role: BuilderRole,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Component {
    pub id: StableId,
    pub name: String,
    pub qualified_name: String,
    pub source: String,
    pub constructor: StableId,
    pub builders: Vec<BuilderNamespace>,
    pub modules: Vec<StableId>,
    pub parameters: Vec<StableId>,
    pub entrypoints: Vec<StableId>,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ArchitectureEdge {
    pub id: StableId,
    pub from: StableId,
    pub to: StableId,
    pub via_function: StableId,
    pub source: String,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Module {
    pub id: StableId,
    pub component: StableId,
    pub parent: Option<StableId>,
    pub type_name: String,
    pub qualified_type: Option<String>,
    pub field: Option<String>,
    pub builder_root: String,
    pub prefix: String,
    pub repeat: Option<String>,
    pub source: String,
    pub confidence: Confidence,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Parameter {
    pub id: StableId,
    pub component: StableId,
    pub module: StableId,
    pub key: String,
    pub builder_root: String,
    pub role: ParameterRole,
    pub kind: String,
    pub symbolic_shape: Option<String>,
    pub checkpoint_shape: Option<Vec<usize>>,
    pub checkpoint_dtype: Option<String>,
    pub source: String,
    pub uses: Vec<StableId>,
    pub optimizer_memberships: Vec<StableId>,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Function {
    pub id: StableId,
    pub name: String,
    pub qualified_name: String,
    pub owner_type: Option<String>,
    pub visibility: Visibility,
    pub parameters: Vec<FunctionParameter>,
    pub return_type: Option<String>,
    /// Source-level `#[cfg(...)]` predicates inherited by this definition.
    pub cfg_predicates: Vec<String>,
    /// Whether those predicates match the selected Cargo feature/target context.
    /// `None` means no Cargo context was available or a predicate was unsupported.
    pub cfg_active: Option<bool>,
    pub source: String,
    pub calls: Vec<StableId>,
    pub tensor_inputs: Vec<StableId>,
    pub tensor_outputs: Vec<StableId>,
    pub is_entrypoint: bool,
    pub is_loss: bool,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FunctionParameter {
    pub name: String,
    pub type_name: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Operation {
    pub id: StableId,
    pub function: StableId,
    pub name: String,
    pub qualified_name: Option<String>,
    pub inputs: Vec<StableId>,
    pub output: StableId,
    pub source: String,
    pub dtype_rule: String,
    pub gradient_rule: String,
    pub device_rule: String,
    pub shape_rule: String,
    /// Float-range transfer after rounding (`real`, `non_negative`, `saturating_unit`, …).
    #[serde(default)]
    pub domain_rule: String,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StageKind {
    Prepare,
    Train,
    Evaluate,
    Export,
    Probe,
    Unknown,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum StageDispatchKind {
    #[default]
    Unknown,
    Inline,
    Subprocess,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PipelineStage {
    pub id: StableId,
    pub name: String,
    pub kind: StageKind,
    pub function: StableId,
    pub order: Option<usize>,
    pub components: Vec<StableId>,
    pub consumes: Vec<StableId>,
    pub produces: Vec<StableId>,
    pub depends_on: Vec<StableId>,
    pub source: String,
    pub evidence: Vec<Evidence>,
    #[serde(default)]
    pub dispatch: StageDispatchKind,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub subprocess_key: Option<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub cli_flags: Vec<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub launcher: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub orchestrator: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ArtifactKind {
    Checkpoint,
    OptimizerState,
    Dataset,
    Vocabulary,
    Cache,
    EvaluationReport,
    Configuration,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Artifact {
    pub id: StableId,
    pub name: String,
    pub kind: ArtifactKind,
    pub path_expr: String,
    pub produced_by: Vec<StableId>,
    pub consumed_by: Vec<StableId>,
    pub source: String,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BuilderSourceKind {
    VarMap,
    MmapSafetensors,
    FromTensors,
    BufferedSafetensors,
    Unknown,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AssemblySite {
    pub id: StableId,
    pub function: StableId,
    pub function_name: String,
    pub component: StableId,
    pub component_name: String,
    pub builder_root: String,
    pub prefix_chain: Vec<String>,
    pub varmap: Option<String>,
    pub source_kind: BuilderSourceKind,
    pub role: BuilderRole,
    pub checkpoint_load: Option<String>,
    pub source: String,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct OptimizerMembership {
    pub id: StableId,
    pub stage: StableId,
    pub optimizer: String,
    pub varmap: String,
    pub components: Vec<StableId>,
    pub builder_roots: Vec<String>,
    pub include_patterns: Vec<String>,
    pub exclude_patterns: Vec<String>,
    pub conditional: Option<String>,
    pub source: String,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum FindingSeverity {
    Error,
    Warning,
    Information,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Finding {
    pub id: StableId,
    pub rule: String,
    pub severity: FindingSeverity,
    pub confidence: Confidence,
    pub message: String,
    pub source: Option<String>,
    pub related: Vec<StableId>,
    pub evidence: Vec<Evidence>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
pub struct ModelCoverage {
    pub components: usize,
    pub architecture_edges: usize,
    pub modules: usize,
    pub parameters: usize,
    pub functions: usize,
    pub entrypoints: usize,
    pub component_entrypoints: usize,
    pub composition_edges: usize,
    pub assembly_sites: usize,
    pub subprocess_stages: usize,
    pub tensors: usize,
    pub operations: usize,
    pub pipeline_stages: usize,
    pub artifacts: usize,
    pub optimizer_memberships: usize,
    pub linked_parameter_uses: usize,
    pub tensors_with_shape: usize,
    pub tensors_with_dtype: usize,
    pub tensors_with_device: usize,
    pub runtime_observations: usize,
    pub diagnostics: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CargoSummary {
    /// Deterministic identity of the exact Cargo configuration used for this scan.
    #[serde(default)]
    pub build_id: String,
    pub workspace_root: String,
    pub manifest_path: String,
    pub package_name: String,
    pub package_version: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub selected_target: Option<String>,
    pub active_features: Vec<String>,
    pub active_cfg: Vec<String>,
    pub candle_packages: BTreeMap<String, String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct RuntimeSummary {
    pub trace_schema: String,
    pub entrypoint: Option<String>,
    pub profile: Option<String>,
    pub tensor_observations: usize,
    #[serde(default)]
    pub operation_observations: usize,
    pub gradient_observations: usize,
    pub missing_gradients: usize,
    pub zero_gradients: usize,
    pub non_finite_gradients: usize,
    #[serde(default)]
    pub tensor_conflicts: usize,
    #[serde(default)]
    pub gradient_conflicts: usize,
    #[serde(default)]
    pub identity_mismatches: usize,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub first_non_finite_step: Option<u64>,
    #[serde(default)]
    pub saturating_activations: usize,
    #[serde(default)]
    pub value_observations: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ModelIr {
    pub schema: String,
    pub analysis_id: StableId,
    pub cargo: Option<CargoSummary>,
    pub coverage: ModelCoverage,
    pub components: Vec<Component>,
    pub architecture_edges: Vec<ArchitectureEdge>,
    pub modules: Vec<Module>,
    pub parameters: Vec<Parameter>,
    pub functions: Vec<Function>,
    pub tensors: Vec<TensorContract>,
    pub operations: Vec<Operation>,
    pub stages: Vec<PipelineStage>,
    pub artifacts: Vec<Artifact>,
    pub optimizers: Vec<OptimizerMembership>,
    pub assembly_sites: Vec<AssemblySite>,
    pub findings: Vec<Finding>,
    pub runtime: Option<RuntimeSummary>,
}

impl ModelIr {
    pub fn empty(analysis_id: StableId) -> Self {
        Self {
            schema: MODEL_IR_SCHEMA.to_string(),
            analysis_id,
            cargo: None,
            coverage: ModelCoverage::default(),
            components: Vec::new(),
            architecture_edges: Vec::new(),
            modules: Vec::new(),
            parameters: Vec::new(),
            functions: Vec::new(),
            tensors: Vec::new(),
            operations: Vec::new(),
            stages: Vec::new(),
            artifacts: Vec::new(),
            optimizers: Vec::new(),
            assembly_sites: Vec::new(),
            findings: Vec::new(),
            runtime: None,
        }
    }

    pub fn normalize(&mut self) {
        self.components.sort_by(|a, b| a.id.cmp(&b.id));
        self.architecture_edges.sort_by(|a, b| a.id.cmp(&b.id));
        self.modules.sort_by(|a, b| a.id.cmp(&b.id));
        self.parameters.sort_by(|a, b| a.id.cmp(&b.id));
        self.functions.sort_by(|a, b| a.id.cmp(&b.id));
        self.tensors.sort_by(|a, b| a.id.cmp(&b.id));
        self.operations.sort_by(|a, b| a.id.cmp(&b.id));
        self.stages.sort_by(|a, b| {
            (a.order.unwrap_or(usize::MAX), &a.id).cmp(&(b.order.unwrap_or(usize::MAX), &b.id))
        });
        self.artifacts.sort_by(|a, b| a.id.cmp(&b.id));
        self.optimizers.sort_by(|a, b| a.id.cmp(&b.id));
        self.findings.sort_by(|a, b| a.id.cmp(&b.id));
        self.components.dedup_by(|a, b| a.id == b.id);
        self.architecture_edges.dedup_by(|a, b| a.id == b.id);
        self.modules.dedup_by(|a, b| a.id == b.id);
        self.parameters.dedup_by(|a, b| a.id == b.id);
        self.functions.dedup_by(|a, b| a.id == b.id);
        self.tensors.dedup_by(|a, b| a.id == b.id);
        self.operations.dedup_by(|a, b| a.id == b.id);
        self.artifacts.dedup_by(|a, b| a.id == b.id);
        self.optimizers.dedup_by(|a, b| a.id == b.id);
        let mut merged_findings: Vec<Finding> = Vec::with_capacity(self.findings.len());
        for finding in self.findings.drain(..) {
            if let Some(existing) = merged_findings
                .last_mut()
                .filter(|existing| existing.id == finding.id)
            {
                existing.related.extend(finding.related);
                existing.evidence.extend(finding.evidence);
            } else {
                merged_findings.push(finding);
            }
        }
        self.findings = merged_findings;
        for component in &mut self.components {
            component.modules.sort();
            component.modules.dedup();
            component.parameters.sort();
            component.parameters.dedup();
            component.entrypoints.sort();
            component.entrypoints.dedup();
            component.builders.sort_by(|a, b| a.name.cmp(&b.name));
        }
        for function in &mut self.functions {
            function.calls.sort();
            function.calls.dedup();
            function.tensor_inputs.sort();
            function.tensor_inputs.dedup();
            function.tensor_outputs.sort();
            function.tensor_outputs.dedup();
        }
        for parameter in &mut self.parameters {
            parameter.uses.sort();
            parameter.uses.dedup();
            parameter.optimizer_memberships.sort();
            parameter.optimizer_memberships.dedup();
        }
        for finding in &mut self.findings {
            finding.related.sort();
            finding.related.dedup();
            finding
                .evidence
                .sort_by(|a, b| (&a.source, &a.detail).cmp(&(&b.source, &b.detail)));
            finding
                .evidence
                .dedup_by(|a, b| a.source == b.source && a.detail == b.detail);
        }
        self.refresh_coverage();
    }

    pub fn refresh_coverage(&mut self) {
        self.coverage.components = self.components.len();
        self.coverage.architecture_edges = self.architecture_edges.len();
        self.coverage.modules = self.modules.len();
        self.coverage.parameters = self.parameters.len();
        self.coverage.functions = self.functions.len();
        self.coverage.entrypoints = self.functions.iter().filter(|f| f.is_entrypoint).count();
        let component_types: BTreeMap<String, ()> = self
            .components
            .iter()
            .flat_map(|component| [component.name.clone(), component.qualified_name.clone()])
            .map(|name| (name, ()))
            .collect();
        self.coverage.component_entrypoints = self
            .functions
            .iter()
            .filter(|function| {
                function.is_entrypoint
                    && function
                        .owner_type
                        .as_ref()
                        .is_some_and(|owner| component_types.contains_key(owner))
            })
            .count();
        self.coverage.composition_edges = self
            .architecture_edges
            .iter()
            .filter(|edge| edge.id.0.starts_with("composition-edge:"))
            .count();
        self.coverage.assembly_sites = self.assembly_sites.len();
        self.coverage.subprocess_stages = self
            .stages
            .iter()
            .filter(|stage| stage.dispatch == StageDispatchKind::Subprocess)
            .count();
        self.coverage.tensors = self.tensors.len();
        self.coverage.operations = self.operations.len();
        self.coverage.pipeline_stages = self.stages.len();
        self.coverage.artifacts = self.artifacts.len();
        self.coverage.optimizer_memberships = self.optimizers.len();
        self.coverage.linked_parameter_uses =
            self.parameters.iter().map(|p| p.uses.len()).sum::<usize>();
        self.coverage.tensors_with_shape = self
            .tensors
            .iter()
            .filter(|t| t.shape.rank.is_some() || !t.shape.dimensions.is_empty())
            .count();
        self.coverage.tensors_with_dtype =
            self.tensors.iter().filter(|t| t.dtype != "Unknown").count();
        self.coverage.tensors_with_device = self
            .tensors
            .iter()
            .filter(|t| !matches!(t.device, DeviceFact::Unknown))
            .count();
        self.coverage.diagnostics = self.findings.len();
    }
}

fn escape_id_part(part: &str, out: &mut String) {
    for byte in part.bytes() {
        match byte {
            b'%' | b':' | b'/' | b'\\' | b' ' => {
                out.push('%');
                out.push_str(&format!("{byte:02X}"));
            }
            _ => out.push(byte as char),
        }
    }
}