Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

llama_decode lock #595

Merged
merged 2 commits into from
Mar 13, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 15 additions & 2 deletions LLama/Native/SafeLLamaContextHandle.cs
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,18 @@ public uint TokenToSpan(LLamaToken token, Span<byte> dest)
#endregion

#region infer
/// <summary>
/// This object exists to ensure there is only ever 1 inference running at a time. This is a workaround for thread safety issues in llama.cpp itself.
/// Most notably CUDA, which seems to use some global singleton resources and will crash if multiple inferences are run (even against different models).
///
/// For more information see these issues:
/// - https://github.com/SciSharp/LLamaSharp/issues/596
/// - https://github.com/ggerganov/llama.cpp/issues/3960
///
/// If these are ever resolved this lock can probably be removed.
/// </summary>
private static readonly object GlobalInferenceLock = new();

/// <summary>
/// </summary>
/// <param name="batch"></param>
Expand All @@ -202,8 +214,9 @@ public uint TokenToSpan(LLamaToken token, Span<byte> dest)
/// </returns>
public DecodeResult Decode(LLamaBatch batch)
{
using (batch.ToNativeBatch(out var nb))
return (DecodeResult)NativeApi.llama_decode(this, nb);
lock (GlobalInferenceLock)
using (batch.ToNativeBatch(out var nb))
return (DecodeResult)NativeApi.llama_decode(this, nb);
}

/// <summary>
Expand Down
Loading