add multi predictor support to l4, working for ver 5 of mat parallel

This commit is contained in:
Youmu Liu
2026-04-09 18:07:49 +08:00
parent 0bad6bb480
commit f7187ca7fd
19 changed files with 653 additions and 187 deletions
@@ -1,30 +1,27 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="L4.CacheLine.cs"
// file="L4.CacheLine"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
// AuthorGroup: Nitload
// Copyright (c) Nitload. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and
// this permission notice shall be included in all copies
// or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”,
// WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
@@ -51,8 +48,8 @@ namespace StgSharp.HighPerformance.Memory
internal int _refCount;
internal nuint _address;
internal nuint _origin;
internal ulong _profile;
internal uint _predictor;
internal uint _profile;
}
@@ -42,16 +42,7 @@ namespace StgSharp.HighPerformance.Memory
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void AgeAll()
{
Vector128<byte> one = Vector128.Create((byte)0x01);
Vector128<byte> max = Vector128.Create((byte)0x03);
byte* p = (byte*)_eviction;
for (int i = 0; i < CacheLineCount; i += 16)
{
Vector128<byte> v = Sse2.LoadVector128(p + i);
v = Sse2.AddSaturate(v, one);
v = Sse2.Min(v, max);
Sse2.Store(p + i, v);
}
_intrinsic.AgeAll(_eviction);
}
/// <summary>
@@ -69,15 +60,12 @@ namespace StgSharp.HighPerformance.Memory
)
{
int remain = count;
Vector128<byte> one = Vector128.Create((byte)0x01);
Vector128<byte> three = Vector128.Create((byte)0x03);
byte* p = (byte*)_eviction;
for (int i = 0; i < CacheLineCount && remain > 0; i += 16)
for (int i = 0; (i < CacheLineCount) && (remain > 0); i += 16)
{
Vector128<byte> v = Sse2.LoadVector128(p + i);
Vector128<byte> mask = Sse2.CompareEqual(v, three);
int evictMask = Sse2.MoveMask(mask);
while (evictMask != 0 && remain > 0)
int evictMask = _intrinsic.ScanEvict(p + i, three);
while ((evictMask != 0) && (remain > 0))
{
int bitPos = BitOperations.TrailingZeroCount(evictMask);
int index = bitPos + i;
@@ -86,7 +74,10 @@ namespace StgSharp.HighPerformance.Memory
{
// EvictLine(i + index);
_ = _map.TryRemove(head->_origin, out _);
PrefetchPredict.WriteBack(head->_origin, head->_profile, new ReadOnlySpan<byte>((byte*)head->_address, Unsafe.SizeOf<CacheLineData>()));
int id = (int)head->_predictor;
IL4Predict predict = _predictions[id] ??
throw new L4PredictUnregisteredException(id);
predict.WriteBack(head->_origin, head->_profile, new ReadOnlySpan<byte>((byte*)head->_address, Unsafe.SizeOf<CacheLineData>()));
RecycleLine(index);
remain--;
}
@@ -0,0 +1,45 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="L4.Exceptions"
// Project: StgSharp
// AuthorGroup: Nitload
// Copyright (c) Nitload. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.HighPerformance.Memory
{
public sealed class L4PredictUnregisteredException : Exception
{
public L4PredictUnregisteredException(
int id
)
: base($"L4 predictor with id {id} is null. Maybe it has been unregistered.") { }
}
}
@@ -0,0 +1,105 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="L4.IntrinsicKernel"
// Project: StgSharp
// AuthorGroup: Nitload
// Copyright (c) Nitload. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.HighPerformance.Memory
{
public unsafe partial class L4
{
private interface IIntrinsicKernel
{
static IIntrinsicKernel Instance { get; } = Create();
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AgeAll(
EvictionArray* eviction
);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ScanEvict(
byte* vPtr,
Vector128<byte> three
);
private static IIntrinsicKernel Create()
{
if (Sse42.IsSupported)
{
return new SseKernel();
} else
{
throw new PlatformNotSupportedException("No supported intrinsic kernel found for current platform.");
}
}
}
private struct SseKernel : IIntrinsicKernel
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AgeAll(
EvictionArray* eviction
)
{
Vector128<byte> one = Vector128.Create((byte)0x01);
Vector128<byte> max = Vector128.Create((byte)0x03);
byte* p = (byte*)eviction;
for (int i = 0; i < CacheLineCount; i += 16)
{
Vector128<byte> v = Sse2.LoadVector128(p + i);
v = Sse2.AddSaturate(v, one);
v = Sse2.Min(v, max);
Sse2.Store(p + i, v);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public int ScanEvict(
byte* vPtr,
Vector128<byte> three
)
{
Vector128<byte> v = Sse2.LoadVector128(vPtr);
Vector128<byte> mask = Sse2.CompareEqual(v, three);
return Sse2.MoveMask(mask);
}
}
}
}
@@ -2,8 +2,8 @@
// -----------------------------------------------------------------------
// file="L4.Predict"
// Project: StgSharp
// AuthorGroup: Nitload Space
// Copyright (c) Nitload Space. All rights reserved.
// AuthorGroup: Nitload
// Copyright (c) Nitload. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
@@ -25,6 +25,8 @@
//
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
using StgSharp.Common.Collections;
using StgSharp.Mathematics.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -33,85 +35,65 @@ using System.Threading.Tasks;
namespace StgSharp.HighPerformance.Memory
{
[Flags]
public enum PredictResult
public partial class L4
{
Success = 1,
Exhausted = 2,
private ConcurrentBufferStack<int> _idReuse = new(32);
}
private ConcurrentFlexibleArray<IL4Predict> _predictions = new(32);
public interface IL4Predict
{
private int _largestId = 0;
PredictResult Predict(Span<CacheLinePrediction> node, out int count);
private Queue<int> _predictionQueue = [];
/// <summary>
/// Materializes the cache line identified by <paramref name="origin" /> into <paramref /// ///
/// name="cache" />.
/// </summary>
/// <param name="origin">
/// Source address associated with the cache line.
/// </param>
/// <param name="policy">
/// Mapping policy associated with the cache line.
/// </param>
/// <param name="cache">
/// Destination cache line buffer.
/// </param>
void Prefetch(nuint origin, ulong policy, Span<byte> cache);
private IL4Predict CurrentPredict { get; set; }
/// <summary>
/// Writes the cache line in <paramref name="cache" /> back to <paramref name="origin" />.
/// </summary>
/// <param name="origin">
/// Source address associated with the cache line.
/// </param>
/// <param name="policy">
/// Mapping policy associated with the cache line.
/// </param>
/// <param name="cache">
/// Source cache line buffer.
/// </param>
void WriteBack(nuint origin, ulong policy, ReadOnlySpan<byte> cache);
}
public struct CacheLinePrediction : IEquatable<CacheLinePrediction>
{
public override readonly bool Equals(object? obj)
public int RegisterPredict(
IL4Predict predict
)
{
return (obj is CacheLinePrediction prediction) &&
Address.Equals(prediction.Address) &&
(MapPolicy == prediction.MapPolicy);
if (predict is null) {
return -1;
}
if (!_idReuse.TryPop(out int id)) {
id = _largestId++;
}
_predictions[id] = predict;
_predictionQueue.Enqueue(id);
return id;
}
public readonly bool Equals(CacheLinePrediction other)
public IL4Predict? UnregisterPredict(
int id
)
{
return
(Address == other.Address) && (MapPolicy == other.MapPolicy);
if (id < 0) {
return null;
}
IL4Predict p = _predictions[id];
if (p == null) {
return p;
}
_predictions[id] = null!;
// TODO: scan and write back
_idReuse.Push(id);
return p;
}
public override readonly int GetHashCode()
private void UseNewPredict()
{
return HashCode.Combine(Address, MapPolicy);
if (_predictionQueue.Count == 0) {
return;
}
if (_predictionQueue.TryDequeue(out int id))
{
IL4Predict predict = _predictions[id] ??
throw new L4PredictUnregisteredException(id);
CurrentPredict = predict;
}
}
public static bool operator !=(CacheLinePrediction left, CacheLinePrediction right)
{
return !(left == right);
}
public static bool operator ==(CacheLinePrediction left, CacheLinePrediction right)
{
return left.Equals(right);
}
#pragma warning disable CA1051
public nuint Address;
public ulong MapPolicy;
#pragma warning restore CA1051
}
}
@@ -0,0 +1,138 @@
//-----------------------------------------------------------------------
// -----------------------------------------------------------------------
// file="L4.Predictor"
// Project: StgSharp
// AuthorGroup: Nitload
// Copyright (c) Nitload. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// -----------------------------------------------------------------------
// -----------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace StgSharp.HighPerformance.Memory
{
[Flags]
public enum PredictResult
{
Success = 1,
Exhausted = 2,
}
public interface IL4Predict
{
PredictResult Predict(
Span<CacheLinePrediction> node,
out int count
);
/// <summary>
/// Materializes the cache line identified by <paramref name="origin" /> into <paramref
/// name="cache" />.
/// </summary>
/// <param name="origin">
/// Source address associated with the cache line.
/// </param>
/// <param name="policy">
/// Mapping policy associated with the cache line.
/// </param>
/// <param name="cache">
/// Destination cache line buffer.
/// </param>
void Prefetch(
nuint origin,
ulong policy,
Span<byte> cache
);
/// <summary>
/// Writes the cache line in <paramref name="cache" /> back to <paramref name="origin" />.
/// </summary>
/// <param name="origin">
/// Source address associated with the cache line.
/// </param>
/// <param name="policy">
/// Mapping policy associated with the cache line.
/// </param>
/// <param name="cache">
/// Source cache line buffer.
/// </param>
void WriteBack(
nuint origin,
uint policy,
ReadOnlySpan<byte> cache
);
}
public struct CacheLinePrediction : IEquatable<CacheLinePrediction>
{
public override readonly bool Equals(
object? obj
)
{
return (obj is CacheLinePrediction prediction) &&
Address.Equals(prediction.Address) &&
(MapPolicy == prediction.MapPolicy);
}
public readonly bool Equals(
CacheLinePrediction other
)
{
return
(Address == other.Address) && (MapPolicy == other.MapPolicy);
}
public override readonly int GetHashCode()
{
return HashCode.Combine(Address, MapPolicy);
}
public static bool operator !=(
CacheLinePrediction left,
CacheLinePrediction right
)
{
return !(left == right);
}
public static bool operator ==(
CacheLinePrediction left,
CacheLinePrediction right
)
{
return left.Equals(right);
}
#pragma warning disable CA1051
public nuint Address;
public uint MapPolicy;
internal uint Predictor;
#pragma warning restore CA1051
}
}
@@ -36,14 +36,15 @@ namespace StgSharp.HighPerformance.Memory
private partial void Prefetch()
{
if (PrefetchPredict is null) {
if (CurrentPredict is null) {
return;
}
if (_activeCount > MaxActivateCacheLineCount) {
throw new OverflowException("Too many activated cache line in external reference.");
}
Span<CacheLinePrediction> span = new(_prediction, PredictionCount);
if (!PrefetchPredict.Predict(span, out int actualCount) && (actualCount <= 0))
PredictResult result = PrefetchPredict.Predict(span, out int actualCount);
if ((result == PredictResult.Exhausted) && (actualCount <= 0))
{
_exhausted = true;
return;
@@ -87,7 +88,7 @@ namespace StgSharp.HighPerformance.Memory
head->_origin = address;
head->_profile = handle.MapPolicy;
head->_refCount = 0;
head->_address = nuint & _data[index];
head->_address = (nuint)(_data + index);
// pre fetch them here
PrefetchPredict.Prefetch(head->_origin, head->_profile, new Span<byte>((byte*)head->_address, Unsafe.SizeOf<CacheLineData>()));
+6 -4
View File
@@ -38,12 +38,14 @@ namespace StgSharp.HighPerformance.Memory
private const int PredictionCount = 2048;
private const int PredictionLeastAhead = 1024;
private static readonly IIntrinsicKernel _intrinsic = IIntrinsicKernel.Instance;
private readonly CacheLineData* _data;
private readonly EvictionArray* _eviction;
private readonly CacheLineHead* _head;
private readonly CacheLinePrediction* _prediction;
private bool _disposed;
private bool _exhausted;
private int _activeCount;
private int _aheadCount;
@@ -84,7 +86,7 @@ namespace StgSharp.HighPerformance.Memory
ptr += stackSize;
}
public IL4Predict PrefetchPredict { get; set; }
// public IL4Predict PrefetchPredict { get; set; }
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ContinueOnce(
@@ -121,7 +123,7 @@ namespace StgSharp.HighPerformance.Memory
nuint origin
)
{
if ((_aheadCount < PredictionLeastAhead) && !PrefetchPredict.IsExhausted)
if ((_aheadCount < PredictionLeastAhead) && !_exhausted)
{
if (Interlocked.CompareExchange(ref _prefetching, 1, 0) == 0)
{
@@ -193,7 +195,7 @@ namespace StgSharp.HighPerformance.Memory
_activeCount = ref activeCount;
}
[Obsolete("You should not create a CacheLineHandle outside a L4", true)]
[Obsolete("You should not create a CacheLineHandle instance outside a L4", true)]
public L4CacheLine() { }
public readonly nuint Address => _handle;