morok-schedule 0.1.0-alpha.2

Optimization passes and pattern engine for the Morok ML compiler
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
//! Optimizer configuration types.
//!
//! Provides typed configuration for kernel optimization with bon builders.
//! Supports both explicit configuration and environment variable fallbacks.

use std::time::Duration;

use bon::bon;

// ============================================================================
// OPTIMIZATION STRATEGY
// ============================================================================

/// Optimization strategy for kernel tuning.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum OptStrategy {
    /// No optimization (for debugging/regression testing).
    None,

    /// Hand-coded heuristics (default).
    #[default]
    Heuristic,

    /// Beam search optimization.
    Beam {
        /// Beam width - number of candidates to keep at each step.
        width: usize,
    },
}

impl OptStrategy {
    /// Get optimization strategy from environment variables.
    ///
    /// # Environment Variables
    ///
    /// * `MOROK_NOOPT=1` - Disable all optimizations
    /// * `MOROK_BEAM=N` - Use beam search with width N
    pub fn from_env() -> Self {
        if std::env::var("MOROK_NOOPT").is_ok() {
            return Self::None;
        }

        if let Ok(beam_str) = std::env::var("MOROK_BEAM")
            && let Ok(width) = beam_str.parse::<usize>()
            && width > 0
        {
            return Self::Beam { width };
        }

        Self::Heuristic
    }

    /// Check if this strategy disables optimization.
    pub fn is_none(&self) -> bool {
        matches!(self, Self::None)
    }

    /// Check if this strategy uses beam search.
    pub fn is_beam(&self) -> bool {
        matches!(self, Self::Beam { .. })
    }
}

// ============================================================================
// TENSOR CORE SETTINGS
// ============================================================================

/// Tensor core usage level.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TcUsage {
    /// Disabled (USE_TC=0).
    Disabled,

    /// Enabled (USE_TC=1, default).
    #[default]
    Enabled,

    /// Shape-only mode (USE_TC=2).
    ShapeOnly,
}

impl TcUsage {
    /// Convert to integer value for internal APIs.
    pub fn as_usize(&self) -> usize {
        match self {
            Self::Disabled => 0,
            Self::Enabled => 1,
            Self::ShapeOnly => 2,
        }
    }
}

/// Tensor core optimization level.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TcOpt {
    /// Strict matching (TC_OPT=0).
    Strict,

    /// Relaxed matching (TC_OPT=1).
    Relaxed,

    /// Padded matching (TC_OPT=2, default).
    #[default]
    Padded,
}

impl TcOpt {
    /// Convert to integer value for internal APIs.
    pub fn as_usize(&self) -> usize {
        match self {
            Self::Strict => 0,
            Self::Relaxed => 1,
            Self::Padded => 2,
        }
    }
}

/// Tensor core selection mode.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum TcSelect {
    /// Auto-select best tensor core (TC_SELECT=-1, default).
    #[default]
    Auto,

    /// Use specific tensor core index.
    Index(usize),
}

impl TcSelect {
    /// Convert to integer value for internal APIs.
    pub fn as_i32(&self) -> i32 {
        match self {
            Self::Auto => -1,
            Self::Index(idx) => *idx as i32,
        }
    }
}

// ============================================================================
// BEAM SEARCH CONFIGURATION
// ============================================================================

/// Configuration for beam search auto-tuning.
#[derive(Debug, Clone)]
pub struct BeamConfig {
    /// Beam width - number of candidates to keep at each step.
    pub beam_width: usize,
    /// Maximum search time.
    pub timeout: Duration,
    /// Maximum upcast size (product of UPCAST/UNROLL dimensions).
    pub max_upcast: usize,
    /// Maximum local size (product of LOCAL/WARP/GROUP_REDUCE dimensions).
    pub max_local: usize,
    /// Maximum UOps in kernel before rejecting.
    pub max_uops: usize,
    /// Number of benchmark runs per kernel.
    pub num_runs: usize,
    /// Disable disk cache.
    pub disable_cache: bool,
}

impl Default for BeamConfig {
    fn default() -> Self {
        Self {
            beam_width: 4,
            timeout: Duration::from_secs(60),
            max_upcast: 256,
            max_local: 1024,
            max_uops: 3000,
            num_runs: 3,
            disable_cache: false,
        }
    }
}

