N4YuC4 commited on
Commit
76ee3eb
·
verified ·
1 Parent(s): 1f93d93

deploy: update to glibc 2.35 ubuntu-22.04 sm_120 native wheel

Browse files
requirements.txt CHANGED
@@ -17,6 +17,6 @@ openpyxl>=3.1.0
17
  beautifulsoup4>=4.12.0
18
  rank-bm25>=0.2.2
19
  pypdfium2>=4.30.0
20
- llama-cpp-python @ https://github.com/N4YuC4/llama-wheel-builder/releases/download/wheel-v0.3.36-sm120/llama_cpp_python-0.3.36-py3-none-linux_x86_64.whl ; platform_system == "Linux" and platform_machine == "x86_64"
21
  llama-cpp-python>=0.3.0 ; platform_system != "Linux" or platform_machine != "x86_64"
22
  tomli>=2.0.0; python_version < "3.11"
 
17
  beautifulsoup4>=4.12.0
18
  rank-bm25>=0.2.2
19
  pypdfium2>=4.30.0
20
+ llama-cpp-python @ https://github.com/N4YuC4/llama-wheel-builder/releases/download/wheel-v0.3.36-sm120/llama_cpp_python-0.3.36-py3-none-linux_x86_64.whl ; platform_system == "Linux" and platform_machine == "x86_64" # sm120-glibc235
21
  llama-cpp-python>=0.3.0 ; platform_system != "Linux" or platform_machine != "x86_64"
22
  tomli>=2.0.0; python_version < "3.11"
src/docneedle/extraction/service.py CHANGED
@@ -332,7 +332,7 @@ class ExtractionService:
332
  )
333
 
334
  t_ret_start = time.perf_counter()
335
- item_matches, sorted_chunks, context_str = self._collect_field_matches(
336
  items=items,
337
  store=store,
338
  top_k=k,
@@ -340,10 +340,6 @@ class ExtractionService:
340
  )
341
  t_ret_elapsed = time.perf_counter() - t_ret_start
342
 
343
- t_img_start = time.perf_counter()
344
- image_bytes_list = self._collect_visual_page_images(store, sorted_chunks)
345
- t_img_elapsed = time.perf_counter() - t_img_start
346
-
347
  batch_size = max(1, settings.extraction_schema_batch_size)
348
  total_items_count = len(items)
349
  processed_idx = 0
@@ -351,6 +347,24 @@ class ExtractionService:
351
  t_llm_start = time.perf_counter()
352
  for b_start in range(0, total_items_count, batch_size):
353
  batch_items = items[b_start : b_start + batch_size]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
