You’re an expert programmer with a expert understanding of best coding practices and…
- User
You’re an expert programmer with a expert understanding of best coding practices and numerical computing. this is a class library for neural networks for real world applications, the library must be able to handle small networks like simple classifiers and large networks like LLMs . so you must always consider for best possible answer with best performance, optimizations and least memory footprint, use Tensor.ParallelizationThreshold static property when preferred or required for best practices. you will produce fully complete and working code. When I ask you for code improvements or bug fix, you will only generate new code or code changes, don't re-generate unchanged or old code, also with the changes you provide code copy paste explanation so I can avoid any copy paste errors and to avoid human confusion. Please note this class library is on multiply file and large code base, so If you want to know about certain implementation to provide complete answer then assume it is already implemented and well optimized, also you can ask for code snippets and I will provide to you my current up-to-date implementation.
Programming language : c# Application Type: class library public async Task<Tensor> ElementWiseOperationAsync(Tensor other, Func<T, T, T> operation) { return await Task.Run(() => ElementWiseOperation(other, operation)); } public Tensor ElementWiseOperation(Tensor other, Func<T, T, T> operation) { EnsureNotDisposed(); other.EnsureNotDisposed(); var broadcastInfo = GetOrAddBroadcastCache(shape, other.shape, other.strides); int[] resultShape = broadcastInfo.ResultShape; int resultSize = resultShape.Aggregate(1, (a, b) => a * b); Tensor result = new Tensor(resultShape); var dataResult = result.data; var stridesA = broadcastInfo.BroadcastStridesA; var stridesB = broadcastInfo.BroadcastStridesB; bool isContiguousA = IsContiguous(stridesA, shape); bool isContiguousB = IsContiguous(stridesB, other.shape); bool isContiguousResult = result.IsContiguous(); bool shapesAreEqual = shape.SequenceEqual(other.shape); bool stridesAreEqual = strides.SequenceEqual(other.strides); bool operationIsSupported = operation.Method == ((Func<T, T, T>)((x, y) => x + y)).Method || operation.Method == ((Func<T, T, T>)((x, y) => x - y)).Method || operation.Method == ((Func<T, T, T>)((x, y) => x * y)).Method || operation.Method == ((Func<T, T, T>)((x, y) => x / y)).Method; bool canUseSIMD = ( (typeof(T) == typeof(float) || typeof(T) == typeof(double)) && isContiguousA && isContiguousB && isContiguousResult && shapesAreEqual && stridesAreEqual && operationIsSupported ); if (canUseSIMD) { int vectorSize = Vector.Count; int vectorizableLength = resultSize - (resultSize % vectorSize); if (resultSize >= ParallelizationThreshold) { Parallel.For(0, vectorizableLength / vectorSize, index => { int baseIndex = index * vectorSize; int indexA = offset + baseIndex; int indexB = other.offset + baseIndex; int indexResult = result.offset + baseIndex; var vectorA = new Vector(data, indexA); var vectorB = new Vector(other.data, indexB); var vectorResult = PerformVectorOperation(vectorA, vectorB, operation); vectorResult.CopyTo(dataResult, indexResult); }); for (int i = vectorizableLength; i < resultSize; i++) { int indexA = offset + i; int indexB = other.offset + i; int indexResult = result.offset + i; dataResult[indexResult] = operation(data[indexA], other.data[indexB]); } } else { int i = 0; for (; i <= vectorizableLength - vectorSize; i += vectorSize) { int indexA = offset + i; int indexB = other.offset + i; int indexResult = result.offset + i; var vectorA = new Vector(data, indexA); var vectorB = new Vector(other.data, indexB); var vectorResult = PerformVectorOperation(vectorA, vectorB, operation); vectorResult.CopyTo(dataResult, indexResult); } for (; i < resultSize; i++) { int indexA = offset + i; int indexB = other.offset + i; int indexResult = result.offset + i; dataResult[indexResult] = operation(data[indexA], other.data[indexB]); } } } else { if (resultSize >= ParallelizationThreshold) { Parallel.For(0, resultSize, i => { int[] multiIndex = GetIndicesFromRawIndex(i, resultShape); int indexA = GetFlatIndex(multiIndex, stridesA, offset); int indexB = GetFlatIndex(multiIndex, stridesB, other.offset); int indexResult = GetFlatIndex(multiIndex, result.strides, result.offset); dataResult[indexResult] = operation(data[indexA], other.data[indexB]); }); } else { for (int i = 0; i < resultSize; i++) { int[] multiIndex = GetIndicesFromRawIndex(i, resultShape); int indexA = GetFlatIndex(multiIndex, stridesA, offset); int indexB = GetFlatIndex(multiIndex, stridesB, other.offset); int indexResult = GetFlatIndex(multiIndex, result.strides, result.offset); dataResult[indexResult] = operation(data[indexA], other.data[indexB]); } } } return result; } private Vector PerformVectorOperation(Vector vectorA, Vector vectorB, Func<T, T, T> operation) { if (operation.Method == ((Func<T, T, T>)((x, y) => x + y)).Method) { return vectorA + vectorB; } else if (operation.Method == ((Func<T, T, T>)((x, y) => x - y)).Method) { return vectorA - vectorB; } else if (operation.Method == ((Func<T, T, T>)((x, y) => x * y)).Method) { return vectorA * vectorB; } else if (operation.Method == ((Func<T, T, T>)((x, y) => x / y)).Method) { return vectorA / vectorB; } else { T[] resultArray = new T[Vector.Count]; for (int i = 0; i < Vector.Count; i++) { resultArray[i] = operation(vectorA[i], vectorB[i]); } return new Vector(resultArray); } } public async Task<Tensor> ScalarOperationAsync(Func<T, T> operation) { return await Task.Run(() => ScalarOperation(operation)); } public Tensor ScalarOperation(Func<T, T> operation) { EnsureNotDisposed(); T[] resultData = new T[totalSize]; var offsetResult = 0; bool isContiguous = IsContiguous(); bool canUseSIMD = (typeof(T) == typeof(float) || typeof(T) == typeof(double)) && isContiguous && operation.Method == ((Func<T, T>)(x => -x)).Method; if (canUseSIMD) { int vectorSize = Vector.Count; int vectorizableLength = totalSize - (totalSize % vectorSize); if (totalSize >= ParallelizationThreshold) { Parallel.For(0, vectorizableLength / vectorSize, index => { int baseIndex = index * vectorSize; int indexData = offset + baseIndex; int indexResult = offsetResult + baseIndex; var vectorData = new Vector(data, indexData); var vectorResult = PerformVectorOperation(vectorData, operation); vectorResult.CopyTo(resultData, indexResult); }); for (int i = vectorizableLength; i < totalSize; i++) { int indexData = offset + i; resultData[offsetResult + i] = operation(data[indexData]); } } else { int i = 0; for (; i <= vectorizableLength - vectorSize; i += vectorSize) { int indexData = offset + i; int indexResult = offsetResult + i; var vectorData = new Vector(data, indexData); var vectorResult = PerformVectorOperation(vectorData, operation); vectorResult.CopyTo(resultData, indexResult); } for (; i < totalSize; i++) { int indexData = offset + i; resultData[offsetResult + i] = operation(data[indexData]); } } } else { if (totalSize >= ParallelizationThreshold) { Parallel.For(0, totalSize, i => { int[] multiIndex = GetIndicesFromRawIndex(i, shape); int indexData = GetFlatIndex(multiIndex, strides, offset); resultData[offsetResult + i] = operation(data[indexData]); }); } else { for (int i = 0; i < totalSize; i++) { int[] multiIndex = GetIndicesFromRawIndex(i, shape); int indexData = GetFlatIndex(multiIndex, strides, offset); resultData[offsetResult + i] = operation(data[indexData]); } } } return new Tensor(resultData, (int[])shape.Clone(), (int[])strides.Clone(), totalSize, isRowMajor, disposed: false, offset: offsetResult); } private Vector PerformVectorOperation(Vector vectorData, Func<T, T> operation) { if (operation.Method == ((Func<T, T>)(x => -x)).Method) { return -vectorData; } else { T[] resultArray = new T[Vector.Count]; for (int i = 0; i < Vector.Count; i++) { resultArray[i] = operation(vectorData[i]); } return new Vector(resultArray); } } public static Tensor operator /(T scalar, Tensor a) { return a.Reciprocal().MultiplyScalar(scalar); } public void ElementWiseInPlaceOperation(Tensor other, Func<T, T, T> operation) { EnsureNotDisposed(); other.EnsureNotDisposed(); var broadcastInfo = GetOrAddBroadcastCache(this.shape, other.shape, other.strides); int[] resultShape = broadcastInfo.ResultShape.ToArray(); if (!this.shape.SequenceEqual(resultShape)) throw new InvalidOperationException("Result shape after broadcasting must match the shape of the tensor being modified."); var stridesA = broadcastInfo.BroadcastStridesA.ToArray(); var stridesB = broadcastInfo.BroadcastStridesB.ToArray(); int resultSize = resultShape.Aggregate(1, (a, b) => a * b); var dataA = data; var dataB = other.data; var offsetA = offset; var offsetB = other.offset; if (resultSize >= ParallelizationThreshold) { Parallel.For(0, resultSize, i => { int indexA = offsetA; int indexB = offsetB; int idx = i; for (int dim = resultShape.Length - 1; dim >= 0; dim--) { int currentIndex = idx % resultShape[dim]; idx /= resultShape[dim]; indexA += stridesA[dim] * currentIndex; indexB += stridesB[dim] * currentIndex; } dataA[indexA] = operation(dataA[indexA], dataB[indexB]); }); } else { for (int i = 0; i < resultSize; i++) { int indexA = offsetA; int indexB = offsetB; int idx = i; for (int dim = resultShape.Length - 1; dim >= 0; dim--) { int currentIndex = idx % resultShape[dim]; idx /= resultShape[dim]; indexA += stridesA[dim] * currentIndex; indexB += stridesB[dim] * currentIndex; } dataA[indexA] = operation(dataA[indexA], dataB[indexB]); } } } public void ScalarInPlaceOperation(Func<T, T> operation) { EnsureNotDisposed(); bool isContiguous = IsContiguous(); if ((typeof(T) == typeof(float) || typeof(T) == typeof(double)) && isContiguous && operation.Method == ((Func<T, T>)(x => -x)).Method) { int vectorSize = Vector.Count; int vectorizableLength = totalSize - (totalSize % vectorSize); if (totalSize >= ParallelizationThreshold) { Parallel.For(0, vectorizableLength / vectorSize, index => { int baseIndex = index * vectorSize; int indexData = offset + baseIndex; var vectorData = new Vector(data, indexData); var vectorResult = PerformVectorOperation(vectorData, operation); vectorResult.CopyTo(data, indexData); }); for (int i = vectorizableLength; i < totalSize; i++) { int indexData = offset + i; data[indexData] = operation(data[indexData]); } } else { int i = 0; for (; i <= vectorizableLength - vectorSize; i += vectorSize) { int indexData = offset + i; var vectorData = new Vector(data, indexData); var vectorResult = PerformVectorOperation(vectorData, operation); vectorResult.CopyTo(data, indexData); } for (; i < totalSize; i++) { int indexData = offset + i; data[indexData] = operation(data[indexData]); } } } else { if (totalSize >= ParallelizationThreshold) { Parallel.For(0, totalSize, i => { data[offset + i] = operation(data[offset + i]); }); } else { for (int i = 0; i < totalSize; i++) { data[offset + i] = operation(data[offset + i]); } } } } public void SubtractScalarInPlace(T scalar) { ScalarInPlaceOperation(x => x - scalar); } public void DivideScalarInPlace(T scalar) { ScalarInPlaceOperation(x => x / scalar); } private void PerformBatchMatMul(int batchIndex, int m, int n, int p, int[] resultBatchShape, Tensor result, Tensor a, Tensor b) { var batchIndices = GetIndicesFromRawIndex(batchIndex, resultBatchShape); int aBatchOffset = a.GetBatchOffset(batchIndices, a.strides); int bBatchOffset = b.GetBatchOffset(batchIndices, b.strides); int resultBatchOffset = result.GetBatchOffset(batchIndices, result.strides); for (int i = 0; i < m; i++) { for (int j = 0; j < p; j++) { T sum = T.Zero; for (int k = 0; k < n; k++) { int aIndex = aBatchOffset + i * a.strides[a.Rank - 2] + k * a.strides[a.Rank - 1]; int bIndex = bBatchOffset + k * b.strides[b.Rank - 2] + j * b.strides[b.Rank - 1]; sum += a.data[aIndex] * b.data[bIndex]; } int resultIndex = resultBatchOffset + i * result.strides[result.Rank - 2] + j * result.strides[result.Rank - 1]; result.data[resultIndex] = sum; } } } public Tensor MatMulBatchOffset(Tensor other) { EnsureNotDisposed(); other.EnsureNotDisposed(); if (this.Rank < 2 || other.Rank < 2) throw new InvalidOperationException("MatMul requires tensors with at least 2 dimensions."); int[] batchShapeA = this.shape.Take(this.Rank - 2).ToArray(); int[] batchShapeB = other.shape.Take(other.Rank - 2).ToArray(); int[] resultBatchShape = BroadcastShapes(batchShapeA, batchShapeB); int aLastDim = this.shape[this.Rank - 1]; int bSecondLastDim = other.shape[other.Rank - 2]; if (aLastDim != bSecondLastDim) throw new InvalidOperationException("Axis {axis} is out of range for tensor of rank {ndim}."); Tensor maxTensor = Max(axis, keepDims: true); Tensor shiftedInput = Subtract(maxTensor); Tensor expShifted = shiftedInput.ScalarOperation(x => T.Exp(x)); Tensor sumExp = expShifted.Sum(axis, keepDims: true); Tensor logSumExp = sumExp.ScalarOperation(x => T.Log(x)); return maxTensor.Add(logSumExp); } public Tensor Softmax(int axis) { EnsureNotDisposed(); int ndim = shape.Length; if (ndim == 0) throw new InvalidOperationException("Softmax cannot be applied on a scalar tensor."); if (axis < 0) axis += ndim; if (axis < 0 || axis >= ndim) throw new ArgumentOutOfRangeException(nameof(axis), $"Axis {axis} is out of range for tensor of rank {ndim}."); Tensor maxTensor = Max(axis, keepDims: true); Tensor shiftedInput = Subtract(maxTensor); Tensor expShifted = shiftedInput.ScalarOperation(x => T.Exp(x)); Tensor sumExp = expShifted.Sum(axis, keepDims: true); Tensor softmaxResult = expShifted.Divide(sumExp); return softmaxResult; }
- Assistant