NoJobEngine 2.0.7
Loading...
Searching...
No Matches
NeuralEditorPanel.cpp
Go to the documentation of this file.
1#include "NeuralEditorPanel.h"
3#include <fstream>
4#include <imgui.h>
5#include <algorithm>
6#include <cmath>
7#include <cstdio>
8#include <cstring>
9#include <filesystem>
10#include <stdexcept>
11#include <utility>
12
13namespace NoJob {
14namespace {
15constexpr const char* kActivationNames[] = {"Linear", "ReLU", "Sigmoid", "Tanh"};
16const std::vector<std::vector<float>> kX = {{0,0},{0,1},{1,0},{1,1}};
17const std::vector<std::vector<float>> kY = {{0},{1},{1},{0}};
18void CopyError(char (&out)[512], const std::string& text) { std::snprintf(out, sizeof(out), "%s", text.c_str()); }
19}
22void NeuralEditorPanel::StopTraining() { cancel_ = true; if(worker_.joinable()) worker_.join(); running_ = false; }
23void NeuralEditorPanel::FinishWorker() {
24 if(running_) return;
25 if(worker_.joinable()) worker_.join();
26 std::lock_guard<std::mutex> lock(workerMutex_);
27 if(resultReady_) { network_ = std::move(trained_); resultReady_ = false; dirty_=true; }
28 if(!workerError_.empty()) { CopyError(error_, workerError_); workerError_.clear(); }
29}
30void NeuralEditorPanel::Build() {
31 if(running_) return;
32 try {
33 if(widths_.size()<2 || widths_.size()!=activations_.size()+1) throw std::invalid_argument("Invalid architecture");
34 Neural::NeuralNetwork net(42);
35 for(size_t i=1;i<widths_.size();++i) {
36 if(widths_[i-1]<1 || widths_[i-1]>256 || widths_[i]<1 || widths_[i]>256) throw std::invalid_argument("Neuron count must be 1..256");
37 net.AddDense(static_cast<size_t>(widths_[i-1]), static_cast<size_t>(widths_[i]), static_cast<Neural::Activation>(activations_[i-1]));
38 }
39 network_ = std::move(net); inputs_.assign(widths_.front(), 0.f);
40 ResetTrainingSamples();
41 lastPrediction_.clear(); lastActivations_.clear(); losses_.clear(); error_[0]=0; dirty_=true;
42 } catch(const std::exception& e) { CopyError(error_,e.what()); }
43}
44void NeuralEditorPanel::StartTraining() {
45 if(running_) return;
46 FinishWorker();
47 if(network_.Layers().empty()) { CopyError(error_, "Build a network first"); return; }
48 const size_t in = network_.Layers().front().Inputs(), out = network_.Layers().back().Outputs();
49 if (trainingX_.empty() || trainingX_.size()!=trainingY_.size()) { CopyError(error_, "Add training samples first"); return; }
50 for(size_t i=0;i<trainingX_.size();++i) if(trainingX_[i].size()!=in || trainingY_[i].size()!=out) {
51 CopyError(error_, "Dataset dimensions do not match the active network. Reset dataset after Rebuild."); return;
52 }
53 if(epochs_<1 || batchSize_<1 || learningRate_<=0.f) { CopyError(error_,"Invalid training parameters"); return; }
54 error_[0]=0; cancel_=false; currentEpoch_=0; losses_.clear();
55 Neural::NeuralNetwork copy = network_;
56 const Neural::TrainingOptions opt{static_cast<size_t>(epochs_),static_cast<size_t>(batchSize_),learningRate_,adam_,42};
57 running_=true;
58 const auto samplesX = trainingX_, samplesY = trainingY_;
59 worker_=std::thread([this, net=std::move(copy),opt,samplesX,samplesY]() mutable {
60 try {
61 net.Train(samplesX,samplesY,opt,[this](size_t epoch,float loss) {
62 { std::lock_guard<std::mutex> lock(workerMutex_); losses_.push_back(loss); }
63 currentEpoch_=static_cast<int>(epoch);
64 return !cancel_.load();
65 });
66 if(!cancel_) { std::lock_guard<std::mutex> lock(workerMutex_); trained_=std::move(net); resultReady_=true; }
67 } catch(const std::exception& e) { std::lock_guard<std::mutex> lock(workerMutex_); workerError_=e.what(); }
68 running_=false;
69 });
70}
71void NeuralEditorPanel::DrawGraph() {
72 ImGui::TextUnformatted("Network topology (click a layer to inspect)");
73 ImVec2 canvasSize(ImGui::GetContentRegionAvail().x, 285.f);
74 if(canvasSize.x<200.f) canvasSize.x=200.f;
75 ImGui::InvisibleButton("##neural_canvas",canvasSize);
76 const ImVec2 origin=ImGui::GetItemRectMin();
77 auto* draw=ImGui::GetWindowDrawList();
78 if(network_.Layers().empty()) { ImGui::TextDisabled("No network available"); return; }
79 // Always render the active network, not uncommitted architecture edits.
80 std::vector<int> graphWidths{static_cast<int>(network_.Layers().front().Inputs())};
81 for(const auto& layer : network_.Layers()) graphWidths.push_back(static_cast<int>(layer.Outputs()));
82 if(graphWidths != widths_) ImGui::TextDisabled("Unsaved architecture edits: click Rebuild network to apply");
83 const float dx=canvasSize.x/static_cast<float>(graphWidths.size()+1);
84 const float centerY=origin.y+canvasSize.y*.5f;
85 auto pos=[&](size_t layer,int neuron) { const int count=std::min(graphWidths[layer],12);return ImVec2(origin.x+dx*(layer+1),centerY+(neuron-(count-1)*.5f)*std::min(26.f,245.f/std::max(1,count))); };
86 for(size_t l=1;l<graphWidths.size();++l) {
87 const auto& w=network_.Layers()[l-1].Weights();
88 const int prev=std::min(graphWidths[l-1],12),curr=std::min(graphWidths[l],12);
89 for(int j=0;j<curr;++j)for(int i=0;i<prev;++i) {
90 float weight=w(static_cast<size_t>(j),static_cast<size_t>(i));
91 ImU32 col=weight>=0?IM_COL32(80,190,135,125):IM_COL32(235,105,100,125);
92 draw->AddLine(pos(l-1,i),pos(l,j),col,std::clamp(std::abs(weight),.6f,3.5f));
93 }
94 }
95 for(size_t l=0;l<graphWidths.size();++l) {
96 int count=std::min(graphWidths[l],12);
97 for(int j=0;j<count;++j) {
98 ImVec2 p=pos(l,j);
99 float a=0.f;
100 if(l<lastActivations_.size() && j<static_cast<int>(lastActivations_[l].size())) a=lastActivations_[l][j];
101 const int intensity=static_cast<int>(std::clamp((a+1.f)*.5f,0.f,1.f)*140.f);
102 draw->AddCircleFilled(p,8.f,IM_COL32(60+intensity,110+intensity/2,205,255));
103 draw->AddCircle(p,8.f,l>0 && selectedLayer_==static_cast<int>(l-1)?IM_COL32(255,215,90,255):IM_COL32(215,220,235,255),0,1.5f);
104 }
105 char title[48];std::snprintf(title,sizeof(title),"%s (%d)",l==0?"Input":(l+1==graphWidths.size()?"Output":"Hidden"),graphWidths[l]);
106 draw->AddText(ImVec2(origin.x+dx*(l+1)-35.f,origin.y+8.f),IM_COL32(215,220,235,255),title);
107 if(l>0 && ImGui::IsItemHovered() && ImGui::IsMouseClicked(0)) {
108 ImVec2 mouse=ImGui::GetMousePos();if(std::abs(mouse.x-(origin.x+dx*(l+1)))<dx*.35f) selectedLayer_=static_cast<int>(l-1);
109 }
110 }
111 ImGui::TextDisabled("Green: positive weight | Red: negative weight | Thickness: magnitude | Max 12 visible neurons per layer");
112}
113void NeuralEditorPanel::DrawInspector() {
114 if(ImGui::CollapsingHeader("Architecture / Layer Editor",ImGuiTreeNodeFlags_DefaultOpen)) {
115 ImGui::BeginDisabled(running_);
116 ImGui::InputInt("Input neurons",&widths_[0]); widths_[0]=std::clamp(widths_[0],1,256);
117 for(size_t l=1;l<widths_.size();++l) {
118 ImGui::PushID(static_cast<int>(l));ImGui::Separator();
119 ImGui::Text("Layer %d",static_cast<int>(l));ImGui::SameLine();
120 if(widths_.size()>2 && ImGui::SmallButton("Remove")) { widths_.erase(widths_.begin()+static_cast<std::ptrdiff_t>(l)); activations_.erase(activations_.begin()+static_cast<std::ptrdiff_t>(l-1)); ImGui::PopID(); break; }
121 ImGui::InputInt("Neurons",&widths_[l]);widths_[l]=std::clamp(widths_[l],1,256);
122 ImGui::Combo("Activation",&activations_[l-1],kActivationNames,4);
123 ImGui::PopID();
124 }
125 if(widths_.size()<12 && ImGui::Button("Add hidden layer")) { widths_.insert(widths_.end()-1,4);activations_.insert(activations_.end()-1,3); }
126 ImGui::SameLine();if(ImGui::Button("Rebuild network")) Build();
127 ImGui::EndDisabled();
128 ImGui::TextDisabled("Architecture edits take effect after Rebuild (resets weights).");
129 }
130 if(ImGui::CollapsingHeader("Selected Layer / Weights",ImGuiTreeNodeFlags_DefaultOpen) && !network_.Layers().empty()) {
131 selectedLayer_=std::clamp(selectedLayer_,0,static_cast<int>(network_.Layers().size()-1));
132 ImGui::SliderInt("Inspect layer",&selectedLayer_,0,static_cast<int>(network_.Layers().size()-1));
133 auto& layer=network_.Layers()[selectedLayer_];
134 ImGui::Text("Dense: %zu -> %zu | %s",layer.Inputs(),layer.Outputs(),kActivationNames[static_cast<int>(layer.Function())]);
135 ImGui::BeginChild("##weight_table",ImVec2(0,170),true);
136 const int rows=static_cast<int>(std::min<size_t>(layer.Outputs(),16)),cols=static_cast<int>(std::min<size_t>(layer.Inputs(),12));
137 if(ImGui::BeginTable("Weights",cols+2,ImGuiTableFlags_Borders|ImGuiTableFlags_ScrollX)) {
138 ImGui::TableSetupColumn("Neuron");for(int i=0;i<cols;++i) {char label[24];std::snprintf(label,sizeof(label),"w%d",i);ImGui::TableSetupColumn(label);}
139 ImGui::TableSetupColumn("Bias");ImGui::TableHeadersRow();
140 for(int r=0;r<rows;++r) {ImGui::TableNextRow();ImGui::TableSetColumnIndex(0);ImGui::Text("%d",r);
141 for(int c=0;c<cols;++c){ImGui::TableSetColumnIndex(c+1);ImGui::Text("%.3f",layer.Weights()(r,c));}
142 ImGui::TableSetColumnIndex(cols+1);ImGui::Text("%.3f",layer.Biases()[r]);}
143 ImGui::EndTable();
144 }
145 ImGui::EndChild();
146 if(layer.Inputs()>12 || layer.Outputs()>16) ImGui::TextDisabled("Weight preview truncated for large layers.");
147 }
148}
149void NeuralEditorPanel::ResetTrainingSamples() {
150 trainingX_.clear(); trainingY_.clear();
151 if(network_.Layers().empty()) return;
152 const size_t in = network_.Layers().front().Inputs(), out = network_.Layers().back().Outputs();
153 if(in==2 && out==1) { trainingX_=kX; trainingY_=kY; }
154 else { trainingX_.push_back(std::vector<float>(in,0.f)); trainingY_.push_back(std::vector<float>(out,0.f)); }
155}
156void NeuralEditorPanel::DrawTraining() {
157 if(!ImGui::CollapsingHeader("Native Training / Loss",ImGuiTreeNodeFlags_DefaultOpen))return;
158 ImGui::BeginDisabled(running_);
159 ImGui::InputInt("Epochs",&epochs_);epochs_=std::clamp(epochs_,1,1000000);
160 ImGui::InputInt("Batch size",&batchSize_);batchSize_=std::clamp(batchSize_,1,4096);
161 ImGui::InputFloat("Learning rate",&learningRate_,0.001f,0.01f,"%.5f");
162 ImGui::Checkbox("Adam optimizer",&adam_);
163 const size_t in = network_.Layers().empty()?0:network_.Layers().front().Inputs();
164 const size_t out = network_.Layers().empty()?0:network_.Layers().back().Outputs();
165 ImGui::Text("Training dataset: %zu samples | %zu inputs -> %zu outputs",trainingX_.size(),in,out);
166 if(ImGui::Button("Add sample") && in && out && trainingX_.size()<4096) {
167 trainingX_.push_back(std::vector<float>(in,0.f)); trainingY_.push_back(std::vector<float>(out,0.f));
168 }
169 ImGui::SameLine();
170 if(ImGui::Button("Reset dataset")) ResetTrainingSamples();
171 if(in==2 && out==1) { ImGui::SameLine(); if(ImGui::Button("Load XOR samples")) {trainingX_=kX;trainingY_=kY;} }
172 ImGui::BeginChild("##training_samples",ImVec2(0,185),true);
173 for(size_t row=0;row<trainingX_.size();++row) {
174 ImGui::PushID(static_cast<int>(row));
175 ImGui::Separator(); ImGui::Text("Sample %zu",row+1); ImGui::SameLine();
176 if(ImGui::SmallButton("Delete") && trainingX_.size()>1) {
177 trainingX_.erase(trainingX_.begin()+static_cast<std::ptrdiff_t>(row));
178 trainingY_.erase(trainingY_.begin()+static_cast<std::ptrdiff_t>(row));
179 ImGui::PopID(); break;
180 }
181 for(size_t i=0;i<trainingX_[row].size();++i) {
182 ImGui::PushID(static_cast<int>(i)); ImGui::SetNextItemWidth(90);
183 ImGui::InputFloat("Input",&trainingX_[row][i],0,0,"%.3f");
184 if(i+1<trainingX_[row].size()) ImGui::SameLine(); ImGui::PopID();
185 }
186 for(size_t i=0;i<trainingY_[row].size();++i) {
187 ImGui::PushID(static_cast<int>(i)); ImGui::SetNextItemWidth(90);
188 ImGui::InputFloat("Target",&trainingY_[row][i],0,0,"%.3f");
189 if(i+1<trainingY_[row].size()) ImGui::SameLine(); ImGui::PopID();
190 }
191 ImGui::PopID();
192 }
193 ImGui::EndChild();
194 if(ImGui::Button("Train dataset")) StartTraining();
195 ImGui::EndDisabled();
196 if(running_) {ImGui::SameLine();if(ImGui::Button("Stop")) cancel_=true;}
197 ImGui::ProgressBar(epochs_?static_cast<float>(currentEpoch_.load())/epochs_:0.f,ImVec2(-1,0));
198 std::vector<float> snapshot; {std::lock_guard<std::mutex> lock(workerMutex_);snapshot=losses_;}
199 if(!snapshot.empty()) {
200 const float maxLoss=std::max(.01f,*std::max_element(snapshot.begin(),snapshot.end()));
201 ImGui::PlotLines("MSE",snapshot.data(),static_cast<int>(snapshot.size()),0,nullptr,0.f,maxLoss,ImVec2(-1,130));
202 ImGui::Text("Epoch %d / %d | MSE %.8f",currentEpoch_.load(),epochs_,snapshot.back());
203 }
204 ImGui::TextDisabled("XOR is an optional 2-input/1-output demo; other architectures use editable training samples.");
205}
206void NeuralEditorPanel::DrawPredictions() {
207 if(!ImGui::CollapsingHeader("Neural Inspector / Inference",ImGuiTreeNodeFlags_DefaultOpen))return;
208 if(inputs_.size()!=network_.Layers().front().Inputs()) inputs_.assign(network_.Layers().front().Inputs(),0.f);
209 for(size_t i=0;i<inputs_.size() && i<16;++i){ImGui::PushID(static_cast<int>(i));char label[32];std::snprintf(label,sizeof(label),"Input %zu",i);ImGui::InputFloat(label,&inputs_[i]);ImGui::PopID();}
210 if(inputs_.size()>16) ImGui::TextDisabled("Showing first 16 inputs; others are zero.");
211 if(ImGui::Button("Run inference")) {
212 try {lastActivations_.clear();lastActivations_.push_back(inputs_);auto value=inputs_;
213 for(const auto& layer:network_.Layers()){value=layer.Forward(value);lastActivations_.push_back(value);}
214 lastPrediction_=value;error_[0]=0;
215 } catch(const std::exception& e){CopyError(error_,e.what());}
216 }
217 for(size_t i=0;i<lastPrediction_.size();++i)ImGui::Text("Output %zu: %.6f",i,lastPrediction_[i]);
218 for(size_t l=0;l<lastActivations_.size();++l) {
219 if(ImGui::TreeNode(reinterpret_cast<void*>(static_cast<uintptr_t>(l+1)),"Layer %zu activations",l)) {
220 for(size_t j=0;j<lastActivations_[l].size() && j<32;++j)ImGui::Text("Neuron %zu: %.5f",j,lastActivations_[l][j]);
221 ImGui::TreePop();
222 }
223 }
224 if(network_.Layers().front().Inputs()==2 && network_.Layers().back().Outputs()==1) {
225 if(ImGui::BeginTable("XOR results",3,ImGuiTableFlags_Borders|ImGuiTableFlags_RowBg)) {
226 ImGui::TableSetupColumn("Input");ImGui::TableSetupColumn("Expected");ImGui::TableSetupColumn("Predicted");ImGui::TableHeadersRow();
227 for(size_t i=0;i<kX.size();++i){const auto pred=network_.Predict(kX[i]);ImGui::TableNextRow();ImGui::TableNextColumn();ImGui::Text("%.0f, %.0f",kX[i][0],kX[i][1]);ImGui::TableNextColumn();ImGui::Text("%.0f",kY[i][0]);ImGui::TableNextColumn();ImGui::Text("%.5f",pred[0]);}
228 ImGui::EndTable();
229 }
230 }
231}
232void NeuralEditorPanel::RememberAsset(const std::string& name) const {
233 std::error_code ec;
234 std::filesystem::create_directories(NeuralAssetDirectory(), ec);
235 if (ec) return;
236 std::ofstream out(NeuralAssetDirectory() / ".last-opened-neural", std::ios::trunc);
237 if (out) out << name << '\n';
238}
239void NeuralEditorPanel::LoadNamed(const std::string& name) {
240 if (running_) throw std::runtime_error("Stop training before loading another network");
241 auto loaded = Neural::NeuralNetwork::Load(NeuralAssetPath(name).string());
242 if (loaded.Layers().empty()) throw std::runtime_error("Neural asset has no layers");
243 std::vector<int> widths;
244 std::vector<int> activations;
245 widths.push_back(static_cast<int>(loaded.Layers().front().Inputs()));
246 for (const auto& layer : loaded.Layers()) {
247 widths.push_back(static_cast<int>(layer.Outputs()));
248 activations.push_back(static_cast<int>(layer.Function()));
249 }
250 FinishWorker();
251 network_ = std::move(loaded);
252 widths_ = std::move(widths);
253 activations_ = std::move(activations);
254 inputs_.assign(widths_.front(), 0.f);
255 ResetTrainingSamples();
256 selectedLayer_ = 0;
257 losses_.clear(); lastActivations_.clear(); lastPrediction_.clear();
258 currentName_ = name;
259 std::snprintf(assetName_, sizeof(assetName_), "%s", name.c_str());
260 dirty_ = false;
261 error_[0] = 0;
262 RememberAsset(name);
263 assetMessage_ = "Loaded " + NeuralAssetPath(name).string();
264}
265void NeuralEditorPanel::SaveNamed(const std::string& name, bool saveAs) {
266 if (running_) throw std::runtime_error("Stop training before saving");
267 if (network_.Layers().size()+1 != widths_.size()) throw std::runtime_error("Rebuild network before saving architecture changes");
268 for(size_t i=1;i<widths_.size();++i)
269 if(network_.Layers()[i-1].Inputs()!=static_cast<size_t>(widths_[i-1]) ||
270 network_.Layers()[i-1].Outputs()!=static_cast<size_t>(widths_[i]) ||
271 static_cast<int>(network_.Layers()[i-1].Function())!=activations_[i-1])
272 throw std::runtime_error("Rebuild network before saving architecture changes");
273 const auto path = NeuralAssetPath(name); // validates the name
274 if (saveAs && name != currentName_ && std::filesystem::exists(path))
275 throw std::runtime_error("A neural network with that name already exists");
276 std::filesystem::create_directories(path.parent_path());
277 network_.Save(path.string());
278 currentName_ = name;
279 std::snprintf(assetName_, sizeof(assetName_), "%s", name.c_str());
280 dirty_ = false;
281 error_[0] = 0;
282 RememberAsset(name);
283 assetMessage_ = "Saved " + path.string();
284}
285void NeuralEditorPanel::RestoreLastAsset() {
286 if (restoreAttempted_) return;
287 restoreAttempted_ = true;
288 const auto available = ListNeuralAssetNames();
289 std::string preferred;
290 { std::ifstream in(NeuralAssetDirectory() / ".last-opened-neural"); std::getline(in, preferred); }
291 if (std::find(available.begin(), available.end(), preferred) == available.end())
292 preferred = available.empty() ? std::string{} : available.front();
293 if (!preferred.empty()) {
294 try { LoadNamed(preferred); }
295 catch (const std::exception& e) { assetMessage_ = e.what(); }
296 }
297}
299 FinishWorker();
300 if(!open_)return;
301 RestoreLastAsset();
302 if(!ImGui::Begin("Neural Network Editor & Inspector",&open_)) {ImGui::End();return;}
303 ImGui::TextUnformatted("NoJobEngine V2.0.4 / V2.0.5 | Native C++ neural networks");
304 ImGui::Separator();
305 ImGui::Text("Current asset: %s%s", currentName_.c_str(), dirty_ ? " *" : "");
306 ImGui::BeginDisabled(running_);
307 const auto available = ListNeuralAssetNames();
308 if (ImGui::BeginCombo("Saved networks", currentName_.c_str())) {
309 for (const auto& name : available) {
310 if (ImGui::Selectable(name.c_str(), name == currentName_)) {
311 try { LoadNamed(name); } catch(const std::exception& e) { CopyError(error_, e.what()); }
312 }
313 }
314 ImGui::EndCombo();
315 }
316 ImGui::InputText("Network name", assetName_, sizeof(assetName_));
317 if (ImGui::Button("Load")) {
318 try { LoadNamed(assetName_); } catch(const std::exception& e) { CopyError(error_, e.what()); }
319 }
320 ImGui::SameLine();
321 if (ImGui::Button("Save")) {
322 try { SaveNamed(currentName_, false); } catch(const std::exception& e) { CopyError(error_, e.what()); }
323 }
324 ImGui::SameLine();
325 if (ImGui::Button("Save As")) {
326 try { SaveNamed(assetName_, true); } catch(const std::exception& e) { CopyError(error_, e.what()); }
327 }
328 ImGui::SameLine();
329 if (ImGui::Button("New")) {
330 widths_ = {2,4,1}; activations_ = {3,2};
331 currentName_ = "Untitled";
332 std::snprintf(assetName_, sizeof(assetName_), "%s", currentName_.c_str());
333 Build(); dirty_ = true;
334 assetMessage_ = "New network. Enter a name and click Save As.";
335 }
336 ImGui::EndDisabled();
337 if (!assetMessage_.empty()) ImGui::TextWrapped("%s", assetMessage_.c_str());
338 if(error_[0]) ImGui::TextColored(ImVec4(1.f,.45f,.4f,1.f),"%s",error_);
339 DrawGraph();
340 if(ImGui::BeginTabBar("NeuralTabs")) {
341 if(ImGui::BeginTabItem("Architecture & Weights")){DrawInspector();ImGui::EndTabItem();}
342 if(ImGui::BeginTabItem("Training")){DrawTraining();ImGui::EndTabItem();}
343 if(ImGui::BeginTabItem("Inference & Activations")){DrawPredictions();ImGui::EndTabItem();}
344 ImGui::EndTabBar();
345 }
346 ImGui::End();
347}
348}
Path resolution and validation for neural model assets.
NeuralEditorPanel declarations for the Editor Panels subsystem.
static NeuralNetwork Load(const std::string &path)
Loads a serialized network.
std::filesystem::path NeuralAssetDirectory()
std::vector< std::string > ListNeuralAssetNames()
std::filesystem::path NeuralAssetPath(const std::string &name)