354
  fields_payload = [
355
  {
356
  "key": it.key,
@@ -363,8 +377,8 @@ class ExtractionService:
363
 
364
  extracted_dict = await self.llm_client.extract_schema(
365
  fields=fields_payload,
366
- context=context_str,
367
- image_bytes_list=image_bytes_list if image_bytes_list else None,
368
  )
369
 
370
  for item in batch_items:
@@ -379,8 +393,11 @@ class ExtractionService:
379
 
380
  if is_found and raw_val is not None:
381
  matches = item_matches.get(item.key, [])
382
- if not matches and sorted_chunks:
383
- matches = [SearchResult(chunk=c, score=1.0) for c in sorted_chunks[:k]]
 
 
 
384
  is_cover = bool(
385
  _COVER_PAGE_PATTERN.search(item.description or "")
386
  or _COVER_PAGE_PATTERN.search(item.key.replace("_", " "))
@@ -422,11 +439,9 @@ class ExtractionService:
422
  found_count = sum(1 for r in results if r.found)
423
  elapsed_ms = (time.perf_counter() - start_time) * 1000.0
424
  logger.info(
425
- "--> [EXTRACTION TIMING] Retrieval: %.2fs | Images: %.2fs (imgs=%d) | "
426
  "LLM Inference: %.2fs | Collision: %.2fs | Total: %.2fs",
427
  t_ret_elapsed,
428
- t_img_elapsed,
429
- len(image_bytes_list) if image_bytes_list else 0,
430
  t_llm_elapsed,
431
  t_col_elapsed,
432
  elapsed_ms / 1000.0,
 
332
  )
333
 
334
  t_ret_start = time.perf_counter()
335
+ item_matches, all_candidate_chunks, _ = self._collect_field_matches(
336
  items=items,
337
  store=store,
338
  top_k=k,
 
340
  )
341
  t_ret_elapsed = time.perf_counter() - t_ret_start
342
 
 
 
 
 
343
  batch_size = max(1, settings.extraction_schema_batch_size)
344
  total_items_count = len(items)
345
  processed_idx = 0
 
347
  t_llm_start = time.perf_counter()
348
  for b_start in range(0, total_items_count, batch_size):
349
  batch_items = items[b_start : b_start + batch_size]
350
+ batch_chunks_map: dict[str, Any] = {}
351
+ for it in batch_items:
352
+ for m in item_matches.get(it.key, []):
353
+ batch_chunks_map[m.chunk.chunk_id] = m.chunk
354
+
355
+ if not batch_chunks_map and store.chunks:
356
+ for c in store.chunks[:k]:
357
+ batch_chunks_map[c.chunk_id] = c
358
+
359
+ sorted_batch_chunks = sorted(
360
+ batch_chunks_map.values(),
361
+ key=lambda c: (c.doc_name, c.page_number or 0, c.chunk_index),
362
+ )
363
+ batch_context_str = settings.extraction_context_delimiter.join(
364
+ c.text.strip() for c in sorted_batch_chunks
365
+ )
366
+ batch_images = self._collect_visual_page_images(store, sorted_batch_chunks)
367
+
368
  fields_payload = [
369
  {
370
  "key": it.key,
 
377
 
378
  extracted_dict = await self.llm_client.extract_schema(
379
  fields=fields_payload,
380
+ context=batch_context_str,
381
+ image_bytes_list=batch_images if batch_images else None,
382
  )
383
 
384
  for item in batch_items:
 
393
 
394
  if is_found and raw_val is not None:
395
  matches = item_matches.get(item.key, [])
396
+ if not matches and sorted_batch_chunks:
397
+ matches = [
398
+ SearchResult(chunk=c, score=1.0)
399
+ for c in sorted_batch_chunks[:k]
400
+ ]
401
  is_cover = bool(
402
  _COVER_PAGE_PATTERN.search(item.description or "")
403
  or _COVER_PAGE_PATTERN.search(item.key.replace("_", " "))
 
439
  found_count = sum(1 for r in results if r.found)
440
  elapsed_ms = (time.perf_counter() - start_time) * 1000.0
441
  logger.info(
442
+ "--> [EXTRACTION TIMING] Retrieval: %.2fs | "
443
  "LLM Inference: %.2fs | Collision: %.2fs | Total: %.2fs",
444
  t_ret_elapsed,
 
 
445
  t_llm_elapsed,
446
  t_col_elapsed,
447
  elapsed_ms / 1000.0,
src/docneedle/llm/local_engine.py CHANGED
@@ -1,13 +1,17 @@
1
  """Local in-process GGUF LLM engine for information extraction."""
2
 
3
  import base64
 
4
  import logging
 
5
  import os
6
  import threading
7
  import time
8
  from pathlib import Path
9
  from typing import Any
10
 
 
 
11
  from docneedle.config import settings
12
  from docneedle.llm.handlers import (
13
  DocNeedleGemma4ChatHandler,
@@ -390,16 +394,20 @@ class LocalLLMEngine:
390
  )
391
  )
392
  reserved_gen_room = min(target_gen_limit, 512)
393
- safety_margin = 64
394
- tokens_per_image = 1280
395
 
396
- # Cap images if total image budget would starve context window
397
- max_image_budget = max(0, self.n_ctx - reserved_gen_room - 2048 - safety_margin)
398
- max_allowed_images = max(1, max_image_budget // tokens_per_image)
399
- if len(valid_images) > max_allowed_images:
400
- valid_images = valid_images[:max_allowed_images]
 
 
 
 
 
401
 
402
- total_image_tokens = len(valid_images) * tokens_per_image
403
 
404
  clean_context = context.strip()
405
  has_real_text = any(
@@ -420,11 +428,9 @@ class LocalLLMEngine:
420
  wrapper_tokens = len(self.llm.tokenize(wrapper_no_ctx.encode("utf-8")))
421
  max_ctx_budget = max(
422
  256,
423
- self.n_ctx
424
- - reserved_gen_room
425
  - wrapper_tokens
426
- - total_image_tokens
427
- - safety_margin,
428
  )
429
 
430
  ctx_tokens = self.llm.tokenize(clean_context.encode("utf-8"))
@@ -477,7 +483,7 @@ class LocalLLMEngine:
477
  actual_text_tokens = len(self.llm.tokenize(instruction_text.encode("utf-8")))
478
  total_prompt_tokens = total_image_tokens + actual_text_tokens + 16
479
  avail_tokens = max(
480
- 16, min(target_gen_limit, self.n_ctx - total_prompt_tokens - 16)
481
  )
482
  res = self.llm.create_chat_completion(
483
  messages=messages,
@@ -680,21 +686,20 @@ class LocalLLMEngine:
680
 
681
  target_gen_limit = min(settings.llm_max_tokens, 4096)
682
  reserved_gen_room = min(target_gen_limit, 2048)
683
- safety_margin = 64
684
- tokens_per_image = 1280
685
-
686
- # Cap images if total image budget would starve context window
687
- max_image_budget = max(0, self.n_ctx - reserved_gen_room - 4096 - safety_margin)
688
- max_allowed_images = max(0, max_image_budget // tokens_per_image)
689
- if len(valid_images) > max_allowed_images:
690
- logger.info(
691
- "--> [LLM Unified Schema] Capping images from %d to %d to preserve context budget.",
692
- len(valid_images),
693
- max_allowed_images,
694
- )
695
- valid_images = valid_images[:max_allowed_images]
696
 
697
- total_image_tokens = len(valid_images) * tokens_per_image
698
 
699
  # Measure prompt wrapper without context
700
  wrapper_prompt = _build_schema_extraction_prompt(fields, "")
@@ -702,11 +707,7 @@ class LocalLLMEngine:
702
 
703
  max_ctx_budget = max(
704
  256,
705
- self.n_ctx
706
- - reserved_gen_room
707
- - wrapper_tokens
708
- - total_image_tokens
709
- - safety_margin,
710
  )
711
 
712
  ctx_tokens = self.llm.tokenize(context.encode("utf-8"))
@@ -768,7 +769,7 @@ class LocalLLMEngine:
768
  actual_text_tokens = len(self.llm.tokenize(full_user_text.encode("utf-8")))
769
  total_prompt_tokens = total_image_tokens + actual_text_tokens + 16
770
  avail_tokens = max(
771
- 64, min(target_gen_limit, self.n_ctx - total_prompt_tokens - 16)
772
  )
773
  res = self.llm.create_chat_completion(
774
  messages=messages,
 
1
  """Local in-process GGUF LLM engine for information extraction."""
2
 
3
  import base64
4
+ import io
5
  import logging
6
+ import math
7
  import os
8
  import threading
9
  import time
10
  from pathlib import Path
11
  from typing import Any
12
 
13
+ from PIL import Image
14
+
15
  from docneedle.config import settings
16
  from docneedle.llm.handlers import (
17
  DocNeedleGemma4ChatHandler,
 
394
  )
395
  )
396
  reserved_gen_room = min(target_gen_limit, 512)
397
+ safety_margin = max(512, settings.model_n_ubatch * 2)
 
398
 
399
+ total_image_tokens = 0
400
+ if valid_images:
401
+ for img_b in valid_images:
402
+ try:
403
+ with Image.open(io.BytesIO(img_b)) as im:
404
+ w, h = im.size
405
+ toks = max(64, math.ceil(w / 32) * math.ceil(h / 32))
406
+ total_image_tokens += toks
407
+ except Exception:
408
+ total_image_tokens += 1800
409
 
410
+ max_prompt_ceiling = min(self.n_ctx - reserved_gen_room - safety_margin, 24000)
411
 
412
  clean_context = context.strip()
413
  has_real_text = any(
 
428
  wrapper_tokens = len(self.llm.tokenize(wrapper_no_ctx.encode("utf-8")))
429
  max_ctx_budget = max(
430
  256,
431
+ max_prompt_ceiling
 
432
  - wrapper_tokens
433
+ - total_image_tokens,
 
434
  )
435
 
436
  ctx_tokens = self.llm.tokenize(clean_context.encode("utf-8"))
 
483
  actual_text_tokens = len(self.llm.tokenize(instruction_text.encode("utf-8")))
484
  total_prompt_tokens = total_image_tokens + actual_text_tokens + 16
485
  avail_tokens = max(
486
+ 16, min(target_gen_limit, self.n_ctx - total_prompt_tokens - safety_margin)
487
  )
488
  res = self.llm.create_chat_completion(
489
  messages=messages,
 
686
 
687
  target_gen_limit = min(settings.llm_max_tokens, 4096)
688
  reserved_gen_room = min(target_gen_limit, 2048)
689
+ safety_margin = max(512, settings.model_n_ubatch * 2)
690
+
691
+ total_image_tokens = 0
692
+ if valid_images:
693
+ for img_b in valid_images:
694
+ try:
695
+ with Image.open(io.BytesIO(img_b)) as im:
696
+ w, h = im.size
697
+ toks = max(64, math.ceil(w / 32) * math.ceil(h / 32))
698
+ total_image_tokens += toks
699
+ except Exception:
700
+ total_image_tokens += 1800
 
701
 
702
+ max_prompt_ceiling = min(self.n_ctx - reserved_gen_room - safety_margin, 24000)
703
 
704
  # Measure prompt wrapper without context
705
  wrapper_prompt = _build_schema_extraction_prompt(fields, "")
 
707
 
708
  max_ctx_budget = max(
709
  256,
710
+ max_prompt_ceiling - wrapper_tokens - total_image_tokens,
 
 
 
 
711
  )
712
 
713
  ctx_tokens = self.llm.tokenize(context.encode("utf-8"))
 
769
  actual_text_tokens = len(self.llm.tokenize(full_user_text.encode("utf-8")))
770
  total_prompt_tokens = total_image_tokens + actual_text_tokens + 16
771
  avail_tokens = max(
772
+ 64, min(target_gen_limit, self.n_ctx - total_prompt_tokens - safety_margin)
773
  )
774
  res = self.llm.create_chat_completion(
775
  messages=messages,