#[bon]
impl BeamConfig {
    /// Create a beam configuration with builder pattern.
    #[builder]
    pub fn builder(
        #[builder(default = 4)] beam_width: usize,
        #[builder(default = 60)] timeout_secs: u64,
        #[builder(default = 256)] max_upcast: usize,
        #[builder(default = 1024)] max_local: usize,
        #[builder(default = 3000)] max_uops: usize,
        #[builder(default = 3)] num_runs: usize,
        #[builder(default = false)] disable_cache: bool,
    ) -> Self {
        Self {
            beam_width,
            timeout: Duration::from_secs(timeout_secs),
            max_upcast,
            max_local,
            max_uops,
            num_runs,
            disable_cache,
        }
    }

    /// Create configuration from environment variables.
    ///
    /// # Environment Variables
    ///
    /// * `MOROK_BEAM` - Beam width (default: 4)
    /// * `MOROK_BEAM_TIMEOUT` - Max search time in seconds (default: 60)
    /// * `BEAM_UPCAST_MAX` - Max upcast size (default: 256)
    /// * `BEAM_LOCAL_MAX` - Max local memory elements (default: 1024)
    /// * `BEAM_UOPS_MAX` - Max UOps before rejecting (default: 3000)
    /// * `BEAM_RUNS` - Benchmark runs per kernel (default: 3)
    /// * `IGNORE_BEAM_CACHE` - Bypass disk cache if set
    pub fn from_env() -> Self {
        let beam_width = std::env::var("MOROK_BEAM").ok().and_then(|s| s.parse().ok()).unwrap_or(4);
        let timeout_secs = std::env::var("MOROK_BEAM_TIMEOUT").ok().and_then(|s| s.parse().ok()).unwrap_or(60);
        let max_upcast = std::env::var("BEAM_UPCAST_MAX").ok().and_then(|s| s.parse().ok()).unwrap_or(256);
        let max_local = std::env::var("BEAM_LOCAL_MAX").ok().and_then(|s| s.parse().ok()).unwrap_or(1024);
        let max_uops = std::env::var("BEAM_UOPS_MAX").ok().and_then(|s| s.parse().ok()).unwrap_or(3000);
        let num_runs = std::env::var("BEAM_RUNS").ok().and_then(|s| s.parse().ok()).unwrap_or(3);
        let disable_cache = std::env::var("IGNORE_BEAM_CACHE").is_ok();

        Self {
            beam_width,
            timeout: Duration::from_secs(timeout_secs),
            max_upcast,
            max_local,
            max_uops,
            num_runs,
            disable_cache,
        }
    }

    /// Get beam width from strategy if applicable.
    pub fn with_strategy_width(mut self, strategy: &OptStrategy) -> Self {
        if let OptStrategy::Beam { width } = strategy {
            self.beam_width = *width;
        }
        self
    }
}

// ============================================================================
// HEURISTICS CONFIGURATION
// ============================================================================

/// Configuration for heuristic-based optimization.
#[derive(Debug, Clone)]
pub struct HeuristicsConfig {
    // Tensor cores
    /// Tensor core usage level.
    pub tc_enabled: TcUsage,
    /// Tensor core optimization level.
    pub tc_opt: TcOpt,
    /// Tensor core selection mode.
    pub tc_select: TcSelect,

    // Matrix-vector optimization
    /// Enable matrix-vector optimization.
    pub matvec_enabled: bool,
    /// Matrix-vector block size (rows per workgroup).
    pub matvec_blocksize: usize,

    // Reduction thresholds
    /// Threshold for applying grouped reduction.
    pub grouped_threshold: usize,
    /// Threshold for applying unroll.
    pub unroll_threshold: usize,

    // Local memory
    /// Disable local memory globally.
    pub disable_locals: bool,

    // Threading
    /// Maximum thread count for CPU parallelization.
    /// Default: std::thread::available_parallelism().
    /// Set to 1 to disable threading.
    pub thread_count: usize,

    // Vectorization
    /// Enable K-axis vectorization for matmul.
    /// When enabled, UPCAST is applied to the reduce (K) axis creating vector accumulators.
    /// Disabled by default: K-vectorization complicates output tiling and horizontal reduce.
    /// Tinygrad doesn't use K-vectorization - they rely on output tiling (register blocking).
    /// Default: false.
    pub k_vectorize: bool,

