Deep Dive: egui/eframe for instant UIs — why Immediate Mode fits system languages, State management with Rust's ownership, Layout & Style, Custom painting, and when Retained Mode is the better choice.
WebAssembly with Rust: wasm-pack, wasm-bindgen, JS interop, performance optimization and deployment. From Rust code to a running Wasm binary in the browser.
In the world of Artificial Intelligence, Python dominates. This isn't due to the language itself, but rather the massive ecosystem of C++ bindings. When we looked at migrating from C++ to Rust in Module 25, we saw that Rust inherits the safety guarantees of C++ without sacrificing performance. For AI applications, this means: we can offload the computational load to the GPU, but write the control logic (the "orchestration") in a language that is deterministic.
A critical point in production is latency. Python uses a Garbage Collector (GC), which can lead to unpredictable "Stop-the-World" pauses. In a real-time inference pipeline, where milliseconds determine the user experience, such pauses are unacceptable. Rust provides performance without a GC, enabling consistent latency. We trade the runtime checks of the GC for the compile-time checks of the Borrow Checker.
Deterministic Latency
Unlike GC-based languages, Rust has no unpredictable pauses for memory cleanup. This is essential for AI models in edge computing environments or for high-frequency inference.
AI models work with tensors—multi-dimensional arrays. In Python, these are often dynamically typed, which leads to ShapeMismatch errors only at runtime. In Rust, we try to lift as much as possible into the type system. Libraries like candle implement tensors such that dimensions and data types (dtype) are clearly defined.
A tensor in Rust is not just a blob of data, but an object that knows its shape (Shape) and its type (e.g., f32). While we often have to guess in Python whether an operation returns a Float or an Int, Rust forces us to handle types explicitly or define them via generics like Tensor<f32>.
// Example usage of a tensor concept (inspired by candle)
// Here we simulate the creation of a 2D tensor for embeddings
use candle_core::{Tensor, Device, DType};
fn main() -> candle_core::Result<()> {
// Define the device (CPU or CUDA)
let device = Device::Cpu;
// Create a tensor with 2 rows and 3 columns (f32)
// The data is organized in a flat slice
let data: &[f32] = &[1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
let tensor = Tensor::from_slice(data, (2, 3), &device)?;
println!("Tensor Shape: {:?}", tensor.shape());
// → Tensor Shape: [2,3]
println!("DType: {:?}", tensor.dtype());
// → DType: F32
// A simple matrix multiplication would happen type-safely here
// Errors with incompatible dimensions are returned as a Result
Ok(())
}
We don't need to reinvent the wheel. There are already several frameworks that leverage Rust's strengths for AI:
These tools allow us to build complete AI pipelines that can be delivered as a single, statically linked binary—without the end user needing to install a Python environment.
unsafe?A common misconception is that AI frameworks in Rust are completely "safe." This is not true. To get maximum performance from the GPU, we must access CUDA kernels or cuBLAS. These APIs are C-based and therefore naturally unsafe.
This is where the lesson from Module 25, Lesson 4 applies: unsafe is not a tool to bypass the Borrow Checker, but a "gated seam" (a controlled interface). In a framework like candle, the unsafe code is highly isolated within the hardware backends. As a library user, you interact with a safe API, while the "dangerous" work inside is protected by strict invariants.
// Conceptual representation of a hardware wrapper
struct GpuBuffer {
ptr: *mut f32,
size: usize,
}
impl GpuBuffer {
// The dangerous operation is encapsulated in a safe method
pub fn write_data(&mut self, data: &[f32]) {
assert_eq!(data.len(), self.size);
unsafe {
// The raw pointer is only used here (Foreign Function Interface)
std::ptr::copy_nonoverlapping(data.as_ptr(), self.ptr, self.size);
}
}
}
Rust is not always the first choice. For exploratory experimentation, data science, and model training, Python remains superior due to its iteration speed. However, Rust is the right choice when the following conditions apply:
pip install ...).// Comparison: A simple inference wrapper
struct ModelInference {
weights: Vec<f32>, // Simplified
threshold: f32,
}
impl ModelInference {
fn predict(&self, input: &[f32]) -> bool {
// In Rust, this path is deterministic and extremely fast
let score: f32 = input.iter()
.zip(&self.weights)
.map(|(i, w)| i * w)
.sum();
score > self.threshold
}
}
Check: Why is Rust often more advantageous than Python for the real-time inference of AI models?
Answer: Because there is no Garbage Collector causing unpredictable pauses
The absence of a Garbage Collector prevents 'Stop-the-World' pauses, which is crucial for consistent response times (latency) in production systems.
⚠ Common mistake: Assuming the type system catches bad tensor shapes too.
Tensor::from_slicechecks only at runtime whether the element count matches the shape — a mismatch comes back as anErrin theResult, not as a compile error. Anunwrap()at that spot panics precisely when the model is loading.
Takeaways:
candle.unsafe in AI libraries serves as an isolated interface for hardware acceleration (CUDA), analogous to the principles from Module 25.In the world of LLMs, text is invisible to the model. A Transformer model does not operate on letters or words, but on vectors, which in turn are based on integer indices. The process of converting text into these numbers is called tokenization. In Rust, this isn't just about calling a library, but making a conscious decision about the typing of these data streams.
Many beginners make the mistake of modeling the entire pipeline flow as String or Vec<u32>. This quickly leads to the so-called "string-string swamp," where it's no longer clear whether a variable is a raw prompt, a tokenized string, or an already decoded result. In this deep dive, we look at how to use Rust's type system to strictly separate these states.
Before we venture into the tokenizers crate, we must review a fundamental lesson from Module 25: the difference between chars and bytes.
Internally, a tokenizer often operates at the byte level (Byte-Pair Encoding, BPE) to ensure that any Unicode character can be represented without the vocabulary exploding. However, if you are validating the length of a prompt or trimming text for the UI, .len() in Rust is dangerous because it returns the byte length. A single emoji can take up 4 bytes but counts as one character.
Unicode-Awareness in Tokenizers
Modern tokenizers like BPE often break text down into byte sequences to avoid Out-of-Vocabulary (OOV) problems. In Rust, we must consistently distinguish between &str (UTF-8 bytes) and .chars() (Unicode Scalar Values) to avoid slicing characters in the middle of a byte cluster.
fn main() {
let text = "Rust AI 🦀";
// DANGEROUS: Returns the byte length (12)
println!("Byte length: {}", text.len());
// CORRECT: Counts the actual Unicode characters (9)
println!("Character count: {}", text.chars().count());
// Why this matters for tokenizers:
// A tokenizer might split the emoji 🦀 into multiple tokens,
// but the logical character count remains crucial for prompt validation.
}
To avoid logic errors, we introduce newtypes. Instead of using u32 for a token ID, we define our own type. This prevents us from accidentally adding a TokenId to a SequenceLength or another u32 value.
Similarly, we separate the Prompt (the user's input) from the Vocab (the map between text and ID).
use std::collections::HashMap;
use tokenizers::Tokenizer;
// Newtype for token IDs: Prevents confusion with other u32s
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct TokenId(u32);
// Wrapper for the prompt to separate it from decoded strings
struct Prompt(String);
// Representation of the vocabulary
struct Vocab(HashMap<String, TokenId>);
fn main() -> Result<(), Box<dyn std::error::Error>> {
// Load tokenizer from HuggingFace pretrained
let tokenizer = Tokenizer::from_pretrained("bert-base-uncased", None)
.map_err(|e| format!("Failed to load tokenizer: {}", e))?;
let prompt = Prompt("Hello Rust AI!".to_string());
// Encoding returns a Result because tokens might be missing (though BPE minimizes this)
let encoding = tokenizer.encode(prompt.0, true)
.map_err(|e| format!("Encoding Error: {}", e))?;
// Convert raw IDs into our newtype `Vec<TokenId>`
let token_ids: Vec<TokenId> = encoding.get_ids()
.iter()
.map(|&id| TokenId(id))
.collect();
println!("Tokens: {:?}", token_ids);
Ok(())
}
In production AI systems, an unknown character or corrupt input must never lead to a panic!. The tokenizers crate is exemplary here and returns Result.
A critical point is decoding. If a model generates sequences that are no longer consistent with the vocabulary (e.g., due to bit-flips or extremely poor sampling parameters), the decoding must fail safely. We use Rust's ? operator here to delegate errors to the top level instead of working with .unwrap().
Newtype Pattern for AI Pipelines
By using struct TokenId(u32) instead of u32, we force ourselves to convert explicitly. This makes the code self-documenting: a function that expects Vec<TokenId> can never be accidentally called with a list of VocabularyIndices, even if both are internally u32.
// Example of a type-safe function
fn process_tokens(tokens: &[TokenId]) {
println!("Processing {} tokens", tokens.len());
// → Processing 3 tokens
}
fn main() {
let raw_ids = vec![101, 2023, 102];
// process_tokens(&raw_ids); // ERROR: Expects &[TokenId], not &[u32]
let safe_ids: Vec<TokenId> = raw_ids.into_iter().map(TokenId).collect();
process_tokens(&safe_ids); // OK
}
Check: Why should you use
struct TokenId(u32)instead of a simpleu32in an AI pipeline?Answer: To prevent type confusion with other numerical values (e.g., lengths) at compile time
The newtype pattern leverages Rust's type system to prevent logical errors. There is no performance loss, as the
structis usually identical to the underlyingu32in the compiled binary.
⚠ Common mistake: Truncating prompts with
&text[..n]— the slice lands in the middle of a UTF-8 sequence and panics with "byte index n is not a char boundary" as soon as an emoji or umlaut sits at that position. Trim safely viatext.chars().take(n).collect::<String>()orchar_indices().
Takeaways:
.len() (bytes) and .chars().count() (Unicode) in the context of tokenizers.tokenizers crate to convert text into Vec<TokenId> without using unwrap().struct Prompt(String) and struct TokenId(u32).In theory, inference sounds simple: input data, apply model, output prediction. In Rust practice, however, the inference pipeline is where most runtime errors occur, usually in the form of a Panic caused by incompatible tensor dimensions or type mismatches. A robust pipeline must not only execute the model but also precisely control data streams, transform dimensions, and monitor latency.
When using frameworks like candle or ort (ONNX Runtime), we leave the world of strongly typed Rust structures and enter the world of dynamic tensor shapes. Here, the developer takes responsibility for validating data formats before they flow into the backend core (which is often written in C++ or CUDA).
Tensor Dimensions & Squeezing
A tensor often has dimensions that are necessary for the model but redundant for the result (e.g., a batch dimension of 1). "Squeezing" removes these dimensions of size 1 to move from a shape like [1, 1, 768] to a flat vector [768].
A classic error in AI pipelines is confusing f32 and f64. While most deep learning models are optimized for f32 (Single Precision) or even f16/bf16, Rust often leans toward f64 in mathematical contexts. The wrong type leads either to a compilation error (if the library uses generics like Tensor<T>) or a runtime crash if the backend expects a strict format.
Checking shapes is particularly critical. For example, a model might expect an input tensor with the shape [batch_size, sequence_length, hidden_dim]. If you are processing a single sentence, the batch_size is 1. However, many models return results in the same shape. To use the result as a simple vector for a Softmax operation or a comparison, we must remove the redundant dimensions.
// Example of a schematic inference pipeline
// We are simulating the logic as it appears in candle or ort.
use std::time::Instant;
#[derive(Debug)]
struct InferenceResult {
prediction: Vec<f32>,
latency: std::time::Duration,
}
struct SimpleModel {
weights: Vec<f32>, // Simplified: a flat tensor
input_dim: usize,
output_dim: usize,
}
impl SimpleModel {
// Simulates a forward pass
fn forward(&self, input: &[f32]) -> Result<Vec<f32>, String> {
if input.len() != self.input_dim {
return Err(format!("Shape mismatch: Expected {}, got {}", self.input_dim, input.len()));
}
// Simulate a matrix multiplication: [1, input_dim] * [input_dim, output_dim]
let mut output = vec![0.0; self.output_dim];
for j in 0..self.output_dim {
for i in 0..self.input_dim {
output[j] += input[i] * self.weights[i * self.output_dim + j];
}
}
Ok(output)
}
}
fn main() {
// Model initialization
let model = SimpleModel {
weights: vec![0.1; 128 * 10], // 128 input -> 10 output
input_dim: 128,
output_dim: 10,
};
// Input data: simulating a tensor shape [1, 128]
// In a real pipeline, this would be a Tensor object with dtype f32
let input_data = vec![0.5f32; 128];
// Measuring latency
let start = Instant::now();
let result = model.forward(&input_data).expect("Inference failed");
let duration = start.elapsed();
println!("Inference successful. Shape: [1, {}]", result.len());
// → Inference successful. Shape: [1, 10]
println!("Latency: {:?}", duration);
// → Latency: 41.7µs
}
In a production environment, pure correctness is not enough; latency per request is the decisive metric. We use std::time::Instant to measure the time between the start of the forward pass and the receipt of the result tensor.
A key lever for increasing performance is batching. Instead of sending 10 individual requests with the shape [1, seq, hidden], it is more efficient to bundle them into a single tensor with the shape [10, seq, hidden]. This utilizes the CPU's SIMD units or the GPU's parallel CUDA cores much more effectively, as the overhead for the model call only occurs once.
Here we see the effect of batch sizes on latency:
fn benchmark_batch_size(model: &SimpleModel, batch_size: usize) {
// Simulate a batch tensor [batch_size, input_dim]
let batch_data = vec![0.5f32; batch_size * model.input_dim];
let start = Instant::now();
// Simulate batch processing
for chunk in batch_data.chunks_exact(model.input_dim) {
let _ = model.forward(chunk).unwrap();
}
let duration = start.elapsed();
println!("Batch size {}: Total time {:?}, per item {:?}",
batch_size, duration, duration / batch_size as u32);
}
The biggest danger in Rust AI pipelines is "silent" error propagation in C-bindings. If a library like ort receives a tensor with the wrong dtype, it might not return a clean Rust Result, but instead trigger a signal that leads to a crash.
Therefore, always keep the following checklist in mind:
f32? An f64 array will not be implicitly converted.[batch, seq, dim] exactly match the model's expectations?// Example of a validation function before inference
fn validate_tensor_shape(shape: &[usize], expected: &[usize]) -> Result<(), String> {
if shape != expected {
return Err(format!("Invalid shape. Expected {:?}, found {:?}", expected, shape));
}
Ok(())
}
// Application in the pipeline
// let input_shape = [1, 128];
// validate_tensor_shape(&input_shape, &[1, 128])?;
Check: Why is 'squeezing' tensors important in an inference pipeline?
Answer: To remove redundant dimensions (e.g., batch size 1) for further processing
Squeezing does not change the data or the calculation speed; instead, it adjusts the shape of the result tensor so it is easier to handle in subsequent Rust functions (e.g., as a simple vector).
⚠ Common mistake: Writing
vec![0.5; 128]without a suffix — the literal defaults tof64, and passing it to a function expecting&[f32]fails with E0308 ("mismatched types"). With dynamic backends likecandleorort, the failure instead surfaces only at runtime as aDTypeMismatch. Always write0.5f32or convert explicitly withas f32.
Takeaways:
std::time::Instant and understand the impact of batching on performance.dtype mismatches (e.g., f32 vs. f64) in AI frameworks.Retrieval Augmented Generation (RAG) is often misunderstood as a simple process of "searching for data and sending it to an LLM." In a production Rust environment, however, this process is a chain of transformations where type safety is crucial to avoid runtime errors during vector search or chunking. Instead of treating data as loose collections of Strings, in this deep-dive we use the Sum Type pattern from Module 25 to explicitly and exhaustively model different retrieval strategies.
A robust RAG workflow defines every step—from the Chunk and Embedding to the final Score—as its own type. This prevents us from accidentally using an embedding of the wrong dimension or confusing a BM25 score with cosine similarity.
Sum Types for Retrieval Strategies
By modeling the retriever as an enum, Rust uses match to enforce that every possible search strategy (e.g., vector search vs. keyword search) is explicitly handled. This makes the pipeline extensible and prevents "silent failures" when selecting a strategy.
We begin by defining our building blocks. A Chunk is more than just text; it contains metadata for traceability. The Embedding is a wrapper around Vec<f32> to avoid type confusion with other numerical vectors.
#[derive(Debug, Clone)]
struct Chunk {
text: String,
metadata: std::collections::HashMap<String, String>,
}
#[derive(Debug, Clone)]
struct Embedding(Vec<f32>);
impl Embedding {
// Calculates the cosine similarity between two vectors
fn cosine_similarity(&self, other: &Self) -> f32 {
let dot_product: f32 = self.0.iter().zip(&other.0).map(|(a, b)| a * b).sum();
let norm_a: f32 = self.0.iter().map(|x| x * x).sum::<f32>().sqrt();
let norm_b: f32 = other.0.iter().map(|x| x * x).sum::<f32>().sqrt();
dot_product / (norm_a * norm_b)
}
}
/// The Sum Type modeling of our retrieval methods
enum Retriever {
VectorStore { index_id: String },
BM25 { corpus_id: String },
Hybrid { vector_weight: f32, bm25_weight: f32 },
}
struct ScoredChunk {
chunk: Chunk,
score: f32,
}
Here we see the application of the Sum Type pattern: the Retriever is not just a configuration string, but a type that bundles the necessary parameters for the respective strategy.
The actual RAG logic is a chain of typed steps. We avoid "string typing" by strictly defining the flow: Query Embedding Vec<ScoredChunk> TopK.
async fn retrieve(
query: &str,
retriever: &Retriever,
embedder: &impl Embedder
) -> Result<Vec<ScoredChunk>, RagError> {
match retriever {
Retriever::VectorStore { index_id } => {
let query_vec = embedder.embed(query).await?;
// In reality: Call to Vector DB (e.g., Qdrant/Milvus)
println!("Searching in vector index {}", index_id);
Ok(vec![]) // Placeholder for results
}
Retriever::BM25 { corpus_id } => {
println!("Keyword search in corpus {}", corpus_id);
Ok(vec![]) // Placeholder for results
}
Retriever::Hybrid { vector_weight, bm25_weight } => {
// Combination of both worlds
println!("Hybrid search with weights {}/{}", vector_weight, bm25_weight);
Ok(vec![])
}
}
}
// Helper trait for embedding logic
#[async_trait::async_trait]
trait Embedder {
async fn embed(&self, text: &str) -> Result<Embedding, RagError>;
}
#[derive(Debug)]
enum RagError {
EmbeddingFailed,
RetrievalError(String),
}
Thanks to the match block, the pipeline is exhaustive. If we later add a new strategy like GraphRetrieval, the Rust compiler will point out every location in the code where the logic needs to be supplemented.
When retrieved chunks are sent to the LLM, we want to stream the response to minimize Time-to-First-Token (TTFT). For this, we use tokio::sync::mpsc. A key advantage of Rust is automatic cancellation: if the consumer drops the Receiver (e.g., because the user cancels the request), the Sender in the producer task will return an error on the next send(), allowing us to terminate the expensive LLM call immediately.
use tokio::sync::mpsc;
struct LLMResponse {
token: String,
is_final: bool,
}
async fn stream_llm_answer(
context: Vec<Chunk>,
tx: mpsc::Sender<LLMResponse>
) {
let tokens = vec!["The", "answer", "according", "to", "the", "document", "is..."];
for token in tokens {
// If the receiver was dropped, send() fails.
// This is our signal for cancellation.
if tx.send(LLMResponse {
token: token.to_string(),
is_final: false,
}).await.is_err() {
println!("Consumer cancelled. Ending LLM streaming.");
return;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
let _ = tx.send(LLMResponse { token: "".into(), is_final: true }).await;
}
#[tokio::main]
async fn main() {
let (tx, mut rx) = mpsc::channel(32);
let context = vec![]; // Populated chunks from retrieve()
tokio::spawn(async move {
stream_llm_answer(context, tx).await;
});
// Simulate partial reading and then cancellation (dropping the receiver)
if let Some(res) = rx.recv().await {
println!("Token received: {}", res.token);
}
drop(rx); // This triggers the cancellation in the producer task
}
Check: Why is modeling the retriever as an Enum (Sum Type) preferable to a string-based configuration system?
Answer: It allows the compiler to check for the exhaustiveness of strategies.
By using the Enum pattern, Rust forces the developer to handle every case in the
matchblock. This prevents new retrieval strategies from being implemented but forgotten at critical points in the pipeline.
⚠ Common mistake: Calling
tx.send(...)without.await—sendis asynchronous, and a future that is never polled never runs, so nothing ever crosses the channel. The compiler only warns ("futures do nothing unless you .await or poll them") while the token stream stays empty.
Takeaways:
Embedding as a wrapper for Vec<f32> increases type safety in vector searches.Retriever as a Sum Type to handle different search strategies exhaustively.tokio::sync::mpsc for asynchronous streaming and implement cancellation via the drop of the Receiver.In this module, we have implemented complex AI architectures in Rust. However, in the world of high-performance AI, where we often operate on the boundary between Rust and C++/CUDA libraries, a successful compiler run is not enough. When we use unsafe to manipulate GPU buffers directly or send FFI calls to tensor runtimes, we take personal responsibility for memory and thread safety.
A "Safe Seam" is a pattern where we wrap a tiny, highly controlled unsafe block and expose a strict, safe API to the outside world. The goal is not to avoid unsafe entirely, but to isolate it so that invariants remain provable.
The Named Invariant
An unsafe block without documentation of its prerequisites is a time bomb. A named invariant is an explicit comment that defines exactly which conditions (e.g., alignment, lifetime, thread safety) must be guaranteed by the caller to prevent the block from leading to Undefined Behavior (UB).
A classic problem in AI pipelines is accessing GPU memory via raw pointers. When using a C library that returns a pointer to a tensor, we must ensure that this pointer does not outlive the underlying context.
This is where verification comes in. While the standard compiler protects us in Safe Rust, we need specialized tools for these "seams":
cargo miri) executes Rust code in a virtual machine and detects UB, such as out-of-bounds accesses or data races, which would go unnoticed in a normal release build.cargo kani. Unlike tests, which check individual inputs, Kani mathematically proves that a function will not panic for all possible inputs within a given range./// A Safe Gate for a hypothetical CUDA tensor access.
struct GpuTensor {
ptr: *mut f32,
len: usize,
}
impl GpuTensor {
/// Reads a value at index `i`.
///
/// # Safety
/// Invariant: `ptr` must point to a valid memory region
/// allocated by the GPU driver that encompasses at least `len`
/// elements and is not being modified by other threads
/// simultaneously.
pub unsafe fn read_value(&self, i: usize) -> f32 {
// We encapsulate the unsafe access in a safe method,
// but check bounds explicitly to provoke panics instead of UB.
if i >= self.len {
panic!("Index out of bounds in GpuTensor");
}
// SAFETY: The invariant guarantees the validity of the pointer.
// The bounds check prevents illegal memory access.
*self.ptr.add(i)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_gpu_tensor_bounds() {
let data = vec![1.0, 2.0, 3.0];
let tensor = GpuTensor {
ptr: data.as_ptr() as *mut f32,
len: data.len(),
};
// Tests the invariant: The Safe Gate must panic on index violation
// instead of creating UB through an illegal pointer offset.
let result = std::panic::catch_unwind(|| {
unsafe { tensor.read_value(10) }
});
assert!(result.is_err(), "Should panic on index overflow");
}
}
In AI development, "randomness" is the enemy of verification. When evaluating the quality of our RAG pipeline, our golden datasets must not be based on stochastic samples. We use Table-Driven Testing with fixed seeds for all random components. Every test run must be bit-identically reproducible; otherwise, we cannot know if a performance gain resulted from code optimization or a "lucky" seed.
When migrating existing C++/CUDA bases to Rust, we apply the Ship-of-Theseus principle: we do not replace the entire system at once, but component by component. We use the 7-point checklist from Module 25 as a quality filter for every new Rust component:
enum instead of integer codes?unsafe seam?unsafe block commented with a named invariant?Iterators and Option instead of manual C-style loops?/// Example of a deterministic evaluation
struct EvalCase {
input: &'static str,
expected_output: &'static str,
}
fn evaluate_pipeline(cases: &[EvalCase], seed: u64) -> f32 {
// ponytail: We use a fixed seed to eliminate randomness in the
// sampling strategy of the LLM adapter.
let mut rng = deterministic_rng(seed);
let mut passed = 0;
for case in cases {
let output = run_rag_pipeline(case.input, &mut rng);
if output == case.expected_output {
passed += 1;
}
}
passed as f32 / cases.len() as f32
}
fn main() {
let golden_dataset = [
EvalCase { input: "What is Rust?", expected_output: "A systems language." },
EvalCase { input: "What is Miri?", expected_output: "A UB detector." },
];
// A fixed seed guarantees that the eval metric remains stable.
let score = evaluate_pipeline(&golden_dataset, 42);
println!("Accuracy: {:.2}%", score * 100.0);
// → Accuracy: 100.00%
}
Check: Which tool is best suited for finding Undefined Behavior (UB) in a custom
unsafeblock by interpreting the bytecode?Answer: cargo miri
Miri is an interpreter for Rust bytecode (MIR) specifically designed to find UB such as memory errors or data races. Kani, on the other hand, is a model checker for formal verification (panic-freedom).
⚠ Common mistake: Misreading
data.as_ptr() as *mut f32as write access — casting from a shared reference grants no write permission, and writing through that pointer is instant UB, whichcargo mirireports as an aliasing violation. Mutable raw pointers must come from a genuine&mutsource.
Takeaways:
unsafe blocks must be documented via named invariants and isolated through Safe Gates.cargo miri to search for UB and cargo kani to verify panic-freedom in AI pipelines.Course navigation: ← Module 25 · All 27 modules · Module 27 →