spagestic commited on
Commit
f8fe299
·
1 Parent(s): 71a7158

Update requirements and improve model loading logic

Browse files

- Added a comment in requirements.txt to clarify the optional dependency on transformers for local inference mode.
- Suppressed warnings related to missing PyTorch in transformers within the UI initialization.
- Refactored model.py to use TYPE_CHECKING for imports, ensuring compatibility and avoiding runtime errors when PyTorch is not available.
- Enhanced device resolution logic and added assertions to ensure the device is properly set before model operations.

Files changed (3) hide show
  1. requirements.txt +1 -1
  2. ui/__init__.py +6 -0
  3. ui/agent/minicpm/model.py +16 -25
requirements.txt CHANGED
@@ -6,8 +6,8 @@ openai==2.41.0
6
  langchain-core==1.4.6
7
  langchain-openai==1.3.0
8
  langgraph==1.2.4
9
- transformers>=4.56
10
  mcp==1.27.2
 
11
 
12
  # Tools / APIs
13
  firecrawl-py==4.28.2
 
6
  langchain-core==1.4.6
7
  langchain-openai==1.3.0
8
  langgraph==1.2.4
 
9
  mcp==1.27.2
10
+ # Optional for BORDERLESS_INFERENCE_MODE=local only: transformers>=4.56 (HF Spaces injects torch)
11
 
12
  # Tools / APIs
13
  firecrawl-py==4.28.2
ui/__init__.py CHANGED
@@ -7,3 +7,9 @@ warnings.filterwarnings(
7
  category=UserWarning,
8
  module=r"firecrawl\.v2\.types",
9
  )
 
 
 
 
 
 
 
7
  category=UserWarning,
8
  module=r"firecrawl\.v2\.types",
9
  )
10
+ warnings.filterwarnings(
11
+ "ignore",
12
+ message="PyTorch was not found",
13
+ category=UserWarning,
14
+ module=r"transformers",
15
+ )
ui/agent/minicpm/model.py CHANGED
@@ -4,29 +4,34 @@ from __future__ import annotations
4
  import logging
5
  import os
6
  import threading
7
- from typing import Any
8
 
9
- import torch
10
- from huggingface_hub import login
11
  from langchain_core.messages import AIMessage
12
- from transformers import AutoModelForCausalLM, AutoTokenizer
13
 
14
  from ..config import ENABLE_THINKING, MODEL_ID
15
  from .messages import append_tool_instructions, normalize_messages
16
 
 
 
 
 
17
  logger = logging.getLogger(__name__)
18
 
19
  _GENERATE_LOCK = threading.Lock()
20
  _MODEL: AutoModelForCausalLM | None = None
21
  _TOKENIZER: AutoTokenizer | None = None
22
- _DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
23
 
24
 
25
  def _resolve_device() -> torch.device:
 
 
26
  return torch.device("cuda" if torch.cuda.is_available() else "cpu")
27
 
28
 
29
  def _hub_login() -> None:
 
 
30
  hf_token = os.environ.get("HF_TOKEN")
31
  if hf_token:
32
  login(token=hf_token)
@@ -37,9 +42,13 @@ def _hub_login() -> None:
37
 
38
  def _load_model() -> tuple[AutoTokenizer, AutoModelForCausalLM]:
39
  global _MODEL, _TOKENIZER, _DEVICE
 
 
 
 
40
  device = _resolve_device()
41
 
42
- if _MODEL is not None and _TOKENIZER is not None:
43
  if device.type != _DEVICE.type:
44
  logger.info("Moving MiniCPM model from %s to %s", _DEVICE, device)
45
  _MODEL = _MODEL.to(device)
@@ -103,6 +112,7 @@ def chat_complete(
103
  ) -> AIMessage:
104
  """Run one MiniCPM chat turn and return a LangChain AIMessage."""
105
  tokenizer, model = _load_model()
 
106
  normalized = normalize_messages(messages)
107
  if tools:
108
  normalized = append_tool_instructions(normalized, tools)
@@ -136,22 +146,3 @@ def chat_complete(
136
  additional_kwargs["reasoning_content"] = reasoning
137
 
138
  return AIMessage(content=content or raw_text, additional_kwargs=additional_kwargs)
139
-
140
-
141
- def _maybe_preload() -> None:
142
- if os.environ.get("BORDERLESS_INFERENCE_MODE", "local") != "local":
143
- return
144
- if os.environ.get("BORDERLESS_PRELOAD_MODEL", "0") != "1":
145
- return
146
- if not torch.cuda.is_available():
147
- logger.info(
148
- "Skipping MiniCPM eager preload — CUDA not available yet (loads on first ZeroGPU chat)"
149
- )
150
- return
151
- try:
152
- _load_model()
153
- except Exception as exc:
154
- logger.warning("MiniCPM eager preload skipped: %s", exc)
155
-
156
-
157
- _maybe_preload()
 
4
  import logging
5
  import os
6
  import threading
7
+ from typing import TYPE_CHECKING, Any
8
 
 
 
9
  from langchain_core.messages import AIMessage
 
10
 
11
  from ..config import ENABLE_THINKING, MODEL_ID
12
  from .messages import append_tool_instructions, normalize_messages
13
 
14
+ if TYPE_CHECKING:
15
+ import torch
16
+ from transformers import AutoModelForCausalLM, AutoTokenizer
17
+
18
  logger = logging.getLogger(__name__)
19
 
20
  _GENERATE_LOCK = threading.Lock()
21
  _MODEL: AutoModelForCausalLM | None = None
22
  _TOKENIZER: AutoTokenizer | None = None
23
+ _DEVICE: torch.device | None = None
24
 
25
 
26
  def _resolve_device() -> torch.device:
27
+ import torch
28
+
29
  return torch.device("cuda" if torch.cuda.is_available() else "cpu")
30
 
31
 
32
  def _hub_login() -> None:
33
+ from huggingface_hub import login
34
+
35
  hf_token = os.environ.get("HF_TOKEN")
36
  if hf_token:
37
  login(token=hf_token)
 
42
 
43
  def _load_model() -> tuple[AutoTokenizer, AutoModelForCausalLM]:
44
  global _MODEL, _TOKENIZER, _DEVICE
45
+ from transformers import AutoModelForCausalLM, AutoTokenizer
46
+
47
+ import torch
48
+
49
  device = _resolve_device()
50
 
51
+ if _MODEL is not None and _TOKENIZER is not None and _DEVICE is not None:
52
  if device.type != _DEVICE.type:
53
  logger.info("Moving MiniCPM model from %s to %s", _DEVICE, device)
54
  _MODEL = _MODEL.to(device)
 
112
  ) -> AIMessage:
113
  """Run one MiniCPM chat turn and return a LangChain AIMessage."""
114
  tokenizer, model = _load_model()
115
+ assert _DEVICE is not None
116
  normalized = normalize_messages(messages)
117
  if tools:
118
  normalized = append_tool_instructions(normalized, tools)
 
146
  additional_kwargs["reasoning_content"] = reasoning
147
 
148
  return AIMessage(content=content or raw_text, additional_kwargs=additional_kwargs)