    /// Enable output dimension upcasting for matmul (register blocking).
    /// When enabled, UPCAST is applied to M/N axes creating register tiles.
    /// Each thread computes an MxN tile instead of a single element.
    /// Default: false (blocked by vector width mismatch issue in expand.rs).
    pub output_upcast: bool,

    // Debug
    /// Debug verbosity level.
    pub debug_level: u8,
}

/// Get default thread count from system (used by Default and builder).
fn default_thread_count() -> usize {
    std::thread::available_parallelism().map(|p| p.get()).unwrap_or(8)
}

impl HeuristicsConfig {
    /// Create configuration from environment variables.
    ///
    /// # Environment Variables
    ///
    /// * `MOROK_THREADS` - Maximum thread count (default: available_parallelism)
    /// * `MOROK_K_VECTORIZE` - Enable K-axis vectorization (default: disabled)
    /// * `MOROK_NO_OUTPUT_UPCAST` - Disable output dimension upcasting (default: enabled)
    pub fn from_env() -> Self {
        let thread_count =
            std::env::var("MOROK_THREADS").ok().and_then(|s| s.parse().ok()).unwrap_or_else(default_thread_count);
        let k_vectorize = std::env::var("MOROK_K_VECTORIZE").is_ok();
        // Default enabled, use MOROK_NO_OUTPUT_UPCAST to disable
        let output_upcast = std::env::var("MOROK_NO_OUTPUT_UPCAST").is_err();

        Self { thread_count, k_vectorize, output_upcast, ..Default::default() }
    }
}

impl Default for HeuristicsConfig {
    fn default() -> Self {
        Self {
            tc_enabled: TcUsage::Enabled,
            tc_opt: TcOpt::Padded,
            tc_select: TcSelect::Auto,
            matvec_enabled: true,
            matvec_blocksize: 4,
            grouped_threshold: 256,
            unroll_threshold: 32,
            disable_locals: false,
            thread_count: default_thread_count(),
            k_vectorize: false,
            output_upcast: true,
            debug_level: 0,
        }
    }
}

#[bon]
impl HeuristicsConfig {
    /// Create a heuristics configuration with builder pattern.
    #[builder]
    pub fn builder(
        #[builder(default)] tc_enabled: TcUsage,
        #[builder(default)] tc_opt: TcOpt,
        #[builder(default)] tc_select: TcSelect,
        #[builder(default = true)] matvec_enabled: bool,
        #[builder(default = 4)] matvec_blocksize: usize,
        #[builder(default = 256)] grouped_threshold: usize,
        #[builder(default = 32)] unroll_threshold: usize,
        #[builder(default = false)] disable_locals: bool,
        #[builder(default = default_thread_count())] thread_count: usize,
        #[builder(default = false)] k_vectorize: bool,
        #[builder(default = true)] output_upcast: bool,
        #[builder(default = 0)] debug_level: u8,
    ) -> Self {
        Self {
            tc_enabled,
            tc_opt,
            tc_select,
            matvec_enabled,
            matvec_blocksize,
            grouped_threshold,
            unroll_threshold,
            disable_locals,
            thread_count,
            k_vectorize,
            output_upcast,
            debug_level,
        }
    }
}

// ============================================================================
// TOP-LEVEL OPTIMIZER CONFIGURATION
// ============================================================================

/// Top-level optimizer configuration.
///
/// Combines strategy selection, beam search settings, and heuristic parameters.
#[derive(Debug, Clone, Default)]
pub struct OptimizerConfig {
    /// Optimization strategy (None, Heuristic, or Beam).
    pub strategy: OptStrategy,
    /// Beam search configuration (used when strategy is Beam).
    pub beam: BeamConfig,
    /// Heuristics configuration (used when strategy is Heuristic).
    pub heuristics: HeuristicsConfig,
}

#[bon]
impl OptimizerConfig {
    /// Create an optimizer configuration with builder pattern.
    #[builder]
    pub fn builder(
        #[builder(default)] strategy: OptStrategy,
        #[builder(default)] beam: BeamConfig,
        #[builder(default)] heuristics: HeuristicsConfig,
    ) -> Self {
        Self { strategy, beam, heuristics }
    }

