lling-llang 0.1.0

WFST framework for text normalization and grammar 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
# Determinization

Determinization transforms a non-deterministic WFST into an equivalent deterministic one, where each state has at most one outgoing transition per input label. This enables efficient single-pass recognition and is often a prerequisite for minimization.

## Concepts

### What is a Deterministic WFST?

A WFST is **deterministic** if:
1. It has exactly one start state
2. For each state, all outgoing transitions have distinct input labels
3. There are no epsilon (ε) transitions on the input

```
Non-deterministic:              Deterministic:

       a/1.0                          a/1.0
   ┌──────────► 1                 ┌──────────► 1
   │                              │
   0                              0
   │                              │
   └──────────► 2                 └──────────► 2
       a/2.0                          b/2.0

   (Two 'a' arcs)                 (Distinct labels)
```

### Why Determinize?

1. **Efficient recognition**: Single path per input string—no backtracking needed
2. **Prerequisite for minimization**: Weighted minimization requires deterministic input
3. **Unique path property**: Simplifies lattice generation and scoring
4. **Composition optimization**: Deterministic components compose more efficiently

### The Weighted Powerset Construction

Unlike classical automata theory where determinization uses simple state sets, **weighted determinization** uses **weighted subsets**—sets of (state, residual_weight) pairs:

```
Non-deterministic state set:  {1, 2}

Weighted subset:  {(1, 0.5), (2, 1.5)}
                    │    │     │    │
                    │    │     │    └─ residual weight for state 2
                    │    │     └─ state 2
                    │    └─ residual weight for state 1
                    └─ state 1
```

The residual weight tracks "how much extra weight" each original state carries compared to the minimum.

## Core API

### Types

```rust
/// Configuration for determinization
pub struct DeterminizeConfig {
    /// Maximum number of states in output (prevents runaway)
    pub max_states: Option<usize>,
    /// Whether to epsilon-remove first (recommended)
    pub remove_epsilon_first: bool,
    /// Whether to connect (trim) after determinization
    pub connect_after: bool,
}

/// Errors during determinization
pub enum DeterminizeError {
    NoStartState,
    StateLimitExceeded { limit: usize },
    NotDeterminizable { reason: String },
}
```

### Functions

```rust
/// Determinize a WFST using weighted powerset construction
pub fn determinize<L, W, F>(
    fst: &F,
    config: DeterminizeConfig,
) -> Result<F, DeterminizeError>;

/// Check if a WFST is deterministic
pub fn is_deterministic<L, W, F>(fst: &F) -> bool;

/// Count degree of non-determinism (max same-label arcs from one state)
pub fn non_determinism_degree<L, W, F>(fst: &F) -> usize;
```

## Examples

### Basic Usage

```rust
use lling_llang::prelude::*;
use lling_llang::algorithms::{determinize, is_deterministic, DeterminizeConfig};

// Build a non-deterministic WFST
// Two 'a' transitions from state 0:
//   0 --a/1.0--> 1 --b--> 3 (final)
//   0 --a/2.0--> 2 --c--> 3 (final)
let mut fst = VectorWfst::<char, TropicalWeight>::new();
fst.add_states(4);
fst.set_start(0);
fst.add_arc(0, Some('a'), Some('a'), 1, TropicalWeight::new(1.0));
fst.add_arc(0, Some('a'), Some('a'), 2, TropicalWeight::new(2.0));
fst.add_arc(1, Some('b'), Some('b'), 3, TropicalWeight::new(1.0));
fst.add_arc(2, Some('c'), Some('c'), 3, TropicalWeight::new(1.0));
fst.set_final(3, TropicalWeight::one());

// Check: not deterministic
assert!(!is_deterministic(&fst));
assert_eq!(non_determinism_degree(&fst), 2);

// Determinize
let det_fst = determinize(&fst, DeterminizeConfig::standard())?;

// Verify: now deterministic
assert!(is_deterministic(&det_fst));
```

### Diamond Pattern (Merging Paths)

```rust
// Diamond: two paths with same label sequence
//   0 --a/1--> 1 --b--> 3 (final)
//   0 --a/2--> 2 --b--> 3 (final)
let mut fst = VectorWfst::<char, TropicalWeight>::new();
fst.add_states(4);
fst.set_start(0);
fst.add_arc(0, Some('a'), Some('a'), 1, TropicalWeight::new(1.0));
fst.add_arc(0, Some('a'), Some('a'), 2, TropicalWeight::new(2.0));
fst.add_arc(1, Some('b'), Some('b'), 3, TropicalWeight::new(1.0));
fst.add_arc(2, Some('b'), Some('b'), 3, TropicalWeight::new(1.0));
fst.set_final(3, TropicalWeight::one());

let det_fst = determinize(&fst, DeterminizeConfig::standard())?;

// Diamond collapses to linear chain
// Result: 0 --a/1--> {1,2} --b/1--> {3}
// Fewer states than original
assert!(det_fst.num_states() <= fst.num_states());
```

