skip to content
← Scientific Spaces English

Brute-Force Aesthetics in Matrix Function Approximation

Previously, in "Efficient Computation of Matrix Square Roots and Inverse Square Roots" and "Efficient Computation of Matrix r-th Roots and Inverse r-th Roots", we explored the efficient computation of matrix powers, which extended the Newton-Schulz iteration originally used to compute to matrix powers. Meanwhile, a paper recently posted on arXiv, 《Muonp: Muon with Fractional Spectral Powers》, provides another line of thought for constructing iterations to compute matrix powers, which also gave me some inspiration.

However, whether looking at my own ideas or Muonp's approach, broadly speaking, both are "usable, but not general enough"—for instance, they can only be used to compute rational matrix powers, and their complexity grows as the numerator and denominator of the irreducible fraction increase, which is clearly not scientific enough. To overcome these shortcomings, this article proposes a general approximation framework that can theoretically fit arbitrary matrix functions.

Two Types of Functions #

When it comes to matrix functions, they actually carry two slightly different meanings; here is a brief introduction.

The first type consists of matrix functions that operate on eigenvalues (EIG-type). Let matrix have the eigenvalue decomposition , then we define , where means applying elementwise to the diagonal. This is actually what we usually refer to as matrix functions; for instance, the matrix exponential and the matrix logarithm both belong to this category, and they are typically defined via power series.

The second type consists of matrix functions that operate on singular values (SVD-type). Let matrix have the singular value decomposition , then we define . Muon's operation, and—as we discussed in "Computing Singular Value Clipping mclip via msign (Part 1)" and "Computing Singular Value Clipping mclip via msign (Part 2)"—the operation both belong to this category.

EIG-type matrix functions are defined only for square matrices, and the existence of the eigenvalue decomposition is guaranteed only over the complex field, so the definition of usually also needs to be extended to complex numbers (unless the input matrix is restricted to real symmetric matrices); SVD-type matrix functions can be defined for matrices of any shape, any real matrix has a singular value decomposition over the reals, and singular values are always non-negative. These properties make the definition and analysis of SVD-type matrix functions relatively simpler.

These two classes of matrix functions each have their own application scenarios, and there is no fundamental difference in their computational difficulty, but they differ in computational details. When it comes to powers, any positive integer power of eigenvalues can be computed directly, but for singular values we can only efficiently compute odd powers:

That is, coincides with defined via matrix multiplication, whereas relies on for indirect computation. Therefore, when we want to approximate a matrix function with polynomials, EIG-type functions can choose polynomials of arbitrary degree, while SVD-type functions can only choose odd-degree polynomials.

Existing Methods #

In this section, we take the SVD-type fractional power as an example to introduce two existing approximation schemes. For simplicity, assume that has all its singular values in .

The first line of thought is to use the identity , and then substitute the results from "Efficient Computation of Matrix r-th Roots and Inverse r-th Roots" to obtain

Ultimately, we will have . Note that iterates independently. The principle of this scheme is to choose appropriate such that , and then the cumulative product of the separated can converge to . Its main problem is that it requires first explicitly computing , which squares the condition number, causing the computational precision to drop accordingly.

The second line of thought comes from 《Muonp: Muon with Fractional Spectral Powers》, which views the computation of as solving the equation for its root. In that case, we only need to design an odd-degree polynomial iteration to find the root of this equation, from which we can write down the corresponding matrix iteration. The paper considers the fixed-point iteration

Through a simple analysis, one can prove that the condition guaranteeing convergence for any is ; if taking a fixed value, one can consider . The greatest inspiration this idea gave me is incorporating the input into each step of the iterative process, rather than relying solely on the previous step's result , yet it still leaves many unresolved questions. For example, when the iteration scheme has multiple parameters, how to determine these parameters one by one, and whether different parameters can be chosen at each step to accelerate convergence—the answers to these questions remain unknown.

