Warrior_EA/AI/Network.mqh

1158 lines
58 KiB
MQL5
Raw Permalink Normal View History

refactor(perf): pin CPU threads per network, drop the TargetCPULoad input Dividing a machine budget by the live chart count was wrong twice over. The count is a snapshot taken when each net's pool is built, and charts attach one at a time: five charts measured 10/6/5/4/4% of the same budget, because the first only ever saw itself and the last saw all five. So the earliest chart got several times the threads of the latest - skewing any cross-topology comparison run on those charts, which is the exact thing the setting existed to make fair. Nothing rebalanced afterwards either, and rebalancing would mean tearing down a DLL context under a live trainer. Both problems disappear once the answer stops depending on how many charts are running. Each net now asks for a fixed 2 worker threads, converted to the percentage the DLL wants from the detected core count. Two is not a compromise: since the topology became data-derived the widest dense layer is 64 units, so each ParallelFor has almost nothing to split and per-dispatch overhead dominates. An MLP era cost ~66s at a wildly oversubscribed 12 threads and ~80s at 1 thread - a 20% spread across a 12x difference in thread count. Two per net also lands six concurrent charts exactly on a 12-core box. Removing the input costs nothing on the product side: a Market build has no DLL tier at all, so it was already compiled out to a constant there and no buyer could reach it. Both builds compile 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 15:33:37 -04:00
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#include <Arrays\ArrayDouble.mqh>
#include <Arrays\ArrayInt.mqh>
#include <Arrays\ArrayObj.mqh>
#include <OpenCL\OpenCL.mqh>
fix: make sidecar writes atomic; extract shared AtomicFile helper FileOpen(FILE_WRITE) truncates its target on open. CNet::Save already staged the .nnw through a temp file + rename for that reason, but the three sidecars written beside it did not: .stats ExpertSignalAIBase.mqh:5918 .arrows ExpertSignalAIBase.mqh:6224 .cfg ExpertSignalAIBase.mqh:7329 Two defects followed. 1. An interrupted write published a truncated sidecar. For .cfg that is the worst case: LoadAndCompareTopologyConfiguration() reads a short file as a mismatch, which discards the trained model and restarts from era 0. 2. Windows file sharing is a mutual contract - a writer opened with no FILE_SHARE_* blocks every concurrent open regardless of the reader's flags. All three read paths carry FILE_SHARE_READ|FILE_SHARE_WRITE specifically so a tester agent can read them while a live chart runs; an exclusive writer on the same path defeated that. Extracted CNet::Save's proven pattern into System\AtomicFile.mqh (AtomicWriteBegin/AtomicWriteEnd) and routed all four writers through it. This also encodes the FileMove gotcha once instead of per call site: the destination location comes from FILE_COMMON inside the 4th arg, NOT inherited from the source, and getting it wrong moves the file to the wrong sandbox silently. Also fixed while in these functions: - SaveTopologyConfiguration had 13 copy-pasted 6-line error blocks that each returned WITHOUT FileClose(handle), leaking the handle on every write failure. Collapsed to one ok-chain that closes exactly once. The on-disk field order and types are unchanged (asserted during the rewrite) so existing .cfg files still load. - SaveChartSignals documented that pruning runs only after a successful write ("a failed write above leaves both the file AND the chart untouched") but never checked any write result, so a partial write still deleted the chart objects. Results are checked now, making the existing comment true. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 00:31:29 -04:00
#include "..\System\AtomicFile.mqh"
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
//--- 2nd-tier CPU fallback (used when OpenCL is unavailable, e.g. a VM with no GPU passthrough,
//--- or this machine's OpenCL init failed).
refactor(perf): pin CPU threads per network, drop the TargetCPULoad input Dividing a machine budget by the live chart count was wrong twice over. The count is a snapshot taken when each net's pool is built, and charts attach one at a time: five charts measured 10/6/5/4/4% of the same budget, because the first only ever saw itself and the last saw all five. So the earliest chart got several times the threads of the latest - skewing any cross-topology comparison run on those charts, which is the exact thing the setting existed to make fair. Nothing rebalanced afterwards either, and rebalancing would mean tearing down a DLL context under a live trainer. Both problems disappear once the answer stops depending on how many charts are running. Each net now asks for a fixed 2 worker threads, converted to the percentage the DLL wants from the detected core count. Two is not a compromise: since the topology became data-derived the widest dense layer is 64 units, so each ParallelFor has almost nothing to split and per-dispatch overhead dominates. An MLP era cost ~66s at a wildly oversubscribed 12 threads and ~80s at 1 thread - a 20% spread across a 12x difference in thread count. Two per net also lands six concurrent charts exactly on a 12-core box. Removing the input costs nothing on the product side: a Market build has no DLL tier at all, so it was already compiled out to a constant there and no buyer could reach it. Both builds compile 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 15:33:37 -04:00
#define CPU_THREADS_PER_NETWORK 2
//+------------------------------------------------------------------+
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
//| The percentage CComputeDll needs in order to land on |
refactor(perf): pin CPU threads per network, drop the TargetCPULoad input Dividing a machine budget by the live chart count was wrong twice over. The count is a snapshot taken when each net's pool is built, and charts attach one at a time: five charts measured 10/6/5/4/4% of the same budget, because the first only ever saw itself and the last saw all five. So the earliest chart got several times the threads of the latest - skewing any cross-topology comparison run on those charts, which is the exact thing the setting existed to make fair. Nothing rebalanced afterwards either, and rebalancing would mean tearing down a DLL context under a live trainer. Both problems disappear once the answer stops depending on how many charts are running. Each net now asks for a fixed 2 worker threads, converted to the percentage the DLL wants from the detected core count. Two is not a compromise: since the topology became data-derived the widest dense layer is 64 units, so each ParallelFor has almost nothing to split and per-dispatch overhead dominates. An MLP era cost ~66s at a wildly oversubscribed 12 threads and ~80s at 1 thread - a 20% spread across a 12x difference in thread count. Two per net also lands six concurrent charts exactly on a 12-core box. Removing the input costs nothing on the product side: a Market build has no DLL tier at all, so it was already compiled out to a constant there and no buyer could reach it. Both builds compile 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 15:33:37 -04:00
//| CPU_THREADS_PER_NETWORK workers, given the detected core count. |
//| (WarriorCPU.dll takes a percentage of cores, not a thread count.) |
fix(perf): treat TargetCPULoad as a machine budget split across charts The CPU-DLL thread pool was sized from TargetCPULoad undivided, on the reasoning that only one pool is ever actively computing at a time. That is true WITHIN a chart - MQL5 gives one chart's EA a single execution thread, and every WarriorCPU.dll entry point blocks it until its ParallelFor() completes, so the live net, the EMA shadow and HYBRID's fused pair take turns. It does not hold ACROSS charts, which each get their own execution thread and really do run their pools simultaneously. At the 100% default on a 12-core box, five training charts asked for 12 threads each: 60 threads contending for 12 cores. Measured today, dropping to ~2 threads apiece made every chart train "super fast". This had previously been read as one architecture being mysteriously 10x slower than another on the CPU-DLL tier while identical on OpenCL - oversubscription of that degree degrades superlinearly and punishes whichever model issues the most small sequential dispatches, which fits an MLP being the victim. TargetCPULoad now means the budget for the whole machine, divided by the number of charts running this EA. Counting charts is the correct axis: concurrency here is one execution thread per chart, not one per CNet, and the within-chart division that was previously removed stays removed. Snapshot at pool-creation time on purpose - attaching another chart later does not resize pools that already exist, because that would mean tearing down a DLL context underneath a live training run. Skipped entirely in the tester/optimizer, where the terminal already pins one strategy per agent. This matters most for buyers: a Market build compiles the input out and pins it to 100%, so they cannot reach the setting at all and would have hit the pathological case with no way to diagnose or fix it. The tier log line now reports the split rather than just the result. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 14:06:35 -04:00
//+------------------------------------------------------------------+
int EffectiveCpuLoadPercent()
{
refactor(perf): pin CPU threads per network, drop the TargetCPULoad input Dividing a machine budget by the live chart count was wrong twice over. The count is a snapshot taken when each net's pool is built, and charts attach one at a time: five charts measured 10/6/5/4/4% of the same budget, because the first only ever saw itself and the last saw all five. So the earliest chart got several times the threads of the latest - skewing any cross-topology comparison run on those charts, which is the exact thing the setting existed to make fair. Nothing rebalanced afterwards either, and rebalancing would mean tearing down a DLL context under a live trainer. Both problems disappear once the answer stops depending on how many charts are running. Each net now asks for a fixed 2 worker threads, converted to the percentage the DLL wants from the detected core count. Two is not a compromise: since the topology became data-derived the widest dense layer is 64 units, so each ParallelFor has almost nothing to split and per-dispatch overhead dominates. An MLP era cost ~66s at a wildly oversubscribed 12 threads and ~80s at 1 thread - a 20% spread across a 12x difference in thread count. Two per net also lands six concurrent charts exactly on a 12-core box. Removing the input costs nothing on the product side: a Market build has no DLL tier at all, so it was already compiled out to a constant there and no buyer could reach it. Both builds compile 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 15:33:37 -04:00
int cores = (int)TerminalInfoInteger(TERMINAL_CPU_CORES);
//--- Unknown core count: assume a small machine rather than a large one. Guessing high here would
//--- reintroduce exactly the oversubscription this function exists to prevent.
if(cores <= 0)
cores = 4;
//--- Fewer cores than we would ask for: take the machine as it is. 100 also means "all cores" to the
//--- DLL, so this is the one value that needs no arithmetic.
if(cores <= CPU_THREADS_PER_NETWORK)
return 100;
//--- Round UP: the DLL truncates when turning this back into a thread count, and landing one thread
//--- short of the target is a worse error than landing one over.
int pct = (int)MathCeil(100.0 * (double)CPU_THREADS_PER_NETWORK / (double)cores);
return (int)MathMax(1, MathMin(100, pct));
fix(perf): treat TargetCPULoad as a machine budget split across charts The CPU-DLL thread pool was sized from TargetCPULoad undivided, on the reasoning that only one pool is ever actively computing at a time. That is true WITHIN a chart - MQL5 gives one chart's EA a single execution thread, and every WarriorCPU.dll entry point blocks it until its ParallelFor() completes, so the live net, the EMA shadow and HYBRID's fused pair take turns. It does not hold ACROSS charts, which each get their own execution thread and really do run their pools simultaneously. At the 100% default on a 12-core box, five training charts asked for 12 threads each: 60 threads contending for 12 cores. Measured today, dropping to ~2 threads apiece made every chart train "super fast". This had previously been read as one architecture being mysteriously 10x slower than another on the CPU-DLL tier while identical on OpenCL - oversubscription of that degree degrades superlinearly and punishes whichever model issues the most small sequential dispatches, which fits an MLP being the victim. TargetCPULoad now means the budget for the whole machine, divided by the number of charts running this EA. Counting charts is the correct axis: concurrency here is one execution thread per chart, not one per CNet, and the within-chart division that was previously removed stays removed. Snapshot at pool-creation time on purpose - attaching another chart later does not resize pools that already exist, because that would mean tearing down a DLL context underneath a live training run. Skipped entirely in the tester/optimizer, where the terminal already pins one strategy per agent. This matters most for buyers: a Market build compiles the input out and pins it to 100%, so they cannot reach the setting at all and would have hit the pathological case with no way to diagnose or fix it. The tier log line now reports the split rather than just the result. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 14:06:35 -04:00
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
//--- Adam (Kingma & Ba, 2014) hyperparameters. 3.0e-4 also happens to sit inside the noisy/non-
//--- stationary-trading-data range (0.0003-0.0005) this project had separately tuned lr to before
//--- this input existed, so no behavior conflict.
input double AdamLearningRate = 0.0003; // Adam learning rate
input double AdamBeta1 = 0.9; // Adam beta1
input double AdamBeta2 = 0.999; // Adam beta2
//--- SGD+momentum hyperparameters.
input double SgdLearningRate = 0.0003; // SGD learning rate
input double SgdMomentum = 0.9; // SGD momentum
//--- Live learning rate: starts at the Adam input, then decayed and restored by the training loop,
//--- so it is a mutable global rather than a constant.
//--- g_-PREFIXED, and it has to be: as a bare `eta` this collided with a local of the same name in
//--- the standard library's Math\Stat\Math.mqh (the incomplete-gamma branch), which the compiler
//--- reports as "declaration of 'eta' hides global variable". Same fault as the b1/b2/lr/momentum
//--- macros retired in ea2552e - a single-token global name in a header that library code is
//--- compiled beside. The ETA_DECAY_FACTOR/ETA_MIN/m_etaCeiling vocabulary around it is unchanged,
//--- so the symbol still reads as the learning rate everywhere it appears.
double g_eta = AdamLearningRate;
#define defConnect 0x7781
#define defArrayConnects 0x7782
#define defNeuronBase 0x7783
#define defNeuron 0x7784
#define defNeuronConv 0x7785
#define defNeuronPool 0x7786
#define defLayer 0x7787
#define defArrayLayer 0x7788
#define defNet 0x7789
#define defNeuronLSTM 0x7791
feat(ai): batch normalization between dense layers The only bounded stage in the entire forward path was the sigmoid classification head - every hidden stage is PRELU. That is a network with no internal scale control, and the failure ordered exactly by depth: on SP500 H1 the shallow perceptron held ~52% balanced accuracy while the deepest topology sat on the 33.3% one-class floor, with the per-bar logit spread decaying monotonically (0.45 -> 0.38 over ~200 eras) until the evidence tilt fell under the class-prior tilt. That is the signature of internal covariate shift, which chapter 6.1 of the reference book is entirely about and which the NeuroNet_DNG engine addresses with a layer this project never had. Two mechanisms make this the right fix rather than more hyperparameter nudging: - it decouples WEIGHT_DECAY from the learned function (van Laarhoven 2017) - with a normalized layer downstream, decay can no longer grind the discriminative signal away, it only rescales the effective learning rate; - it is the precondition for ever running an unbounded logit head here. The 2026-07-27 attempt blew up (IS error 5.6e15) precisely because nothing upstream constrained scale. Implementation notes: - CNeuronBatchNormOCL computes host-side rather than as a fourth copy of a kernel across Network.cl + WarriorCPU.cpp + WarriorDML.cpp. The math is elementwise O(n); this way it behaves identically on all four compute tiers, needs no DLL rebuild, and cannot drift between backends. Same precedent as the softmax+CCE gradient and the per-sample loss weighting, both computed in MQL5 for that reason. - Statistics are exponential moving, not a stored mini-batch: training is pure online SGD, one update per sample, so there is no batch to average over. BatchNormWindow is an EMA window length. - gamma/beta are excluded from weight decay, deliberately - decaying gamma toward zero is the exact pathology being fixed. - The layer self-sizes from whatever sits below it, because a conv/pool stage's output width is derived inside the CNet constructor and is not knowable to the topology builder. - Checkpoint capture/restore/blend carry gamma/beta and the running statistics alongside the dense matrix, so the plateau ladder cannot restore a mismatched pair. - SeedOutputLayerBias accepted only an exact defNeuronBaseOCL as the weight-carrying penultimate layer; with normalization enabled that is the batch-norm layer, so the cold-start bias seed would have silently stopped being applied. - Refuses to build, loudly, if a topology asks for normalization with no compute backend at all - rather than quietly training a different architecture than the one requested. EnableBatchNorm (default on) and BatchNormWindow (1000 samples) are inputs so the effect can be A/B'd without a recompile. Both feed the weights-filename fingerprint, appended conditionally so existing non-BN configs keep their fingerprints and are not forced to retrain. Verified: analytic gradients match finite differences to 1.5e-7 relative over 200 random cases; a faithful port of the full forward/backward chain collapses to the 33.3% floor by era 4 without this layer and holds 36-43% with it. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:34:29 -04:00
//--- Topology-descriptor form of the batch-normalization layer (CLayerDescription::type). Like
//--- defNeuronConv/defNeuronPool it has no scalar-CPU neuron class behind it - CNet's constructor maps
//--- it onto CNeuronBatchNormOCL, which is the only implementation. See AI\NeuronBatchNorm.mqh.
#define defNeuronBatchNorm 0x7792
//---
#define defBufferDouble 0x7882
#define defNeuronBaseOCL 0x7883
#define defNeuronLSTMOCL 0x7884
#define defNeuronConvOCL 0x7885
#define defNeuronPoolOCL 0x7886
feat(ai): batch normalization between dense layers The only bounded stage in the entire forward path was the sigmoid classification head - every hidden stage is PRELU. That is a network with no internal scale control, and the failure ordered exactly by depth: on SP500 H1 the shallow perceptron held ~52% balanced accuracy while the deepest topology sat on the 33.3% one-class floor, with the per-bar logit spread decaying monotonically (0.45 -> 0.38 over ~200 eras) until the evidence tilt fell under the class-prior tilt. That is the signature of internal covariate shift, which chapter 6.1 of the reference book is entirely about and which the NeuroNet_DNG engine addresses with a layer this project never had. Two mechanisms make this the right fix rather than more hyperparameter nudging: - it decouples WEIGHT_DECAY from the learned function (van Laarhoven 2017) - with a normalized layer downstream, decay can no longer grind the discriminative signal away, it only rescales the effective learning rate; - it is the precondition for ever running an unbounded logit head here. The 2026-07-27 attempt blew up (IS error 5.6e15) precisely because nothing upstream constrained scale. Implementation notes: - CNeuronBatchNormOCL computes host-side rather than as a fourth copy of a kernel across Network.cl + WarriorCPU.cpp + WarriorDML.cpp. The math is elementwise O(n); this way it behaves identically on all four compute tiers, needs no DLL rebuild, and cannot drift between backends. Same precedent as the softmax+CCE gradient and the per-sample loss weighting, both computed in MQL5 for that reason. - Statistics are exponential moving, not a stored mini-batch: training is pure online SGD, one update per sample, so there is no batch to average over. BatchNormWindow is an EMA window length. - gamma/beta are excluded from weight decay, deliberately - decaying gamma toward zero is the exact pathology being fixed. - The layer self-sizes from whatever sits below it, because a conv/pool stage's output width is derived inside the CNet constructor and is not knowable to the topology builder. - Checkpoint capture/restore/blend carry gamma/beta and the running statistics alongside the dense matrix, so the plateau ladder cannot restore a mismatched pair. - SeedOutputLayerBias accepted only an exact defNeuronBaseOCL as the weight-carrying penultimate layer; with normalization enabled that is the batch-norm layer, so the cold-start bias seed would have silently stopped being applied. - Refuses to build, loudly, if a topology asks for normalization with no compute backend at all - rather than quietly training a different architecture than the one requested. EnableBatchNorm (default on) and BatchNormWindow (1000 samples) are inputs so the effect can be A/B'd without a recompile. Both feed the weights-filename fingerprint, appended conditionally so existing non-BN configs keep their fingerprints and are not forced to retrain. Verified: analytic gradients match finite differences to 1.5e-7 relative over 200 random cases; a faithful port of the full forward/backward chain collapses to the 33.3% floor by era 4 without this layer and holds 36-43% with it. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:34:29 -04:00
#define defNeuronBatchNormOCL 0x7887
//---
#define def_k_FeedForward 0
#define def_k_ff_matrix_w 0
#define def_k_ff_matrix_i 1
#define def_k_ff_matrix_o 2
#define def_k_ff_inputs 3
#define def_k_ff_activation 4
//---
#define def_k_CaclOutputGradient 1
#define def_k_cog_matrix_t 0
#define def_k_cog_matrix_o 1
#define def_k_cog_matrix_ig 2
#define def_k_cog_activation 3
//---
#define def_k_CaclHiddenGradient 2
#define def_k_chg_matrix_w 0
#define def_k_chg_matrix_g 1
#define def_k_chg_matrix_o 2
#define def_k_chg_matrix_ig 3
#define def_k_chg_outputs 4
#define def_k_chg_activation 5
//---
#define def_k_UpdateWeightsMomentum 3
#define def_k_uwm_matrix_w 0
#define def_k_uwm_matrix_g 1
#define def_k_uwm_matrix_i 2
#define def_k_uwm_matrix_dw 3
#define def_k_uwm_inputs 4
#define def_k_uwm_learning_rates 5
#define def_k_uwm_momentum 6
#define def_k_uwm_optimizer 7
//---
#define def_k_UpdateWeightsAdam 4
#define def_k_uwa_matrix_w 0
#define def_k_uwa_matrix_g 1
#define def_k_uwa_matrix_i 2
#define def_k_uwa_matrix_m 3
#define def_k_uwa_matrix_v 4
#define def_k_uwa_inputs 5
#define def_k_uwa_l 6
#define def_k_uwa_b1 7
#define def_k_uwa_b2 8
//---
#define def_k_FeedForwardProof 15
#define def_k_ffp_matrix_i 0
#define def_k_ffp_matrix_o 1
#define def_k_ffp_inputs 2
#define def_k_ffp_window 3
#define def_k_ffp_step 4
//---
#define def_k_CalcInputGradientProof 16
#define def_k_cigp_matrix_i 0
#define def_k_cigp_matrix_g 1
#define def_k_cigp_matrix_o 2
#define def_k_cigp_matrix_ig 3
#define def_k_cigp_outputs 4
#define def_k_cigp_window 5
#define def_k_cigp_step 6
//---
#define def_k_FeedForwardConv 5
#define def_k_ffc_matrix_w 0
#define def_k_ffc_matrix_i 1
#define def_k_ffc_matrix_o 2
#define def_k_ffc_inputs 3
#define def_k_ffc_step 4
#define def_k_ffc_window_in 5
#define def_k_ffc_window_out 6
#define def_k_ffc_activation 7
//---
#define def_k_CalcHiddenGradientConv 6
#define def_k_chgc_matrix_w 0
#define def_k_chgc_matrix_g 1
#define def_k_chgc_matrix_o 2
#define def_k_chgc_matrix_ig 3
#define def_k_chgc_outputs 4
#define def_k_chgc_step 5
#define def_k_chgc_window_in 6
#define def_k_chgc_window_out 7
#define def_k_chgc_activation 8
//---
#define def_k_UpdateWeightsConvMomentum 7
#define def_k_uwcm_matrix_w 0
#define def_k_uwcm_matrix_g 1
#define def_k_uwcm_matrix_i 2
#define def_k_uwcm_matrix_dw 3
#define def_k_uwcm_inputs 4
#define def_k_uwcm_learning_rates 5
#define def_k_uwcm_momentum 6
#define def_k_uwcm_window_in 7
#define def_k_uwcm_window_out 8
#define def_k_uwcm_step 9
#define def_k_uwcm_optimizer 10
//---
#define def_k_UpdateWeightsConvAdam 8
#define def_k_uwca_matrix_w 0
#define def_k_uwca_matrix_g 1
#define def_k_uwca_matrix_i 2
#define def_k_uwca_matrix_m 3
#define def_k_uwca_matrix_v 4
#define def_k_uwca_inputs 5
#define def_k_uwca_l 6
#define def_k_uwca_b1 7
#define def_k_uwca_b2 8
#define def_k_uwca_window_in 9
#define def_k_uwca_window_out 10
#define def_k_uwca_step 11
//---
//--- LSTM (CNeuronLSTMOCL) - single-timestep-truncated BPTT (no gradient flows back into
//--- h_prev/c_prev from a prior step).
#define def_k_LSTM_Gates 9
#define def_k_lstmg_matrix_w 0
#define def_k_lstmg_hidden_prev 1
#define def_k_lstmg_inputs 2
#define def_k_lstmg_concatenated 3
#define def_k_lstmg_hidden_size 4
#define def_k_lstmg_input_size 5
//---
#define def_k_LSTM_State 10
#define def_k_lstms_concatenated 0
#define def_k_lstms_memory 1
#define def_k_lstms_hidden_prev 2
#define def_k_lstms_hidden_cache 3
#define def_k_lstms_output 4
#define def_k_lstms_hidden_size 5
//---
#define def_k_LSTM_GateGradient 11
#define def_k_lstmgg_gradient 0
#define def_k_lstmgg_memory 1
#define def_k_lstmgg_concatenated 2
#define def_k_lstmgg_concatenated_gradient 3
#define def_k_lstmgg_hidden_size 4
//---
#define def_k_LSTM_WeightsGradient 12
#define def_k_lstmwg_concatenated_gradient 0
#define def_k_lstmwg_hidden_cache 1
#define def_k_lstmwg_inputs 2
#define def_k_lstmwg_weights_gradient 3
#define def_k_lstmwg_hidden_size 4
#define def_k_lstmwg_input_size 5
//---
#define def_k_LSTM_InputsGradient 13
#define def_k_lstmig_concatenated_gradient 0
#define def_k_lstmig_matrix_w 1
#define def_k_lstmig_inputs_gradient 2
#define def_k_lstmig_hidden_size 3
#define def_k_lstmig_input_size 4
//---
#define def_k_LSTM_UpdateWeightsAdam 14
#define def_k_lstmuwa_matrix_w 0
#define def_k_lstmuwa_weights_gradient 1
#define def_k_lstmuwa_matrix_m 2
#define def_k_lstmuwa_matrix_v 3
#define def_k_lstmuwa_l 4
#define def_k_lstmuwa_b1 5
#define def_k_lstmuwa_b2 6
//---
// SGD+momentum counterpart to LSTM_UpdateWeightsAdam above - see
// AI\Network.cl's LSTM_UpdateWeightsMomentum for the kernel body.
#define def_k_LSTM_UpdateWeightsMomentum 17
#define def_k_lstmuwm_matrix_w 0
#define def_k_lstmuwm_weights_gradient 1
#define def_k_lstmuwm_matrix_dw 2
#define def_k_lstmuwm_learning_rates 3
#define def_k_lstmuwm_momentum 4
#define def_k_lstmuwm_optimizer 5
//---
feat(ai): sequence-LSTM kernels for the OpenCL tier Closes the gap left by 7a08197, which refused sequence mode under OpenCL. That was defensible for a private build and not for a shipped one: the release path includes an OpenCL laptop, and a customer with a GPU would have found LSTM and HYBRID simply unavailable. One launch PER TIMESTEP rather than a single kernel looping with barrier(). Every hidden unit's gates read all of h_{t-1}, OpenCL barriers only span a work-group, and nothing here constrains how the runtime partitions the global size - so an in-kernel loop would be correct only by luck of the partitioning. Host-driven launches make each step an implicit global barrier: more enqueues, correct on every device. Backward reuses the buffers the single-timestep path leaves idle in sequence mode - ConcatenatedGradient (4H) for gate gradients, HiddenCache (H) for dh, Memory (2H) for dc - so BPTT costs no extra allocations. dW is zeroed once and accumulated across steps, matching the fused DLL kernel. Verification available on this machine has limits worth recording. The math is the same as CPU_LSTMSeqForward/Backward, which is gradient-checked to 2.3e-10; the kernels are syntax/type-checked offline (DirectML\opencl_seq_syntax_check.cpp, compiled as C++ with OpenCL shims) because there is no OpenCL device or ICD here. That check exists because a typo in Network.cl fails the WHOLE program build, which would take the dense and conv kernels down with it - not just the new ones. KernelCreate results are now checked and reported for these four for the same reason; a build failure degrades to "LSTM/HYBRID unavailable on this device" instead of an Execute error mid-training. STILL NEEDS A RUN ON REAL OPENCL HARDWARE before release. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 18:40:56 -04:00
// Sequence LSTM. One launch PER TIMESTEP - the recurrence is sequential and OpenCL
// barriers only span a work-group, so the host loop is what provides the global
// ordering. See the block comment above LSTM_SeqStepForward in AI\Network.cl.
#define def_k_LSTM_SeqStepForward 18
#define def_k_lsf_matrix_w 0
#define def_k_lsf_inputs 1
#define def_k_lsf_cache_gates 2
#define def_k_lsf_cache_cell 3
#define def_k_lsf_cache_hidden 4
#define def_k_lsf_output 5
#define def_k_lsf_hidden_size 6
#define def_k_lsf_step_inputs 7
#define def_k_lsf_steps 8
#define def_k_lsf_t 9
//---
#define def_k_LSTM_SeqStepGateGrad 19
#define def_k_lsgg_out_gradient 0
#define def_k_lsgg_dh_buf 1
#define def_k_lsgg_dc_buf 2
#define def_k_lsgg_cache_gates 3
#define def_k_lsgg_cache_cell 4
#define def_k_lsgg_gate_grad 5
#define def_k_lsgg_hidden_size 6
#define def_k_lsgg_steps 7
#define def_k_lsgg_t 8
//---
#define def_k_LSTM_SeqStepWeightGrad 20
#define def_k_lswg_gate_grad 0
#define def_k_lswg_cache_hidden 1
#define def_k_lswg_inputs 2
#define def_k_lswg_weights_gradient 3
#define def_k_lswg_hidden_size 4
#define def_k_lswg_step_inputs 5
#define def_k_lswg_t 6
//---
#define def_k_LSTM_SeqStepInputGrad 21
#define def_k_lsig_gate_grad 0
#define def_k_lsig_matrix_w 1
#define def_k_lsig_inputs_gradient 2
#define def_k_lsig_dh_buf 3
#define def_k_lsig_hidden_size 4
#define def_k_lsig_step_inputs 5
#define def_k_lsig_t 6
//---
//--- Mini-batch gradient accumulation - see the block comment above AccumulateWeightGrad in
//--- AI\Network.cl.
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
#define def_k_AccumulateWeightGrad 22
#define def_k_awg_matrix_acc 0
#define def_k_awg_matrix_g 1
#define def_k_awg_matrix_i 2
#define def_k_awg_inputs 3
//---
#define def_k_AccumulateWeightGradConv 23
#define def_k_awgc_matrix_acc 0
#define def_k_awgc_matrix_g 1
#define def_k_awgc_matrix_i 2
#define def_k_awgc_inputs 3
#define def_k_awgc_window_in 4
#define def_k_awgc_window_out 5
#define def_k_awgc_step 6
//---
#define def_k_AccumulateBufferInto 24
#define def_k_abi_dst 0
#define def_k_abi_src 1
//---
//--- Mini-batch APPLY.
perf: mini-batch apply becomes a kernel - 8 weight-matrix transfers per batch become 0 Market builds cannot import a DLL, so OpenCL is the tier paying clients run. It was several times slower than the CPU DLL, and the dominant reason was a host-side optimizer step I shipped with the mini-batch work in 274630f. ApplyAccumToBlock read the weights, the accumulator and both Adam moments back over the bus, stepped them in MQL5, and wrote four buffers out - eight full weight-matrix transfers per batch PER WEIGHT BLOCK, each a blocking sync. At TRAIN_BATCH_SIZE 8 that is roughly one entire weight matrix crossing the bus per training sample. It was host-side for a good reason (one optimizer implementation shared by all four tiers instead of four that can drift), and that reason turned out to cost the product's own compute tier. - ApplyAccumAdam / ApplyAccumMomentum in Network.cl: flat, elementwise, and they zero the accumulator themselves so there is no separate clear dispatch and no way to leave it dirty via an early return - ApplyAccumOnDevice dispatches them; the host step stays as the reference and as the implementation for DirectML, the CPU DLL and pure-MQL5 - failure latches OFF process-wide with one warning rather than a failed Execute per batch, since a kernel that did not build will not build later - m_applyKernelsOk is tracked SEPARATELY from m_batchKernelsOk: without the accumulation kernels a device cannot batch and must drop to per-sample updates, whereas without these it batches normally and merely pays the transfers. Conflating them would turn a missing optimisation into a changed optimizer The kernel runs fp32 where the host step ran fp64. That is the OpenCL tier becoming self-consistent, not a regression: its device buffers are already fp32 (CBufferDouble::m_data_f) and its unbatched optimizer already ran in fp32, so the batched path was the odd one out. DLL tiers keep fp64 throughout. Validated: no OpenCL platform exists on this box, so the kernel source is syntax/type checked as C against a shim and driven for 4000 steps. It clears the accumulator, and it is scale-invariant - displacement 1.199336 at |g|=1 versus 1.199333 at |g|=1e-4, matching the figure DirectML/batch_accum_check produced for the fixed CPU_UpdateWeightsAdam. It reproduces the corrected Adam, not the pre-371f8aa one. Both build variants compile 0 errors, 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 17:09:52 -04:00
#define def_k_ApplyAccumAdam 25
#define def_k_aaa_matrix_w 0
#define def_k_aaa_matrix_acc 1
#define def_k_aaa_matrix_m 2
#define def_k_aaa_matrix_v 3
#define def_k_aaa_scale 4
#define def_k_aaa_l 5
#define def_k_aaa_b1 6
#define def_k_aaa_b2 7
//---
#define def_k_ApplyAccumMomentum 26
#define def_k_aam_matrix_w 0
#define def_k_aam_matrix_acc 1
#define def_k_aam_matrix_dw 2
#define def_k_aam_scale 3
#define def_k_aam_lr 4
#define def_k_aam_momentum 5
//--- One latch for the whole process, not per net: the apply kernels either built on this machine's
//--- OpenCL device or they did not, and that answer cannot change mid-run.
perf: mini-batch apply becomes a kernel - 8 weight-matrix transfers per batch become 0 Market builds cannot import a DLL, so OpenCL is the tier paying clients run. It was several times slower than the CPU DLL, and the dominant reason was a host-side optimizer step I shipped with the mini-batch work in 274630f. ApplyAccumToBlock read the weights, the accumulator and both Adam moments back over the bus, stepped them in MQL5, and wrote four buffers out - eight full weight-matrix transfers per batch PER WEIGHT BLOCK, each a blocking sync. At TRAIN_BATCH_SIZE 8 that is roughly one entire weight matrix crossing the bus per training sample. It was host-side for a good reason (one optimizer implementation shared by all four tiers instead of four that can drift), and that reason turned out to cost the product's own compute tier. - ApplyAccumAdam / ApplyAccumMomentum in Network.cl: flat, elementwise, and they zero the accumulator themselves so there is no separate clear dispatch and no way to leave it dirty via an early return - ApplyAccumOnDevice dispatches them; the host step stays as the reference and as the implementation for DirectML, the CPU DLL and pure-MQL5 - failure latches OFF process-wide with one warning rather than a failed Execute per batch, since a kernel that did not build will not build later - m_applyKernelsOk is tracked SEPARATELY from m_batchKernelsOk: without the accumulation kernels a device cannot batch and must drop to per-sample updates, whereas without these it batches normally and merely pays the transfers. Conflating them would turn a missing optimisation into a changed optimizer The kernel runs fp32 where the host step ran fp64. That is the OpenCL tier becoming self-consistent, not a regression: its device buffers are already fp32 (CBufferDouble::m_data_f) and its unbatched optimizer already ran in fp32, so the batched path was the odd one out. DLL tiers keep fp64 throughout. Validated: no OpenCL platform exists on this box, so the kernel source is syntax/type checked as C against a shim and driven for 4000 steps. It clears the accumulator, and it is scale-invariant - displacement 1.199336 at |g|=1 versus 1.199333 at |g|=1e-4, matching the figure DirectML/batch_accum_check produced for the fixed CPU_UpdateWeightsAdam. It reproduces the corrected Adam, not the pre-371f8aa one. Both build variants compile 0 errors, 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 17:09:52 -04:00
bool g_applyAccumKernelUsable = true;
//---
//--- Batch-norm kernels (2026-08-09) - see the BATCH NORM block in AI\Network.cl.
fix: live trades now use the geometry the gate certifies; perf: BN kernels Three changes, one theme: the trade placed, the trade graded, and the trade computed are now the same trade. 1) GEOMETRY WIRE (correctness, the ranked #1 open issue). The measured barrier pair reached the LABELS only - OpenParams still placed orders at the enum geometry (2*ATR/6*ATR), so the deploy gate certified "reaches 1.62*ATR before 3.33*ATR above break-even" about trades the EA never placed. Published via g_DerivedSlAtrMult/g_DerivedTpAtrMult (ConfidenceBridge, same same-tick contract as the confidence globals, because OpenParams runs on the root signal which has no pointer to the AI filter). Two writers: DeriveBarrierGeometry at era 0, and the .cfg adoption a deployed model takes. Overrides both legs and both Intelligent modes - the certificate is exact or it is nothing. TP is ATR-anchored like the label, NOT risk-relative, so a floor-widened stop cannot reshape the certified target. 2) BATCH NORM RUNS DEVICE-SIDE ON OPENCL. Four kernels in Network.cl - forward, hidden gradient, gamma/beta accumulate, gamma/beta apply - each a line-for-line transcription of the host implementation (NormalizeHost / HiddenGradHost / StepGammaBeta) including every NaN guard, clamp, and the exact moment-write ordering. The host copies remain the runtime for the DLL and pure-MQL5 tiers and the reference the kernels must match. Because this box has no OpenCL platform, the safety story is layered: - shim validation: kernels compiled as C and driven against a fp64 host transcription over NaN-poisoned stats, NaN gamma, over-clamp inputs, the frozen path, both optimizers, 3 batches - ALL PASS, worst normalized diff 0.132 vs tolerance 1.0 - in-situ self-check: each kernel is compared against its host twin ON FIRST USE on the real device (SelfCheckBn*), covering what the shim cannot - arg indices and buffer bindings. Any disagreement resyncs from the good copy, latches all BN kernels off process-wide, and training continues host-side. A transcription bug costs a warning and some speed, never a poisoned .nnw. - sync discipline: BatchOptions is now a CBufferDouble with explicit authority tracking (m_bnDeviceAuthoritative). Checkpoints/saves pull read-only; restores/loads/resets push; a mid-batch handover drains the device gamma/beta accumulator into the host arrays so no sample is lost. 3) SMALL FIXES. Apply-kernel build failure now latches the dispatch path at init (one warning instead of warning + failed Execute). Build tag bumped to win-scoring-gpu-v1 - first tag change since expectancy-stop-v1 despite five binary-changing commits. Both build variants compile 0 errors, 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 17:51:40 -04:00
#define def_k_BatchNormForward 27
#define def_k_bnf_matrix_i 0
#define def_k_bnf_matrix_o 1
#define def_k_bnf_options 2
#define def_k_bnf_w 3
#define def_k_bnf_frozen 4
//---
#define def_k_BatchNormHiddenGrad 28
#define def_k_bnh_matrix_g 0
#define def_k_bnh_prev_o 1
#define def_k_bnh_prev_g 2
#define def_k_bnh_options 3
#define def_k_bnh_activation 4
//---
#define def_k_BatchNormAccumGammaBeta 29
#define def_k_bna_matrix_g 0
#define def_k_bna_options 1
#define def_k_bna_acc 2
//---
#define def_k_BatchNormApplyGammaBeta 30
#define def_k_bnp_options 0
#define def_k_bnp_acc 1
#define def_k_bnp_scale 2
#define def_k_bnp_lt 3
#define def_k_bnp_b1 4
#define def_k_bnp_b2 5
#define def_k_bnp_lr 6
#define def_k_bnp_momentum 7
#define def_k_bnp_optimizer 8
bool g_bnKernelUsable = true;
//---
refactor(stdlib): adopt Math\Stat for the deploy gate's normal tail; retire the b1/b2/lr/momentum macros The gate's NormalUpperTail was a hand-rolled Abramowitz & Stegun 26.2.17 approximation. Its own comment gave the reason - "drags a chain of headers behind it" - and that turned out to be one file: Math\Stat\Normal.mqh includes only Math.mqh, which includes nothing. Swapped for Cody's rational approximation in the library (~18 significant digits vs |error| < 7.5e-8). No past verdict changes: at the z the gate operates on, the difference is orders of magnitude below DEPLOY_FAMILY_WISE_ALPHA. Adopting it needed the four bare macros in AI\Network.mqh gone first. "#define b1 AdamBeta1" collides with an identifier in Math.mqh, so the include would have macro-expanded the library's own local and failed to compile - the same landmine that made the original author rename the approximation's coefficients to ntB1..ntB5 rather than use the reference's b1..b5. lr, b2 and momentum are the same class of hazard: single-token global macros in a 52k-line codebase. All four now resolve to the input names they always aliased, which is a pure textual identity - verified zero bare occurrences remain. Also: - SelectionSort over the buffered signals was O(n^2) with an O(n^2) count of StructToTime calls, because the comparison rebuilt both datetimes from the six int date fields every time. Now materialises the keys once and does an insertion sort; ArraySort cannot permute a struct array. IsEarlier goes with it, MakeDateTime becomes SignalTime. - Seven FileOpen sites lacked FILE_SHARE_READ|FILE_SHARE_WRITE, including AtomicWriteBegin, which stages every model save. All 43 sites now carry them - an exclusive open fails outright when another process holds the path, which here has meant a silently skipped save. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 19:31:36 -04:00
// The Adam betas are ordinary inputs (book defaults 0.9/0.999) - see
// AdamLearningRate's declaration comment for why the earlier 0.8 experiment (fighting a multi-era
// same-class-streak bug via a shorter momentum window) was reverted: that symptom's likely root
// cause was the independent-sigmoid+BCE output gradient, since replaced with a joint softmax+CCE
refactor(stdlib): adopt Math\Stat for the deploy gate's normal tail; retire the b1/b2/lr/momentum macros The gate's NormalUpperTail was a hand-rolled Abramowitz & Stegun 26.2.17 approximation. Its own comment gave the reason - "drags a chain of headers behind it" - and that turned out to be one file: Math\Stat\Normal.mqh includes only Math.mqh, which includes nothing. Swapped for Cody's rational approximation in the library (~18 significant digits vs |error| < 7.5e-8). No past verdict changes: at the z the gate operates on, the difference is orders of magnitude below DEPLOY_FAMILY_WISE_ALPHA. Adopting it needed the four bare macros in AI\Network.mqh gone first. "#define b1 AdamBeta1" collides with an identifier in Math.mqh, so the include would have macro-expanded the library's own local and failed to compile - the same landmine that made the original author rename the approximation's coefficients to ntB1..ntB5 rather than use the reference's b1..b5. lr, b2 and momentum are the same class of hazard: single-token global macros in a 52k-line codebase. All four now resolve to the input names they always aliased, which is a pure textual identity - verified zero bare occurrences remain. Also: - SelectionSort over the buffered signals was O(n^2) with an O(n^2) count of StructToTime calls, because the comparison rebuilt both datetimes from the six int date fields every time. Now materialises the keys once and does an insertion sort; ArraySort cannot permute a struct array. IsEarlier goes with it, MakeDateTime becomes SignalTime. - Seven FileOpen sites lacked FILE_SHARE_READ|FILE_SHARE_WRITE, including AtomicWriteBegin, which stages every model save. All 43 sites now carry them - an exclusive open fails outright when another process holds the path, which here has meant a silently skipped save. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-19 19:31:36 -04:00
// gradient in backProp()/backPropOCL(), which addresses it more directly than shortening beta1 ever
// could. Both are passed as runtime parameters into every backend (not baked into compiled
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
// kernels - see DirectML\WarriorCPU.cpp/AI\Network.cl's UpdateWeightsAdam
// signatures), so they're safe to expose as ordinary inputs.
// Tightened from 1.0e6 - that ceiling was so loose it never actually engaged before training had
// already gone unstable (real collapses were happening at weight magnitudes several orders of
// magnitude below it). 100.0 matches the equivalent clamp in Dmitriy Gizlyk's reference NeuroNet.mqh
// engine (references\MQL5\Experts\NeuroNet_DNG\NeuroNet.mqh) and gives a hard ceiling that's actually
// reachable-and-meaningful given MAX_WEIGHT_DELTA=0.1 per step below.
#define MAX_WEIGHT 100.0
// Decoupled (AdamW-style) weight decay applied inside every Adam weight update below and in
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
// DirectML\WarriorCPU.cpp/AI\Network.cl (all three backends kept in sync) - see
// WarriorCPU.cpp's WEIGHT_DECAY comment for the full rationale: MAX_WEIGHT only stops outright
// +-Infinity blowups, it does nothing to stop weights slowly, unboundedly growing over hundreds of
// training eras on a fixed, heavily class-balance-oversampled dataset, which was producing multi-
// hour climb-to-90%+-then-collapse-to-single-digits OOS accuracy cycles.
// 0.001, NOT the 0.01 Loshchilov & Hutter default: decay here is applied per SAMPLE (online updates,
// ~20k+ steps per era), and AdamW's data term is invariant to gradient scale, so a weight's
// sustainable magnitude is roughly (its gradient stream's signal-to-noise ratio)/WEIGHT_DECAY. For a
// weak-signal domain like this one, 0.01 was observed (2026-07-19, SP500 H4) to grind the
// discriminative weights down until the per-bar logit spread (avg 0.19 at era 1) fell BELOW the
// calibration-capped class-prior offsets (~0.008): recall stayed healthy for ~30 eras while the
// spread decayed monotonically, then argmax degenerated to constant-Neutral once the evidence tilt
// dropped under the prior tilt. The prior offsets are capped by calibration regardless of decay
// strength; the evidence tilts scale with 1/WEIGHT_DECAY - so decay strength decides which one wins
// argmax. 0.001 lifts the evidence ceiling 10x while still bounding long-run weight growth.
#define WEIGHT_DECAY 0.001
// Per-step update clip - see WarriorCPU.cpp's matching MAX_WEIGHT_DELTA comment for the full
// rationale: weight decay alone didn't stop the collapse cycles, since they turned out to be sudden
// Adam overshoot events (OOS accuracy falling below the 3-class random-guess floor within ~20 eras),
// most likely from 5x back-to-back oversampling replay building artificially correlated momentum.
// Applied to the raw delta BEFORE it's added to the weight, unlike MAX_WEIGHT which only clamps the
// post-update weight value and is far too loose (1e6) to prevent this.
#define MAX_WEIGHT_DELTA 0.1
//--- Floor on |activationFunctionDerivative()| for saturated tanh/sigmoid units (see
//--- SigmoidFunctionDerivative/TanhFunctionDerivative below) - without this, a neuron pinned near
//--- its activation extremes (output near -1/0/1) produces a near-zero derivative, which zeroes
//--- that neuron's entire backprop gradient contribution regardless of how wrong its output is.
#define MIN_ACTIVATION_DERIVATIVE 1.0e-3
//--- Logit temperature for the 3-class softmax head (training gradient in backProp/backPropOCL AND
//--- read-time ApplyClassificationSoftmax - the two MUST stay in sync or the model is scored
//--- against a different distribution than it was trained on).
#define CLASS_LOGIT_SCALE 6.0
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#resource "Network.cl" as string cl_program
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
enum ENUM_ACTIVATION
{
NONE,
TANH,
SIGMOID,
PRELU // fixed param=0.01, matches CNeuronConv's CPU activationFunction
};
//+------------------------------------------------------------------+
//| Translates ENUM_ACTIVATION to the "activation" int code every |
//| native compute backend actually understands (Network.cl's |
//| kernels, and the mirrored Activation()/inline switches in |
//| WarriorCPU.cpp / WarriorDML.cpp): 0=TANH, 1=SIGMOID, 2=PRELU, |
//| and deliberately anything else (incl. |
//+------------------------------------------------------------------+
int NativeActivationCode(ENUM_ACTIVATION value)
{
switch(value)
{
case TANH: return 0;
case SIGMOID: return 1;
case PRELU: return 2;
default: return -1; // NONE (and anything unrecognized) - no kernel/DLL case matches
}
}
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
//+------------------------------------------------------------------+
//| Human-readable ENUM_ACTIVATION, for diagnostics only. Used by the |
//| load-time architecture repair (CNet::EnforceOutputActivation) so |
//| the log names the stale value it found instead of printing a bare |
//| integer nobody can decode months later. |
//+------------------------------------------------------------------+
string ActivationName(ENUM_ACTIVATION value)
{
switch(value)
{
case NONE: return "NONE";
case TANH: return "TANH";
case SIGMOID: return "SIGMOID";
case PRELU: return "PRELU";
}
return "UNKNOWN(" + IntegerToString((int)value) + ")";
}
//--- Guarded so an identical copy can live in Enumerations\InputEnums.mqh too: that lets Variables\
//--- Inputs.mqh (which needs this type for the TrainingOptimizer input) be included FIRST - ahead
//--- of this AI header - without a duplicate-definition error.
#ifndef WARRIOR_ENUM_OPTIMIZATION_DEFINED
#define WARRIOR_ENUM_OPTIMIZATION_DEFINED
//--- 2026-07-28: a third DFA entry was removed. SGD/ADAM keep their ordinal values 0/1 -
//--- m_optimizationAlgo feeds the weights-filename fingerprint, so these must never be renumbered.
enum ENUM_OPTIMIZATION
{
SGD, // SGD + Momentum (heavy-ball, simpler, needs more eras)
ADAM // Adam (adaptive step, faster convergence, can overfit)
};
#endif
//---
enum ENUM_BUFFERS
{
WEIGHTS,
DELTA_WEIGHTS,
OUTPUT,
GRADIENT,
FIRST_MOMENTUM,
SECOND_MOMENTUM
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
refactor(AI): split 8 self-contained classes out of the Network.mqh god-file AI/Network.mqh was 5,805 lines / 18 classes in one file. Investigation found method implementations for several classes (CNeuronBase/Pool/Conv, CNeuronBaseOCL) hand-interleaved across thousands of lines - not safe to split without risky manual reassembly. But 8 classes turned out to be genuinely self-contained (declaration + every method body physically contiguous, and only ever depended upon, never depending on anything declared later): CConnection/CArrayCon, CNeuron, CDirectMLMy (+ its WarriorDML.dll/WarriorCPU.dll #import blocks), CArrayLayer, CLayerDescription, CBufferDouble, and CNeuronConvOCL/CNeuronPoolOCL. Extracted each verbatim, via exact line-range extraction (not manual retyping) to eliminate transcription risk, into its own AI/*.mqh file, included from Network.mqh at the exact point each class used to sit - preserving original declaration order exactly. Mathematically verified byte-for-byte: reconstructing the original file from the 7 new files' bodies + Network.mqh's remaining segments is line-for-line identical to the pre-split git history. Compiled clean (MetaEditor, 0 errors/0 warnings) both before and after. The remaining tangled classes (CNeuronBase, CNeuronPool, CNeuronConv, CNet, CNeuronLSTM, CNeuronBaseOCL, CNeuronConvOCL/PoolOCL's shared base, CNeuronLSTMOCL, COpenCLMy) stay in Network.mqh (now ~4,450 lines) - splitting those safely needs deliberate per-method surgery, deferred to a future dedicated pass rather than rushed into this one. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 16:13:03 -04:00
#include "NeuronPrimitives.mqh"
class CLayer;
//---
class CNeuronBase : public CObject
{
protected:
double outputVal;
double prevVal;
uint m_myIndex;
double gradient;
CArrayCon *Connections;
ENUM_ACTIVATION activation;
ENUM_OPTIMIZATION optimization;
int t;
//---
virtual bool feedForward(CLayer *prevLayer) { return false; }
virtual bool calcHiddenGradients(CLayer *&nextLayer) { return false; }
virtual double activationFunction(double x);
virtual double SigmoidFunction(double x) { return MathPow(1 + exp(-x), -1); }
virtual double TanhFunction(double x) { return tanh(x); }
virtual CLayer *getOutputLayer(void) { return NULL; }
public:
CNeuronBase(void);
~CNeuronBase(void);
virtual bool Init(uint numOutputs, uint myIndex, ENUM_OPTIMIZATION optimization_type, double weighScale = -1.0);
virtual void SetActivationFunction(ENUM_ACTIVATION value) { activation = value; }
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
//--- Mirrors CNeuronBaseOCL::Activation(). Needed so CNet::EnforceOutputActivation() can read back
//--- what a Load() restored from disk without caring which neuron model the net was built from.
virtual ENUM_ACTIVATION Activation(void) { return activation; }
//---
static double alpha;
//---
virtual void setOutputVal(double val) { prevVal = outputVal; outputVal = val; }
virtual double getOutputVal() { return outputVal; }
virtual double getPrevVal() { return prevVal; }
virtual void setGradient(double val) { gradient = val; }
virtual double getGradient() { return gradient; }
virtual CArrayCon *getConnections() { return Connections;}
virtual double activationFunctionDerivative(double x);
virtual double SigmoidFunctionDerivative(double x) { return MathMax(MIN_ACTIVATION_DERIVATIVE, x * (1 - x)); }
virtual double TanhFunctionDerivative(double x) { return MathMax(MIN_ACTIVATION_DERIVATIVE, (1 + x) * (1 - x)); }
//---
virtual bool feedForward(CObject *&SourceObject);
virtual bool calcHiddenGradients(CObject *&TargetObject);
virtual bool updateInputWeights(CLayer *prevLayer) { return false; }
virtual bool updateInputWeights(CObject *SourceObject);
//---
virtual bool Save(int const file_handle);
virtual bool Load(int const file_handle)
{
activation = (ENUM_ACTIVATION)FileReadInteger(file_handle, INT_VALUE);
optimization = (ENUM_OPTIMIZATION)FileReadInteger(file_handle, INT_VALUE);
t = (ENUM_OPTIMIZATION)FileReadInteger(file_handle, INT_VALUE);
return(Connections.Load(file_handle));
}
//--- Forget the optimizer's trajectory memory (Adam m/v, SGD momentum, step counter) while
//--- leaving the weights untouched - see CNet::ResetOptimizerState for when and why.
fix: training-stability audit fixes F1/F2/F3/F5 - unbiased shuffle, real plateau escapes, fresh optimizer state on restore, pure OOS metric Four of the six findings from research/training_pipeline_audit_2026-08-09.md (F4 mini-batching and F6 feature re-encode deliberately deferred - see the report's implementation-status section for why): - F1: pass-2 Fisher-Yates (and AutoTune's MI block shuffle) used MathRand()%, which is 15-bit - provably non-uniform on every full-history era over 32,768 queued samples. New 30-bit ShuffleRandomIndex(). - F2: plateau warm restarts were a no-op whenever eta already sat at its ceiling (the normal state of a non-regressing plateau) - the ladder was just a 24-era countdown. Restarts now overshoot to 5x the ceiling (PLATEAU_RESTART_BOOST) and anneal geometrically back over the patience window, SGDR-style; ETA_MIN widened 1e-4 -> 1e-5 so the decay schedule has real range. - F3: checkpoint restores put weights back but kept the rejected trajectory's Adam moments, so the optimizer immediately pushed back toward the rolled-back state (the restore->regress->restore oscillation). CNet::ResetOptimizerState() zeroes moments/momentum/step counters (weights, BN statistics, gamma/beta untouched) on every mid-run restore, every boosted restart, and the deploy-time restore that online learning continues from. - F5: batch-norm running statistics now freeze for the pass-3 OOS scoring walk, so the selection metric the checkpoint ranking and deploy gate read is a pure function of the checkpoint instead of partly measuring BN drift. Defensive unfreeze in FinalizeTrainRun covers stop-mid-pass; live/online adaptation and the OOS continual-learning simulation stay adaptive by design. Compiled clean (0 errors, 0 warnings) via the staged-tree recipe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 10:54:09 -04:00
virtual bool ResetOptimizerState(void)
{
t = 1;
if(CheckPointer(Connections) == POINTER_INVALID)
return true;
for(int i = 0; i < Connections.Total(); i++)
{
CConnection *con = Connections.At(i);
if(CheckPointer(con) == POINTER_INVALID)
continue;
con.deltaWeight = 0.0;
con.mt = 0.0;
con.vt = 0.0;
}
return true;
}
//---
virtual int Type(void) const { return defNeuronBase; }
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
refactor(AI): split 8 self-contained classes out of the Network.mqh god-file AI/Network.mqh was 5,805 lines / 18 classes in one file. Investigation found method implementations for several classes (CNeuronBase/Pool/Conv, CNeuronBaseOCL) hand-interleaved across thousands of lines - not safe to split without risky manual reassembly. But 8 classes turned out to be genuinely self-contained (declaration + every method body physically contiguous, and only ever depended upon, never depending on anything declared later): CConnection/CArrayCon, CNeuron, CDirectMLMy (+ its WarriorDML.dll/WarriorCPU.dll #import blocks), CArrayLayer, CLayerDescription, CBufferDouble, and CNeuronConvOCL/CNeuronPoolOCL. Extracted each verbatim, via exact line-range extraction (not manual retyping) to eliminate transcription risk, into its own AI/*.mqh file, included from Network.mqh at the exact point each class used to sit - preserving original declaration order exactly. Mathematically verified byte-for-byte: reconstructing the original file from the 7 new files' bodies + Network.mqh's remaining segments is line-for-line identical to the pre-split git history. Compiled clean (MetaEditor, 0 errors/0 warnings) both before and after. The remaining tangled classes (CNeuronBase, CNeuronPool, CNeuronConv, CNet, CNeuronLSTM, CNeuronBaseOCL, CNeuronConvOCL/PoolOCL's shared base, CNeuronLSTMOCL, COpenCLMy) stay in Network.mqh (now ~4,450 lines) - splitting those safely needs deliberate per-method surgery, deferred to a future dedicated pass rather than rushed into this one. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 16:13:03 -04:00
#include "NeuronCPU.mqh"
class COpenCLMy : public COpenCL
{
public:
COpenCLMy(void) {};
~COpenCLMy(void) {};
template<typename T>
int AddBufferFromArray(T &data[], const uint data_array_offset, const uint data_array_count, const uint flags);
};
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
#include "ComputeDll.mqh"
class CLayer: public CArrayObj
{
private:
uint iOutputs;
int iFileHandle;
COpenCLMy *OpenCL;
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
CComputeDll *ComputeDll;
public:
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
CLayer(uint outputs = 0, int handle = INVALID_HANDLE, COpenCLMy *OpenCL = NULL, CComputeDll *ComputeDll = NULL);
~CLayer(void) {};
//--- Fan-in-scaled element factory. Deliberately NOT named CreateElement: see the override below.
bool CreateElementScaled(int const index, double weighScale);
//--- CRITICAL: this MUST keep CArrayObj::CreateElement's EXACT signature - `virtual bool
//--- CreateElement(const int index)` - because it is the real virtual override that
//--- CArrayObj::Load() dispatches through, and CArrayObj::Load() is how EVERY saved layer is
//--- read back (CLayer::Load -> CNet::Load).
virtual bool CreateElement(const int index) { return CreateElementScaled(index, -1.0); }
virtual void IncreaseTotal() { m_data_total++; }
virtual int Type(void) const { return defLayer; }
virtual bool Load(const int file_handle);
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
refactor(AI): split 8 self-contained classes out of the Network.mqh god-file AI/Network.mqh was 5,805 lines / 18 classes in one file. Investigation found method implementations for several classes (CNeuronBase/Pool/Conv, CNeuronBaseOCL) hand-interleaved across thousands of lines - not safe to split without risky manual reassembly. But 8 classes turned out to be genuinely self-contained (declaration + every method body physically contiguous, and only ever depended upon, never depending on anything declared later): CConnection/CArrayCon, CNeuron, CDirectMLMy (+ its WarriorDML.dll/WarriorCPU.dll #import blocks), CArrayLayer, CLayerDescription, CBufferDouble, and CNeuronConvOCL/CNeuronPoolOCL. Extracted each verbatim, via exact line-range extraction (not manual retyping) to eliminate transcription risk, into its own AI/*.mqh file, included from Network.mqh at the exact point each class used to sit - preserving original declaration order exactly. Mathematically verified byte-for-byte: reconstructing the original file from the 7 new files' bodies + Network.mqh's remaining segments is line-for-line identical to the pre-split git history. Compiled clean (MetaEditor, 0 errors/0 warnings) both before and after. The remaining tangled classes (CNeuronBase, CNeuronPool, CNeuronConv, CNet, CNeuronLSTM, CNeuronBaseOCL, CNeuronConvOCL/PoolOCL's shared base, CNeuronLSTMOCL, COpenCLMy) stay in Network.mqh (now ~4,450 lines) - splitting those safely needs deliberate per-method surgery, deferred to a future dedicated pass rather than rushed into this one. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 16:13:03 -04:00
#include "ArrayLayer.mqh"
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
class CNeuronPool : public CNeuronBase
{
protected:
CLayer *OutputLayer;
int iWindow;
int iStep;
virtual bool feedForward(CLayer *prevLayer);
virtual bool calcHiddenGradients(CLayer *&nextLayer);
public:
CNeuronPool(void) {};
~CNeuronPool(void);
virtual bool Init(uint numOutputs, uint myIndex, int window, int step, int units_count, ENUM_OPTIMIZATION optimization_type);
//---
virtual CLayer *getOutputLayer(void) { return OutputLayer; }
virtual bool calcInputGradients(CLayer *prevLayer) ;
virtual bool calcInputGradients(CNeuronBase *prevNeuron, uint index) ;
//--- methods for working with files
virtual bool Save(int const file_handle);
virtual bool Load(int const file_handle);
virtual int Type(void) const { return defNeuronPool; }
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
class CNeuronConv : public CNeuronPool
{
protected:
double param; //PReLU param
virtual bool feedForward(CLayer *prevLayer);
virtual bool calcHiddenGradients(CLayer *&nextLayer);
virtual double activationFunction(double x);
virtual bool updateInputWeights(CLayer *prevLayer);
public:
CNeuronConv() : param(0.01) { };
~CNeuronConv(void) { };
//---
virtual bool calcInputGradients(CLayer *prevLayer) ;
virtual bool calcInputGradients(CNeuronBase *prevNeuron, uint index) ;
virtual double activationFunctionDerivative(double x);
virtual int Type(void) const { return defNeuronConv; }
//--- methods for working with files
virtual bool Save(int const file_handle);
virtual bool Load(int const file_handle);
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
refactor(AI): split 8 self-contained classes out of the Network.mqh god-file AI/Network.mqh was 5,805 lines / 18 classes in one file. Investigation found method implementations for several classes (CNeuronBase/Pool/Conv, CNeuronBaseOCL) hand-interleaved across thousands of lines - not safe to split without risky manual reassembly. But 8 classes turned out to be genuinely self-contained (declaration + every method body physically contiguous, and only ever depended upon, never depending on anything declared later): CConnection/CArrayCon, CNeuron, CDirectMLMy (+ its WarriorDML.dll/WarriorCPU.dll #import blocks), CArrayLayer, CLayerDescription, CBufferDouble, and CNeuronConvOCL/CNeuronPoolOCL. Extracted each verbatim, via exact line-range extraction (not manual retyping) to eliminate transcription risk, into its own AI/*.mqh file, included from Network.mqh at the exact point each class used to sit - preserving original declaration order exactly. Mathematically verified byte-for-byte: reconstructing the original file from the 7 new files' bodies + Network.mqh's remaining segments is line-for-line identical to the pre-split git history. Compiled clean (MetaEditor, 0 errors/0 warnings) both before and after. The remaining tangled classes (CNeuronBase, CNeuronPool, CNeuronConv, CNet, CNeuronLSTM, CNeuronBaseOCL, CNeuronConvOCL/PoolOCL's shared base, CNeuronLSTMOCL, COpenCLMy) stay in Network.mqh (now ~4,450 lines) - splitting those safely needs deliberate per-method surgery, deferred to a future dedicated pass rather than rushed into this one. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-18 16:13:03 -04:00
#include "LayerDescription.mqh"
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
class CNet
{
protected:
feat(ai): logit-adjusted loss, replacing oversampling and the post-hoc prior Menon et al. 2021 (ICLR), "Long-tail learning via logit adjustment": add tau*log(prior_c) to each class logit inside the training gradient. Softmax CE on adjusted logits is consistent for BALANCED error - the metric checkpoint selection already ranks on - so the loss and the deploy decision finally optimize the same thing. The engine already computed a true softmax + categorical-CE gradient and wrote it over the per-neuron sigmoid delta, so this is an offset added to three logits in the two places that gradient is built (backProp scalar path and backPropOCL). No backend, kernel or DLL change; the forward pass and every inference path are untouched, which is the point - the network learns to absorb the offset, so its raw argmax becomes the balanced-optimal decision with nothing applied at inference. Replaces rather than stacks. Minority replay is disabled while this is on, and the post-hoc inference prior is forced off. Stacking is not a theoretical worry: simulated on the measured 1118/1119/34298 distribution in the weak-signal regime, plain CE collapses to Neutral (33.4% balanced, Buy 0%), replay reaches 48.1%, logit adjustment 50.9% with better balance - and BOTH together score 45.4% with Neutral recall at 0%, worse than either alone. Buda et al. 2018 predicts exactly that. Motivation from the six-chart run: every topology took one direction to ~50% recall and abandoned the other, the direction chosen arbitrarily (the batch-norm control went Buy 1% / Sell 42%, the inverse of the other five). One era in 1,301 cleared the per-class recall floor. Fingerprinted conditionally, so the converged 60.7% models on disk keep their filenames and stay loadable as the fallback. Both builds compile 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 19:05:14 -04:00
double dLogitAdjust[3];
bool bLogitAdjust;
fix: replace class-balance oversample replay with loss weighting The training log showed the model had genuinely collapsed to always-predict- Neutral: 100+ consecutive eras with Buy/Sell OOS recall flat at 0% and IS error frozen exactly at 0.14, not a "still early" transient. Root cause is the 33:1 Buy/Sell-vs-Neutral label imbalance combined with the oversample replay cap - capped at 3x specifically because more identical back-to-back backProp() calls fed Adam highly-correlated gradients and caused runaway momentum (a past incident: OOS accuracy diving from 90%+ to single digits within ~20 eras). That cap meant minority classes never got enough gradient influence to matter once the model settled into all-Neutral. Replaced the N-times replay with a single backProp() call per example, with its output-layer gradient scaled by inverse class frequency (maxCount/ trueCount from the previous era's true label distribution, uncapped - the existing MAX_WEIGHT_DELTA per-step clip already bounds how far any single step can move a weight regardless of gradient magnitude, so there's no repeated-gradient momentum risk left to cap against). AI/Network.mqh: CNet::backProp()/backPropOCL() take a new optional sampleWeight parameter (default 1.0, so every other caller is unaffected). For the OCL/DirectML path, since WarriorCPU.dll/WarriorDML.dll/Network.cl have no notion of per-sample weighting, the raw gradient computed by the native CalcOutputGradient call is read back into MQL5, scaled, and written back via a new CNeuronBaseOCL::setGradient() before the hidden layers read it - no changes needed to any of the 3 compute backends themselves. Also fixed: a run that "converged" at era 63 only because that specific era's small OOS sample happened to contain zero true Buy/Sell examples (recall shows n/a and auto-passes the gate when a class is absent from an era's sample) - the model had already fully collapsed several eras earlier; this was a lucky/unlucky sampling fluke, not real convergence. Not fixed in this commit (separate, narrower issue - the gate's n/a auto-pass exists to avoid deadlocking on a genuinely rare class, and distinguishing that from a collapsed model needs its own follow-up). Needs a fresh retrain like the prior structural fixes. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 19:04:56 -04:00
void backPropOCL(CArrayDouble *targetVals, double sampleWeight = 1.0);
bool InitOpenCL(void);
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
bool InitComputeDll(void);
//--- Pure-MQL5 forward pass over OCL-format layers loaded host-only (no backend) - see SetCpuInference.
bool feedForwardCPU(CArrayDouble *inputVals);
public:
CNet(CArrayObj *Description);
~CNet(void);
bool feedForward(CArrayDouble *inputVals);
fix: replace class-balance oversample replay with loss weighting The training log showed the model had genuinely collapsed to always-predict- Neutral: 100+ consecutive eras with Buy/Sell OOS recall flat at 0% and IS error frozen exactly at 0.14, not a "still early" transient. Root cause is the 33:1 Buy/Sell-vs-Neutral label imbalance combined with the oversample replay cap - capped at 3x specifically because more identical back-to-back backProp() calls fed Adam highly-correlated gradients and caused runaway momentum (a past incident: OOS accuracy diving from 90%+ to single digits within ~20 eras). That cap meant minority classes never got enough gradient influence to matter once the model settled into all-Neutral. Replaced the N-times replay with a single backProp() call per example, with its output-layer gradient scaled by inverse class frequency (maxCount/ trueCount from the previous era's true label distribution, uncapped - the existing MAX_WEIGHT_DELTA per-step clip already bounds how far any single step can move a weight regardless of gradient magnitude, so there's no repeated-gradient momentum risk left to cap against). AI/Network.mqh: CNet::backProp()/backPropOCL() take a new optional sampleWeight parameter (default 1.0, so every other caller is unaffected). For the OCL/DirectML path, since WarriorCPU.dll/WarriorDML.dll/Network.cl have no notion of per-sample weighting, the raw gradient computed by the native CalcOutputGradient call is read back into MQL5, scaled, and written back via a new CNeuronBaseOCL::setGradient() before the hidden layers read it - no changes needed to any of the 3 compute backends themselves. Also fixed: a run that "converged" at era 63 only because that specific era's small OOS sample happened to contain zero true Buy/Sell examples (recall shows n/a and auto-passes the gate when a class is absent from an era's sample) - the model had already fully collapsed several eras earlier; this was a lucky/unlucky sampling fluke, not real convergence. Not fixed in this commit (separate, narrower issue - the gate's n/a auto-pass exists to avoid deadlocking on a genuinely rare class, and distinguishing that from a collapsed model needs its own follow-up). Needs a fresh retrain like the prior structural fixes. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-16 19:04:56 -04:00
//--- sampleWeight scales this example's output-layer gradient before it propagates back through the
//--- hidden layers - see the matching declaration comment on ExpertSignalAIBase.mqh's oversampling
//--- replacement for why (inverse-class-frequency loss weighting instead of replaying the same
//--- example multiple times).
void backProp(CArrayDouble *targetVals, double sampleWeight = 1.0);
feat(ai): logit-adjusted loss, replacing oversampling and the post-hoc prior Menon et al. 2021 (ICLR), "Long-tail learning via logit adjustment": add tau*log(prior_c) to each class logit inside the training gradient. Softmax CE on adjusted logits is consistent for BALANCED error - the metric checkpoint selection already ranks on - so the loss and the deploy decision finally optimize the same thing. The engine already computed a true softmax + categorical-CE gradient and wrote it over the per-neuron sigmoid delta, so this is an offset added to three logits in the two places that gradient is built (backProp scalar path and backPropOCL). No backend, kernel or DLL change; the forward pass and every inference path are untouched, which is the point - the network learns to absorb the offset, so its raw argmax becomes the balanced-optimal decision with nothing applied at inference. Replaces rather than stacks. Minority replay is disabled while this is on, and the post-hoc inference prior is forced off. Stacking is not a theoretical worry: simulated on the measured 1118/1119/34298 distribution in the weak-signal regime, plain CE collapses to Neutral (33.4% balanced, Buy 0%), replay reaches 48.1%, logit adjustment 50.9% with better balance - and BOTH together score 45.4% with Neutral recall at 0%, worse than either alone. Buda et al. 2018 predicts exactly that. Motivation from the six-chart run: every topology took one direction to ~50% recall and abandoned the other, the direction chosen arbitrarily (the batch-norm control went Buy 1% / Sell 42%, the inverse of the other five). One era in 1,301 cleared the per-class recall floor. Fingerprinted conditionally, so the converged 60.7% models on disk keep their filenames and stay loadable as the fallback. Both builds compile 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 19:05:14 -04:00
//--- LOGIT ADJUSTMENT (Menon et al. 2021, "Long-tail learning via logit adjustment"). Per-class
//--- additive offsets tau*log(prior_c) folded into the 3-class softmax during the BACKWARD pass
//--- only.
feat(ai): logit-adjusted loss, replacing oversampling and the post-hoc prior Menon et al. 2021 (ICLR), "Long-tail learning via logit adjustment": add tau*log(prior_c) to each class logit inside the training gradient. Softmax CE on adjusted logits is consistent for BALANCED error - the metric checkpoint selection already ranks on - so the loss and the deploy decision finally optimize the same thing. The engine already computed a true softmax + categorical-CE gradient and wrote it over the per-neuron sigmoid delta, so this is an offset added to three logits in the two places that gradient is built (backProp scalar path and backPropOCL). No backend, kernel or DLL change; the forward pass and every inference path are untouched, which is the point - the network learns to absorb the offset, so its raw argmax becomes the balanced-optimal decision with nothing applied at inference. Replaces rather than stacks. Minority replay is disabled while this is on, and the post-hoc inference prior is forced off. Stacking is not a theoretical worry: simulated on the measured 1118/1119/34298 distribution in the weak-signal regime, plain CE collapses to Neutral (33.4% balanced, Buy 0%), replay reaches 48.1%, logit adjustment 50.9% with better balance - and BOTH together score 45.4% with Neutral recall at 0%, worse than either alone. Buda et al. 2018 predicts exactly that. Motivation from the six-chart run: every topology took one direction to ~50% recall and abandoned the other, the direction chosen arbitrarily (the batch-norm control went Buy 1% / Sell 42%, the inverse of the other five). One era in 1,301 cleared the per-class recall floor. Fingerprinted conditionally, so the converged 60.7% models on disk keep their filenames and stay loadable as the fallback. Both builds compile 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 19:05:14 -04:00
void SetLogitAdjustment(const double &offsets[]);
void ClearLogitAdjustment(void) { bLogitAdjust = false; }
void getResults(CArrayDouble *&resultVals) ;
double getRecentAverageError() { return recentAverageError; }
//--- indicatorParams: flattened AutoTuneIndicators "winning" AD indicator param values (see
//--- CExpertSignalAIBase::FlattenIndicatorParams/UnflattenIndicatorParams); pass an empty array
//--- when there is nothing to persist/restore.
bool Save(string file_name, double error, double undefine, double forecast, datetime time, bool common, long era, bool trainingComplete, const double &indicatorParams[]);
//--- `quiet` suppresses the on-reject diagnostic Prints for callers that EXPECT a miss and handle it
//--- gracefully (the EMA shadow-net bootstrap on a CPU-DLL box, which can't hold a 2nd full net - see
//--- EnsureShadowNet). The main-model load leaves it false so a real failure is still loud.
bool Load(string file_name, double &error, double &undefine, double &forecast, datetime &time, bool common, long &era, bool &trainingComplete, double &indicatorParams[], bool quiet=false);
//--- In-MEMORY weight checkpoint (host-only, zero extra device tensors). In-place weight copy
//--- uses only getWeights/setWeights, which the per-era shadow blend already exercises
//--- successfully on that backend.
string LayerLearningReport(void);
bool CaptureWeights(void);
bool RestoreWeights(void);
//--- MINI-BATCH CONTROL (2026-08-09 audit, F4). SetBatchSize() is how training asks for
//--- accumulation; 1 restores the exact per-sample path the engine used before.
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
void SetBatchSize(int size) { m_batchSizeRequested = (size > 1 ? size : 1); }
int BatchSize(void);
bool FlushBatch(void);
fix: training-stability audit fixes F1/F2/F3/F5 - unbiased shuffle, real plateau escapes, fresh optimizer state on restore, pure OOS metric Four of the six findings from research/training_pipeline_audit_2026-08-09.md (F4 mini-batching and F6 feature re-encode deliberately deferred - see the report's implementation-status section for why): - F1: pass-2 Fisher-Yates (and AutoTune's MI block shuffle) used MathRand()%, which is 15-bit - provably non-uniform on every full-history era over 32,768 queued samples. New 30-bit ShuffleRandomIndex(). - F2: plateau warm restarts were a no-op whenever eta already sat at its ceiling (the normal state of a non-regressing plateau) - the ladder was just a 24-era countdown. Restarts now overshoot to 5x the ceiling (PLATEAU_RESTART_BOOST) and anneal geometrically back over the patience window, SGDR-style; ETA_MIN widened 1e-4 -> 1e-5 so the decay schedule has real range. - F3: checkpoint restores put weights back but kept the rejected trajectory's Adam moments, so the optimizer immediately pushed back toward the rolled-back state (the restore->regress->restore oscillation). CNet::ResetOptimizerState() zeroes moments/momentum/step counters (weights, BN statistics, gamma/beta untouched) on every mid-run restore, every boosted restart, and the deploy-time restore that online learning continues from. - F5: batch-norm running statistics now freeze for the pass-3 OOS scoring walk, so the selection metric the checkpoint ranking and deploy gate read is a pure function of the checkpoint instead of partly measuring BN drift. Defensive unfreeze in FinalizeTrainRun covers stop-mid-pass; live/online adaptation and the OOS continual-learning simulation stay adaptive by design. Compiled clean (0 errors, 0 warnings) via the staged-tree recipe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 10:54:09 -04:00
//--- Zero every neuron's optimizer state - Adam first/second moments, SGD momentum deltas, the
//--- per-neuron bias-correction step counters, and batch-norm's gamma/beta moment slots - while
//--- leaving weights, activations and batch-norm running STATISTICS untouched (those belong to
//--- the model, not the optimizer).
fix: training-stability audit fixes F1/F2/F3/F5 - unbiased shuffle, real plateau escapes, fresh optimizer state on restore, pure OOS metric Four of the six findings from research/training_pipeline_audit_2026-08-09.md (F4 mini-batching and F6 feature re-encode deliberately deferred - see the report's implementation-status section for why): - F1: pass-2 Fisher-Yates (and AutoTune's MI block shuffle) used MathRand()%, which is 15-bit - provably non-uniform on every full-history era over 32,768 queued samples. New 30-bit ShuffleRandomIndex(). - F2: plateau warm restarts were a no-op whenever eta already sat at its ceiling (the normal state of a non-regressing plateau) - the ladder was just a 24-era countdown. Restarts now overshoot to 5x the ceiling (PLATEAU_RESTART_BOOST) and anneal geometrically back over the patience window, SGDR-style; ETA_MIN widened 1e-4 -> 1e-5 so the decay schedule has real range. - F3: checkpoint restores put weights back but kept the rejected trajectory's Adam moments, so the optimizer immediately pushed back toward the rolled-back state (the restore->regress->restore oscillation). CNet::ResetOptimizerState() zeroes moments/momentum/step counters (weights, BN statistics, gamma/beta untouched) on every mid-run restore, every boosted restart, and the deploy-time restore that online learning continues from. - F5: batch-norm running statistics now freeze for the pass-3 OOS scoring walk, so the selection metric the checkpoint ranking and deploy gate read is a pure function of the checkpoint instead of partly measuring BN drift. Defensive unfreeze in FinalizeTrainRun covers stop-mid-pass; live/online adaptation and the OOS continual-learning simulation stay adaptive by design. Compiled clean (0 errors, 0 warnings) via the staged-tree recipe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 10:54:09 -04:00
bool ResetOptimizerState(void);
//--- EMA shadow-weight deployment: blends this net's weights a small step (tau) toward another
//--- net's weights, layer by layer, neuron by neuron - this.weight = (1-tau)*this.weight +
//--- tau*live.weight.
bool BlendWeightsFrom(CNet &live, double tau);
//--- Cold-start fix: overwrites just the bias term (not the per-input weights, which stay randomly
//--- initialized and carry the real learning signal) of each output neuron's incoming weight block,
//--- on the layer immediately before the output layer - see ExpertSignalAIBase.mqh's call site
//--- (AdvanceLabelCachePrebuild()) for why: a freshly-initialized network's argmax is close to
//--- uniform noise across classes, so on a heavily imbalanced label distribution it fires far more
//--- non-majority classes than the true base rate warrants until backProp corrects it over many
//--- steps. biasValues.Size() must equal the output layer's neuron count. Only supports the
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
//--- OpenCL/CPU-DLL batched neuron model (CNeuronBaseOCL) this project actually runs on - returns
//--- false (no-op) rather than corrupt anything if that assumption doesn't hold.
bool SeedOutputLayerBias(const double &biasValues[]);
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
//--- Pure-MQL5 (no OpenCL/DLL) inference mode. Training/optimization never set this
//--- (they always want a backend), so their behaviour is unchanged.
void SetCpuInference(bool v) { m_cpuInference = v; }
bool CpuInference(void) const { return m_cpuInference; }
//--- Re-assert the output layer's activation after a Load(), and report what it used to be. WHY
//--- THIS EXISTS: a .nnw persists the ARCHITECTURE, not just the weights. Every reload restores
//--- whatever is on disk and the next Save() writes it back out - a wrong value can never heal
//--- on its own, while the source file reads as though it were already fixed.
fix: stop a .nnw from pinning a superseded architecture A .nnw persists the ARCHITECTURE, not just the weights: Save writes (int)activation per neuron and Load reads it straight back. The activation chosen in BuildFreshTopology() therefore only ever reached a brand-new topology - every reload restored the file's value and the next save wrote it back out, so a wrong value could never heal while the source read as though it were already fixed. That is how five models kept training with an unbounded NONE classification head for a full day after the 07-28 revert to SIGMOID. Confirmed by parsing the binaries: 848cb42c.nnw / 2e754b43.nnw carry `act=NONE` on the 3-neuron output layer, while a genuinely reset model of the same config carries act=SIGMOID. In the log it showed as negative "OOS raw out" values - impossible under sigmoid - escalating to a 4.14e13 logit spread with all three classes numerically identical (input-independent output) and balanced accuracy pinned on the 33.3% one-class floor. - OutputLayerActivation() is now the single source of truth, called by both BuildFreshTopology() and the new load-time repair, so the two can no longer diverge the way a duplicated literal did. - CNet::EnforceOutputActivation() re-asserts it after Load and reports the stale value; CExpertSignalAIBase::EnforceTopologyContract() logs the repair loudly, since weights learned under the old head may not be worth keeping even once the head is corrected. - Hidden layers are deliberately left alone: they legitimately differ per stage (PRELU dense/conv, NONE pool, TANH LSTM). Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 12:00:40 -04:00
bool EnforceOutputActivation(ENUM_ACTIVATION intended, ENUM_ACTIVATION &previous);
feat(ai): real conv receptive field + the reference's channel pool CONV's convolution used window = step = one bar, which is a per-bar projection - a 1x1 conv with a temporal receptive field of ONE BAR. It never mixed information across time, so "convolutional" described the layer type and nothing about what it computed. Same finding that sank HYBRID's LSTM. Pooling was removed on 2026-07-29 for being misconfigured against the conv output's memory layout. That removal was right; leaving the conv at a one-bar window was not. The two belong together: the NeuroNet_DNG reference (references\MQL5\Experts\EDL\Trajectory.mqh layers 2-5, kernels byte-identical to ours) pairs conv(window=2, step=1, window_out=4) with pool(window=4, step=4), and the pool only earns its place because a conv with a real receptive field sits above it. The input is bar-major (BufferTempData appends m_neuronsCount contiguous features per bar), so a flat window of k*m_neuronsCount spans exactly k bars - the receptive field needed NO kernel change. The conv output is position-major, so window == step == window_out is a clean max-over-channels, which is what the reference does and what the existing pool kernels already implement correctly. New chain at H1 defaults (420 = 20 bars x 21): conv1 w=42 s=21 out=8 -> 19 pos x 8 = 152 pool w=8 s=8 -> 19 conv2 w=2 s=1 out=8 -> 18 pos x 8 = 144 (effective field: 3 bars) We deliberately stop before the reference's SECOND pool: a channel pool emits one scalar per position, so a trailing pool would hand the dense stack 18 values and force it to fan out 18 -> 64. That is a bottleneck below every learnable layer - the same class of mistake the 2026-07-29 removal was about. Fixes a latent sizing bug this exposed: CNet's conv/pool position cursor tracked sliding POSITIONS, but a conv's real width is units_count * window_out. Any pool stacked on a conv would therefore have sized against a width window_out times too small and silently built the wrong shape. Both branches now read the built layer's actual Neurons(), which is what the batch-norm branch already did for the same reason. Also closes the architecture-pinning trap: a .nnw persists the window each conv was built with, so an existing CONV/HYBRID model would have loaded cleanly and gone on training under the OLD architecture. The conv weight tensor is (window+1)*window_out, so this cannot be repaired in place - EnforceTopologyContract now detects it, reports both shapes, and retrains. Conv chain shape is derived in one place (ConvReceptiveFieldBars / ConvFirstStagePositions / HasSecondConvStage / ConvOutputPositions / ConvOutputWidth) and consumed by AddConvStage, LstmFanIn and the startup config line, so what is built and what is logged cannot drift. Both builds compile 0 errors, 0 warnings. Forces a CONV and HYBRID retrain. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:05:37 -04:00
//--- Receptive field of the first conv layer as LOADED, for the stale-architecture check in
//--- CExpertSignalAIBase::EnforceTopologyContract. 0 when the net has no conv layer.
uint FirstConvWindow(void);
//--- Freeze/unfreeze every batch-normalization layer's running statistics
//--- (AI\NeuronBatchNorm.mqh). Frozen, a forward pass is a pure function of its input; unfrozen
//--- (the default) it also advances the statistics.
void SetBatchNormFrozen(bool frozen);
feat(hud): per-member neuron lines + a vote label that moves as the nets learn Both 2026-08-19 reports were the same staleness: every source behind the label was an ERA artifact (live cache refills at pass-3 completion, the snapshot copies once per era, dPrevSignal is the frozen purge-band edge bar) - so the readout stepped at era cadence at best, stayed glued to one direction, and lagged the era counter. DisplayInference(): throttled (4s, 1s across an era boundary), SIDE-EFFECT-FREE forward of the current decision bar (window ending on bar 1, same question the live path asks) through the LEARNER net. Batch-norm running stats are bracketed frozen/RESTORED via the new CNet::GetBatchNormFrozen() + CNeuronBatchNormOCL::StatsFrozen() - restore, not unfreeze, because a display tick can land between pass-3 chunks whose whole scan holds them frozen. Writes nothing a trading or training path reads (dPrevSignal, NMS state, tallies, watermarks all untouched; RefreshLatestSignal is not reusable here precisely because it writes all of them). LSTM safe by construction: h/c zeroed per forward. ProspectiveVote() reads the fresh forward as its FIRST source; the era-artifact chain becomes the fallback (meta head, warm-up, window holes). DisplayHudLine(): the reference library's training label, per ensemble member - name, output activations (softmax probs or raw scalar), the decision, its weighted vote (the exact consensus numerator term), era, recent average error, "(trn)" while not vote-capable. Rendered under the vote line in RefreshVoteReadout BEFORE the live-vote defer (member lines are telemetry, not tradable readings), coloured by the member's own direction in muted tones - the vote line's strict green-only-when-it-would-trade rule is untouched. NOT COMPILED - user compiles in MetaEditor. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 08:48:34 -04:00
//--- Current freeze state (the first normalization layer's flag; they only ever move together).
//--- False on a net with no normalization layers.
feat(hud): per-member neuron lines + a vote label that moves as the nets learn Both 2026-08-19 reports were the same staleness: every source behind the label was an ERA artifact (live cache refills at pass-3 completion, the snapshot copies once per era, dPrevSignal is the frozen purge-band edge bar) - so the readout stepped at era cadence at best, stayed glued to one direction, and lagged the era counter. DisplayInference(): throttled (4s, 1s across an era boundary), SIDE-EFFECT-FREE forward of the current decision bar (window ending on bar 1, same question the live path asks) through the LEARNER net. Batch-norm running stats are bracketed frozen/RESTORED via the new CNet::GetBatchNormFrozen() + CNeuronBatchNormOCL::StatsFrozen() - restore, not unfreeze, because a display tick can land between pass-3 chunks whose whole scan holds them frozen. Writes nothing a trading or training path reads (dPrevSignal, NMS state, tallies, watermarks all untouched; RefreshLatestSignal is not reusable here precisely because it writes all of them). LSTM safe by construction: h/c zeroed per forward. ProspectiveVote() reads the fresh forward as its FIRST source; the era-artifact chain becomes the fallback (meta head, warm-up, window holes). DisplayHudLine(): the reference library's training label, per ensemble member - name, output activations (softmax probs or raw scalar), the decision, its weighted vote (the exact consensus numerator term), era, recent average error, "(trn)" while not vote-capable. Rendered under the vote line in RefreshVoteReadout BEFORE the live-vote defer (member lines are telemetry, not tradable readings), coloured by the member's own direction in muted tones - the vote line's strict green-only-when-it-would-trade rule is untouched. NOT COMPILED - user compiles in MetaEditor. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-19 08:48:34 -04:00
bool GetBatchNormFrozen(void);
//---
static double recentAverageSmoothingFactor;
private:
CArrayLayer *layers;
COpenCLMy *opencl;
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
CComputeDll *computeDll;
double recentAverageError;
bool m_cpuInference;
//--- In-memory best-weights checkpoint (see CaptureWeights/RestoreWeights). One CArrayDouble per
//--- neuron in layer-major order; host-only, no device tensors. NULL/false until the first capture.
CArrayObj *m_weightSnapshot;
bool m_haveWeightSnapshot;
//--- Previous call's per-layer weight L2 norms, for LayerLearningReport(). Sized lazily to the layer
//--- count; -1 marks "no baseline yet" so the first report says (init) instead of a bogus 0% change.
double m_prevLayerNorm[];
//--- Previous call's per-layer weight VECTORS, for the |dW| term of LayerLearningReport(). One
//--- CArrayDouble per layer index (empty for layers that own no weights), host-only.
CArrayObj *m_prevLayerWeights;
//--- One-shot latch for BlendWeightsFrom's skip warning - it runs every era, and the condition it
//--- reports is permanent, so the second print would only be noise.
bool m_blendSkipLogged;
//--- PROCESS-WIDE compute-probe latches (shared by every CNet in this terminal process). A host
//--- that HAS OpenCL never latches, so every CNet still gets its own COpenCLMy. Failure messages
//--- stay loud every time.
static bool s_openclUnavailable;
static bool s_computeTierLogged;
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
//--- Mini-batch state. m_batchSizeRequested is what training asked for; m_batchCount is how many
//--- samples have been accumulated into the current batch. m_batchKernelsOk records whether this
//--- net's OpenCL device actually built the accumulation kernels - false forces per-sample updates
//--- rather than failing, so an old device trains exactly as it did before (see InitOpenCL).
//--- m_batchBegun guards BeginBatch so the first sample of a batch zeroes the accumulators exactly
//--- once. m_batchWarned latches the one-time "cannot batch on this tier" notice.
int m_batchSizeRequested;
int m_batchCount;
bool m_batchKernelsOk;
//--- Whether the DEVICE-SIDE apply kernels built (def_k_ApplyAccumAdam). Conflating them would
//--- turn a missing optimisation into a change of optimizer.
perf: mini-batch apply becomes a kernel - 8 weight-matrix transfers per batch become 0 Market builds cannot import a DLL, so OpenCL is the tier paying clients run. It was several times slower than the CPU DLL, and the dominant reason was a host-side optimizer step I shipped with the mini-batch work in 274630f. ApplyAccumToBlock read the weights, the accumulator and both Adam moments back over the bus, stepped them in MQL5, and wrote four buffers out - eight full weight-matrix transfers per batch PER WEIGHT BLOCK, each a blocking sync. At TRAIN_BATCH_SIZE 8 that is roughly one entire weight matrix crossing the bus per training sample. It was host-side for a good reason (one optimizer implementation shared by all four tiers instead of four that can drift), and that reason turned out to cost the product's own compute tier. - ApplyAccumAdam / ApplyAccumMomentum in Network.cl: flat, elementwise, and they zero the accumulator themselves so there is no separate clear dispatch and no way to leave it dirty via an early return - ApplyAccumOnDevice dispatches them; the host step stays as the reference and as the implementation for DirectML, the CPU DLL and pure-MQL5 - failure latches OFF process-wide with one warning rather than a failed Execute per batch, since a kernel that did not build will not build later - m_applyKernelsOk is tracked SEPARATELY from m_batchKernelsOk: without the accumulation kernels a device cannot batch and must drop to per-sample updates, whereas without these it batches normally and merely pays the transfers. Conflating them would turn a missing optimisation into a changed optimizer The kernel runs fp32 where the host step ran fp64. That is the OpenCL tier becoming self-consistent, not a regression: its device buffers are already fp32 (CBufferDouble::m_data_f) and its unbatched optimizer already ran in fp32, so the batched path was the odd one out. DLL tiers keep fp64 throughout. Validated: no OpenCL platform exists on this box, so the kernel source is syntax/type checked as C against a shim and driven for 4000 steps. It clears the accumulator, and it is scale-invariant - displacement 1.199336 at |g|=1 versus 1.199333 at |g|=1e-4, matching the figure DirectML/batch_accum_check produced for the fixed CPU_UpdateWeightsAdam. It reproduces the corrected Adam, not the pre-371f8aa one. Both build variants compile 0 errors, 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 17:09:52 -04:00
bool m_applyKernelsOk;
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
bool m_batchBegun;
bool m_batchWarned;
//--- Zero every accumulator, starting a fresh batch.
bool BeginBatch(void);
};
//+------------------------------------------------------------------+
//| |
feat(ai): real conv receptive field + the reference's channel pool CONV's convolution used window = step = one bar, which is a per-bar projection - a 1x1 conv with a temporal receptive field of ONE BAR. It never mixed information across time, so "convolutional" described the layer type and nothing about what it computed. Same finding that sank HYBRID's LSTM. Pooling was removed on 2026-07-29 for being misconfigured against the conv output's memory layout. That removal was right; leaving the conv at a one-bar window was not. The two belong together: the NeuroNet_DNG reference (references\MQL5\Experts\EDL\Trajectory.mqh layers 2-5, kernels byte-identical to ours) pairs conv(window=2, step=1, window_out=4) with pool(window=4, step=4), and the pool only earns its place because a conv with a real receptive field sits above it. The input is bar-major (BufferTempData appends m_neuronsCount contiguous features per bar), so a flat window of k*m_neuronsCount spans exactly k bars - the receptive field needed NO kernel change. The conv output is position-major, so window == step == window_out is a clean max-over-channels, which is what the reference does and what the existing pool kernels already implement correctly. New chain at H1 defaults (420 = 20 bars x 21): conv1 w=42 s=21 out=8 -> 19 pos x 8 = 152 pool w=8 s=8 -> 19 conv2 w=2 s=1 out=8 -> 18 pos x 8 = 144 (effective field: 3 bars) We deliberately stop before the reference's SECOND pool: a channel pool emits one scalar per position, so a trailing pool would hand the dense stack 18 values and force it to fan out 18 -> 64. That is a bottleneck below every learnable layer - the same class of mistake the 2026-07-29 removal was about. Fixes a latent sizing bug this exposed: CNet's conv/pool position cursor tracked sliding POSITIONS, but a conv's real width is units_count * window_out. Any pool stacked on a conv would therefore have sized against a width window_out times too small and silently built the wrong shape. Both branches now read the built layer's actual Neurons(), which is what the batch-norm branch already did for the same reason. Also closes the architecture-pinning trap: a .nnw persists the window each conv was built with, so an existing CONV/HYBRID model would have loaded cleanly and gone on training under the OLD architecture. The conv weight tensor is (window+1)*window_out, so this cannot be repaired in place - EnforceTopologyContract now detects it, reports both shapes, and retrains. Conv chain shape is derived in one place (ConvReceptiveFieldBars / ConvFirstStagePositions / HasSecondConvStage / ConvOutputPositions / ConvOutputWidth) and consumed by AddConvStage, LstmFanIn and the startup config line, so what is built and what is logged cannot drift. Both builds compile 0 errors, 0 warnings. Forces a CONV and HYBRID retrain. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-30 20:05:37 -04:00
//+------------------------------------------------------------------+
class CNeuronLSTM : public CNeuronPool
{
protected:
CLayer *ForgetGate;
CLayer *InputGate;
CLayer *OutputGate;
CLayer *NewContent;
CArrayDouble *Memory;
CArrayDouble *PrevMemory;
CArrayDouble *Input;
CArrayDouble *InputGradient;
//---
virtual bool feedForward(CLayer *prevLayer);
virtual bool calcHiddenGradients(CLayer *&nextLayer);
virtual bool updateInputWeights(CLayer *prevLayer);
virtual bool updateInputWeights(CLayer *gate, CArrayDouble *input_data);
virtual bool InitLayer(CLayer *layer, int numOutputs, int numUnits, ENUM_OPTIMIZATION optimization_type);
fix(lstm): the CPU LSTM leaked four buffers per forward pass, and the input-gradient loop checked nothing Found auditing pointer discipline, per the standing rule that CheckPointer comes before every dereference. THE LEAKS. CNeuronLSTM::feedForward allocated forget_gate, input_gate, output_gate and new_content on the heap and deleted them only on the success path. Eight error returns sit between the first allocation and that delete, and every one of them abandoned whatever had been built so far. calcHidden- Gradients was the same shape with fourteen returns past MemoryGradient. This is the CPU path, which is the only path this machine has - no OpenCL, no DirectML - so it ran on every era of every LSTM and CONVLSTM member. Fixed by construction rather than by adding deletes: none of the five buffers escapes its function, so each is now an automatic object. The return itself destroys them, which means the leak cannot come back the next time someone adds an error path - which is exactly how it got here. CalculateGate had to change shape for that: it now fills a caller-supplied CArrayDouble and answers bool, instead of handing back an object each caller was responsible for deleting on its own error paths and none of them did. It also allocated BEFORE testing `gate`, leaking on that very check, and never tested `sequence` at all before dereferencing it. Both arguments are checked first now. Protected virtual with three call sites, all in this file - no public API moves. THE UNCHECKED DEREFERENCES. The input-gradient loop did four rounds of `temp = SomeGate.At(i); con = temp.getConnections().At(n); value += temp.getGradient() * con.weight` with no check on either pointer, and At() answers NULL for an out-of-range index rather than failing loudly. The four copies are now one AccumulateGateInputGradient() that checks the layer, the neuron and the connection. The line above them read `temp.getConnections()` off whatever the previous loop happened to leave in `temp` - NULL if OutputLayer was empty - and is now checked too. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 13:54:08 -04:00
//--- Fills `result` rather than returning a fresh CArrayDouble. The old shape handed every caller
//--- an object to delete on each of its own error paths, and none of them did - see feedForward().
virtual bool CalculateGate(CLayer *gate, CArrayDouble *sequence, CArrayDouble &result);
bool AccumulateGateInputGradient(CLayer *gate, const int i, const int n, double &value);
public:
CNeuronLSTM(void);
~CNeuronLSTM(void);
virtual bool Init(uint numOutputs, uint myIndex, int window, int step, int units_count, ENUM_OPTIMIZATION optimization_type);
//---
virtual CLayer *getOutputLayer(void) { return OutputLayer; }
virtual bool calcInputGradients(CLayer *prevLayer) ;
virtual bool calcInputGradients(CNeuronBase *prevNeuron, uint index) ;
//--- methods for working with files
virtual bool Save(int const file_handle);
virtual bool Load(int const file_handle);
virtual int Type(void) const { return defNeuronLSTM; }
};
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
template<typename T>
int COpenCLMy::AddBufferFromArray(T &data[], const uint data_array_offset, const uint data_array_count, const uint flags)
{
int result = -1;
for(int i = 0; i < m_buffers_total; i++)
{
if(m_buffers[i] != INVALID_HANDLE)
continue;
result = i;
break;
}
//---
if(result < 0)
{
if(ArrayResize(m_buffers, m_buffers_total + 1) > 0)
fix(perf): treat TargetCPULoad as a machine budget split across charts The CPU-DLL thread pool was sized from TargetCPULoad undivided, on the reasoning that only one pool is ever actively computing at a time. That is true WITHIN a chart - MQL5 gives one chart's EA a single execution thread, and every WarriorCPU.dll entry point blocks it until its ParallelFor() completes, so the live net, the EMA shadow and HYBRID's fused pair take turns. It does not hold ACROSS charts, which each get their own execution thread and really do run their pools simultaneously. At the 100% default on a 12-core box, five training charts asked for 12 threads each: 60 threads contending for 12 cores. Measured today, dropping to ~2 threads apiece made every chart train "super fast". This had previously been read as one architecture being mysteriously 10x slower than another on the CPU-DLL tier while identical on OpenCL - oversubscription of that degree degrades superlinearly and punishes whichever model issues the most small sequential dispatches, which fits an MLP being the victim. TargetCPULoad now means the budget for the whole machine, divided by the number of charts running this EA. Counting charts is the correct axis: concurrency here is one execution thread per chart, not one per CNet, and the within-chart division that was previously removed stays removed. Snapshot at pool-creation time on purpose - attaching another chart later does not resize pools that already exist, because that would mean tearing down a DLL context underneath a live training run. Skipped entirely in the tester/optimizer, where the terminal already pins one strategy per agent. This matters most for buyers: a Market build compiles the input out and pins it to 100%, so they cannot reach the setting at all and would have hit the pathological case with no way to diagnose or fix it. The tier log line now reports the split rather than just the result. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 14:06:35 -04:00
{
m_buffers_total = ArraySize(m_buffers);
result = m_buffers_total - 1;
m_buffers[result] = INVALID_HANDLE;
fix(perf): treat TargetCPULoad as a machine budget split across charts The CPU-DLL thread pool was sized from TargetCPULoad undivided, on the reasoning that only one pool is ever actively computing at a time. That is true WITHIN a chart - MQL5 gives one chart's EA a single execution thread, and every WarriorCPU.dll entry point blocks it until its ParallelFor() completes, so the live net, the EMA shadow and HYBRID's fused pair take turns. It does not hold ACROSS charts, which each get their own execution thread and really do run their pools simultaneously. At the 100% default on a 12-core box, five training charts asked for 12 threads each: 60 threads contending for 12 cores. Measured today, dropping to ~2 threads apiece made every chart train "super fast". This had previously been read as one architecture being mysteriously 10x slower than another on the CPU-DLL tier while identical on OpenCL - oversubscription of that degree degrades superlinearly and punishes whichever model issues the most small sequential dispatches, which fits an MLP being the victim. TargetCPULoad now means the budget for the whole machine, divided by the number of charts running this EA. Counting charts is the correct axis: concurrency here is one execution thread per chart, not one per CNet, and the within-chart division that was previously removed stays removed. Snapshot at pool-creation time on purpose - attaching another chart later does not resize pools that already exist, because that would mean tearing down a DLL context underneath a live training run. Skipped entirely in the tester/optimizer, where the terminal already pins one strategy per agent. This matters most for buyers: a Market build compiles the input out and pins it to 100%, so they cannot reach the setting at all and would have hit the pathological case with no way to diagnose or fix it. The tier log line now reports the split rather than just the result. Compiles 0 errors, 0 warnings. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-29 14:06:35 -04:00
}
else
return result;
}
//---
if(!BufferFromArray(result, data, data_array_offset, data_array_count, flags))
return -1;
//---
return result;
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
#include "BufferDouble.mqh"
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
class CNeuronBaseOCL : public CObject
{
protected:
COpenCLMy *OpenCL;
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
CComputeDll *ComputeDll;
CBufferDouble *Output;
CBufferDouble *PrevOutput;
CBufferDouble *Weights;
CBufferDouble *DeltaWeights;
CBufferDouble *Gradient;
CBufferDouble *FirstMomentum;
CBufferDouble *SecondMomentum;
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
//--- MINI-BATCH ACCUMULATOR (2026-08-09 audit, F4). Same shape as Weights; holds the SUM of this
//--- weight block's per-sample gradients over the current batch.
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
CBufferDouble *GradAccum;
//---
const double alpha;
int t;
//---
ENUM_ACTIVATION activation;
ENUM_OPTIMIZATION optimization;
//---
virtual bool feedForward(CNeuronBaseOCL *NeuronOCL);
virtual bool calcHiddenGradients(CNeuronBaseOCL *NeuronOCL);
//--- Create a buffer's device-side storage on whichever backend is active, or leave it host-only
//--- (its CArrayDouble m_data already holds the values just Load()ed) when neither backend exists -
//--- the pure-MQL5 inference path (see CNet::SetCpuInference / feedForwardCPU).
bool BackendBufferCreate(CBufferDouble *buf)
{
if(CheckPointer(buf) == POINTER_INVALID)
return false;
if(CheckPointer(OpenCL) != POINTER_INVALID)
return buf.BufferCreate(OpenCL);
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
if(CheckPointer(ComputeDll) != POINTER_INVALID)
return buf.BufferCreate(ComputeDll);
return true; // no backend: keep host m_data, skip device allocation
}
//--- THE optimizer step, and the only copy of it in the batched path: one weight block, one Adam
//--- or SGD+momentum update on `acc * scale`, then the accumulator is zeroed.
perf: mini-batch apply becomes a kernel - 8 weight-matrix transfers per batch become 0 Market builds cannot import a DLL, so OpenCL is the tier paying clients run. It was several times slower than the CPU DLL, and the dominant reason was a host-side optimizer step I shipped with the mini-batch work in 274630f. ApplyAccumToBlock read the weights, the accumulator and both Adam moments back over the bus, stepped them in MQL5, and wrote four buffers out - eight full weight-matrix transfers per batch PER WEIGHT BLOCK, each a blocking sync. At TRAIN_BATCH_SIZE 8 that is roughly one entire weight matrix crossing the bus per training sample. It was host-side for a good reason (one optimizer implementation shared by all four tiers instead of four that can drift), and that reason turned out to cost the product's own compute tier. - ApplyAccumAdam / ApplyAccumMomentum in Network.cl: flat, elementwise, and they zero the accumulator themselves so there is no separate clear dispatch and no way to leave it dirty via an early return - ApplyAccumOnDevice dispatches them; the host step stays as the reference and as the implementation for DirectML, the CPU DLL and pure-MQL5 - failure latches OFF process-wide with one warning rather than a failed Execute per batch, since a kernel that did not build will not build later - m_applyKernelsOk is tracked SEPARATELY from m_batchKernelsOk: without the accumulation kernels a device cannot batch and must drop to per-sample updates, whereas without these it batches normally and merely pays the transfers. Conflating them would turn a missing optimisation into a changed optimizer The kernel runs fp32 where the host step ran fp64. That is the OpenCL tier becoming self-consistent, not a regression: its device buffers are already fp32 (CBufferDouble::m_data_f) and its unbatched optimizer already ran in fp32, so the batched path was the odd one out. DLL tiers keep fp64 throughout. Validated: no OpenCL platform exists on this box, so the kernel source is syntax/type checked as C against a shim and driven for 4000 steps. It clears the accumulator, and it is scale-invariant - displacement 1.199336 at |g|=1 versus 1.199333 at |g|=1e-4, matching the figure DirectML/batch_accum_check produced for the fixed CPU_UpdateWeightsAdam. It reproduces the corrected Adam, not the pre-371f8aa one. Both build variants compile 0 errors, 0 warnings. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 17:09:52 -04:00
bool ApplyAccumOnDevice(CBufferDouble *w, CBufferDouble *acc, CBufferDouble *m,
CBufferDouble *v, CBufferDouble *dw, double scale, int total);
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
bool ApplyAccumToBlock(CBufferDouble *w, CBufferDouble *acc, CBufferDouble *m,
CBufferDouble *v, CBufferDouble *dw, double scale);
//--- Lazily allocate the mini-batch accumulator to match `src` (Weights / WeightsConv /
//--- WeightsLSTM, whichever block the caller accumulates into).
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
bool EnsureGradAccumFor(CBufferDouble *&target, CBufferDouble *src)
{
if(CheckPointer(src) == POINTER_INVALID || src.Total() <= 0)
return false;
if(CheckPointer(target) != POINTER_INVALID && target.Total() == src.Total())
return true;
if(CheckPointer(target) != POINTER_INVALID)
delete target;
target = new CBufferDouble();
if(CheckPointer(target) == POINTER_INVALID)
return false;
if(!target.BufferInit(src.Total(), 0.0))
return false;
return BackendBufferCreate(target);
}
bool EnsureGradAccum(CBufferDouble *src) { return EnsureGradAccumFor(GradAccum, src); }
public:
CNeuronBaseOCL(void);
~CNeuronBaseOCL(void);
virtual bool Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint numNeurons, ENUM_OPTIMIZATION optimization_type);
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
virtual bool Init(uint numOutputs, uint myIndex, CComputeDll *compute_dll, uint numNeurons, ENUM_OPTIMIZATION optimization_type);
virtual void SetActivationFunction(ENUM_ACTIVATION value) { activation = value; }
//---
virtual int getOutputIndex(void) { return Output.GetIndex(); }
virtual int getGradientIndex(void) { return Gradient.GetIndex(); }
virtual int getWeightsIndex(void) { return Weights.GetIndex(); }
virtual int getDeltaWeightsIndex(void) { return DeltaWeights.GetIndex(); }
virtual int getFirstMomentumIndex(void) { return FirstMomentum.GetIndex(); }
virtual int getSecondMomentumIndex(void) { return SecondMomentum.GetIndex();}
//---
virtual int getOutputVal(double &values[]) { return Output.GetData(values); }
virtual int getOutputVal(CArrayDouble *values) { return Output.GetData(values); }
virtual int getPrevVal(double &values[]) { return PrevOutput.GetData(values); }
virtual int getGradient(double &values[]) { return Gradient.GetData(values); }
//--- pushes locally-modified gradient values back to this buffer's GPU/CPU-DLL-side copy - used by
//--- CNet::backPropOCL() to apply per-sample loss weighting after the native CalcOutputGradient call
//--- (which only computes the raw, unweighted delta) and before the backward pass reads this same
//--- buffer to propagate into the hidden layers.
virtual bool setGradient(const double &values[])
{
int count = ArraySize(values);
for(int i = 0; i < count; i++)
if(!Gradient.Update(i, values[i]))
return false;
return Gradient.BufferWrite();
}
// Guarded: output-layer neurons (numOutputs==0) have Weights deleted in Init() but not re-created,
// so BlendWeightsFrom() walking every neuron would otherwise dereference a dead pointer here.
virtual int getWeights(double &values[]) { return (CheckPointer(Weights) == POINTER_INVALID ? 0 : Weights.GetData(values)); }
//--- Paired with getWeights() above for CNet::BlendWeightsFrom()'s EMA shadow-weight deployment
//--- (see that method's declaration comment) - writes a full replacement weight array back to
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
//--- this buffer's device-side (OpenCL/CPU-DLL) storage.
virtual bool setWeights(double &values[])
{
if(CheckPointer(Weights) == POINTER_INVALID)
return false;
if(!Weights.AssignArray(values))
return false;
return Weights.BufferWrite();
}
fix: training-stability audit fixes F1/F2/F3/F5 - unbiased shuffle, real plateau escapes, fresh optimizer state on restore, pure OOS metric Four of the six findings from research/training_pipeline_audit_2026-08-09.md (F4 mini-batching and F6 feature re-encode deliberately deferred - see the report's implementation-status section for why): - F1: pass-2 Fisher-Yates (and AutoTune's MI block shuffle) used MathRand()%, which is 15-bit - provably non-uniform on every full-history era over 32,768 queued samples. New 30-bit ShuffleRandomIndex(). - F2: plateau warm restarts were a no-op whenever eta already sat at its ceiling (the normal state of a non-regressing plateau) - the ladder was just a 24-era countdown. Restarts now overshoot to 5x the ceiling (PLATEAU_RESTART_BOOST) and anneal geometrically back over the patience window, SGDR-style; ETA_MIN widened 1e-4 -> 1e-5 so the decay schedule has real range. - F3: checkpoint restores put weights back but kept the rejected trajectory's Adam moments, so the optimizer immediately pushed back toward the rolled-back state (the restore->regress->restore oscillation). CNet::ResetOptimizerState() zeroes moments/momentum/step counters (weights, BN statistics, gamma/beta untouched) on every mid-run restore, every boosted restart, and the deploy-time restore that online learning continues from. - F5: batch-norm running statistics now freeze for the pass-3 OOS scoring walk, so the selection metric the checkpoint ranking and deploy gate read is a pure function of the checkpoint instead of partly measuring BN drift. Defensive unfreeze in FinalizeTrainRun covers stop-mid-pass; live/online adaptation and the OOS continual-learning simulation stay adaptive by design. Compiled clean (0 errors, 0 warnings) via the staged-tree recipe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 10:54:09 -04:00
//--- Forget the optimizer's trajectory memory: Adam first/second moments, SGD's previous-delta
//--- buffer, and the bias-correction step counter, weights untouched. See
fix: training-stability audit fixes F1/F2/F3/F5 - unbiased shuffle, real plateau escapes, fresh optimizer state on restore, pure OOS metric Four of the six findings from research/training_pipeline_audit_2026-08-09.md (F4 mini-batching and F6 feature re-encode deliberately deferred - see the report's implementation-status section for why): - F1: pass-2 Fisher-Yates (and AutoTune's MI block shuffle) used MathRand()%, which is 15-bit - provably non-uniform on every full-history era over 32,768 queued samples. New 30-bit ShuffleRandomIndex(). - F2: plateau warm restarts were a no-op whenever eta already sat at its ceiling (the normal state of a non-regressing plateau) - the ladder was just a 24-era countdown. Restarts now overshoot to 5x the ceiling (PLATEAU_RESTART_BOOST) and anneal geometrically back over the patience window, SGDR-style; ETA_MIN widened 1e-4 -> 1e-5 so the decay schedule has real range. - F3: checkpoint restores put weights back but kept the rejected trajectory's Adam moments, so the optimizer immediately pushed back toward the rolled-back state (the restore->regress->restore oscillation). CNet::ResetOptimizerState() zeroes moments/momentum/step counters (weights, BN statistics, gamma/beta untouched) on every mid-run restore, every boosted restart, and the deploy-time restore that online learning continues from. - F5: batch-norm running statistics now freeze for the pass-3 OOS scoring walk, so the selection metric the checkpoint ranking and deploy gate read is a pure function of the checkpoint instead of partly measuring BN drift. Defensive unfreeze in FinalizeTrainRun covers stop-mid-pass; live/online adaptation and the OOS continual-learning simulation stay adaptive by design. Compiled clean (0 errors, 0 warnings) via the staged-tree recipe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 10:54:09 -04:00
//--- CNet::ResetOptimizerState for the restore/warm-restart rationale.
virtual bool ResetOptimizerState(void)
{
t = 1;
bool ok = ZeroOptimizerBuffer(FirstMomentum);
ok = ZeroOptimizerBuffer(SecondMomentum) && ok;
ok = ZeroOptimizerBuffer(DeltaWeights) && ok;
return ok;
}
virtual int Neurons(void) { return Output.Total(); }
virtual ENUM_ACTIVATION Activation(void) { return activation; }
virtual int getConnections(void) { return (CheckPointer(Weights) != POINTER_INVALID && CheckPointer(Gradient) != POINTER_INVALID && Gradient.Total() > 0 ? Weights.Total() / Gradient.Total() : 0); }
//--- Host-side (no device round-trip) buffer element access for the pure-MQL5 inference path. Safe to
//--- call after Load() with no backend: the CArrayDouble m_data holds the values, unlike getWeights()/
//--- getOutputVal() which route through BufferRead() (a device read that fails without a backend).
double OutputHost(int i) { return (CheckPointer(Output) != POINTER_INVALID && i >= 0 && i < Output.Total()) ? Output.At(i) : 0.0; }
double WeightHost(int i) { return (CheckPointer(Weights) != POINTER_INVALID && i >= 0 && i < Weights.Total()) ? Weights.At(i) : 0.0; }
int WeightsCount(void) { return (CheckPointer(Weights) != POINTER_INVALID) ? Weights.Total() : 0; }
//--- Pure-MQL5, double-precision forward pass mirroring Network.cl's FeedForward kernel, reading only
//--- host buffers. Used exclusively when no compute backend exists (CNet::SetCpuInference). Dense
//--- (fully-connected) here; conv/pool/LSTM subclasses override with their own kernel math.
virtual bool feedForwardCPU(CNeuronBaseOCL *NeuronOCL);
//--- Host-side input write for the CPU inference path's layer 0, and host-side output read for
//--- getResults() - both bypass the device buffer that the CPU path deliberately never allocates.
bool SetInputsCPU(CArrayDouble *inputVals);
int GetOutputsCPU(CArrayDouble *values);
//---
virtual bool feedForward(CObject *SourceObject);
virtual bool calcHiddenGradients(CObject *TargetObject);
virtual bool calcOutputGradients(CArrayDouble *Target);
virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL);
virtual bool updateInputWeights(CObject *SourceObject);
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
//--- MINI-BATCH PAIR (2026-08-09 audit, F4). accumulateInputWeightGrads() adds THIS sample's
//--- per-weight gradient into GradAccum without touching the weights;
//--- ApplyAccumulatedGradients() then takes ONE optimizer step on the batch mean and clears the
//--- accumulator.
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
virtual bool accumulateInputWeightGrads(CNeuronBaseOCL *NeuronOCL);
virtual bool accumulateInputWeightGrads(CObject *SourceObject);
virtual bool ApplyAccumulatedGradients(double scale);
//--- Zero the accumulator at the start of a batch. Separate from ApplyAccumulatedGradients so a
//--- discarded partial batch (a stopped run) can be cleared without taking a step from it.
virtual bool BeginGradAccum(void);
//---
virtual bool Save(int const file_handle);
virtual bool Load(int const file_handle);
//---
virtual int Type(void) const { return defNeuronBaseOCL; }
};
//+------------------------------------------------------------------+
#include "NeuronOCLConvPool.mqh"
#include "NeuronBatchNorm.mqh"
//+------------------------------------------------------------------+
//--- Marks a .nnw LSTM record as the SEQUENCE format. Chosen so it cannot collide with any value the
//--- pre-sequence format could have written in that slot (an input width, i.e. -1 or a positive count).
#define LSTM_SEQ_SAVE_TAG (-424242)
//--- Initial bias of the FORGET gate (gate 0). Every other weight starts near zero; this one must
//--- not.
#define LSTM_FORGET_BIAS_INIT (1.0)
//+------------------------------------------------------------------+
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
//| GPU/CPU-DLL-accelerated LSTM layer (OpenCL + CPU-DLL). Derived |
//| from scratch from the standard LSTM equations - NOT ported from |
//| the NeuroNet_DNG reference (see the note above the LSTM kernels |
//| in Network.cl for why). Single-timestep-truncated BPTT: gradient |
//| does not flow back into h_prev/c_prev from an earlier step. |
//| Adam-only - Init fails for any other optimization type. |
//+------------------------------------------------------------------+
class CNeuronLSTMOCL : public CNeuronBaseOCL
{
protected:
int m_iInputs;
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
//--- Mini-batch running total of WeightsGradient across the samples of one batch - see the note on
//--- accumulateInputWeightGrads below for why WeightsGradient itself cannot serve as it.
CBufferDouble *GradAccumLSTM;
//--- Sequence shape. m_iStepInputs is the width of ONE timestep (the per-bar feature count
//--- reaching this layer), set from the layer descriptor by SetStepWidth() before the first
//--- feedForward; m_iSteps is then m_iInputs / m_iStepInputs.
int m_iStepInputs;
int m_iSteps;
//--- Per-timestep caches, required by backpropagation-through-time: the backward pass needs each
//--- step's gate activations, cell state and hidden state, which the single-buffer Concatenated/
//--- Memory/HiddenCache trio below cannot hold because every step overwrites the last.
CBufferDouble *CacheGates; // T * 4H, gate order [f,i,o,g]
CBufferDouble *CacheCell; // T * H, c_t
CBufferDouble *CacheHidden; // T * H, h_t
CBufferDouble *WeightsLSTM;
CBufferDouble *FirstMomentumLSTM;
CBufferDouble *SecondMomentumLSTM;
CBufferDouble *DeltaWeightsLSTM;
CBufferDouble *WeightsGradient;
CBufferDouble *Concatenated;
CBufferDouble *ConcatenatedGradient;
CBufferDouble *Memory;
CBufferDouble *HiddenCache;
//---
virtual bool feedForward(CNeuronBaseOCL *NeuronOCL);
virtual bool feedForwardCPU(CNeuronBaseOCL *NeuronOCL); // pure-MQL5 mirror of LSTM_Gates + LSTM_State
virtual bool updateInputWeights(CNeuronBaseOCL *NeuronOCL);
virtual bool SetInputs(int count);
bool AllocateSequenceCaches(void);
public:
CNeuronLSTMOCL(void) : m_iInputs(-1), m_iStepInputs(-1), m_iSteps(-1)
{
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
GradAccumLSTM = NULL;
CacheGates = NULL;
CacheCell = NULL;
CacheHidden = NULL;
WeightsLSTM = NULL;
FirstMomentumLSTM = NULL;
SecondMomentumLSTM = NULL;
DeltaWeightsLSTM = NULL;
WeightsGradient = NULL;
Concatenated = NULL;
ConcatenatedGradient = NULL;
Memory = NULL;
HiddenCache = NULL;
}
~CNeuronLSTMOCL(void);
virtual bool Init(uint numOutputs, uint myIndex, COpenCLMy *open_cl, uint numNeurons, ENUM_OPTIMIZATION optimization_type);
refactor(ai): remove the DirectML/D3D12 GPU compute tier (S1.5) Three backends left, as the operator specified: OpenCL, the CPU DLL, and pure MQL5. CDirectMLMy was a two-tier wrapper (GPU via WarriorDML.dll, CPU via WarriorCPU.dll) whose name only ever named the tier being removed here; the CPU DLL tier - the one actually used on the training machine (no OpenCL, no DirectML) - is untouched. AI/NeuronDirectML.mqh -> AI/ComputeDll.mqh: dropped the DML_* #import block and COMPUTE_TIER_GPU (checked first that nothing persists the enum value and only one external site reads .Tier() - safe), collapsed every tier==CPU?CPU_x():DML_x() ternary to a straight CPU_x() call. Renamed CDirectMLMy->CComputeDll, InitDirectML()->InitComputeDll(), member directml/DirectML->computeDll/ComputeDll across every AI/ file that touched a neuron/net backend plus Topology.mqh/OnlineLearning.mqh. NetBuild.mqh's InitComputeDll also lost the dead D3D12 error-code switch and the now-impossible GPU-tier log branch. Verified via per-file brace-balance diff against HEAD and a whole-repo grep for every removed symbol (CDirectMLMy/InitDirectML/ COMPUTE_TIER_GPU/DML_*) - the only surviving hit is an intentional historical-note comment in the new file's header. DirectML\WarriorDML.cpp/.h and its build scripts are now orphaned C++ source, left in place pending an operator decision. Architecture docs (AI_NETWORK.md, Warrior_EA_System_Overview.md, etc.) still describe the 4-backend/GPU-tier shape and are not updated in this pass. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-23 19:32:09 -04:00
virtual bool Init(uint numOutputs, uint myIndex, CComputeDll *compute_dll, uint numNeurons, ENUM_OPTIMIZATION optimization_type);
//--- Per-timestep input width, from CLayerDescription::window (see AddLstmStage). Must be called
//--- between Init() and the first feedForward; <= 0 keeps the legacy single-timestep behaviour.
//--- Not persisted from here - Save/Load carry it, so a loaded model does not depend on call order.
void SetStepWidth(int stepInputs) { m_iStepInputs = (stepInputs > 0 ? stepInputs : -1); }
bool IsSequenceMode(void) const { return (m_iStepInputs > 0 && m_iSteps > 1); }
virtual bool calcInputGradients(CNeuronBaseOCL *NeuronOCL);
virtual bool Save(int const file_handle);
virtual bool Load(int const file_handle);
virtual int Type(void) const { return defNeuronLSTMOCL; }
// See CNeuronBaseOCL::getWeights/setWeights - same pair, targeting WeightsLSTM instead of the
// base class's Weights, for CNet::BlendWeightsFrom()'s EMA shadow-weight deployment.
virtual int getWeightsLSTM(double &values[]) { return (CheckPointer(WeightsLSTM) == POINTER_INVALID ? 0 : WeightsLSTM.GetData(values)); }
//--- Build this layer's weight block to match `src`, for a net that was cloned from one whose
//--- LSTM had not yet run a forward pass.
virtual bool AdoptShapeFrom(CNeuronLSTMOCL &src)
{
if(src.m_iInputs <= 0 || Neurons() != src.Neurons())
return false;
m_iStepInputs = src.m_iStepInputs;
return SetInputs(src.m_iInputs);
}
virtual bool setWeightsLSTM(double &values[])
{
if(CheckPointer(WeightsLSTM) == POINTER_INVALID)
return false;
if(!WeightsLSTM.AssignArray(values))
return false;
return WeightsLSTM.BufferWrite();
}
fix: training-stability audit fixes F1/F2/F3/F5 - unbiased shuffle, real plateau escapes, fresh optimizer state on restore, pure OOS metric Four of the six findings from research/training_pipeline_audit_2026-08-09.md (F4 mini-batching and F6 feature re-encode deliberately deferred - see the report's implementation-status section for why): - F1: pass-2 Fisher-Yates (and AutoTune's MI block shuffle) used MathRand()%, which is 15-bit - provably non-uniform on every full-history era over 32,768 queued samples. New 30-bit ShuffleRandomIndex(). - F2: plateau warm restarts were a no-op whenever eta already sat at its ceiling (the normal state of a non-regressing plateau) - the ladder was just a 24-era countdown. Restarts now overshoot to 5x the ceiling (PLATEAU_RESTART_BOOST) and anneal geometrically back over the patience window, SGDR-style; ETA_MIN widened 1e-4 -> 1e-5 so the decay schedule has real range. - F3: checkpoint restores put weights back but kept the rejected trajectory's Adam moments, so the optimizer immediately pushed back toward the rolled-back state (the restore->regress->restore oscillation). CNet::ResetOptimizerState() zeroes moments/momentum/step counters (weights, BN statistics, gamma/beta untouched) on every mid-run restore, every boosted restart, and the deploy-time restore that online learning continues from. - F5: batch-norm running statistics now freeze for the pass-3 OOS scoring walk, so the selection metric the checkpoint ranking and deploy gate read is a pure function of the checkpoint instead of partly measuring BN drift. Defensive unfreeze in FinalizeTrainRun covers stop-mid-pass; live/online adaptation and the OOS continual-learning simulation stay adaptive by design. Compiled clean (0 errors, 0 warnings) via the staged-tree recipe. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 10:54:09 -04:00
//--- The LSTM's gate-weight block keeps its own moment/momentum buffers beside the base class's -
//--- see CNet::ResetOptimizerState.
virtual bool ResetOptimizerState(void)
{
bool ok = CNeuronBaseOCL::ResetOptimizerState();
ok = ZeroOptimizerBuffer(FirstMomentumLSTM) && ok;
ok = ZeroOptimizerBuffer(SecondMomentumLSTM) && ok;
ok = ZeroOptimizerBuffer(DeltaWeightsLSTM) && ok;
return ok;
}
//--- MINI-BATCH. Batching it is therefore just a running total. Hence a separate accumulator
//--- plus a generic elementwise add (AccumulateBufferInto), which also avoids changing the
//--- signature of an already-deployed export.
feat: mini-batch gradient accumulation (F4), front-end-aware capacity budget (F6), split Wyckoff categoricals (N1) Completes the 2026-08-09 training audit. FORCES A RETRAIN of every Wyckoff-enabled config (N1 re-keys the fingerprint), and BOTH DLLs must be redeployed alongside the .ex5 - they carry new exports. F4 - mini-batch accumulation, TRAIN_BATCH_SIZE=32. Training was pure online SGD (one weight update per bar), which is the mechanical source of the era-to-era whipsaw every downstream guard was built to cope with. The O(n^2) outer product is native - AccumulateWeightGrad / AccumulateWeightGradConv / AccumulateBufferInto in Network.cl, WarriorCPU and WarriorDML - while the optimizer step is host-side MQL5 shared by all tiers (ApplyAccumToBlock), so there is one Adam/SGD implementation instead of four that can drift. - the LSTM needs no outer-product kernel (WeightsGradient already holds the sample's full dW) but could NOT simply be left un-zeroed between samples: CPU_LSTMSeqBackward/DML_LSTMSeqBackward memset it on entry. Hence a separate accumulator plus an elementwise add. - batch-norm gamma/beta accumulate in host arrays, not new BatchOptions slots - BN_OPT_STRIDE is baked into every persisted .nnw. - scoped to pass 2; online learning keeps immediate updates. Every save / checkpoint / scoring boundary flushes, scaling by the real sample count. - degrades to per-sample updates (one log line) on a tier that cannot accumulate, so old devices and DLL-free builds are unaffected. - verified offline: DirectML/batch_accum_check.cpp drives the real exports against an independent reference; at B=1 the accumulator matches the shipped unbatched kernel's own gradient to 1.1e-16. Math only - the in-situ check remains the per-layer dW/W report on a real era. F6 - ComputeFirstLayerWidth budgeted against the RAW input width even where a conv/LSTM front end had already reduced it, so an LSTM's dense stack was charged for 1,280 inputs when it receives 64. Confirmed from the deployed .cfg files: CONV, LSTM and HYBRID were all pinned at the 16-unit floor. Now budgeted against the front-end output and capped at it (never fan out), with the derivation reordered so both stages settle first. N1 - EventCode/EventPhase/StructuralPhase are signed categoricals packing direction and Wyckoff stage into one scalar across a sign discontinuity. Split into direction + [0,1] magnitude, the same convention the base OHLC block uses. Information-preserving; 13 readings now occupy 16 inputs. Compiled clean (0 errors, 0 warnings); both DLLs rebuilt. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-08-09 11:48:03 -04:00
virtual bool accumulateInputWeightGrads(CNeuronBaseOCL *NeuronOCL);
virtual bool BeginGradAccum(void)
{
bool ok = CNeuronBaseOCL::BeginGradAccum();
if(CheckPointer(GradAccumLSTM) != POINTER_INVALID && GradAccumLSTM.Total() > 0)
ok = ZeroOptimizerBuffer(GradAccumLSTM) && ok;
return ok;
}
virtual bool ApplyAccumulatedGradients(double scale)
{
bool ok = ApplyAccumToBlock(Weights, GradAccum, FirstMomentum, SecondMomentum, DeltaWeights, scale);
ok = ApplyAccumToBlock(WeightsLSTM, GradAccumLSTM, FirstMomentumLSTM, SecondMomentumLSTM,
DeltaWeightsLSTM, scale) && ok;
if(optimization == ADAM)
t++;
return ok;
}
};
//+------------------------------------------------------------------+
//| Implementation bodies. |
//+------------------------------------------------------------------+
#include "Impl\NeuronBase.mqh"
#include "Impl\NeuronConvPool.mqh"
#include "Impl\NeuronLSTM.mqh"
#include "Impl\Layer.mqh"
#include "Impl\NetBuild.mqh"
#include "Impl\NetForward.mqh"
#include "Impl\NetPersistence.mqh"
#include "Impl\NetWeights.mqh"
#include "Impl\NeuronOCLBase.mqh"
#include "Impl\NeuronOCLLSTM.mqh"
//+------------------------------------------------------------------+