Skip to main content

oa/core/
env_flag.rs

1//! Environment-variable knobs for OA runtime configuration.
2//!
3//! Port provenance: `oa/core/envFlag.h`.
4//!
5//! [`EnvFlag`] is the single-source convention for reading OA env knobs.
6//! [`NumericMode`] and [`apply_numeric_mode`] translate a process-wide numeric
7//! execution policy into the equivalent env-knob state, called once from
8//! `Engine::create`.
9//!
10//! # Reading pattern
11//!
12//! ```rust,ignore
13//! use oa::EnvFlag;
14//!
15//! // bool toggle — true when set to anything other than 0/false/no/off
16//! if EnvFlag::is_set("OA_DISABLE_COOPMAT") { ... }
17//!
18//! // string override — returns default when var is unset or empty
19//! let prec = EnvFlag::get_string("OA_FORCE_PRECISION", "FP32");
20//!
21//! // integer override — returns default when unset or unparseable
22//! let workers = EnvFlag::get_int("OA_SHADER_LOAD_THREADS", 0);
23//! ```
24//!
25//! # Canonical OA env knobs
26//!
27//! ## Disable toggles
28//! - `OA_DISABLE_COOPMAT` — skip CoopMat extension; route to scalar
29//! - `OA_DISABLE_COOPMAT2` — skip VK_NV_cooperative_matrix2
30//! - `OA_DISABLE_BF16` — force FP32; skip VK_KHR_shader_bfloat16
31//! - `OA_DISABLE_PERSISTENT_LOOP` — force single-step submission
32//! - `OA_DISABLE_INTEGER_DOT_PRODUCT` — skip VK_KHR_shader_integer_dot_product
33//! - `OA_DISABLE_GRU_SCAN` — use decomposed GRU cells instead of fused scan
34//! - `OA_DISABLE_GEMM_ROUTE_CACHE` — skip measured GEMM route-cache replay
35//! - `OA_DISABLE_NARROW_ROW_KERNELS` — skip narrow LayerNorm/softmax schedules
36//! - `OA_DISABLE_TILED_BMM` — skip the shared-memory BMM schedule
37//! - `OA_DISABLE_LINEAR_PARAM_ROWS32` — skip narrow Linear parameter-adjoint schedule
38//! - `OA_DISABLE_DNN_VISION_PREPROCESS` — retain convertColor→resizeNormalize source dispatches
39//! - `OA_JIT_ROUTE=auto|tape|specialized|unfused` — force the L2 route when `OA_JIT_FUSION` is set
40//! - `OA_DISABLE_DNN_QKV` — retain per-projection QKV source dispatches
41//! - `OA_DISABLE_DNN_GATE_UP` — retain gate/up+SwiGLU source dispatches
42//!
43//! ## Force overrides
44//! - `OA_FORCE_PRECISION=FP32|BF16|FP16`
45//! - `OA_FORCE_COOPMAT=1` — bypass vendor-trust blocklist
46//! - `OA_FORCE_COOPVEC=1` — bypass CoopVec NVIDIA-only routing gate
47//! - `OA_FORCE_DEVICE_INDEX=N` — override device pick
48//! - `OA_SHADER_PRELOAD=1` — compile all admitted pipelines during Engine build
49//! - `OA_SHADER_LOAD_THREADS=0|1|N` — shader preload workers
50//!
51//! ## Diagnostic / opt-in logging
52//! - `OA_VK_VALIDATION=1`
53//! - `OA_LOG_GEMM_ROUTER=1`
54//! - `OA_LOG_PIPELINE_LOAD=1`
55//! - `OA_LOG_BARRIERS=1`
56//! - `OA_LOG_CONTEXT_GRAPH=N`
57//! - `OA_GRAPH_REPORT=path|1`
58//! - `OA_LOG_COOPMAT_SHAPES=1`
59//! - `OA_LOG_NUMERIC_DEVIATIONS=1`
60
61use std::env;
62
63// ─── EnvFlag ─────────────────────────────────────────────────────────────────
64
65/// Single-source environment-variable reader for OA runtime knobs.
66pub struct EnvFlag;
67
68impl EnvFlag {
69	/// Return `true` when the environment variable is set to a value that is
70	/// **not** one of `""`, `"0"`, `"false"`, `"no"`, `"off"` (case-insensitive).
71	///
72	/// Mirrors `oa::EnvFlag::isSet`.
73	pub fn is_set(name: &str) -> bool {
74		match env::var(name) {
75			Err(_) => false,
76			Ok(val) => !Self::is_falsy(&val),
77		}
78	}
79
80	/// Return the env value when set and non-empty, otherwise `default`.
81	///
82	/// Mirrors `oa::EnvFlag::getString`.
83	pub fn get_string(name: &str, default: &str) -> String {
84		match env::var(name) {
85			Ok(val) if !val.is_empty() => val,
86			_ => default.to_owned(),
87		}
88	}
89
90	/// Return the env value parsed as `i64` when set, non-empty, and parseable,
91	/// otherwise `default`. Only decimal notation is accepted.
92	///
93	/// Mirrors `oa::EnvFlag::getInt`.
94	pub fn get_int(name: &str, default: i64) -> i64 {
95		match env::var(name) {
96			Ok(val) if !val.is_empty() => val.parse::<i64>().unwrap_or(default),
97			_ => default,
98		}
99	}
100
101	/// Set the environment variable to `value` if it is not already set.
102	///
103	/// Returns `false` when the variable was already set externally (the
104	/// caller's signal that user-supplied env wins over programmatic defaults).
105	///
106	/// Mirrors `oa::EnvFlag::setIfUnset`. Internally used by
107	/// [`apply_numeric_mode`].
108	///
109	/// # Safety
110	///
111	/// Calls `std::env::set_var` which is not signal-safe. Callers must ensure
112	/// this is not called concurrently from multiple threads. Typically called
113	/// once from `Engine::create` during single-threaded startup.
114	pub fn set_if_unset(name: &str, value: &str) -> bool {
115		if env::var(name).is_ok() {
116			return false;
117		}
118		// SAFETY: single-threaded startup contract — see doc comment.
119		unsafe { env::set_var(name, value) };
120		true
121	}
122
123	// ── internal ──────────────────────────────────────────────────────────
124
125	fn is_falsy(val: &str) -> bool {
126		matches!(
127			val.to_ascii_lowercase().as_str(),
128			"" | "0" | "false" | "no" | "off"
129		)
130	}
131}
132
133// ─── NumericMode ──────────────────────────────────────────────────────────────
134
135/// Process-wide numerical execution policy.
136///
137/// Core owns the vocabulary and its environment mapping; the runtime engine
138/// consumes it through `EngineConfig`.
139///
140/// | Mode            | Effect |
141/// |-----------------|--------|
142/// | `Fast`          | vendor math, non-deterministic reductions |
143/// | `Stable`        | FP32 accumulators, CoopMat disabled |
144/// | `Deterministic` | fixed reduction order, no race-dependent atomics |
145///
146/// Port provenance: `oa::NumericMode` in `oa/core/envFlag.h`.
147#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
148#[repr(u8)]
149pub enum NumericMode {
150	/// Vendor math, maximum performance. Non-deterministic reductions allowed.
151	Fast = 0,
152	/// FP32 accumulators; CoopMat and BF16 disabled. Recommended for training.
153	#[default]
154	Stable = 1,
155	/// Fixed reduction order; persistent-loop submission disabled.
156	/// Required for byte-identical reproducibility.
157	Deterministic = 2,
158}
159
160// ─── apply_numeric_mode ───────────────────────────────────────────────────────
161
162/// Translate a [`NumericMode`] into the equivalent env-knob state.
163///
164/// Called **once** at engine init. User-set env vars always win
165/// ([`EnvFlag::set_if_unset`] checks before writing).
166///
167/// | Mode            | Env vars touched |
168/// |-----------------|-----------------|
169/// | `Fast`          | none |
170/// | `Stable`        | `OA_FORCE_PRECISION=FP32`, `OA_DISABLE_COOPMAT=1` |
171/// | `Deterministic` | above + `OA_DISABLE_PERSISTENT_LOOP=1` |
172///
173/// Port provenance: `oa::applyNumericMode` in `oa/core/envFlag.h`.
174pub fn apply_numeric_mode(mode: NumericMode) {
175	match mode {
176		NumericMode::Fast => {}
177		NumericMode::Stable => {
178			EnvFlag::set_if_unset("OA_FORCE_PRECISION", "FP32");
179			EnvFlag::set_if_unset("OA_DISABLE_COOPMAT", "1");
180		}
181		NumericMode::Deterministic => {
182			EnvFlag::set_if_unset("OA_FORCE_PRECISION", "FP32");
183			EnvFlag::set_if_unset("OA_DISABLE_COOPMAT", "1");
184			EnvFlag::set_if_unset("OA_DISABLE_PERSISTENT_LOOP", "1");
185		}
186	}
187}