001/*
002 * Copyright (c) 2021, 2022, Oracle and/or its affiliates. All rights reserved.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package org.tribuo.common.sgd;
018
019import com.google.protobuf.Any;
020import com.google.protobuf.InvalidProtocolBufferException;
021import com.oracle.labs.mlrg.olcut.util.Pair;
022import org.tribuo.common.sgd.protos.FMParametersProto;
023import org.tribuo.math.FeedForwardParameters;
024import org.tribuo.math.Parameters;
025import org.tribuo.math.la.DenseMatrix;
026import org.tribuo.math.la.DenseSparseMatrix;
027import org.tribuo.math.la.DenseVector;
028import org.tribuo.math.la.Matrix;
029import org.tribuo.math.la.SGDVector;
030import org.tribuo.math.la.SparseVector;
031import org.tribuo.math.la.Tensor;
032import org.tribuo.math.la.VectorTuple;
033import org.tribuo.math.protos.ParametersProto;
034import org.tribuo.math.protos.TensorProto;
035import org.tribuo.math.util.HeapMerger;
036import org.tribuo.math.util.Merger;
037import org.tribuo.protos.ProtoUtil;
038
039import java.util.ArrayList;
040import java.util.Arrays;
041import java.util.List;
042import java.util.Random;
043import java.util.SplittableRandom;
044
045/**
046 * A {@link Parameters} for factorization machines.
047 */
048public final class FMParameters implements FeedForwardParameters {
049    private static final long serialVersionUID = 1L;
050
051    /**
052     * Protobuf serialization version.
053     */
054    public static final int CURRENT_VERSION = 0;
055
056    private static final Merger merger = new HeapMerger();
057
058    private Tensor[] weights;
059    private DenseVector biasVector;
060    private DenseMatrix weightMatrix;
061
062    private final int numFactors;
063
064    /**
065     * Constructor. The number of features and the number of outputs must be fixed and known in advance.
066     *
067     * @param rng         The RNG to use for initialization.
068     * @param numFeatures The number of features in the training dataset.
069     * @param numLabels   The number of outputs in the training dataset.
070     * @param numFactors  The size of the factorized feature representation.
071     * @param variance    The variance of the factor initializer.
072     */
073    public FMParameters(SplittableRandom rng, int numFeatures, int numLabels, int numFactors, double variance) {
074        weights = new Tensor[numLabels + 2];
075        biasVector = new DenseVector(numLabels);
076        weightMatrix = new DenseMatrix(numLabels, numFeatures);
077        weights[0] = biasVector;
078        weights[1] = weightMatrix;
079        for (int i = 0; i < numLabels; i++) {
080            DenseMatrix curMatrix = new DenseMatrix(numFactors, numFeatures);
081            initializeMatrix(rng, variance, curMatrix);
082            weights[i + 2] = curMatrix;
083        }
084        this.numFactors = numFactors;
085    }
086
087    /**
088     * Constructs a FMParameters wrapped around the weight array.
089     *
090     * @param weights    The weights to wrap.
091     * @param numFactors The size of the factorized feature representation.
092     */
093    private FMParameters(Tensor[] weights, int numFactors) {
094        this.weights = weights;
095        this.biasVector = (DenseVector) weights[0];
096        this.weightMatrix = (DenseMatrix) weights[1];
097        this.numFactors = numFactors;
098    }
099
100    /**
101     * Deserialization factory.
102     * @param version The serialized object version.
103     * @param className The class name.
104     * @param message The serialized data.
105     * @throws InvalidProtocolBufferException If the protobuf could not be parsed from the {@code message}.
106     * @return The deserialized object.
107     */
108    public static FMParameters deserializeFromProto(int version, String className, Any message) throws InvalidProtocolBufferException {
109        if (version < 0 || version > CURRENT_VERSION) {
110            throw new IllegalArgumentException("Unknown version " + version + ", this class supports at most version " + CURRENT_VERSION);
111        }
112        FMParametersProto proto = message.unpack(FMParametersProto.class);
113        int numFactors = proto.getNumFactors();
114        List<TensorProto> tensorProtoList = proto.getWeightsList();
115        Tensor[] tensors = new Tensor[tensorProtoList.size()];
116        for (int i = 0; i < tensors.length; i++) {
117            tensors[i] = ProtoUtil.deserialize(tensorProtoList.get(i));
118        }
119        if (tensors[0] instanceof DenseVector) {
120            int numOutputs = ((DenseVector) tensors[0]).size();
121            if ((numOutputs + 2) == tensors.length) {
122                if (tensors[1] instanceof DenseMatrix) {
123                    DenseMatrix weightMatrix = (DenseMatrix) tensors[1];
124                    int numFeatures = weightMatrix.getDimension2Size();
125                    if (weightMatrix.getDimension1Size() == numOutputs) {
126                        for (int i = 2; i < tensors.length; i++) {
127                            if (tensors[i] instanceof DenseMatrix) {
128                                DenseMatrix dm = (DenseMatrix) tensors[i];
129                                if ((dm.getDimension1Size() != numFactors) || (dm.getDimension2Size() != numFeatures)) {
130                                    throw new IllegalArgumentException("Invalid protobuf, expected factor matrix of shape [" + numFactors + ", " + numFeatures + "], found " + Arrays.toString(dm.getShape()));
131                                }
132                            }
133                        }
134                        return new FMParameters(tensors, numFactors);
135                    } else {
136                        throw new IllegalArgumentException("Invalid protobuf, expected weight matrix of shape [" + numOutputs + "," + numFeatures + "], found " + Arrays.toString(weightMatrix.getShape()));
137                    }
138                } else {
139                    throw new IllegalArgumentException("Invalid protobuf, expected DenseMatrix, found " + tensors[1].getClass());
140                }
141            } else {
142                throw new IllegalArgumentException("Invalid protobuf, expected " + (numOutputs + 2) + " weight tensors, found " + tensors.length);
143            }
144        } else {
145            throw new IllegalArgumentException("Invalid protobuf, expected bias vector found " + tensors[0].getClass());
146        }
147    }
148
149    @Override
150    public ParametersProto serialize() {
151        ParametersProto.Builder builder = ParametersProto.newBuilder();
152
153        builder.setVersion(CURRENT_VERSION);
154        builder.setClassName(FMParameters.class.getName());
155        FMParametersProto.Builder fmParamsBuilder = FMParametersProto.newBuilder();
156        fmParamsBuilder.setNumFactors(numFactors);
157        for (int i = 0; i < weights.length; i++) {
158            fmParamsBuilder.addWeights(weights[i].serialize());
159        }
160        builder.setSerializedData(Any.pack(fmParamsBuilder.build()));
161
162        return builder.build();
163    }
164
165    /**
166     * Initializes the weight matrix by drawing from a zero mean gaussian with the specified variance.
167     *
168     * @param rng      The RNG to use.
169     * @param variance The variance of the gaussian.
170     * @param matrix   The matrix to initialize.
171     */
172    private void initializeMatrix(SplittableRandom rng, double variance, DenseMatrix matrix) {
173        // This is to get a nextGaussian method. In Java 17 we can use the SplittableRandom directly
174        // though that will prevent reproducibility as there will be different draws from the RNG and
175        // the PRNG algorithm is different.
176        Random innerRNG = new Random(rng.nextLong());
177        int dim1 = matrix.getDimension1Size();
178        int dim2 = matrix.getDimension2Size();
179        for (int i = 0; i < dim1; i++) {
180            for (int j = 0; j < dim2; j++) {
181                matrix.set(i, j, innerRNG.nextGaussian() * variance);
182            }
183        }
184    }
185
186    /**
187     * Generates an unnormalised prediction by multiplying the weights with the incoming features,
188     * adding the bias and adding the feature factors.
189     *
190     * @param example A feature vector
191     * @return A {@link DenseVector} containing a score for each label.
192     */
193    @Override
194    public DenseVector predict(SGDVector example) {
195        // Linear part of the prediction
196        DenseVector pred = weightMatrix.leftMultiply(example);
197
198        // Add in the label biases
199        pred.intersectAndAddInPlace(biasVector);
200
201        // Compute the contribution of the feature factors
202        DenseVector factorizedPred = new DenseVector(biasVector.size());
203        for (int i = 2; i < weights.length; i++) {
204            DenseMatrix curMatrix = (DenseMatrix) weights[i];
205            double curValue = 0.0;
206            for (int k = 0; k < numFactors; k++) {
207                double sumOfSquares = 0.0;
208                double sum = 0.0;
209                for (VectorTuple v : example) {
210                    double curWeight = curMatrix.get(k, v.index);
211                    double value = curWeight * v.value;
212                    sum += value;
213                    sumOfSquares += value * value;
214                }
215                curValue += (sum * sum) - sumOfSquares;
216            }
217            curValue = curValue / 2;
218            factorizedPred.set(i - 2, curValue);
219        }
220
221        // Add factorized portion
222        pred.intersectAndAddInPlace(factorizedPred);
223        return pred;
224    }
225
226    /**
227     * Generate the gradients for a particular feature vector given
228     * the loss and the per output gradients.
229     * <p>
230     * This method returns a {@link Tensor} array with numLabels + 2 elements.
231     *
232     * @param score    The Pair returned by the objective.
233     * @param features The feature vector.
234     * @return A {@link Tensor} array containing all the gradients.
235     */
236    @Override
237    public Tensor[] gradients(Pair<Double, SGDVector> score, SGDVector features) {
238        Tensor[] gradients = new Tensor[weights.length];
239
240        SGDVector outputGradient = score.getB();
241        // Bias gradient
242        if (outputGradient instanceof SparseVector) {
243            gradients[0] = ((SparseVector) outputGradient).densify();
244        } else {
245            gradients[0] = outputGradient.copy();
246        }
247
248        // Feature gradients
249        gradients[1] = outputGradient.outer(features);
250
251        // factorised representation gradients
252        // per label
253        for (int i = 2; i < weights.length; i++) {
254            double curOutputGradient = outputGradient.get(i - 2);
255            DenseMatrix curFactors = (DenseMatrix) weights[i];
256            if (curOutputGradient != 0.0) {
257                // compute /sum_j v_{j,f}x_j
258                SGDVector factorSum = curFactors.leftMultiply(features);
259
260                // grad_f: dy/d0 * (x_i * factorSum_f - v_{i,f} * x_i * x_i)
261                Matrix factorGradMatrix;
262                if (features instanceof SparseVector) {
263                    List<SparseVector> vectors = new ArrayList<>(numFactors);
264                    for (int j = 0; j < numFactors; j++) {
265                        vectors.add(((SparseVector) features).copy());
266                    }
267                    factorGradMatrix = new DenseSparseMatrix(vectors);
268                } else {
269                    factorGradMatrix = new DenseMatrix(numFactors, features.size());
270                    for (int j = 0; j < numFactors; j++) {
271                        for (int k = 0; k < features.size(); k++) {
272                            factorGradMatrix.set(j, k, features.get(k));
273                        }
274                    }
275                }
276                for (int j = 0; j < numFactors; j++) {
277                    // This gets a mutable view of the row
278                    SGDVector curFactorGrad = factorGradMatrix.getRow(j);
279                    double curFactorSum = factorSum.get(j);
280                    final int jFinal = j;
281
282                    // Compute the gradient for this element of the factor vector
283                    curFactorGrad.foreachIndexedInPlace((Integer idx, Double a) -> a * curFactorSum - curFactors.get(jFinal, idx) * a * a);
284
285                    // Multiply by the output gradient
286                    curFactorGrad.scaleInPlace(curOutputGradient);
287                }
288                gradients[i] = factorGradMatrix;
289            } else {
290                // If the output gradient is 0.0 then all the factor gradients are zero.
291                // Technically with regularization we should shrink the weights for the specified features.
292                gradients[i] = new DenseSparseMatrix(numFactors, features.size());
293            }
294        }
295
296        return gradients;
297    }
298
299    /**
300     * This returns a {@link DenseMatrix} the same size as the Parameters.
301     *
302     * @return A {@link Tensor} array containing a single {@link DenseMatrix}.
303     */
304    @Override
305    public Tensor[] getEmptyCopy() {
306        Tensor[] output = new Tensor[weights.length];
307        output[0] = new DenseVector(biasVector.size());
308        output[1] = new DenseMatrix(weightMatrix.getDimension1Size(), weightMatrix.getDimension2Size());
309        for (int i = 2; i < weights.length; i++) {
310            DenseMatrix curMatrix = (DenseMatrix) weights[i];
311            output[i] = new DenseMatrix(curMatrix.getDimension1Size(), curMatrix.getDimension2Size());
312        }
313        return output;
314    }
315
316    @Override
317    public Tensor[] get() {
318        return weights;
319    }
320
321    @Override
322    public void set(Tensor[] newWeights) {
323        if (newWeights.length == weights.length) {
324            weights = newWeights;
325            biasVector = (DenseVector) weights[0];
326            weightMatrix = (DenseMatrix) weights[1];
327        }
328    }
329
330    @Override
331    public void update(Tensor[] gradients) {
332        for (int i = 0; i < gradients.length; i++) {
333            weights[i].intersectAndAddInPlace(gradients[i]);
334        }
335    }
336
337    @Override
338    public Tensor[] merge(Tensor[][] gradients, int size) {
339        Tensor[] output = new Tensor[weights.length];
340        for (int i = 0; i < weights.length; i++) {
341            if (gradients[0][i] instanceof DenseVector) {
342                for (int j = 1; j < size; j++) {
343                    gradients[0][i].intersectAndAddInPlace(gradients[j][i]);
344                }
345                output[i] = gradients[0][i];
346            } else if (gradients[0][i] instanceof DenseMatrix) {
347                for (int j = 1; j < size; j++) {
348                    gradients[0][i].intersectAndAddInPlace(gradients[j][i]);
349                }
350                output[i] = gradients[0][i];
351            } else if (gradients[0][i] instanceof DenseSparseMatrix) {
352                DenseSparseMatrix[] updates = new DenseSparseMatrix[size];
353                for (int j = 0; j < updates.length; j++) {
354                    updates[j] = (DenseSparseMatrix) gradients[j][0];
355                }
356
357                DenseSparseMatrix update = merger.merge(updates);
358
359                output[i] = update;
360            } else {
361                throw new IllegalStateException("Unexpected gradient type, expected DenseVector, DenseMatrix or DenseSparseMatrix, received " + gradients[0][i].getClass().getName());
362            }
363        }
364        return output;
365    }
366
367    @Override
368    public FMParameters copy() {
369        Tensor[] weightCopy = new Tensor[weights.length];
370        for (int i = 0; i < weights.length; i++) {
371            weightCopy[i] = weights[i].copy();
372        }
373        return new FMParameters(weightCopy, numFactors);
374    }
375}