001/*
002 * Copyright (c) 2021, 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 ai.onnx.proto.OnnxMl;
020import com.oracle.labs.mlrg.olcut.util.Pair;
021import org.tribuo.Example;
022import org.tribuo.Excuse;
023import org.tribuo.ImmutableFeatureMap;
024import org.tribuo.ImmutableOutputInfo;
025import org.tribuo.ONNXExportable;
026import org.tribuo.Output;
027import org.tribuo.math.la.DenseMatrix;
028import org.tribuo.math.la.DenseVector;
029import org.tribuo.math.la.Matrix;
030import org.tribuo.math.la.SGDVector;
031import org.tribuo.math.la.Tensor;
032import org.tribuo.math.onnx.ONNXMathUtils;
033import org.tribuo.provenance.ModelProvenance;
034import org.tribuo.util.onnx.ONNXContext;
035import org.tribuo.util.onnx.ONNXInitializer;
036import org.tribuo.util.onnx.ONNXNode;
037import org.tribuo.util.onnx.ONNXOperators;
038import org.tribuo.util.onnx.ONNXPlaceholder;
039import org.tribuo.util.onnx.ONNXRef;
040
041import java.util.ArrayList;
042import java.util.Arrays;
043import java.util.Collections;
044import java.util.Comparator;
045import java.util.HashMap;
046import java.util.List;
047import java.util.Map;
048import java.util.Optional;
049import java.util.PriorityQueue;
050
051/**
052 * A quadratic factorization machine model trained using SGD.
053 * <p>
054 * It's an {@link AbstractSGDTrainer} operating on {@link FMParameters}.
055 * <p>
056 * See:
057 * <pre>
058 * Rendle, S.
059 * Factorization machines.
060 * 2010 IEEE International Conference on Data Mining
061 * </pre>
062 */
063public abstract class AbstractFMModel<T extends Output<T>> extends AbstractSGDModel<T> {
064    private static final long serialVersionUID = 1L;
065
066    /**
067     * Constructs a factorization machine model trained via SGD.
068     *
069     * @param name                   The model name.
070     * @param provenance             The model provenance.
071     * @param featureIDMap           The feature domain.
072     * @param outputIDInfo           The output domain.
073     * @param parameters             The model parameters.
074     * @param generatesProbabilities Does this model generate probabilities?
075     */
076    protected AbstractFMModel(String name, ModelProvenance provenance,
077                              ImmutableFeatureMap featureIDMap, ImmutableOutputInfo<T> outputIDInfo,
078                              FMParameters parameters, boolean generatesProbabilities) {
079        super(name, provenance, featureIDMap, outputIDInfo, parameters, generatesProbabilities, false);
080    }
081
082    /**
083     * Gets the top {@code n} features for each output dimension.
084     * <p>
085     * Note that the feature rankings are based only off the linear portion of the
086     * factorization machine.
087     * @param n The number of features to return. If this value is less than 0,
088     * all features are returned for each class.
089     * @return A map from string outputs to an ordered list of pairs of
090     * feature names and weights associated with that feature in the factorization machine.
091     */
092    // TODO investigate using the factorized representation magnitude as an additional feature weight.
093    @Override
094    public Map<String, List<Pair<String, Double>>> getTopFeatures(int n) {
095        DenseVector biases = (DenseVector) modelParameters.get()[0];
096        DenseMatrix baseWeights = (DenseMatrix) modelParameters.get()[1];
097        int maxFeatures = n < 0 ? featureIDMap.size() + 1 : n;
098
099        Comparator<Pair<String, Double>> comparator = Comparator.comparingDouble(p -> Math.abs(p.getB()));
100
101        //
102        // Use a priority queue to find the top N features.
103        int numClasses = baseWeights.getDimension1Size();
104        int numFeatures = baseWeights.getDimension2Size();
105        Map<String, List<Pair<String, Double>>> map = new HashMap<>();
106        for (int i = 0; i < numClasses; i++) {
107            PriorityQueue<Pair<String, Double>> q = new PriorityQueue<>(maxFeatures, comparator);
108
109            for (int j = 0; j < numFeatures; j++) {
110                Pair<String, Double> curr = new Pair<>(featureIDMap.get(j).getName(), baseWeights.get(i, j));
111
112                if (q.size() < maxFeatures) {
113                    q.offer(curr);
114                } else if (comparator.compare(curr, q.peek()) > 0) {
115                    q.poll();
116                    q.offer(curr);
117                }
118            }
119            Pair<String, Double> curr = new Pair<>(BIAS_FEATURE, biases.get(i));
120
121            if (q.size() < maxFeatures) {
122                q.offer(curr);
123            } else if (comparator.compare(curr, q.peek()) > 0) {
124                q.poll();
125                q.offer(curr);
126            }
127            List<Pair<String, Double>> b = new ArrayList<>();
128            while (q.size() > 0) {
129                b.add(q.poll());
130            }
131
132            Collections.reverse(b);
133            map.put(getDimensionName(i), b);
134        }
135        return map;
136    }
137
138    /**
139     * Returns a copy of the linear weights.
140     *
141     * @return The linear weights.
142     */
143    public DenseMatrix getLinearWeightsCopy() {
144        return ((DenseMatrix) modelParameters.get()[1]).copy();
145    }
146
147    /**
148     * Returns a copy of the output dimension biases.
149     *
150     * @return The biases.
151     */
152    public DenseVector getBiasesCopy() {
153        return ((DenseVector) modelParameters.get()[0]).copy();
154    }
155
156    /**
157     * Returns a copy of the factors.
158     * There is one factor matrix per output dimension.
159     * The first factor matrix dimension is the factor dimension,
160     * the second is the number of features.
161     *
162     * @return The factors.
163     */
164    public Tensor[] getFactorsCopy() {
165        Tensor[] params = modelParameters.get();
166        Tensor[] paramCopy = new Tensor[params.length - 2];
167        for (int i = 0; i < paramCopy.length; i++) {
168            paramCopy[i] = params[i + 2].copy();
169        }
170        return paramCopy;
171    }
172
173    /**
174     * Factorization machines don't provide excuses, use an explainer.
175     *
176     * @param example The input example.
177     * @return Optional.empty.
178     */
179    @Override
180    public Optional<Excuse<T>> getExcuse(Example<T> example) {
181        return Optional.empty();
182    }
183
184    /**
185     * Gets the name of the indexed output dimension.
186     *
187     * @param index The output dimension index.
188     * @return The name of the requested output dimension.
189     */
190    protected abstract String getDimensionName(int index);
191
192    /**
193     * Takes the unnormalized ONNX output of this model and applies an appropriate normalizer from the concrete class.
194     * @param input Unnormalized ONNX leaf node.
195     * @return Normalized ONNX leaf node.
196     */
197    protected abstract ONNXNode onnxOutput(ONNXNode input);
198
199    /**
200     * @return Name to write into the ONNX Model.
201     */
202    protected abstract String onnxModelName();
203
204    /**
205     * Writes this {@link org.tribuo.Model} into {@link OnnxMl.GraphProto.Builder} inside the input's
206     * {@link ONNXContext}.
207     * @param input The input to the model graph.
208     * @return the output node of the model graph.
209     */
210    public ONNXNode writeONNXGraph(ONNXRef<?> input) {
211        ONNXContext onnx = input.onnxContext();
212        Tensor[] modelParams = modelParameters.get();
213
214        ONNXInitializer twoConst = onnx.constant("two_const", 2.0f);
215        ONNXInitializer sumAxes = onnx.array("sum_over_embedding_axes", new long[]{1});
216
217        ONNXInitializer weights = ONNXMathUtils.floatMatrix(onnx, "fm_linear_weights", (Matrix) modelParams[1], true);
218        ONNXInitializer bias = ONNXMathUtils.floatVector(onnx, "fm_biases", (SGDVector) modelParams[0]);
219
220        // Make gemm
221        ONNXNode gemm = input.apply(ONNXOperators.GEMM, Arrays.asList(weights, bias));
222
223        // Make feature pow
224        ONNXNode inputSquared = input.apply(ONNXOperators.POW, twoConst);
225
226        List<ONNXNode> embeddingOutputs = new ArrayList<>();
227        for(int i = 0; i < outputIDInfo.size(); i++) {
228
229            // Embedding Weights
230            ONNXInitializer embWeight = ONNXMathUtils.floatMatrix(onnx, "fm_embedding_" + i, (Matrix) modelParams[i + 2], true);
231
232            // Feature matrix * embedding matrix = batch_size, embedding dim
233            ONNXNode featureEmbedding = input.apply(ONNXOperators.GEMM, embWeight);
234
235            // Square the output
236            ONNXNode embeddingSquared = featureEmbedding.apply(ONNXOperators.POW, twoConst);
237
238            // Square the embeddings
239            ONNXNode embWeightSquared = embWeight.apply(ONNXOperators.POW, twoConst);
240
241            // squared features * squared embeddings
242            ONNXNode inputByEmbeddingSquared = inputSquared.apply(ONNXOperators.GEMM, embWeightSquared);
243
244            // squared product subtract product of squares
245            ONNXNode subtract = embeddingSquared.apply(ONNXOperators.SUB, inputByEmbeddingSquared);
246
247            // sum over embedding dimensions
248            // Divide by 2
249            embeddingOutputs.add(subtract.apply(ONNXOperators.REDUCE_SUM, sumAxes)
250                    .apply(ONNXOperators.DIV, twoConst));
251        }
252
253        ONNXNode concat = onnx.operation(ONNXOperators.CONCAT, embeddingOutputs, "fm_concat", Collections.singletonMap("axis", 1));
254
255        return onnxOutput(gemm.apply(ONNXOperators.ADD, concat));
256    }
257
258    /**
259     * Exports this {@link org.tribuo.Model} as an ONNX protobuf.
260     * @param domain A reverse-DNS name to namespace the model (e.g., org.tribuo.classification.sgd.linear).
261     * @param modelVersion A version number for this model.
262     * @return The ONNX ModelProto representing this Tribuo Model.
263     */
264    public OnnxMl.ModelProto exportONNXModel(String domain, long modelVersion) {
265        ONNXContext onnx = new ONNXContext();
266        onnx.setName(onnxModelName());
267        ONNXPlaceholder input = onnx.floatInput("input", featureIDMap.size());
268        ONNXPlaceholder output = onnx.floatOutput("output", outputIDInfo.size());
269        writeONNXGraph(input).assignTo(output);
270        return ONNXExportable.buildModel(onnx, domain, modelVersion, this);
271    }
272
273}