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 com.oracle.labs.mlrg.olcut.config.Config;
020import com.oracle.labs.mlrg.olcut.provenance.Provenance;
021import com.oracle.labs.mlrg.olcut.util.Pair;
022import org.tribuo.Dataset;
023import org.tribuo.Example;
024import org.tribuo.ImmutableFeatureMap;
025import org.tribuo.ImmutableOutputInfo;
026import org.tribuo.Model;
027import org.tribuo.Output;
028import org.tribuo.Trainer;
029import org.tribuo.WeightedExamples;
030import org.tribuo.math.FeedForwardParameters;
031import org.tribuo.math.StochasticGradientOptimiser;
032import org.tribuo.math.la.DenseVector;
033import org.tribuo.math.la.SGDVector;
034import org.tribuo.math.la.SparseVector;
035import org.tribuo.math.la.Tensor;
036import org.tribuo.math.optimisers.AdaGrad;
037import org.tribuo.provenance.ModelProvenance;
038import org.tribuo.provenance.TrainerProvenance;
039import org.tribuo.provenance.impl.TrainerProvenanceImpl;
040
041import java.time.OffsetDateTime;
042import java.util.Collections;
043import java.util.Map;
044import java.util.SplittableRandom;
045import java.util.logging.Logger;
046
047/**
048 * A trainer for a model which uses SGD.
049 * <p>
050 * See:
051 * <pre>
052 * Bottou L.
053 * "Large-Scale Machine Learning with Stochastic Gradient Descent"
054 * Proceedings of COMPSTAT, 2010.
055 * </pre>
056 * @param <T> The output type.
057 * @param <U> The intermediate representation of the labels.
058 * @param <V> The model type.
059 * @param <X> The parameter type.
060 */
061public abstract class AbstractSGDTrainer<T extends Output<T>,U,V extends Model<T>,X extends FeedForwardParameters> implements Trainer<T>, WeightedExamples {
062    private static final Logger logger = Logger.getLogger(AbstractSGDTrainer.class.getName());
063
064    @Config(description="The gradient optimiser to use.")
065    protected StochasticGradientOptimiser optimiser = new AdaGrad(1.0,0.1);
066
067    @Config(description="The number of gradient descent epochs.")
068    protected int epochs = 5;
069
070    @Config(description="Log values after this many updates.")
071    protected int loggingInterval = -1;
072
073    @Config(description="Minibatch size in SGD.")
074    protected int minibatchSize = 1;
075
076    @Config(description="Seed for the RNG used to shuffle elements.")
077    protected long seed = Trainer.DEFAULT_SEED;
078
079    @Config(description="Shuffle the data before each epoch. Only turn off for debugging.")
080    protected boolean shuffle = true;
081
082    protected final boolean addBias;
083
084    protected SplittableRandom rng;
085
086    private int trainInvocationCounter;
087
088    /**
089     * Constructs an SGD trainer.
090     * @param optimiser The gradient optimiser to use.
091     * @param epochs The number of epochs (complete passes through the training data).
092     * @param loggingInterval Log the loss after this many iterations. If -1 don't log anything.
093     * @param minibatchSize The size of any minibatches.
094     * @param seed A seed for the random number generator, used to shuffle the examples before each epoch.
095     * @param addBias Should the model add a bias feature to the feature vector?
096     */
097    protected AbstractSGDTrainer(StochasticGradientOptimiser optimiser, int epochs, int loggingInterval, int minibatchSize, long seed, boolean addBias) {
098        this.optimiser = optimiser;
099        this.epochs = epochs;
100        this.loggingInterval = loggingInterval;
101        this.minibatchSize = minibatchSize;
102        this.seed = seed;
103        this.addBias = addBias;
104    }
105
106    /**
107     * Base constructor called by subclass no-args constructors used by OLCUT.
108     * @param addBias Should the model add a bias feature to the feature vector?
109     */
110    protected AbstractSGDTrainer(boolean addBias) {
111        this.addBias = addBias;
112    }
113
114    /**
115     * Used by the OLCUT configuration system, and should not be called by external code.
116     */
117    @Override
118    public synchronized void postConfig() {
119        this.rng = new SplittableRandom(seed);
120    }
121
122    /**
123     * Turn on or off shuffling of examples.
124     * <p>
125     * This isn't exposed in the constructor as it defaults to on.
126     * This method should only be used for debugging.
127     * @param shuffle If true shuffle the examples, if false leave them in their current order.
128     */
129    public void setShuffle(boolean shuffle) {
130        this.shuffle = shuffle;
131    }
132
133    @Override
134    public V train(Dataset<T> examples) {
135        return train(examples, Collections.emptyMap());
136    }
137
138    @Override
139    public V train(Dataset<T> examples, Map<String, Provenance> runProvenance) {
140        return (train(examples, runProvenance, INCREMENT_INVOCATION_COUNT));
141    }
142
143    @Override
144    public V train(Dataset<T> examples, Map<String, Provenance> runProvenance, int invocationCount) {
145        if (examples.getOutputInfo().getUnknownCount() > 0) {
146            throw new IllegalArgumentException("The supplied Dataset contained unknown Outputs, and this Trainer is supervised.");
147        }
148        // Creates a new RNG, adds one to the invocation count, generates a local optimiser.
149        TrainerProvenance trainerProvenance;
150        SplittableRandom localRNG;
151        StochasticGradientOptimiser localOptimiser;
152        synchronized(this) {
153            if(invocationCount != INCREMENT_INVOCATION_COUNT) {
154                setInvocationCount(invocationCount);
155            }
156            localRNG = rng.split();
157            localOptimiser = optimiser.copy();
158            trainerProvenance = getProvenance();
159            trainInvocationCounter++;
160        }
161
162        SGDObjective<U> objective = getObjective();
163        ImmutableOutputInfo<T> outputIDInfo = examples.getOutputIDInfo();
164        ImmutableFeatureMap featureIDMap = examples.getFeatureIDMap();
165        int featureSpaceSize = featureIDMap.size();
166
167        SGDVector[] sgdFeatures = new SGDVector[examples.size()];
168        @SuppressWarnings("unchecked")
169        U[] sgdTargets = (U[]) new Object[examples.size()];
170        double[] weights = new double[examples.size()];
171        int n = 0;
172        long featureSize = 0;
173        long denseCount = 0;
174        for (Example<T> example : examples) {
175            weights[n] = example.getWeight();
176            if (example.size() == featureSpaceSize) {
177                sgdFeatures[n] = DenseVector.createDenseVector(example, featureIDMap, addBias);
178                denseCount++;
179            } else {
180                sgdFeatures[n] = SparseVector.createSparseVector(example, featureIDMap, addBias);
181            }
182            sgdTargets[n] = getTarget(outputIDInfo,example.getOutput());
183            featureSize += sgdFeatures[n].numActiveElements();
184            n++;
185        }
186        logger.info(String.format("Training SGD model with %d examples", n));
187        logger.fine("Mean number of active features = " + featureSize / (double)n);
188        logger.fine("Number of dense examples = " + denseCount);
189        logger.info("Outputs - " + outputIDInfo.toReadableString());
190
191        X parameters = createParameters(featureIDMap.size(), outputIDInfo.size(), localRNG);
192
193        localOptimiser.initialise(parameters);
194        double loss = 0.0;
195        int iteration = 0;
196
197        for (int i = 0; i < epochs; i++) {
198            if (shuffle) {
199                shuffleInPlace(sgdFeatures, sgdTargets, weights, localRNG);
200            }
201            if (minibatchSize == 1) {
202                for (int j = 0; j < sgdFeatures.length; j++) {
203                    SGDVector pred = parameters.predict(sgdFeatures[j]);
204                    Pair<Double,SGDVector> output = objective.lossAndGradient(sgdTargets[j],pred);
205                    loss += output.getA()*weights[j];
206
207                    Tensor[] updates = localOptimiser.step(parameters.gradients(output,sgdFeatures[j]),weights[j]);
208                    parameters.update(updates);
209
210                    iteration++;
211                    if ((loggingInterval != -1) && (iteration % loggingInterval == 0)) {
212                        logger.info("At iteration " + iteration + ", average loss = " + loss/loggingInterval);
213                        loss = 0.0;
214                    }
215                }
216            } else {
217                Tensor[][] gradients = new Tensor[minibatchSize][];
218                for (int j = 0; j < sgdFeatures.length; j += minibatchSize) {
219                    double tempWeight = 0.0;
220                    int curSize = 0;
221                    for (int k = j; k < j+minibatchSize && k < sgdFeatures.length; k++) {
222                        SGDVector pred = parameters.predict(sgdFeatures[k]);
223                        Pair<Double,SGDVector> output = objective.lossAndGradient(sgdTargets[k],pred);
224                        loss += output.getA()*weights[k];
225                        tempWeight += weights[k];
226
227                        gradients[k-j] = parameters.gradients(output,sgdFeatures[k]);
228                        curSize++;
229                    }
230                    Tensor[] updates = parameters.merge(gradients,curSize);
231                    for (int k = 0; k < updates.length; k++) {
232                        updates[k].scaleInPlace(minibatchSize);
233                    }
234                    tempWeight /= minibatchSize;
235                    updates = localOptimiser.step(updates,tempWeight);
236                    parameters.update(updates);
237
238                    iteration++;
239                    if ((loggingInterval != -1) && (iteration % loggingInterval == 0)) {
240                        logger.info("At iteration " + iteration + ", average loss = " + loss/loggingInterval);
241                        loss = 0.0;
242                    }
243                }
244            }
245        }
246        localOptimiser.finalise();
247        ModelProvenance provenance = new ModelProvenance(getModelClassName(), OffsetDateTime.now(), examples.getProvenance(), trainerProvenance, runProvenance);
248        V model = createModel(getName(),provenance,featureIDMap,outputIDInfo,parameters);
249        localOptimiser.reset();
250        return model;
251    }
252
253    @Override
254    public int getInvocationCount() {
255        return trainInvocationCounter;
256    }
257
258    @Override
259    public synchronized void setInvocationCount(int invocationCount){
260        if(invocationCount < 0){
261            throw new IllegalArgumentException("The supplied invocationCount is less than zero.");
262        }
263
264        rng = new SplittableRandom(seed);
265
266        for (trainInvocationCounter = 0; trainInvocationCounter < invocationCount; trainInvocationCounter++){
267            SplittableRandom localRNG = rng.split();
268        }
269    }
270
271    /**
272     * Extracts the appropriate training time representation from the supplied output.
273     * @param outputInfo The output info to use.
274     * @param output The output to extract.
275     * @return The training time representation of the output.
276     */
277    protected abstract U getTarget(ImmutableOutputInfo<T> outputInfo, T output);
278
279    /**
280     * Returns the objective used by this trainer.
281     * @return The SGDObjective used by this trainer.
282     */
283    protected abstract SGDObjective<U> getObjective();
284
285    /**
286     * Creates the appropriate model subclass for this subclass of AbstractSGDTrainer.
287     * @param name The model name.
288     * @param provenance The model provenance.
289     * @param featureMap The feature map.
290     * @param outputInfo The output info.
291     * @param parameters The model parameters.
292     * @return A new instance of the appropriate subclass of {@link Model}.
293     */
294    protected abstract V createModel(String name, ModelProvenance provenance, ImmutableFeatureMap featureMap, ImmutableOutputInfo<T> outputInfo, X parameters);
295
296    /**
297     * Returns the class name of the model that's produced by this trainer.
298     * @return The model class name;
299     */
300    protected abstract String getModelClassName();
301
302    /**
303     * Returns the default model name.
304     * @return The default model name.
305     */
306    protected abstract String getName();
307
308    /**
309     * Constructs the trainable parameters object.
310     * @param numFeatures The number of input features.
311     * @param numOutputs The number of output dimensions.
312     * @param localRNG The RNG to use for parameter initialisation.
313     * @return The trainable parameters.
314     */
315    protected abstract X createParameters(int numFeatures, int numOutputs, SplittableRandom localRNG);
316
317    @Override
318    public TrainerProvenance getProvenance() {
319        return new TrainerProvenanceImpl(this);
320    }
321
322    /**
323     * Shuffles the features, outputs and weights in place.
324     * @param features Feature array.
325     * @param labels Output array.
326     * @param weights Weight array.
327     * @param rng Random number generator.
328     * @param <T> The output type.
329     */
330    public static <T> void shuffleInPlace(SGDVector[] features, T[] labels, double[] weights, SplittableRandom rng) {
331        int size = features.length;
332        // Shuffle array
333        for (int i = size; i > 1; i--) {
334            int j = rng.nextInt(i);
335            //swap features
336            SGDVector tmpFeature = features[i-1];
337            features[i-1] = features[j];
338            features[j] = tmpFeature;
339            //swap labels
340            T tmpLabel = labels[i-1];
341            labels[i-1] = labels[j];
342            labels[j] = tmpLabel;
343            //swap weights
344            double tmpWeight = weights[i-1];
345            weights[i-1] = weights[j];
346            weights[j] = tmpWeight;
347        }
348    }
349}