Aside from this, the two approaches above share a common problem: the computational cost depends heavily on the irreducible fraction form of the desired power. For instance, if we want to compute the -th power, whose irreducible fraction is , then both approaches require us to find a way to compute the -th power of some matrix, which represents a substantial amount of computation. But in reality, and are virtually indistinguishable, so there shouldn't be such a large difference.

Brute-Force Aesthetics #

Therefore, we need a more general framework capable of deriving a usable approximation for any specified matrix function, automatically yielding close results for similar matrix functions, and ideally supporting arbitrary functions beyond power functions in theory. This is the goal of this post.

Without loss of generality, consider an SVD-type matrix function , which maps the singular value to , and we need to construct an odd-degree polynomial iteration to approximate . Assuming that each step depends simultaneously on the current value and the input (in general, we could also consider including in the iteration), and the degree of each step does not exceed 3, then a general iteration scheme can be constructed:

where are the parameters to be determined, with 6 parameters at each step, and they are allowed to take different values at each step to improve the degree of approximation. The idea here is actually very straightforward: include all the terms we can think of without insisting on interpretability, letting the subsequent fitting results determine whether they are useful. While this lacks the elegance of deriving an analytical solution theoretically, it possesses a brute-force aesthetic of general-purpose computation.

Next, how should we solve for ? A naive approach is, like in the previous articles "An Appreciation of the Muon Optimizer: An Essential Leap from Vectors to Matrices" and "Newton-Schulz Iteration for the msign Operator (Part 1)", to first fix a number of iteration steps , so that the entire iteration can be viewed as a model, and then by choosing a regression objective, it can be trained end-to-end using a gradient optimizer.

However, although doing so theoretically offers a chance to obtain a solution closer to the global optimum, in practice one often encounters many difficulties—the nonlinearity and non-convexity of the model after multiple iteration steps, as well as the randomness of initialization, will all noticeably affect performance.

Greedy Strategy #

To stabilize performance, I propose a layer-by-layer greedy strategy—assuming at each step that are already known, we solve for , with the optimization objective

Here, constrains so that its maximum absolute value cannot exceed , avoiding precision loss caused by extreme amplification followed by shrinkage; we can also consider choosing for each a different . is the cost function, for which we have two choices:

where is the singular value interval of interest. Clearly, focuses on the average error, while focuses on the maximum error; as we will see later, under both choices we can obtain exact solutions.

Although a greedy strategy cannot guarantee optimality, it has its own unique advantages. First, Polar Express showed that if (i.e., computing ), then the greedy solution is the optimal solution, which indicates that in certain situations the greedy solution can also be very close to the optimal solution; second, each step of the greedy solution is exact and progressive, ensuring that every step gets closer to the goal. We can precompute sufficiently many , and then truncating to the first few steps as needed will always yield a good approximation.

Finally, because each step of the greedy solution approximates the target, its fluctuations remain controllable, avoiding the phenomenon where one step experiences drastic amplification only to be shrunk in the next step. This is especially important for numerical computation, particularly low-precision computation. We can also continue adding constraints to achieve our desired properties; for example, is a very basic constraint, and more can be added if necessary.

Solving One by One #

The main reason for choosing these two cost functions is that their corresponding optimization problems can both be solved exactly. In what follows, we demonstrate their solution process.

First is , which requires calculating an integral. After we approximate it discretely, it becomes a finite-sample regression problem. Notice that with respect to is linear, so this is merely a linear regression problem, which is exactly solvable! Even if we add some linear constraints on this basis, it is still just a convex quadratic program, which remains exactly solvable and has mature solving tools.

Next is , which requires taking the of the error over the entire interval, which we also approximate through discretization. Next, we can transform it into a linear programming problem via an ingenious transformation: introducing a new variable , we have

If we discretize into points, these samples become a system with unknowns and linear inequality constraints. Under these constraints, we minimize . Solving linear programming is simpler and more mature than quadratic programming, so naturally there is no difficulty.

