Why is trainlm in train is extremely faster than lm in trainnet options
Show older comments


Even if I had fully make use of RTX 4070-Ti with trainnet option 'lm', In the same network, it is still much slower than that of 'trainlm' in train. They shared the same TRAIN_DATA and C_OUT_RENORMALIZED as input and output.
NN=feedforwardnet([8,8,8,8,8,8,8,8]);
NN.trainParam.epochs=10000;
NN.trainParam.max_fail=10000;
NN.divideParam.testRatio=0;
NN.divideParam.valRatio=0;
NN.divideParam.trainRatio=1;
NN.trainParam.mu_max=10^300;
NN.trainParam.min_grad=1e-16;
NN=train(NN,TRAIN_DATA',C_OUT_RENORMALIZED');
save('.\results\002\NN_TRAINLM.mat','NN');
net = dlnetwork;
tempNet = [
featureInputLayer(3)
fullyConnectedLayer(8)
reluLayer()
fullyConnectedLayer(8)
reluLayer()
fullyConnectedLayer(8)
reluLayer()
fullyConnectedLayer(8)
reluLayer()
fullyConnectedLayer(8)
reluLayer()
fullyConnectedLayer(8)
reluLayer()
fullyConnectedLayer(8)
reluLayer()
fullyConnectedLayer(8)
reluLayer()
fullyConnectedLayer(1)];
net = addLayers(net,tempNet);
clear tempNet;
net = initialize(net);
options = trainingOptions("lm",ExecutionEnvironment="gpu", ...
GradientTolerance=1e-16,MaxIterations=3000,...
StepTolerance=1e-24,Verbose=true, ...
VerboseFrequency=10,Plots="none");
net = trainnet(TRAIN_DATA,C_OUT_RENORMALIZED,net,"mse",options);
However, with following printed results of 'lm' on gpu
>> COMPRESS_DNN_LM
Iteration TimeElapsed TrainingLoss GradientNorm StepNorm
_________ ___________ ____________ ____________ ________
10 00:19:43 0.00052696 2.2258e-05 1.3158e-05
which means that it takes nearly 20 minutes to run 10 iters,and trainlm in train takes much lesser
Matt J Added:


Notes:
轮=epoches,
历时=time cost
性能=trainloss,
梯度=gradient
验证检查=valid check
5 Comments
Chuguang Pan
on 8 Oct 2026 at 8:30
@天钾. trainlm is not recommended for deep learning workflow. dlnetwork and trainnet offer these advantages as illustrated in Transition Legacy Neural Network Code to dlnetwork Workflows.
天钾
on 8 Oct 2026 at 8:43
The network architectures in the two cases are not equivalent. By default, feedforwardnet uses tansig activations for hidden layers Conversely, your dlnetwork uses ReLUs.
NN=feedforwardnet([8,8,8,8,8,8,8,8]);
string(cellfun(@(L)L.transferFcn, ...
NN.layers,'UniformOutput',false))
The expected performance of LM is unclear when you have ReLUs, because LM assumes a continuously differentiable residual. Further, LM uses a local quadratic approximation in its update, which is invalid near ReLU kinks.
天钾
on 8 Oct 2026 at 13:25
Accepted Answer
More Answers (1)
Answer from AI:
The massive speed difference you are experiencing is due to a fundamental mismatch between the network size, the underlying data precision requirements, and how the GPU handles communication overhead.
While the RTX 4070-Ti is an incredibly powerful graphics card, the classic trainlm (with train) runs significantly faster than lm (with trainnet) for this specific configuration due to three key architectural reasons:
1. Massive GPU Overhead on a Tiny Network
Your architecture ([8,8,8,8,8,8,8,8]) with only 3 inputs and 1 output is extremely small.
- train / trainlm: This is the legacy, highly optimized CPU/RAM-based engine. Because the network is small, the entire Levenberg-Marquardt (LM) matrix formulation, Jacobian calculation, and matrix inversion fit seamlessly into your CPU's fast cache layers. There is virtually zero overhead. [1, 2]
- trainnet / lm on GPU: For every iteration, the GPU has to spawn thousands of parallel threads. However, because each layer only has 8 neurons, the GPU cannot saturate its streaming multiprocessors. You end up spending far more time on kernel launch overhead and data transfer across the PCIe bus than on actual computation. [1]
2. Double vs. Single Precision (The RTX Bottleneck)
The Levenberg-Marquardt algorithm requires extreme numerical precision because it explicitly calculates and inverts a massive Hessian approximation matrix (\(J^TJ + \mu I\)).
- train defaults to 64-bit Double Precision (double). CPUs handle double-precision math natively at full speed.
- trainnet is designed for modern deep learning and heavily relies on 32-bit Single Precision (single) or mixed-precision to leverage GPU cores efficiently. [1]
- The Catch: Because you explicitly set an extreme StepTolerance of 1e-24 and GradientTolerance of 1e-16, the GPU engine is forced to fall back to FP64 (Double Precision) calculations to prevent underflow. Consumer GPUs like the RTX 4070-Ti have severely throttled FP64 performance (typically 1:64 or 1:32 of its FP32 speed). Your GPU is choking on the math constraints you provided. [1]
3. Different Codebase Optimization
- trainlm is an older, mature codebase built in pure C/C++ compiled specifically to execute flat matrix calculations. It treats your multi-layer network as a single unrolled sequence of algebraic weights. [1]
- trainnet handles objects through the dlnetwork framework. It passes variables through structural layers (fullyConnectedLayer, reluLayer), tracking execution graphs dynamically for automatic differentiation. For a massive Deep Learning model (like a CNN or transformer), trainnet is faster; for an 8-neuron MLP, the tracking overhead dominates the runtime. [1, 2, 3]
Summary Comparison
Feature Legacy train (trainlm) Modern trainnet (lm)
Execution Target Optimized for CPU / RAM Cache Optimized for massive GPUs (FP32)
Ideal Network Size Small to Medium (Fewer than 1,000 Large to Massive (Millions of weights)
weights)
FP64 Performance Excellent (Native CPU capability) Very Slow on consumer cards (RTX 4070-Ti)
Framework Overhead Flat matrix calculations (minimal) Dynamic execution graphs (dlnetwork)
Recommendation
If your network is going to remain this small, stick to train with trainlm on the CPU. It will comfortably beat any modern GPU framework for micro-networks. [1, 2]
If you plan to scale up your network to hundreds or thousands of hidden units, you can keep using trainnet but change the ExecutionEnvironment to "cpu" or use a first-order stochastic solver like "adam" which utilizes the GPU's FP32 cores efficiently.
Categories
Find more on Define Shallow Neural Network Architectures in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!