function [dZ, dZdT] = internal_l2lossBackward(dZ, X, T, weights, mask, normFactor)
% This function is undocumented and will change in a future release.

%   Copyright 2021-2023 The MathWorks, Inc.

if ~isreal(dZ)
    error(message('deep:dlarray:ComplexGradientOutput', 'l2loss'));
end

if isempty(normFactor)
    % Assign normalization factor of 1 for 'Reduction' value 'none'.
    normFactor = 1;
end

normFactor = 2./normFactor;
dZ = dZ.*weights.*(X - T).*normFactor;
dZ = internal_mask(dZ, mask);

if nargout > 1
    dZdT = -dZ;
end

end