NoJobEngine 2.0.7
Loading...
Searching...
No Matches
NeuralAgentTraining.h
Go to the documentation of this file.
1
6#pragma once
9#include <algorithm>
10#include <cmath>
11#include <filesystem>
12#include <mutex>
13#include <string>
14#include <unordered_map>
15#include <vector>
16#include <stdexcept>
17
20struct Snapshot {
21 std::string model, status;
22 std::vector<float> inputs, outputs;
23 std::vector<std::vector<float>> activations;
24 float distance = 0.f;
25};
26inline std::mutex& Mutex() { static std::mutex m; return m; }
27inline std::unordered_map<unsigned int, Snapshot>& Snapshots() { static std::unordered_map<unsigned int, Snapshot> m; return m; }
29inline void Publish(unsigned int entity, Snapshot snapshot) { std::lock_guard<std::mutex> lock(Mutex()); Snapshots()[entity]=std::move(snapshot); }
31inline bool Read(unsigned int entity, Snapshot& out) { std::lock_guard<std::mutex> lock(Mutex()); auto it=Snapshots().find(entity); if(it==Snapshots().end()) return false; out=it->second; return true; }
33inline void Clear(unsigned int entity) { std::lock_guard<std::mutex> lock(Mutex()); Snapshots().erase(entity); }
34inline std::vector<std::vector<float>> Activations(const Neural::NeuralNetwork& net, const std::vector<float>& input) {
35 std::vector<std::vector<float>> result{input}; auto values=input;
36 for(const auto& layer:net.Layers()) {
37 if(values.size()!=layer.Inputs()) throw std::runtime_error("Neural input dimensions mismatch");
38 std::vector<float> next(layer.Outputs());
39 for(size_t i=0;i<layer.Outputs();++i) {
40 float sum=layer.Biases()[i];
41 for(size_t j=0;j<values.size();++j) sum+=layer.Weights()(i,j)*values[j];
42 next[i]=Neural::Activate(sum,layer.Function());
43 }
44 result.push_back(next); values=std::move(next);
45 }
46 return result;
47}
48// Reusable supervised training presets. The agent's active model is never changed
49// by training; source and destination assets are separate and explicit.
51enum class TrainingPreset { FollowXZ = 0, TrackY = 1, Pong = 2 };
52inline const char* PresetLabel(TrainingPreset p) {
53 switch (p) { case TrainingPreset::FollowXZ: return "Follow target (XZ)";
54 case TrainingPreset::TrackY: return "Track target (Y)";
55 default: return "Pong paddle (supervised)"; }
56}
57
66inline Neural::TrainingHistory TrainPreset(const std::string& outputName,
67 const std::string& sourceName, TrainingPreset preset,
68 int epochs, float learningRate, bool resume, bool overwrite) {
69 const auto output = NeuralAssetPath(outputName); // also validates name
70 if (resume && sourceName.empty()) throw std::runtime_error("Select a source model to resume training");
71 if (std::filesystem::exists(output) && !overwrite)
72 throw std::runtime_error("Output already exists. Choose another Save As name or enable Overwrite Output");
74 const size_t nIn = preset == TrainingPreset::FollowXZ ? 2 : (preset == TrainingPreset::TrackY ? 3 : 6);
75 const size_t nOut = preset == TrainingPreset::FollowXZ ? 2 : 1;
76 if (resume) {
77 net = Neural::NeuralNetwork::Load(NeuralAssetPath(sourceName).string());
78 if (net.Layers().empty() || net.Layers().front().Inputs()!=nIn || net.Layers().back().Outputs()!=nOut)
79 throw std::runtime_error("Source model dimensions do not match the selected training preset");
80 } else if (preset == TrainingPreset::FollowXZ) {
83 } else if (preset == TrainingPreset::TrackY) {
86 } else {
90 }
91 std::vector<std::vector<float>> xs, ys;
92 if (preset == TrainingPreset::FollowXZ) {
93 for (int x=-8;x<=8;++x) for (int z=-8;z<=8;++z) {
94 const float dx=x/8.f,dz=z/8.f,len=std::sqrt(dx*dx+dz*dz);
95 xs.push_back({dx,dz});
96 ys.push_back(len>1e-5f?std::vector<float>{dx/len,dz/len}:std::vector<float>{0.f,0.f});
97 }
98 } else if (preset == TrainingPreset::TrackY) {
99 // Inputs: normalized target Y, self Y, relative Y. Output: vertical direction.
100 for(int target=-10;target<=10;++target) for(int self=-10;self<=10;++self) {
101 float t=target/10.f, p=self/10.f, d=t-p;
102 xs.push_back({t,p,std::clamp(d,-1.f,1.f)});
103 ys.push_back({std::clamp(d*3.f,-1.f,1.f)});
104 }
105 } else {
106 // Inputs: ball X/Y, velocity X/Y, paddle Y, horizontal distance.
107 // Labels use a deterministic intercept heuristic, not reinforcement learning.
108 for(int i=0;i<6000;++i) {
109 const float bx=static_cast<float>((i*37)%199-99)/100.f;
110 const float by=static_cast<float>((i*53)%199-99)/100.f;
111 const float vx=static_cast<float>((i*17)%161-80)/100.f;
112 const float vy=static_cast<float>((i*29)%161-80)/100.f;
113 const float py=static_cast<float>((i*71)%199-99)/100.f;
114 const float dx=std::clamp((1.f-bx)*0.5f,0.f,1.f);
115 const float time=vx>0.05f ? std::min(3.f,(1.f-bx)/vx) : 0.f;
116 float intercept=by+vy*time;
117 // Reflect off normalized +/-1 playfield bounds.
118 while(intercept>1.f || intercept< -1.f) {
119 if(intercept>1.f) intercept=2.f-intercept;
120 if(intercept< -1.f) intercept=-2.f-intercept;
121 }
122 xs.push_back({bx,by,vx,vy,py,dx});
123 ys.push_back({std::clamp((intercept-py)*3.f,-1.f,1.f)});
124 }
125 }
127 options.epochs=static_cast<size_t>(std::clamp(epochs,1,20000));
128 options.learningRate=std::clamp(learningRate,0.00001f,0.1f);
129 options.batchSize=16; options.adam=true; options.seed=42;
130 auto history=net.Train(xs,ys,options);
131 std::filesystem::create_directories(output.parent_path());
132 net.Save(output.string());
133 return history;
134}
135// Backward compatible entry point for the original V2.0.6 follow-agent demo.
136inline Neural::TrainingHistory TrainDirectionModel(const std::string& name, int epochs, float learningRate,
137 bool resume=false, bool overwrite=false) {
138 return TrainPreset(name, name, TrainingPreset::FollowXZ, epochs, learningRate, resume, overwrite);
139}
140} // namespace NoJob::NeuralAgent
Path resolution and validation for neural model assets.
Dense neural network inference, training and serialization.
CPU-based feed-forward neural network with native C++ training.
static NeuralNetwork Load(const std::string &path)
Loads a serialized network.
void Save(const std::string &path) const
Serializes the network to a model asset.
const std::vector< DenseLayer > & Layers() const
void AddDense(size_t inputs, size_t outputs, Activation activation)
Appends a dense layer to the network.
TrainingHistory Train(const std::vector< std::vector< float > > &inputs, const std::vector< std::vector< float > > &targets, const TrainingOptions &options={}, const std::function< bool(size_t, float)> &onEpoch={})
Trains on paired input and target samples.
std::vector< std::vector< float > > Activations(const Neural::NeuralNetwork &net, const std::vector< float > &input)
const char * PresetLabel(TrainingPreset p)
void Clear(unsigned int entity)
Removes diagnostics when an agent is destroyed or reset.
bool Read(unsigned int entity, Snapshot &out)
Copies the latest snapshot, if one exists for the entity.
TrainingPreset
Supported supervised training datasets and target mappings.
std::unordered_map< unsigned int, Snapshot > & Snapshots()
Neural::TrainingHistory TrainDirectionModel(const std::string &name, int epochs, float learningRate, bool resume=false, bool overwrite=false)
void Publish(unsigned int entity, Snapshot snapshot)
Publishes an entity snapshot for live AI debugging.
Neural::TrainingHistory TrainPreset(const std::string &outputName, const std::string &sourceName, TrainingPreset preset, int epochs, float learningRate, bool resume, bool overwrite)
Trains a preset model and saves it independently of the active model.
float Activate(float x, Activation a)
std::filesystem::path NeuralAssetPath(const std::string &name)
Per-epoch loss values returned by a training run.
Parameters controlling supervised neural network optimization.
A copy of neural agent inference state for editor diagnostics.
std::vector< std::vector< float > > activations