Being able to transform the case into linear programming is also one of the advantages of the greedy strategy. If we attempt to use gradient-descent-like optimizers to jointly optimize all the , then the 's will be the core obstacle to optimization, because gradients can hardly propagate through effectively, and in addition, the function after multiple iterative steps is already extremely nonlinear, making efforts to seek a global solution rarely succeed. In contrast, through the transformation of "greedy solution + linear programming", we can stably obtain an effective solution.

Reference Implementation #

If we restrict ourselves to NumPy and SciPy, for linear regression with bound constraints, we can use scipy.optimize.lsq_linear to solve it; as for general linear programming, we can use scipy.optimize.linprog to solve it. But considering the generality and simplicity of the code, as well as the possibility of adding custom constraints at any time, we recommend relying on CVXPY and other specialized convex optimization tools.

Below, taking as an example, we provide a reference implementation based on CVXPY:

import numpy as np
import cvxpy as cp

N = 10000  # Number of discretization points
B = 10  # Parameter bound
m = np.linspace(0, 1.01, N)  # The singular value range we care about is 0 to 1, but we consider a slightly larger range during parameter estimation to ensure stability

x, f = m, m**(1 / 3)
coefs = []
for t in range(10):
    A = np.array([x, m, x**3, m**3, x**2 * m, x * m**2]).T
    c = cp.Variable(6)
    objective = cp.Minimize(cp.sum_squares(A @ c - f))  # L2
    # objective = cp.Minimize(cp.max(cp.abs(A @ c - f)))  # L∞
    constraints = [cp.abs(c) <= B]
    problem = cp.Problem(objective, constraints)
    result = problem.solve()
    coefs.append(c.value.round(3))
    x = A @ c.value.round(3)
    print(f'iter {t + 1}, max error:', np.abs(x - f).max())
    print(f'iter {t + 1}, mse error:', np.square(x - f).mean())

coefs = np.array(coefs)

Comparison of Results #

Below, we compare the greedy solution, the greedy solution, and Muonp's fixed step-size iteration on the cube root . All methods start from , with a discretization interval of , parameter bound , and being the total number of iteration steps.

greedy solution with 10 iterations: maximum error approx. , mean squared error approx. ;

greedy solution, 10 iterations: maximum error about , mean squared error about ;

Muonp, 10 iterations: maximum error about , mean squared error about ;

Muonp, 20 iterations: maximum error about , mean squared error about .

The comparison plot is shown below:

Comparison of cube root approximation methods

Comparison of cube root approximation methods

Numerically, greedy solution has a clear advantage in maximum error, with coming second; the fixed-step Muonp scheme at has a worse maximum error than the version of the greedy solution; as can be seen from the figure, the Muonp scheme's underperforming region is mainly near 0, which is because , while balancing the entire interval, is too small near 0; this is the main drawback of a static step size.

By replacing in the code with , we can obtain an approximation of the fifth root with the iteration order unchanged, but if we use the Muonp scheme or my previous -th root algorithm, the iteration order must be increased to at least 5; this demonstrates the generality of the framework in this post.

Some Results #

Below, for computing (), , , and , the greedy solution iteration coefficients are given. All coefficients are rounded to three decimal places, with parameter bound . Among them, the fitting interval for is ; (i.e., constant 1) has a fitting interval of .

The iteration format at each step is

where , assuming that 's singular values have all been normalized to within . Note that and must be computed in the first step and can be saved, while and can be combined into , so although this iteration has six terms, in practice, compared to the Muonp iteration, it only adds one matrix multiplication step .

The coefficients are as follows:

Summary #

This article proposes a general matrix function approximation framework based on a greedy strategy—without pursuing strict interpretability, it directly constructs a simple polynomial iteration, regresses toward the target at each step based on a greedy strategy, and then chooses an appropriate cost function to transform the problem into quadratic programming or linear programming, accurately and stably solving for the iteration parameters to ultimately obtain an effective computational scheme.