libgrammstein 0.1.0

Hybrid language model (N-gram + Embeddings) for WFST text correction
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
# Acoustic Models

Neural network acoustic models using the Candle ML framework.

## What are Acoustic Models?

Acoustic models map audio features to probability distributions over output units (phonemes, characters, or subword tokens). In the ASR cascade, they compute the emission probabilities that drive CTC or HMM decoding.

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         Acoustic Model in ASR                                │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   Audio Features              Acoustic Model                Posteriors      │
│   [T, F]                      (Neural Network)              [T, U]          │
│                                                                             │
│   ┌───┬───┬───┐              ┌──────────────────┐         ┌───┬───┬───┐   │
│   │f₀₀│f₀₁│...│──────────────│  Transformer or  │─────────│p₀₀│p₀₁│...│   │
│   ├───┼───┼───┤              │  Linear Encoder  │         ├───┼───┼───┤   │
│   │f₁₀│f₁₁│...│              └──────────────────┘         │p₁₀│p₁₁│...│   │
│   ├───┼───┼───┤                                           ├───┼───┼───┤   │
│   │...│...│...│              T = time frames              │...│...│...│   │
│   └───┴───┴───┘              F = feature dim (40)         └───┴───┴───┘   │
│                              U = output units (4096)                        │
│                                                                             │
│   Posteriors represent: log P(unit | features)                              │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

## Feature Flag

Acoustic models require the `candle-model` feature:

```toml
[dependencies]
libgrammstein = { version = "0.1", features = ["candle-model"] }
```

This enables:
- `candle-core` - Tensor operations
- `candle-nn` - Neural network layers
- `acoustic` - Feature extraction (automatically included)

## AcousticModel Trait

The core interface for acoustic models.

```rust
pub trait AcousticModel: Send + Sync {
    /// Input feature dimension (e.g., 40 for filterbank)
    fn feature_dim(&self) -> usize;

    /// Number of output units (vocabulary size)
    fn num_units(&self) -> usize;

    /// Compute log posteriors for input frames
    /// Input: [batch_size, feature_dim]
    /// Output: [batch_size, num_units]
    fn forward(&self, frames: &[Vec<f32>]) -> Vec<Vec<f32>>;

    /// CTC blank token ID (if using CTC)
    fn blank_id(&self) -> Option<u32> { None }

    /// Optional: Get unit name for debugging
    fn unit_name(&self, unit: u32) -> Option<String> { None }
}
```

## AcousticModelConfig

Configuration for all acoustic model types.

### Parameters

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `feature_dim` | `usize` | 40 | Input feature dimension |
| `hidden_dim` | `usize` | 256 | Hidden layer dimension |
| `num_units` | `usize` | 4096 | Output vocabulary size |
| `num_layers` | `usize` | 6 | Encoder layers |
| `dropout` | `f64` | 0.1 | Dropout probability |
| `num_heads` | `usize` | 4 | Attention heads (transformer) |
| `ff_dim` | `usize` | 1024 | Feed-forward dimension |
| `is_ctc` | `bool` | false | Has CTC blank token |
| `blank_id` | `u32` | 0 | Blank token ID |

### Preset Configurations

```rust
use libgrammstein::acoustic::AcousticModelConfig;

// Small: Fast inference, lower accuracy
let small = AcousticModelConfig::small();
// hidden_dim: 128, num_layers: 2, num_heads: 2

// Medium: Balanced (default)
let medium = AcousticModelConfig::medium();
// hidden_dim: 256, num_layers: 6, num_heads: 4

// Large: High accuracy, slower
let large = AcousticModelConfig::large();
// hidden_dim: 512, num_layers: 12, num_heads: 8
```

### Builder Pattern

```rust
let config = AcousticModelConfig::default()
    .with_feature_dim(80)      // 80-dim filterbank
    .with_num_units(4096)      // Vocabulary size
    .with_hidden_dim(512)      // Larger hidden layer
    .with_num_layers(12)       // More layers
    .with_ctc(0);              // Enable CTC with blank_id=0
```

## LinearAcousticModel

A simple baseline model with a single hidden layer.

### Architecture

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                         LinearAcousticModel                                  │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   Input [B, F]                                                              │
│       │                                                                     │
│       ▼                                                                     │
│   ┌─────────────────────┐                                                   │
│   │  Linear (F → H)     │                                                   │
│   └──────────┬──────────┘                                                   │
│              │                                                              │
│              ▼                                                              │
│   ┌─────────────────────┐                                                   │
│   │       ReLU          │                                                   │
│   └──────────┬──────────┘                                                   │
│              │                                                              │
│              ▼                                                              │
│   ┌─────────────────────┐                                                   │
│   │  Linear (H → U)     │                                                   │
│   └──────────┬──────────┘                                                   │
│              │                                                              │
│              ▼                                                              │
│   ┌─────────────────────┐                                                   │
│   │    Log Softmax      │                                                   │
│   └──────────┬──────────┘                                                   │
│              │                                                              │
│              ▼                                                              │
│   Output [B, U]  (log posteriors)                                           │
│                                                                             │
│   B = batch size, F = feature_dim, H = hidden_dim, U = num_units            │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Usage