### Weight Preservation

```rust
// Non-deterministic with two paths to final states
//   0 --a/1--> 1 (final, w=0)
//   0 --a/3--> 2 (final, w=0)
let mut fst = VectorWfst::<char, TropicalWeight>::new();
fst.add_states(3);
fst.set_start(0);
fst.add_arc(0, Some('a'), Some('a'), 1, TropicalWeight::new(1.0));
fst.add_arc(0, Some('a'), Some('a'), 2, TropicalWeight::new(3.0));
fst.set_final(1, TropicalWeight::one());
fst.set_final(2, TropicalWeight::one());

let det_fst = determinize(&fst, DeterminizeConfig::standard())?;

// After determinization:
// - 'a' transition has weight 1.0 (minimum of 1.0 and 3.0)
// - Final state merges both original finals
// - Residual weights incorporated into final weight
```

## Algorithm Details

### Weighted Subset Construction

The algorithm maintains a mapping from weighted subsets to deterministic states:

```
procedure DETERMINIZE(fst):
    result ← new WFST

    // Initial state: {(start, 1̄)}
    initial_subset ← {(fst.start, W::one())}
    result.start ← new_state(initial_subset)
    queue.push(result.start, initial_subset)

    while queue not empty:
        (output_state, subset) ← queue.pop()

        // Compute final weight
        for (state, residual) in subset:
            if fst.is_final(state):
                result.final[output_state] ⊕= residual ⊗ fst.final_weight(state)

        // Group transitions by input label
        for label in input_labels(subset):
            target_subset ← compute_target_subset(subset, label)

            // Normalize: factor out minimum weight
            min_w ← min{w : (s, w) ∈ target_subset}
            normalized ← {(s, w ⊘ min_w) : (s, w) ∈ target_subset}

            // Get or create state for normalized subset
            target_state ← get_or_create(normalized)

            // Add transition with minimum weight
            result.add_arc(output_state, label, min_w, target_state)

    return result
```

### Weight Normalization

The key insight is **weight normalization** using the semiring's divide operation:

```
Before normalization:
  target_subset = {(1, 2.0), (2, 5.0), (3, 3.0)}

Compute minimum:
  min_w = min(2.0, 5.0, 3.0) = 2.0

Normalized (each weight divided by min):
  normalized = {(1, 0.0), (2, 3.0), (3, 1.0)}

Transition weight = min_w = 2.0
```

This ensures:
- The arc carries the "common" weight factor
- Residuals track the "extra" weight per original state
- Total path weight is preserved

### Handling Final Weights

When a weighted subset contains final states, the deterministic state's final weight combines all contributions:

```
subset = {(q₁, r₁), (q₂, r₂), ...}

final_weight = ⊕ᵢ { rᵢ ⊗ ρ(qᵢ) : qᵢ is final }

where ρ(q) is the final weight of state q
```

## Complexity

### Time Complexity

| Case | Complexity |
|------|------------|
| Worst case | O(2^|Q|) - exponential (powerset) |
| Unambiguous input | O(|Q| + |E|) - linear |
| Practical | Often near-linear for speech/NLP |

### Space Complexity

