大量OCR時的高峰內存問題
同時對多個PDF片段運行OCR會倍增內存使用。 每個任務透過OcrInput渲染全頁位圖,且每個段的全新IronTesseract引擎在每次重新載入時都會載入語言模型文件。在全處理器並行運作下,這會將峰值記憶體推至多GB範圍,並在記憶體限制的環境中出現失敗的情形。
OCR本質上是內存密集型的。 每個 OcrInput 都會渲染全頁位圖,而每個 IronTesseract 引擎則會將語言模型文件加載到記憶體中。 為每個段落創建一個新的引擎會重複加載那些模型,而每個 CPU 核心運行一個 OCR 任務 (Environment.ProcessorCount) 允許許多重度位圖的工作並行運行。在沒有任何限制活躍任務數量的情況下,內存峰值會直接隨著併發性增長。
解決方案是限制飛行中的作業數量:限制並發,從池中重用引擎,並使用信號量來限制工作。
解決方案
1. 限制OCR的並發性
將同時OCR任務的數量限制在一個小的上限。 更少的並發任務意味著內存中同時存在的完整頁面位圖更少,這直接降低了峰值。 根據機器的能力調整上限。
// Clamp concurrency to avoid memory saturation and CPU over-subscription.
int concurrency = Math.Clamp(Environment.ProcessorCount / 2, 1, 4);Dim concurrency As Integer = Math.Clamp(Environment.ProcessorCount \ 2, 1, 4)Dim concurrency As Integer = Math.Clamp(Environment.ProcessorCount \ 2, 1, 4)2. 將引擎放入池
在啟動時為每個併發插槽創建恰好一個IronTesseract引擎,並在每個階段中重複使用它們,而不是每次都構建新的引擎和重新加載語言模型。
// Pre-create one engine per concurrent slot and reuse them across segments.
var enginePool = new ConcurrentBag<IronTesseract>(
Enumerable.Range(0, concurrency).Select(_ => new IronTesseract())
);// Pre-create one engine per concurrent slot and reuse them across segments.
var enginePool = new ConcurrentBag<IronTesseract>(
Enumerable.Range(0, concurrency).Select(_ => new IronTesseract())
);' Pre-create one engine per concurrent slot and reuse them across segments.
Dim enginePool = New ConcurrentBag(Of IronTesseract)(
Enumerable.Range(0, concurrency).Select(Function(_) New IronTesseract())
)' Pre-create one engine per concurrent slot and reuse them across segments.
Dim enginePool = New ConcurrentBag(Of IronTesseract)(
Enumerable.Range(0, concurrency).Select(Function(_) New IronTesseract())
)一次構建池將語言模型的加載成本分攤到整個運行,而不是每個段都支付。
3. 使用信號量來限制工作
將SemaphoreSlim初始化為並發限制,並將其包裝在using中。 每項任務在開始前會呼叫WaitAsync(),在finally中呼叫Release(),因此每次只有允許數量的段在飛行中。
using var semaphore = new SemaphoreSlim(concurrency);
await semaphore.WaitAsync();
try
{
// Rent a pre-loaded engine from the pool.
if (!enginePool.TryTake(out var ocr))
ocr = new IronTesseract(); // Defensive fallback; should never be reached.
try
{
using var input = new OcrInput();
input.LoadPdf(segmentStream); // page-range segment produced upstream
var ocrResult = await ocr.ReadAsync(input);
ocrResult.SaveAsSearchablePdf(outputPath);
}
finally
{
enginePool.Add(ocr); // Return engine to pool for the next waiting segment.
}
}
finally
{
semaphore.Release();
}using var semaphore = new SemaphoreSlim(concurrency);
await semaphore.WaitAsync();
try
{
// Rent a pre-loaded engine from the pool.
if (!enginePool.TryTake(out var ocr))
ocr = new IronTesseract(); // Defensive fallback; should never be reached.
try
{
using var input = new OcrInput();
input.LoadPdf(segmentStream); // page-range segment produced upstream
var ocrResult = await ocr.ReadAsync(input);
ocrResult.SaveAsSearchablePdf(outputPath);
}
finally
{
enginePool.Add(ocr); // Return engine to pool for the next waiting segment.
}
}
finally
{
semaphore.Release();
}Using semaphore As New SemaphoreSlim(concurrency)
Await semaphore.WaitAsync()
Try
' Rent a pre-loaded engine from the pool.
Dim ocr As IronTesseract
If Not enginePool.TryTake(ocr) Then
ocr = New IronTesseract() ' Defensive fallback; should never be reached.
End If
Try
Using input As New OcrInput()
input.LoadPdf(segmentStream) ' page-range segment produced upstream
Dim ocrResult = Await ocr.ReadAsync(input)
ocrResult.SaveAsSearchablePdf(outputPath)
End Using
Finally
enginePool.Add(ocr) ' Return engine to pool for the next waiting segment.
End Try
Finally
semaphore.Release()
End Try
End UsingUsing semaphore As New SemaphoreSlim(concurrency)
Await semaphore.WaitAsync()
Try
' Rent a pre-loaded engine from the pool.
Dim ocr As IronTesseract
If Not enginePool.TryTake(ocr) Then
ocr = New IronTesseract() ' Defensive fallback; should never be reached.
End If
Try
Using input As New OcrInput()
input.LoadPdf(segmentStream) ' page-range segment produced upstream
Dim ocrResult = Await ocr.ReadAsync(input)
ocrResult.SaveAsSearchablePdf(outputPath)
End Using
Finally
enginePool.Add(ocr) ' Return engine to pool for the next waiting segment.
End Try
Finally
semaphore.Release()
End Try
End UsingWaitAsync() 呼叫將阻塞直到有空閒的插槽,並且在內部 finally 返回引擎,將預先加載的引擎直接交給下一個等待的段。
4. 每段處理OcrInput
將每個 OcrInput 包裹在 using 中,這樣它的渲染頁面位圖會在讀取段的那一刻釋放,然後在下個任務宣告槽位之前完成。
using在OcrInput上是防止位圖記憶體在各段之間累積的原因; 沒有它,釋放的插槽仍然保留其頁面位圖。5. 限制每次讀取的並行數
上面的步驟限制了同時運行的段的數量,但每個IronTesseract也會在單個Read調用中並行讀取頁面,默認為每個邏輯處理器一頁。 這兩個限制相乘:四個並行段與預設的16個相對,結果是64個原生引擎,而不是四個。 在每個池化引擎上設置MaxDegreeOfParallelism,以便內層也受到約束。
// Bound the inner layer as well as the outer one.
// Without this, each of the `concurrency` segments still fans out
// across every logical processor.
foreach (var engine in enginePool)
engine.MaxDegreeOfParallelism = 2;// Bound the inner layer as well as the outer one.
// Without this, each of the `concurrency` segments still fans out
// across every logical processor.
foreach (var engine in enginePool)
engine.MaxDegreeOfParallelism = 2;' Bound the inner layer as well as the outer one.
' Without this, each of the `concurrency` segments still fans out
' across every logical processor.
For Each engine In enginePool
engine.MaxDegreeOfParallelism = 2
Next' Bound the inner layer as well as the outer one.
' Without this, each of the `concurrency` segments still fans out
' across every logical processor.
For Each engine In enginePool
engine.MaxDegreeOfParallelism = 2
Next請參閱如何控制平行OCR記憶體使用,以了解這兩個屬性如何互動以及每個並行頁面花費多少。
Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。