Free cookie consent management tool by TermsFeed Policy Generator

source: branches/2915-AbsoluteSymbol/HeuristicLab.Problems.DataAnalysis.Symbolic/3.4/Interpreter/SymbolicDataAnalysisExpressionTreeBatchInterpreter.cs @ 16345

Last change on this file since 16345 was 16345, checked in by gkronber, 5 years ago

#2915: added cube, cbrt, absolute, aq to batched interpreter (and fixed a bug in power)

File size: 8.5 KB
RevLine 
[16285]1using System;
2using System.Collections.Generic;
3using System.Linq;
4
5using HeuristicLab.Common;
6using HeuristicLab.Core;
7using HeuristicLab.Data;
8using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
9using HeuristicLab.Parameters;
10using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
11
12using static HeuristicLab.Problems.DataAnalysis.Symbolic.BatchOperations;
13
14namespace HeuristicLab.Problems.DataAnalysis.Symbolic {
15  [Item("SymbolicDataAnalysisExpressionTreeBatchInterpreter", "An interpreter that uses batching and vectorization techniques to achieve faster performance.")]
16  [StorableClass]
17  public class SymbolicDataAnalysisExpressionTreeBatchInterpreter : ParameterizedNamedItem, ISymbolicDataAnalysisExpressionTreeInterpreter {
18    private const string EvaluatedSolutionsParameterName = "EvaluatedSolutions";
19
20    #region parameters
21    public IFixedValueParameter<IntValue> EvaluatedSolutionsParameter {
22      get { return (IFixedValueParameter<IntValue>)Parameters[EvaluatedSolutionsParameterName]; }
23    }
24    #endregion
25
26    #region properties
27    public int EvaluatedSolutions {
28      get { return EvaluatedSolutionsParameter.Value.Value; }
29      set { EvaluatedSolutionsParameter.Value.Value = value; }
30    }
31    #endregion
32
33    public void ClearState() { }
34
35    public SymbolicDataAnalysisExpressionTreeBatchInterpreter() {
36      Parameters.Add(new FixedValueParameter<IntValue>(EvaluatedSolutionsParameterName, "A counter for the total number of solutions the interpreter has evaluated", new IntValue(0)));
37    }
38
39
40    [StorableConstructor]
41    protected SymbolicDataAnalysisExpressionTreeBatchInterpreter(bool deserializing) : base(deserializing) { }
42    protected SymbolicDataAnalysisExpressionTreeBatchInterpreter(SymbolicDataAnalysisExpressionTreeBatchInterpreter original, Cloner cloner) : base(original, cloner) {
43    }
44    public override IDeepCloneable Clone(Cloner cloner) {
45      return new SymbolicDataAnalysisExpressionTreeBatchInterpreter(this, cloner);
46    }
47
48    private void LoadData(BatchInstruction instr, int[] rows, int rowIndex, int batchSize) {
49      for (int i = 0; i < batchSize; ++i) {
50        var row = rows[rowIndex] + i;
51        instr.buf[i] = instr.weight * instr.data[row];
52      }
53    }
54
55    private void Evaluate(BatchInstruction[] code, int[] rows, int rowIndex, int batchSize) {
56      for (int i = code.Length - 1; i >= 0; --i) {
57        var instr = code[i];
58        var c = instr.childIndex;
59        var n = instr.narg;
60
61        switch (instr.opcode) {
62          case OpCodes.Variable: {
63              LoadData(instr, rows, rowIndex, batchSize);
64              break;
65            }
[16293]66
[16285]67          case OpCodes.Add: {
68              Load(instr.buf, code[c].buf);
69              for (int j = 1; j < n; ++j) {
70                Add(instr.buf, code[c + j].buf);
71              }
72              break;
73            }
74
75          case OpCodes.Sub: {
76              if (n == 1) {
77                Neg(instr.buf, code[c].buf);
78              } else {
79                Load(instr.buf, code[c].buf);
80                for (int j = 1; j < n; ++j) {
81                  Sub(instr.buf, code[c + j].buf);
82                }
83              }
[16293]84              break;
[16285]85            }
86
87          case OpCodes.Mul: {
88              Load(instr.buf, code[c].buf);
89              for (int j = 1; j < n; ++j) {
90                Mul(instr.buf, code[c + j].buf);
91              }
92              break;
93            }
94
95          case OpCodes.Div: {
96              if (n == 1) {
97                Inv(instr.buf, code[c].buf);
98              } else {
99                Load(instr.buf, code[c].buf);
100                for (int j = 1; j < n; ++j) {
101                  Div(instr.buf, code[c + j].buf);
102                }
103              }
[16293]104              break;
[16285]105            }
106
[16293]107          case OpCodes.Square: {
108              Square(instr.buf, code[c].buf);
109              break;
110            }
111
112          case OpCodes.Root: {
113              Root(instr.buf, code[c].buf);
114              break;
115            }
116
117          case OpCodes.SquareRoot: {
118              Sqrt(instr.buf, code[c].buf);
119              break;
120            }
121
[16345]122          case OpCodes.Cube: {
123              Cube(instr.buf, code[c].buf);
124              break;
125            }
126          case OpCodes.CubeRoot: {
127              CubeRoot(instr.buf, code[c].buf);
128              break;
129            }
130
[16293]131          case OpCodes.Power: {
[16345]132              Load(instr.buf, code[c].buf);
133              Pow(instr.buf, code[c + 1].buf);
[16293]134              break;
135            }
136
[16285]137          case OpCodes.Exp: {
138              Exp(instr.buf, code[c].buf);
139              break;
140            }
141
142          case OpCodes.Log: {
143              Log(instr.buf, code[c].buf);
144              break;
145            }
[16293]146
147          case OpCodes.Sin: {
148              Sin(instr.buf, code[c].buf);
149              break;
150            }
151
152          case OpCodes.Cos: {
153              Cos(instr.buf, code[c].buf);
154              break;
155            }
156
157          case OpCodes.Tan: {
158              Tan(instr.buf, code[c].buf);
159              break;
160            }
[16345]161          case OpCodes.Absolute: {
162              Absolute(instr.buf, code[c].buf);
163              break;
164            }
165          case OpCodes.AnalyticalQuotient: {
166              Load(instr.buf, code[c].buf);
167              AnalyticQuotient(instr.buf, code[c].buf);
168              break;
169            }
[16285]170        }
171      }
172    }
173
[16296]174    [ThreadStatic]
175    private Dictionary<string, double[]> cachedData;
176
177    private void InitCache(IDataset dataset) {
178      cachedData = new Dictionary<string, double[]>();
179      foreach (var v in dataset.DoubleVariables) {
[16301]180        cachedData[v] = dataset.GetDoubleValues(v).ToArray();
[16296]181      }
182    }
183
184    public void InitializeState() {
185      cachedData = null;
186      EvaluatedSolutions = 0;
187    }
188
[16285]189    private double[] GetValues(ISymbolicExpressionTree tree, IDataset dataset, int[] rows) {
190      var code = Compile(tree, dataset, OpCodes.MapSymbolToOpCode);
191      var remainingRows = rows.Length % BATCHSIZE;
192      var roundedTotal = rows.Length - remainingRows;
193
194      var result = new double[rows.Length];
195
196      for (int rowIndex = 0; rowIndex < roundedTotal; rowIndex += BATCHSIZE) {
197        Evaluate(code, rows, rowIndex, BATCHSIZE);
198        Array.Copy(code[0].buf, 0, result, rowIndex, BATCHSIZE);
199      }
200
201      if (remainingRows > 0) {
202        Evaluate(code, rows, roundedTotal, remainingRows);
203        Array.Copy(code[0].buf, 0, result, roundedTotal, remainingRows);
204      }
205
206      return result;
207    }
208
[16293]209    public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, IDataset dataset, int[] rows) {
[16296]210      if (cachedData == null) {
211        InitCache(dataset);
212      }
[16293]213      return GetValues(tree, dataset, rows);
214    }
215
[16285]216    public IEnumerable<double> GetSymbolicExpressionTreeValues(ISymbolicExpressionTree tree, IDataset dataset, IEnumerable<int> rows) {
[16296]217      return GetSymbolicExpressionTreeValues(tree, dataset, rows.ToArray());
[16285]218    }
219
220    private BatchInstruction[] Compile(ISymbolicExpressionTree tree, IDataset dataset, Func<ISymbolicExpressionTreeNode, byte> opCodeMapper) {
221      var root = tree.Root.GetSubtree(0).GetSubtree(0);
222      var code = new BatchInstruction[root.GetLength()];
223      if (root.SubtreeCount > ushort.MaxValue) throw new ArgumentException("Number of subtrees is too big (>65.535)");
224      int c = 1, i = 0;
225      foreach (var node in root.IterateNodesBreadth()) {
[16296]226        if (node.SubtreeCount > ushort.MaxValue) throw new ArgumentException("Number of subtrees is too big (>65.535)");
227        code[i] = new BatchInstruction {
228          opcode = opCodeMapper(node),
229          narg = (ushort)node.SubtreeCount,
230          buf = new double[BATCHSIZE],
231          childIndex = c
232        };
[16285]233        if (node is VariableTreeNode variable) {
234          code[i].weight = variable.Weight;
[16296]235          if (cachedData.ContainsKey(variable.VariableName)) {
236            code[i].data = cachedData[variable.VariableName];
237          } else {
238            code[i].data = dataset.GetReadOnlyDoubleValues(variable.VariableName).ToArray();
239            cachedData[variable.VariableName] = code[i].data;
240          }
[16285]241        } else if (node is ConstantTreeNode constant) {
242          code[i].value = constant.Value;
[16287]243          for (int j = 0; j < BATCHSIZE; ++j)
244            code[i].buf[j] = code[i].value;
[16285]245        }
246        c += node.SubtreeCount;
247        ++i;
248      }
249      return code;
250    }
251  }
252}
Note: See TracBrowser for help on using the repository browser.