```rust
use libgrammstein::acoustic::{LinearAcousticModel, AcousticModelConfig, AcousticModel};
use candle_core::Device;

// Configure model
let config = AcousticModelConfig {
    feature_dim: 40,
    hidden_dim: 256,
    num_units: 4096,
    ..Default::default()
};

// Create on GPU if available
let device = Device::cuda_if_available(0).unwrap_or(Device::Cpu);
let model = LinearAcousticModel::new(config, &device).expect("Failed to create model");

// Forward pass
let features = vec![vec![0.0f32; 40]; 100];  // 100 frames
let posteriors = model.forward(&features);    // [100, 4096]

// Get best unit per frame
for (i, frame_post) in posteriors.iter().enumerate() {
    let best_unit = frame_post
        .iter()
        .enumerate()
        .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
        .map(|(idx, _)| idx)
        .unwrap();
    println!("Frame {}: best unit = {}", i, best_unit);
}
```

### Loading Pretrained Weights

```rust
// Load from safetensors file
let model = LinearAcousticModel::load(
    "linear_acoustic.safetensors",
    config,
    &device,
).expect("Failed to load model");
```

## TransformerAcousticModel

State-of-the-art acoustic model using transformer encoder layers with self-attention.

### Architecture

```
┌─────────────────────────────────────────────────────────────────────────────┐
│                       TransformerAcousticModel                               │
├─────────────────────────────────────────────────────────────────────────────┤
│                                                                             │
│   Input [B, T, F]                                                           │
│       │                                                                     │
│       ▼                                                                     │
│   ┌─────────────────────┐                                                   │
│   │ Linear (F → H)      │  Input projection                                 │
│   └──────────┬──────────┘                                                   │
│              │                                                              │
│              ▼                                                              │
│   ┌─────────────────────┐                                                   │
│   │ + Positional Enc    │  Sinusoidal position encoding                     │
│   └──────────┬──────────┘                                                   │
│              │                                                              │
│              ▼                                                              │
│   ┌─────────────────────────────────────────────────────────────────────┐   │
│   │                     Transformer Layers (×N)                          │   │
│   │  ┌────────────────────────────────────────────────────────────────┐ │   │
│   │  │  ┌─────────────────┐    ┌─────────────────┐                    │ │   │
│   │  │  │  Multi-Head     │───►│   Add & Norm    │                    │ │   │
│   │  │  │  Self-Attention │    └────────┬────────┘                    │ │   │
│   │  │  │  (H heads)      │             │                             │ │   │
│   │  │  └─────────────────┘             ▼                             │ │   │
│   │  │                      ┌─────────────────┐    ┌─────────────────┐│ │   │
│   │  │                      │  Feed-Forward   │───►│   Add & Norm    ││ │   │
│   │  │                      │  (H → FF → H)   │    └────────┬────────┘│ │   │
│   │  │                      │  + GELU         │             │         │ │   │
│   │  │                      └─────────────────┘             ▼         │ │   │
│   │  └─────────────────────────────────────────────────────────────────┘ │   │
│   └──────────────────────────────────┬──────────────────────────────────┘   │
│                                      │                                      │
│                                      ▼                                      │
│   ┌─────────────────────┐                                                   │
│   │ Linear (H → U)      │  Output projection                                │
│   └──────────┬──────────┘                                                   │
│              │                                                              │
│              ▼                                                              │
│   ┌─────────────────────┐                                                   │
│   │    Log Softmax      │                                                   │
│   └──────────┬──────────┘                                                   │
│              │                                                              │
│              ▼                                                              │
│   Output [B, T, U]  (log posteriors per frame)                              │
│                                                                             │
│   B = batch, T = time, F = features, H = hidden, U = units, N = num_layers  │
│                                                                             │
└─────────────────────────────────────────────────────────────────────────────┘
```

### Self-Attention

The self-attention mechanism allows each frame to attend to all other frames:

```
                    Query (Q)      Key (K)       Value (V)
                       ↓             ↓              ↓
                    ┌──────────────────────────────────┐
                    │                                  │
                    │    Attention = softmax(QK^T/√d)V │
                    │                                  │
                    └──────────────────────────────────┘
                              Context-aware
                              representation
```

### Usage

```rust
use libgrammstein::acoustic::{
    TransformerAcousticModel, AcousticModelConfig, AcousticModel
};
use candle_core::Device;

// Configure transformer model
let config = AcousticModelConfig {
    feature_dim: 40,
    hidden_dim: 256,
    num_units: 4096,
    num_layers: 6,
    num_heads: 4,
    ff_dim: 1024,
    dropout: 0.1,
    is_ctc: true,
    blank_id: 0,
    ..Default::default()
};

// Create model
let device = Device::cuda_if_available(0).unwrap_or(Device::Cpu);
let model = TransformerAcousticModel::new(config, &device)
    .expect("Failed to create model");

// Print model info
println!("Feature dim: {}", model.feature_dim());   // 40
println!("Output units: {}", model.num_units());    // 4096
println!("Blank ID: {:?}", model.blank_id());       // Some(0)

// Forward pass maintains temporal structure
let features = vec![vec![0.0f32; 40]; 100];  // 100 frames, 40 dims each
let posteriors = model.forward(&features);    // [100, 4096]

assert_eq!(posteriors.len(), 100);
assert_eq!(posteriors[0].len(), 4096);
```

