Why is trainlm in train is extremely faster than lm in trainnet options

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

@天钾. 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.
However, I was not using trainlm in deep learning. It was used exactly in feedforwardnet([8,8,8,8,8,8,8,8]). I am trying to use lm in deeplearning with trainingOptions, however the default implement is still to slow.
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))
ans = 9×1 string array
"tansig" "tansig" "tansig" "tansig" "tansig" "tansig" "tansig" "tansig" "purelin"
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.
I am actually discussing about calculation speed instead of converging speed. With changing activation function into tanhLayer, while feedforwardnet having run 20+ iters, dlnet only ran less than 10 iters
Matt J
Matt J on 8 Oct 2026 at 13:32
Edited: Matt J on 8 Oct 2026 at 13:36
Fair enough, but the difference in architecture affects not only convergence speed. It also affects time per iteration. The operations needed to compute the Jacobian in each iteration will be different.

Sign in to comment.

 Accepted Answer

Matt J
Matt J on 8 Oct 2026 at 13:29
Edited: Matt J on 9 Oct 2026 at 11:56
I suspect that trainnet does not explicitly compute the Jacobian J and J.'*J the way trainlm does. There are memory-conserving versions of LM that use forward and backpropagation passes to compute matrix-vector products J.'*J*v, but avoid explicitly constructing J. When LM is implemented this way, it needs to run some number of sub-iterations of the conjugate gradient algorithm in every iteration to solve he update equations,
and that can slow things down. It is plausible to me that trainnet would take this approach, however, because it was designed for larger problems, and has good reason to prioritize RAM conservation.

1 Comment

Matt J
Matt J on 8 Oct 2026 at 17:51
Edited: Matt J on 8 Oct 2026 at 17:55
If you want to train dlnetworks with LM in a way that gives you control over how the Jacobian is handled, you can use lsqnonlin's LM implementation. Here you would select SpecifyObjectiveGradient=true and use dljacobian to implement the Jacobian computation in whatever way you see fit.

Sign in to comment.

More Answers (1)

Torsten
Torsten on 8 Oct 2026 at 11:00
Moved: Torsten on 8 Oct 2026 at 11:02
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.

3 Comments

However, In the full training project, 8192000 samples are piplined in GPU, and actually GPU usage is nearly full as is shown in the figure.
Maybe I have to explain that despite the small size of the net, huge samples makes it possible to fully use pipelines in GPU as lm is a global iteration without discarding any sample as ADAM does. And I am actually using NNs to compress vedios, smaller networks means better effect. Since the whole vedio is extracted as this network.
Torsten
Torsten on 8 Oct 2026 at 13:33
Edited: Torsten on 8 Oct 2026 at 13:38
If you have doubts, contact MATLAB support:
The developers team should know best how to explain the difference in speed and what to do for a speed-up.

Sign in to comment.

Products

Release

R2025b

Asked:

on 8 Oct 2026 at 7:10

Edited:

on 9 Oct 2026 at 11:56

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!