    /// Create configuration from environment variables.
    ///
    /// Reads strategy from env, then populates beam and heuristics config accordingly.
    ///
    /// # Environment Variables
    ///
    /// * `MOROK_NOOPT=1` - Disable all optimizations
    /// * `MOROK_BEAM=N` - Use beam search with width N
    pub fn from_env() -> Self {
        let strategy = OptStrategy::from_env();
        let beam = BeamConfig::from_env().with_strategy_width(&strategy);
        let heuristics = HeuristicsConfig::from_env();

        Self { strategy, beam, heuristics }
    }
}

// ============================================================================
// TESTS
// ============================================================================

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

    #[test]
    fn test_opt_strategy_default_is_heuristic() {
        assert_eq!(OptStrategy::default(), OptStrategy::Heuristic);
    }

    #[test]
    fn test_opt_strategy_is_none() {
        assert!(OptStrategy::None.is_none());
        assert!(!OptStrategy::Heuristic.is_none());
        assert!(!OptStrategy::Beam { width: 4 }.is_none());
    }

    #[test]
    fn test_opt_strategy_is_beam() {
        assert!(!OptStrategy::None.is_beam());
        assert!(!OptStrategy::Heuristic.is_beam());
        assert!(OptStrategy::Beam { width: 4 }.is_beam());
    }

    #[test]
    fn test_beam_config_default() {
        let config = BeamConfig::default();
        assert_eq!(config.beam_width, 4);
        assert_eq!(config.timeout, Duration::from_secs(60));
        assert_eq!(config.max_upcast, 256);
        assert_eq!(config.max_local, 1024);
    }

    #[test]
    fn test_beam_config_builder() {
        let config = BeamConfig::builder().beam_width(8).timeout_secs(120).max_upcast(512).build();

        assert_eq!(config.beam_width, 8);
        assert_eq!(config.timeout, Duration::from_secs(120));
        assert_eq!(config.max_upcast, 512);
        assert_eq!(config.max_local, 1024); // default
    }

    #[test]
    fn test_heuristics_config_default() {
        let config = HeuristicsConfig::default();
        assert_eq!(config.tc_enabled, TcUsage::Enabled);
        assert_eq!(config.tc_opt, TcOpt::Padded);
        assert!(config.matvec_enabled);
        assert_eq!(config.grouped_threshold, 256);
    }

    #[test]
    fn test_heuristics_config_builder() {
        let config = HeuristicsConfig::builder()
            .tc_enabled(TcUsage::Disabled)
            .matvec_enabled(false)
            .grouped_threshold(128)
            .build();

        assert_eq!(config.tc_enabled, TcUsage::Disabled);
        assert!(!config.matvec_enabled);
        assert_eq!(config.grouped_threshold, 128);
    }

    #[test]
    fn test_optimizer_config_default() {
        let config = OptimizerConfig::default();
        assert_eq!(config.strategy, OptStrategy::Heuristic);
        assert_eq!(config.beam.beam_width, 4);
    }

    #[test]
    fn test_optimizer_config_builder() {
        let config = OptimizerConfig::builder()
            .strategy(OptStrategy::Beam { width: 8 })
            .beam(BeamConfig::builder().timeout_secs(120).build())
            .build();

        assert_eq!(config.strategy, OptStrategy::Beam { width: 8 });
        assert_eq!(config.beam.timeout, Duration::from_secs(120));
    }

    #[test]
    fn test_tc_usage_as_usize() {
        assert_eq!(TcUsage::Disabled.as_usize(), 0);
        assert_eq!(TcUsage::Enabled.as_usize(), 1);
        assert_eq!(TcUsage::ShapeOnly.as_usize(), 2);
    }

    #[test]
    fn test_tc_opt_as_usize() {
        assert_eq!(TcOpt::Strict.as_usize(), 0);
        assert_eq!(TcOpt::Relaxed.as_usize(), 1);
        assert_eq!(TcOpt::Padded.as_usize(), 2);
    }

    #[test]
    fn test_tc_select_as_i32() {
        assert_eq!(TcSelect::Auto.as_i32(), -1);
        assert_eq!(TcSelect::Index(5).as_i32(), 5);
    }
}