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
// @generated by tool/gen/fn/generate.py; DO NOT EDIT.
// schema=ml_types.json schema_version=1 generator_version=64
// schema_sha256=3071aaa44e74e9e807eaff89728f41cf8af5830a1d734c999df6b82f05c88fa2
use super::training::{TrainingCommandDisposition, TrainingCommandError, TrainingState};
use crate::{DType, Matrix};
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct CheckpointManagerConfig {
/// Root directory beneath which the model directory is created.
pub directory: PathBuf,
/// Stable filename component and master checkpoint stem.
pub model_name: String,
/// Optional incremental-checkpoint directory/filename component.
pub context: String,
/// Maximum retained incremental checkpoints; zero disables rotation.
pub max_keep: usize,
/// Whether an improved metric updates the master checkpoint.
pub save_best: bool,
/// Metric name written into progress metadata and filenames.
pub metric_name: String,
/// Whether a lower metric is considered better.
pub lower_is_better: bool,
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct RolloutCollectorConfig {
/// Number of vector-environment steps in each collection.
pub horizon: usize,
/// Base seed for initial reset and categorical samples.
pub seed: u64,
/// Generalized-advantage estimator policy.
pub gae: GaeConfig,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct TradingConfig {
/// Independent device lanes (round-robin over supplied contiguous segments).
pub environments: u32,
/// Positive closed-bar window length.
pub window: u32,
/// Episode length in bars, 1..=1,000,000; fill counts remain exact in F32.
pub horizon: u32,
/// Full 64-bit deterministic reset seed.
pub seed: u64,
/// Initial analytical capital per independent lane.
pub capital: f32,
/// Fraction of equity budgeted for entry margin and costs, in (0,1]. Instrument execution rules may additionally admit explicit leverage.
pub exposure: f32,
/// Actual-notional taker fee fraction on every execution leg.
pub taker_fee: f32,
/// Adverse one-way slippage in basis points, excluding spread.
pub slippage_bps: f32,
/// Full bid/ask spread in basis points; half is charged per execution leg.
pub spread_bps: f32,
/// Peak-equity drawdown fraction that terminates and closes inventory.
pub max_drawdown: f32,
/// Perpetuals use short/flat/long; Spot uses flat/long (no short category).
pub perpetual: bool,
/// Close and terminate at the horizon; otherwise truncate with final-state bootstrap.
pub liquidate_at_horizon: bool,
}
pub struct BatchNorm2dResult {
/// Normalized and affine-transformed NCHW values.
pub output: Matrix,
/// Population mean for each channel.
pub mean: Matrix,
/// Population variance for each channel.
pub variance: Matrix,
}
pub struct MaxPool2dResult {
/// Maximum value selected from each pooling window.
pub output: Matrix,
/// Flat input index selected for each output element.
pub indices: Matrix,
}
/// Nearest-code indices and gathered code vectors.
pub struct VqAssignResult {
/// I32 nearest-code index for every latent row.
pub indices: Matrix,
/// Gathered winning code for every latent row.
pub quantized: Matrix,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Mamba3PreprocessConfig {
/// Width of the z and x projection slices.
pub inner_size: usize,
/// Width of each B/C state row.
pub state_size: usize,
/// Number of selective-state heads.
pub num_heads: usize,
/// Number of rotary angle pairs.
pub num_rope_angles: usize,
/// Number of shared B/C groups.
pub num_groups: usize,
/// Number of B/C rows per group.
pub mimo_rank: usize,
/// Epsilon used by B/C RMS normalization.
pub epsilon: f32,
/// Inclusive lower bound for transformed dt.
pub dt_min: f32,
/// Inclusive upper bound for transformed dt.
pub dt_max: f32,
/// Positive floor for the magnitude of the negative A token.
pub a_floor: f32,
}
#[derive(Clone)]
pub struct Mamba3PreprocessResult {
/// Value projection slice.
pub x: Matrix,
/// Gate projection slice.
pub z: Matrix,
/// RMS-normalized B rows.
pub bh: Matrix,
/// RMS-normalized C rows.
pub ch: Matrix,
/// Clamped positive time steps.
pub dt: Matrix,
/// Negative A-times-dt log decays.
pub adt: Matrix,
/// Raw trapezoidal gates.
pub trap: Matrix,
/// Raw rotary angular velocities.
pub angle: Matrix,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct SsmConfig {
/// Batch size.
pub batch_size: usize,
/// Sequence length.
pub sequence_length: usize,
/// Number of value heads.
pub num_heads: usize,
/// Number of shared Q/K groups, or zero for num_heads.
pub num_groups: usize,
/// Value width per head.
pub head_dim: usize,
/// Selective recurrent state width.
pub state_size: usize,
/// Number of rotary pairs in the state axis.
pub num_rope_angles: usize,
/// MIMO rank; SISO callers use one.
pub mimo_rank: usize,
/// Apply the SiLU z gate.
pub has_z: bool,
/// Apply the learned D skip.
pub has_d: bool,
/// Apply MIMO output normalization; SISO requires false.
pub has_output_norm: bool,
}
/// One categorical action and its differentiable policy statistics.
pub struct PolicyResult {
/// I32 action index for every environment.
pub action: Matrix,
/// Log probability of each selected action.
pub log_probability: Matrix,
/// Categorical entropy for every environment.
pub entropy: Matrix,
/// Critic value passed through without a storage copy.
pub value: Matrix,
}
/// One bounded continuous action and its differentiable policy statistics.
pub struct ContinuousPolicyResult {
/// Action after tanh squashing and affine mapping to the requested range.
pub action: Matrix,
/// Unsquashed normal sample, retained for exact policy reevaluation.
pub raw_action: Matrix,
/// Summed corrected log probability for every environment.
pub log_probability: Matrix,
/// Summed base-normal entropy for every environment.
pub entropy: Matrix,
/// Critic value passed through without a storage copy.
pub value: Matrix,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ValidationResult {
/// Sample-weighted mean validation loss, or NaN when no value is available.
pub loss: f64,
/// Number of validation batches consumed.
pub batches: u64,
/// Number of validation samples consumed.
pub samples: u64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct DqnTrainerConfig {
/// Number of optimizer updates to complete.
pub updates: u64,
/// Replay transitions consumed by one update.
pub batch_size: usize,
/// Completed-update interval between exact online-to-target copies.
pub target_update_interval: u64,
/// Per-transition observation shape expected from replay.
pub observation_shape: Vec<usize>,
/// Base seed used by deterministic replay sampling.
pub seed: u64,
/// Bellman-target configuration.
pub loss: DqnLossConfig,
}
#[derive(Clone, Debug, PartialEq)]
pub struct SacTrainerConfig {
/// Number of critic/actor update pairs to complete.
pub updates: u64,
/// Replay transitions consumed by each pair.
pub batch_size: usize,
/// Number of scalar continuous action dimensions.
pub action_dimensions: usize,
/// Completed-pair interval between exact critic-to-target copies.
pub target_update_interval: u64,
/// Per-transition observation shape expected from replay.
pub observation_shape: Vec<usize>,
/// Inclusive lower action mapping bound.
pub action_minimum: f32,
/// Inclusive upper action mapping bound.
pub action_maximum: f32,
/// Base deterministic replay and policy seed.
pub seed: u64,
/// Critic discount and fixed entropy coefficient.
pub loss: SacLossConfig,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TrainingCommandResult {
/// Processed command sequence.
pub sequence: u64,
/// Revision after processing.
pub revision: u64,
/// Whether the command was applied.
pub disposition: TrainingCommandDisposition,
/// Live state after processing.
pub state: TrainingState,
/// Rejection evidence, or `None` for an applied command.
pub error: Option<TrainingCommandError>,
}
#[derive(Clone, Copy, Debug)]
pub struct TrainingSessionConfig {
/// Maximum queued commands before non-blocking enqueue rejects work.
pub command_capacity: usize,
/// Maximum retained command results.
pub result_capacity: usize,
/// Maximum retained lifecycle snapshots.
pub snapshot_capacity: usize,
}
#[derive(Clone, Debug)]
pub struct ItTrainingConfig {
/// Completed optimizer steps restored before this lifecycle starts. `total_steps` remains the absolute final budget, not an additional-step count. Restored steps select the next epoch/cursor/scheduler position but are excluded from this process's loss and timing aggregates.
pub initial_step: u64,
/// Completed-step budget; zero keeps the loop open-ended.
pub total_steps: u64,
/// Fixed steps per epoch; zero disables epoch boundaries.
pub steps_per_epoch: u64,
/// Variable epoch lengths. When nonempty, these replace `steps_per_epoch` and their sum becomes `total_steps`.
pub epoch_steps: Vec<u64>,
/// Samples completed by one step. Zero is normalized to one.
pub batch_size: u64,
/// Optional sequence work per sample for throughput accounting.
pub sequence_length: u64,
/// Human-readable sequence unit used by progress and summary callbacks.
pub sequence_unit: String,
/// Optional fixed source units consumed by one sample.
pub source_units_per_sample: f64,
/// Human-readable source unit used by progress and summary callbacks.
pub source_unit: String,
/// Stable name for the device timer represented in reports.
pub timer_name: String,
/// Collect exact device timestamps around submitted training work.
pub enable_gpu_timing: bool,
}
#[derive(Clone, Debug, Default, PartialEq)]
pub struct PpoTrainerConfig {
/// Number of complete rollout/update cycles.
pub rollouts: u64,
/// Time steps collected in each rollout.
pub horizon: usize,
/// Vector environments represented by each step.
pub environments: usize,
/// Full-batch optimizer passes over each finalized rollout.
pub update_epochs: u64,
/// Maximum sequences evaluated by one update tape; zero means full batch. Minibatches accumulate sample-weighted gradients with unchanged parameters and one optimizer step per epoch. Advantages normalize over the rollout. Each minibatch completes before the next to bound live device memory.
pub update_minibatch_size: usize,
/// Per-environment observation shape, excluding the environment axis.
pub observation_shape: Vec<usize>,
/// Base deterministic categorical sampling seed.
pub seed: u64,
/// Whether optimizer updates collect Vulkan timestamp statistics. Time all update submissions, summing disjoint minibatch and optimizer intervals into one sample per epoch. Collection remains caller-owned.
pub enable_gpu_timing: bool,
/// Generalized-advantage estimator policy.
pub gae: GaeConfig,
/// Clipped PPO objective coefficients.
pub loss: PpoLossConfig,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ItRolloutTrainingConfig {
/// Number of complete collection cycles.
pub rollouts: u64,
/// Time steps stored by each rollout.
pub horizon: usize,
/// Vector environments represented by each time step.
pub environments: usize,
/// Full-batch optimizer passes after each collection.
pub update_epochs: u64,
/// Device timer label for update steps.
pub timer_name: String,
/// Whether each optimizer update records and resolves Vulkan timestamps.
pub enable_gpu_timing: bool,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReplayConfig {
/// Maximum number of retained transitions.
pub capacity: usize,
/// Per-transition observation shape, excluding the batch axis.
pub observation_shape: Vec<usize>,
/// Per-transition action shape; empty denotes one scalar action.
pub action_shape: Vec<usize>,
/// Action storage representation; currently F32 or I32.
pub action_dtype: DType,
}
#[derive(Clone, Debug)]
pub struct McpTrainingConfig {
/// Enable safe-point pause/resume/checkpoint/evaluate/parameter/recapture commands.
pub enable_commands: bool,
/// Enable `training_pause` and `training_resume`.
pub enable_pause_resume: bool,
/// Enable `training_checkpoint`.
pub enable_checkpoint: bool,
/// Enable `training_evaluate`.
pub enable_evaluate: bool,
/// Enable `training_set_parameter`.
pub enable_set_parameter: bool,
/// Enable `training_request_recapture`.
pub enable_recapture: bool,
/// Enable `training_stop` (separately gated because it changes the terminal path).
pub enable_stop: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PolicyEvaluationConfig {
/// Number of vector-environment steps to evaluate.
pub horizon: usize,
/// Reset seed and deterministic greedy operation seed.
pub seed: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DqnLossConfig {
/// Next-state value discount in the inclusive range `[0, 1]`.
pub discount: f32,
}
/// Selected action values, detached targets, and scalar DQN loss.
pub struct DqnLossResult {
/// Q values selected by the batch's action indices, shaped `[batch]`.
pub selected_q: Matrix,
/// Detached Bellman targets, shaped `[batch]`.
pub target_q: Matrix,
/// Mean unit-beta Smooth L1 loss between selected and target Q values.
pub loss: Matrix,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PpoLossConfig {
/// Symmetric policy-ratio clipping distance.
pub clip_epsilon: f32,
/// Multiplier for critic mean-squared error.
pub value_coefficient: f32,
/// Multiplier subtracted for policy entropy.
pub entropy_coefficient: f32,
}
/// PPO loss components retained for metrics and reverse mode.
pub struct PpoLossResult {
/// Mean negative clipped surrogate objective.
pub policy_loss: Matrix,
/// Mean-squared critic error.
pub value_loss: Matrix,
/// Mean policy entropy.
pub entropy: Matrix,
/// `policy_loss + value_coefficient * value_loss - entropy_coefficient * entropy`.
pub total_loss: Matrix,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SacLossConfig {
/// Next-state value discount in the inclusive range `[0, 1]`.
pub discount: f32,
/// Non-negative entropy temperature.
pub entropy_coefficient: f32,
}
/// Detached target and twin-critic SAC loss components.
pub struct SacCriticLossResult {
/// Detached entropy-regularized Bellman target, shaped `[batch]`.
pub target_q: Matrix,
/// Mean-squared loss for the first critic.
pub q1_loss: Matrix,
/// Mean-squared loss for the second critic.
pub q2_loss: Matrix,
/// Sum of both critic losses.
pub total_loss: Matrix,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct CategoricalActorCriticConfig {
/// Number of scalar features in each observation.
pub observation_size: usize,
/// Number of discrete actions; must be at least two.
pub action_count: usize,
/// Width of both hidden layers in each independent tower.
pub hidden_size: usize,
/// Seed for the first of six independent Xavier-uniform projections.
pub seed: u64,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GaeConfig {
/// Reward discount applied to value bootstrap and the reverse trace.
pub gamma: f32,
/// Trace discount applied to the next advantage.
pub lambda: f32,
}
/// Generalized advantages and their matching value targets.
pub struct GaeResult {
/// Advantage estimates with the same `[time, environments]` shape as reward.
pub advantage: Matrix,
/// Returns computed as `advantage + value`.
pub returns: Matrix,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RolloutConfig {
/// Number of time steps retained per collection cycle.
pub time: usize,
/// Number of vector environments represented by every step.
pub environments: usize,
/// Per-environment observation shape, excluding the environment axis.
pub observation_shape: Vec<usize>,
}