public static Tensor Tile(this Session session, Tensor x, int axis, int count) { const string ActionName = "tile"; if (axis < 0) { throw new ArgumentException(Properties.Resources.E_NegativeAxisIndex, nameof(axis)); } if (count == 1) { return(ArrayOperations.Copy(session, x)); } return(session.RunOperation( ActionName, () => { bool calculateGradient = session.CalculateGradients && x.CalculateGradient; // allocate destination Tensor y = session.AllocateTensor(ActionName, x.Shape.Reshape(axis, x.Axes[axis] * count), calculateGradient); ArrayOperations.Tile(x, axis, count, y, false); #if !NOLEARNING if (calculateGradient) { session.Push(ActionName, () => ArrayOperations.Untile(y, axis, count, x, true)); } #endif return y; })); }
public static Tensor MaxReduce(this Session session, Tensor x, int axis, int count) { const string ActionName = "max reduce"; if (axis < 0) { throw new ArgumentException(Properties.Resources.E_NegativeAxisIndex, nameof(axis)); } if (count == 1) { return(ArrayOperations.Copy(session, x)); } return(session.RunOperation( ActionName, () => { int xaxis = x.Axes[axis]; int xstride = x.Strides[axis]; if ((xaxis % count) != 0) { throw new ArgumentException("The axis dimension must be a count multiple."); } bool calculateGradient = session.CalculateGradients && x.CalculateGradient; // allocate destination Tensor y = session.AllocateTensor(ActionName, x.Shape.Reshape(axis, xaxis / count), calculateGradient); float[] xw = x.Weights; float[] yw = y.Weights; if (xstride == 1) { int length = x.Length / count; Arrays.Pack(length, xw, 0, count, yw, 0); float[] wsp = new float[length]; for (int i = 1; i < count; i++) { Arrays.Pack(length, xw, i, count, wsp, 0); Vectors.Max(length, wsp, 0, yw, 0); } } else { for (int offx = 0, offy = 0, ylen = y.Length; offy < ylen; offy += xstride) { Vectors.Copy(xstride, xw, offx, yw, offy); offx += xstride; for (int i = 1; i < count; i++, offx += xstride) { Vectors.Max(xstride, xw, offx, yw, offy); } } } #if !NOLEARNING if (calculateGradient) { session.Push( ActionName, () => { float[] dxw = x.Gradient; float[] dyw = y.Gradient; if (xstride == 1) { for (int xpos = 0, ypos = 0, len = y.Length; ypos < len; ypos++) { for (int i = 0; i < count; i++, xpos++) { if (xw[xpos] == yw[ypos]) { dxw[xpos] += dyw[ypos]; } } } } else { for (int xpos = 0, ypos = 0, len = y.Length; ypos < len; ypos += xstride) { for (int i = 0; i < count; i++, xpos += xstride) { Mathematics.MatchAndAdd(xstride, dyw, yw, ypos, dxw, xw, xpos); } } } }); } #endif return y; })); }