| Structure | Size |
|-----------|------|
| Subset cache | O(#unique_subsets) |
| Queue | O(#active_subsets) |
| Output WFST | O(|Q'| + |E'|) |

### Why Exponential Worst Case?

The powerset construction can create 2^|Q| subsets in pathological cases:

```
Exponential blowup example:

  0 → 1 → 2 → ... → n  (with alternating a/b choices)
      ↓   ↓         ↓
      1'  2'        n'

  Each state can be in or out of the subset → 2ⁿ possibilities
```

The `max_states` configuration prevents runaway:

```rust
let config = DeterminizeConfig {
    max_states: Some(1_000_000),  // Limit output size
    ..Default::default()
};
```

## Special Cases

### Epsilon Transitions

Epsilon transitions on the input make determinization more complex:

```rust
// Recommended: remove epsilon first
let config = DeterminizeConfig {
    remove_epsilon_first: true,  // Default
    ..Default::default()
};
```

If `remove_epsilon_first` is true, the algorithm handles ε-removal internally.

### Already Deterministic Input

If the input is already deterministic, the algorithm essentially copies it:

```rust
let fst = build_deterministic_fst();
assert!(is_deterministic(&fst));

let det = determinize(&fst, DeterminizeConfig::standard())?;
// det has same structure as fst
```

### Empty WFST

```rust
let fst: VectorWfst<char, TropicalWeight> = VectorWfst::new();
let det = determinize(&fst, DeterminizeConfig::standard())?;
assert_eq!(det.num_states(), 0);
```

## Semiring Requirements

Determinization requires a **divisible semiring**:

```rust
pub trait DivisibleSemiring: Semiring {
    fn divide(&self, other: &Self) -> Option<Self>;
}
```

| Semiring | Divisible | Division Operation |
|----------|-----------|-------------------|
| Tropical | Yes | a ⊘ b = a - b |
| Log | Yes | a ⊘ b = a - b |
| Probability | Yes | a ⊘ b = a / b |
| Boolean | No | N/A |
| String | No | N/A |

**Why division?** Weight normalization requires dividing each weight by the minimum to compute residuals.

## Common Patterns

### Pre-Minimization Pipeline

```rust
use lling_llang::algorithms::{
    remove_epsilon, determinize, minimize,
    EpsilonRemovalConfig, DeterminizeConfig, MinimizeConfig,
};

// Standard optimization pipeline:
// 1. Remove epsilon transitions
remove_epsilon(&mut fst, EpsilonRemovalConfig::default())?;

// 2. Determinize
let det = determinize(&fst, DeterminizeConfig::standard())?;

// 3. Minimize (requires deterministic input)
let min = minimize(&det, MinimizeConfig::default())?;
```

### Checking Before Determinizing

```rust
if !is_deterministic(&fst) {
    let det = determinize(&fst, DeterminizeConfig::standard())?;
    // Use det...
} else {
    // Already deterministic, skip
}
```

### Measuring Non-Determinism

```rust
let degree = non_determinism_degree(&fst);

match degree {
    0 => println!("Empty WFST"),
    1 => println!("Already deterministic"),
    d => println!("Non-determinism degree: {} (max same-label arcs)", d),
}
```

## Visualization

### Before Determinization

```
          a/1.0                    b/1.0
    [0] ─────────► 1 ─────────────────────► (3)
      │                                      ▲
      │                                      │
      └─────────► 2 ─────────────────────────┘
          a/2.0              c/1.0

Non-deterministic: two 'a' arcs from state 0
```

### After Determinization

```
          a/1.0                    b/1.0
    [0] ─────────► {1,2} ─────────────────► ({3}, final)
                     │                       ▲
                     │                       │
                     └───────────────────────┘
                              c/1.0

Deterministic: single 'a' arc to merged state {1,2}
Arc weight = min(1.0, 2.0) = 1.0
```

### Weight Flow Example

```
Original paths for input "ab":
  Path 1: 0 --a/1--> 1 --b/2--> 3 (final)  Total: 3
  Path 2: 0 --a/3--> 2 --b/2--> 3 (final)  Total: 5

Determinized (tropical = min):
  0 --a/1--> {1:0, 2:2} --b/2--> (final)

  After 'a': weight=1, residuals={1:0, 2:2}
  After 'b': weight=1+2=3, final with residual combination

Best path weight preserved: 3
```

## Error Handling

```rust
use lling_llang::algorithms::DeterminizeError;

match determinize(&fst, config) {
    Ok(det) => {
        // Success - use determinized WFST
    }
    Err(DeterminizeError::NoStartState) => {
        // Input WFST has no start state
    }
    Err(DeterminizeError::StateLimitExceeded { limit }) => {
        // Output grew too large, increase max_states or simplify input
    }
    Err(DeterminizeError::NotDeterminizable { reason }) => {
        // WFST cannot be determinized (cycle issues)
    }
}
```

## Performance Tips

1. **Remove epsilon first**: Epsilon-free WFSTs determinize faster
2. **Set reasonable limits**: Use `max_states` to catch blowup early
3. **Check first**: Use `is_deterministic()` to skip unnecessary work
4. **Measure degree**: High `non_determinism_degree` suggests potential blowup

## Next Steps

- [Epsilon Removal]epsilon-removal.md: Required before determinization
- [Minimization]minimization.md: Uses determinization as prerequisite
- [Weight Pushing]weight-pushing.md: Often combined with determinization
- [Semirings]../architecture/semirings.md: Understanding divisible semirings