### Loading Pretrained Model

```rust
// Load pretrained weights
let model = TransformerAcousticModel::load(
    "transformer_acoustic.safetensors",
    config,
    &device,
).expect("Failed to load model");
```

## MockAcousticModel

A testing model that returns uniform log probabilities.

```rust
use libgrammstein::acoustic::{MockAcousticModel, AcousticModelConfig, AcousticModel};

let config = AcousticModelConfig::default();
let model = MockAcousticModel::new(config);

// All outputs are uniform log probabilities
let features = vec![vec![0.0f32; 40]; 100];
let posteriors = model.forward(&features);

// Each frame has uniform distribution over units
let first_posterior = &posteriors[0];
let expected_log_prob = -(config.num_units as f32).ln();
assert!((first_posterior[0] - expected_log_prob).abs() < 1e-5);
```

## CTC Integration

When using CTC decoding, configure the blank token:

```rust
let config = AcousticModelConfig::default()
    .with_ctc(0);  // blank_id = 0

let model = TransformerAcousticModel::new(config, &device)?;

// Blank token is first output unit
assert_eq!(model.blank_id(), Some(0));

// Forward pass includes blank probability
let posteriors = model.forward(&features);
let blank_log_prob = posteriors[0][0];  // log P(blank | frame_0)
```

## Complete ASR Example

```rust
use libgrammstein::acoustic::{
    FeatureExtractor, FeatureConfig,
    TransformerAcousticModel, AcousticModelConfig,
    AcousticModel,
};
use candle_core::Device;

fn transcribe(audio_path: &str) -> String {
    // Step 1: Configure feature extraction
    let feature_config = FeatureConfig::default();
    let extractor = FeatureExtractor::new(feature_config);

    // Step 2: Load audio
    let audio = load_audio_16khz(audio_path);

    // Step 3: Extract features
    let features = extractor.extract_filterbank(&audio);
    println!("Extracted {} frames", features.len());

    // Step 4: Configure acoustic model
    let model_config = AcousticModelConfig::default()
        .with_num_units(4096)
        .with_ctc(0);

    // Step 5: Load acoustic model
    let device = Device::cuda_if_available(0).unwrap_or(Device::Cpu);
    let model = TransformerAcousticModel::load(
        "acoustic_model.safetensors",
        model_config,
        &device,
    ).expect("Failed to load model");

    // Step 6: Get posteriors
    let posteriors = model.forward(&features);

    // Step 7: Greedy CTC decode
    let blank_id = model.blank_id().unwrap_or(0);
    let mut prev_unit = blank_id;
    let mut decoded = Vec::new();

    for frame_posteriors in &posteriors {
        let best_unit = frame_posteriors
            .iter()
            .enumerate()
            .max_by(|(_, a), (_, b)| a.partial_cmp(b).unwrap())
            .map(|(idx, _)| idx as u32)
            .unwrap();

        // CTC rule: skip blanks and repeated units
        if best_unit != blank_id && best_unit != prev_unit {
            decoded.push(best_unit);
        }
        prev_unit = best_unit;
    }

    // Convert to text (depends on your vocabulary)
    decode_units_to_text(&decoded)
}
```

## Device Selection

```rust
use candle_core::Device;

// CPU (always available)
let device = Device::Cpu;

// CUDA GPU (if available)
let device = Device::cuda_if_available(0)?;  // GPU index 0

// Metal (Apple Silicon)
#[cfg(target_os = "macos")]
let device = Device::new_metal(0)?;

// Automatic best device
let device = if Device::is_cuda_available() {
    Device::new_cuda(0)?
} else if Device::is_metal_available() {
    Device::new_metal(0)?
} else {
    Device::Cpu
};
```

## Performance Tips

### Batch Processing

```rust
// Process multiple frames together for better GPU utilization
let batch_size = 32;
let features: Vec<Vec<f32>> = /* ... */;

for batch in features.chunks(batch_size) {
    let posteriors = model.forward(batch);
    // Process batch...
}
```

### Model Size Trade-offs

| Model | Hidden | Layers | Params | Speed | Accuracy |
|-------|--------|--------|--------|-------|----------|
| Small | 128 | 2 | ~1M | Fast | Lower |
| Medium | 256 | 6 | ~10M | Medium | Good |
| Large | 512 | 12 | ~50M | Slow | Best |

## Related Documentation

- [Acoustic Overview]overview.md - Module introduction
- [Feature Extraction]features.md - Audio preprocessing
- [lling-llang AcousticModel]../../../lling-llang/docs/acoustic/overview.md - Integration