polyollama 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- polyollama-0.1.0/.gitignore +11 -0
- polyollama-0.1.0/.python-version +1 -0
- polyollama-0.1.0/PKG-INFO +35 -0
- polyollama-0.1.0/README.md +15 -0
- polyollama-0.1.0/polyollama/__init__.py +14 -0
- polyollama-0.1.0/polyollama/misc/example_utils.py +124 -0
- polyollama-0.1.0/polyollama/mps.py +184 -0
- polyollama-0.1.0/polyollama/parallel.py +223 -0
- polyollama-0.1.0/polyollama/server.py +135 -0
- polyollama-0.1.0/pyproject.toml +29 -0
- polyollama-0.1.0/tests/test.py +118 -0
- polyollama-0.1.0/uv.lock +1904 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
3.12
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: polyollama
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Run multiple Ollama servers in parallel for concurrent LLM inference
|
|
5
|
+
Project-URL: Homepage, https://github.com/okanyenigun/polyollama
|
|
6
|
+
Project-URL: Repository, https://github.com/okanyenigun/polyollama
|
|
7
|
+
License: MIT
|
|
8
|
+
Keywords: inference,langchain,llm,ollama,parallel
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: Intended Audience :: Science/Research
|
|
12
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
13
|
+
Classifier: Programming Language :: Python :: 3
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Requires-Python: >=3.12
|
|
17
|
+
Requires-Dist: langchain-ollama>=0.2.0
|
|
18
|
+
Requires-Dist: langchain>=0.3.0
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# polyollama
|
|
22
|
+
|
|
23
|
+
Run multiple [Ollama](https://ollama.com) servers in parallel to maximize LLM inference throughput on a single machine.
|
|
24
|
+
|
|
25
|
+
## Installation
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install polyollama
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Requires [Ollama](https://ollama.com/download) on your `PATH`.
|
|
32
|
+
|
|
33
|
+
## License
|
|
34
|
+
|
|
35
|
+
MIT
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# polyollama
|
|
2
|
+
|
|
3
|
+
Run multiple [Ollama](https://ollama.com) servers in parallel to maximize LLM inference throughput on a single machine.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
pip install polyollama
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
Requires [Ollama](https://ollama.com/download) on your `PATH`.
|
|
12
|
+
|
|
13
|
+
## License
|
|
14
|
+
|
|
15
|
+
MIT
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
from .server import OllamaServer
|
|
2
|
+
from .parallel import parallel_inference, parallel_batch_inference
|
|
3
|
+
from .mps import MPSContext
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"OllamaServer",
|
|
8
|
+
"parallel_inference",
|
|
9
|
+
"parallel_batch_inference",
|
|
10
|
+
"MPSContext",
|
|
11
|
+
]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import time
|
|
2
|
+
from typing import Optional, Dict, Any, List
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
DEFAULT_HOST = "127.0.0.1"
|
|
6
|
+
DEFAULT_PORT = 11434
|
|
7
|
+
DEFAULT_URL = f"http://{DEFAULT_HOST}:{DEFAULT_PORT}"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def load_question_dataset(n: int) -> List[str]:
|
|
11
|
+
"""Load a dataset of questions to use for testing."""
|
|
12
|
+
from datasets import load_dataset
|
|
13
|
+
|
|
14
|
+
ds = load_dataset("HiTruong/movie_QA", "default")
|
|
15
|
+
questions = [item["Question"] for item in ds["train_v1"]]
|
|
16
|
+
return questions[:n]
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def get_chain(model: str, base_url: Optional[str] = None) -> Any:
|
|
20
|
+
"""Helper to create a LangChain chain for the specified model and base_url."""
|
|
21
|
+
from langchain_core.prompts import PromptTemplate
|
|
22
|
+
from langchain_ollama import ChatOllama
|
|
23
|
+
|
|
24
|
+
prompt = PromptTemplate.from_template("Answer politely: {question}")
|
|
25
|
+
kwargs = dict(model=model, temperature=0, max_tokens=2048)
|
|
26
|
+
|
|
27
|
+
if base_url:
|
|
28
|
+
kwargs["base_url"] = base_url
|
|
29
|
+
|
|
30
|
+
model = ChatOllama(**kwargs)
|
|
31
|
+
chain = prompt | model
|
|
32
|
+
return chain
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def simple_inference(model:str, question: str, base_url: Optional[str] = None) -> Any:
|
|
36
|
+
"""Run a single inference using the specified model and question."""
|
|
37
|
+
start = time.time()
|
|
38
|
+
|
|
39
|
+
chain = get_chain(model=model, base_url=base_url)
|
|
40
|
+
response = chain.invoke(question)
|
|
41
|
+
|
|
42
|
+
print(f"Time taken: {time.time() - start:.2f} seconds")
|
|
43
|
+
return response
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def sequential_inference(
|
|
47
|
+
model: str,
|
|
48
|
+
questions: List[str],
|
|
49
|
+
base_url: Optional[str] = None,
|
|
50
|
+
) -> List[Dict[str, Any]]:
|
|
51
|
+
"""
|
|
52
|
+
Run *questions* one by one against a single server and return results.
|
|
53
|
+
Prints per-question and total elapsed time.
|
|
54
|
+
"""
|
|
55
|
+
from langchain_ollama import ChatOllama
|
|
56
|
+
from langchain_core.prompts import PromptTemplate
|
|
57
|
+
|
|
58
|
+
prompt = PromptTemplate.from_template("Answer politely: {question}")
|
|
59
|
+
kwargs: dict = dict(model=model, temperature=0, max_tokens=2048)
|
|
60
|
+
if base_url:
|
|
61
|
+
kwargs["base_url"] = base_url
|
|
62
|
+
|
|
63
|
+
llm = ChatOllama(**kwargs)
|
|
64
|
+
chain = prompt | llm
|
|
65
|
+
|
|
66
|
+
url = base_url or DEFAULT_URL
|
|
67
|
+
results = []
|
|
68
|
+
total_start = time.time()
|
|
69
|
+
|
|
70
|
+
for i, question in enumerate(questions):
|
|
71
|
+
start = time.time()
|
|
72
|
+
response = chain.invoke({"question": question})
|
|
73
|
+
elapsed = time.time() - start
|
|
74
|
+
if i % 100 == 0:
|
|
75
|
+
print(f"[{url}] Q{i+1}/{len(questions)} done in {elapsed:.2f}s")
|
|
76
|
+
results.append({"url": url, "question": question, "response": response, "elapsed": elapsed})
|
|
77
|
+
|
|
78
|
+
total_elapsed = time.time() - total_start
|
|
79
|
+
print(f"Sequential total: {total_elapsed:.2f}s for {len(questions)} questions")
|
|
80
|
+
return results
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def batch_inference(
|
|
84
|
+
model: str,
|
|
85
|
+
questions: List[str],
|
|
86
|
+
batch_size: int = 6,
|
|
87
|
+
base_url: Optional[str] = None,
|
|
88
|
+
) -> List[Dict[str, Any]]:
|
|
89
|
+
"""
|
|
90
|
+
Run *questions* through a single server using LangChain's `.batch()`,
|
|
91
|
+
chunked into groups of *batch_size*. Prints per-batch and total time.
|
|
92
|
+
"""
|
|
93
|
+
from langchain_ollama import ChatOllama
|
|
94
|
+
from langchain_core.prompts import PromptTemplate
|
|
95
|
+
|
|
96
|
+
prompt = PromptTemplate.from_template("Answer politely: {question}")
|
|
97
|
+
kwargs: dict = dict(model=model, temperature=0, max_tokens=2048)
|
|
98
|
+
if base_url:
|
|
99
|
+
kwargs["base_url"] = base_url
|
|
100
|
+
|
|
101
|
+
llm = ChatOllama(**kwargs)
|
|
102
|
+
chain = prompt | llm
|
|
103
|
+
|
|
104
|
+
url = base_url or DEFAULT_URL
|
|
105
|
+
results = []
|
|
106
|
+
total_start = time.time()
|
|
107
|
+
batches = [questions[i : i + batch_size] for i in range(0, len(questions), batch_size)]
|
|
108
|
+
|
|
109
|
+
for b_idx, batch in enumerate(batches):
|
|
110
|
+
inputs = [{"question": q} for q in batch]
|
|
111
|
+
start = time.time()
|
|
112
|
+
responses = chain.batch(inputs)
|
|
113
|
+
elapsed = time.time() - start
|
|
114
|
+
if b_idx % 10 == 0:
|
|
115
|
+
print(
|
|
116
|
+
f"[{url}] Batch {b_idx+1}/{len(batches)} "
|
|
117
|
+
f"({len(batch)} examples) done in {elapsed:.2f}s"
|
|
118
|
+
)
|
|
119
|
+
for question, response in zip(batch, responses):
|
|
120
|
+
results.append({"url": url, "question": question, "response": response})
|
|
121
|
+
|
|
122
|
+
total_elapsed = time.time() - total_start
|
|
123
|
+
print(f"Batch total: {total_elapsed:.2f}s for {len(questions)} questions (batch_size={batch_size})")
|
|
124
|
+
return results
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
"""
|
|
2
|
+
NVIDIA Multi-Process Service (MPS) management for polyollama.
|
|
3
|
+
|
|
4
|
+
MPS replaces CUDA's default time-sliced process scheduling with a single
|
|
5
|
+
daemon that submits CUDA kernels from all client processes *concurrently*
|
|
6
|
+
onto the same GPU. On a single high-end GPU (e.g. RTX 5090) this allows
|
|
7
|
+
multiple Ollama servers to share Streaming Multiprocessors in parallel
|
|
8
|
+
instead of waiting for each other.
|
|
9
|
+
|
|
10
|
+
Requirements
|
|
11
|
+
------------
|
|
12
|
+
- NVIDIA GPU (Compute Capability >= 3.5)
|
|
13
|
+
- ``nvidia-cuda-mps-control`` in PATH (comes with the NVIDIA driver)
|
|
14
|
+
- Exclusive or Default compute mode on the GPU
|
|
15
|
+
(check: ``nvidia-smi -q | grep "Compute Mode"``)
|
|
16
|
+
|
|
17
|
+
Quickstart
|
|
18
|
+
----------
|
|
19
|
+
from polyollama.mps import MPSContext
|
|
20
|
+
from polyollama import parallel_distributed_inference
|
|
21
|
+
|
|
22
|
+
with MPSContext(gpu_id=0) as mps:
|
|
23
|
+
results = await parallel_distributed_inference(
|
|
24
|
+
model="gemma2:2b",
|
|
25
|
+
questions=questions,
|
|
26
|
+
extra_ports=[11435, 11436, 11437],
|
|
27
|
+
)
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
import os
|
|
31
|
+
import time
|
|
32
|
+
import shutil
|
|
33
|
+
import subprocess
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import Optional
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class MPSContext:
|
|
39
|
+
def __init__(
|
|
40
|
+
self,
|
|
41
|
+
gpu_id: int = 0,
|
|
42
|
+
pipe_dir: str = "/tmp/nvidia-mps",
|
|
43
|
+
log_dir: str = "/tmp/nvidia-mps-log",
|
|
44
|
+
thread_percentage: Optional[int] = None,
|
|
45
|
+
):
|
|
46
|
+
self.gpu_id = gpu_id
|
|
47
|
+
self.pipe_dir = pipe_dir
|
|
48
|
+
self.log_dir = log_dir
|
|
49
|
+
self.thread_percentage = thread_percentage
|
|
50
|
+
self._daemon_started: bool = False
|
|
51
|
+
|
|
52
|
+
# ------------------------------------------------------------------
|
|
53
|
+
# Context-manager protocol
|
|
54
|
+
# ------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
def __enter__(self) -> "MPSContext":
|
|
57
|
+
return self.start()
|
|
58
|
+
|
|
59
|
+
def __exit__(self, *_) -> None:
|
|
60
|
+
self.stop()
|
|
61
|
+
|
|
62
|
+
# ------------------------------------------------------------------
|
|
63
|
+
# Lifecycle
|
|
64
|
+
# ------------------------------------------------------------------
|
|
65
|
+
|
|
66
|
+
def start(self) -> "MPSContext":
|
|
67
|
+
"""Start the MPS daemon and export required env vars."""
|
|
68
|
+
if not self.is_available():
|
|
69
|
+
raise RuntimeError(
|
|
70
|
+
"nvidia-cuda-mps-control not found in PATH. "
|
|
71
|
+
"Make sure the NVIDIA driver is installed."
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
if self.is_running(self.pipe_dir):
|
|
75
|
+
print(f"MPS daemon already running (pipe={self.pipe_dir}) — reusing.")
|
|
76
|
+
self._inject_env()
|
|
77
|
+
return self
|
|
78
|
+
|
|
79
|
+
# Ensure the pipe and log directories exist before starting the daemon
|
|
80
|
+
Path(self.pipe_dir).mkdir(parents=True, exist_ok=True)
|
|
81
|
+
Path(self.log_dir).mkdir(parents=True, exist_ok=True)
|
|
82
|
+
|
|
83
|
+
# Start the MPS daemon with the appropriate environment variables
|
|
84
|
+
env = os.environ.copy()
|
|
85
|
+
env["CUDA_VISIBLE_DEVICES"] = str(self.gpu_id)
|
|
86
|
+
env["CUDA_MPS_PIPE_DIRECTORY"] = self.pipe_dir
|
|
87
|
+
env["CUDA_MPS_LOG_DIRECTORY"] = self.log_dir
|
|
88
|
+
if self.thread_percentage is not None:
|
|
89
|
+
env["CUDA_MPS_ACTIVE_THREAD_PERCENTAGE"] = str(self.thread_percentage)
|
|
90
|
+
|
|
91
|
+
result = subprocess.run(
|
|
92
|
+
["nvidia-cuda-mps-control", "-d"],
|
|
93
|
+
env=env,
|
|
94
|
+
capture_output=True,
|
|
95
|
+
text=True,
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
if result.returncode != 0:
|
|
99
|
+
raise RuntimeError(
|
|
100
|
+
f"Failed to start MPS daemon: {result.stderr.strip() or result.stdout.strip()}"
|
|
101
|
+
)
|
|
102
|
+
|
|
103
|
+
# Give the daemon a moment to create the socket
|
|
104
|
+
time.sleep(1.0)
|
|
105
|
+
|
|
106
|
+
self._daemon_started = True
|
|
107
|
+
|
|
108
|
+
self._inject_env()
|
|
109
|
+
pct = (
|
|
110
|
+
f", thread_percentage={self.thread_percentage}%"
|
|
111
|
+
if self.thread_percentage
|
|
112
|
+
else ""
|
|
113
|
+
)
|
|
114
|
+
print(f"MPS daemon started (GPU {self.gpu_id}{pct})")
|
|
115
|
+
return self
|
|
116
|
+
|
|
117
|
+
def stop(self) -> None:
|
|
118
|
+
"""Send 'quit' to the MPS daemon and clean up env vars."""
|
|
119
|
+
if not self._daemon_started:
|
|
120
|
+
return
|
|
121
|
+
|
|
122
|
+
env = os.environ.copy()
|
|
123
|
+
env["CUDA_MPS_PIPE_DIRECTORY"] = self.pipe_dir
|
|
124
|
+
|
|
125
|
+
subprocess.run(
|
|
126
|
+
["nvidia-cuda-mps-control"],
|
|
127
|
+
input="quit\n",
|
|
128
|
+
env=env,
|
|
129
|
+
capture_output=True,
|
|
130
|
+
text=True,
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
self._daemon_started = False
|
|
134
|
+
self._cleanup_env()
|
|
135
|
+
print("MPS daemon stopped.")
|
|
136
|
+
return
|
|
137
|
+
|
|
138
|
+
# ------------------------------------------------------------------
|
|
139
|
+
# Static helpers
|
|
140
|
+
# ------------------------------------------------------------------
|
|
141
|
+
@staticmethod
|
|
142
|
+
def is_available() -> bool:
|
|
143
|
+
"""True if the MPS control daemon executable is available."""
|
|
144
|
+
return shutil.which("nvidia-cuda-mps-control") is not None
|
|
145
|
+
|
|
146
|
+
@staticmethod
|
|
147
|
+
def is_running(pipe_dir: str = "/tmp/nvidia-mps") -> bool:
|
|
148
|
+
"""True if the MPS daemon is currently running (i.e. socket exists and is responsive)."""
|
|
149
|
+
env = os.environ.copy()
|
|
150
|
+
env["CUDA_MPS_PIPE_DIRECTORY"] = pipe_dir
|
|
151
|
+
result = subprocess.run(
|
|
152
|
+
["nvidia-cuda-mps-control"],
|
|
153
|
+
input="get_defeault_active_thread_percentage\n",
|
|
154
|
+
env=env,
|
|
155
|
+
capture_output=True,
|
|
156
|
+
text=True,
|
|
157
|
+
)
|
|
158
|
+
return result.returncode == 0
|
|
159
|
+
|
|
160
|
+
@staticmethod
|
|
161
|
+
def _cleanup_env() -> None:
|
|
162
|
+
"""Remove MPS-related env vars from the current process."""
|
|
163
|
+
for key in (
|
|
164
|
+
"CUDA_MPS_PIPE_DIRECTORY",
|
|
165
|
+
"CUDA_MPS_LOG_DIRECTORY",
|
|
166
|
+
"CUDA_MPS_ACTIVE_THREAD_PERCENTAGE",
|
|
167
|
+
):
|
|
168
|
+
os.environ.pop(key, None)
|
|
169
|
+
return
|
|
170
|
+
|
|
171
|
+
# ------------------------------------------------------------------
|
|
172
|
+
# Private helpers
|
|
173
|
+
# ------------------------------------------------------------------
|
|
174
|
+
|
|
175
|
+
def _inject_env(self) -> None:
|
|
176
|
+
"""Set MPS env vars on the current process so children inherit them."""
|
|
177
|
+
os.environ["CUDA_VISIBLE_DEVICES"] = str(self.gpu_id)
|
|
178
|
+
os.environ["CUDA_MPS_PIPE_DIRECTORY"] = self.pipe_dir
|
|
179
|
+
os.environ["CUDA_MPS_LOG_DIRECTORY"] = self.log_dir
|
|
180
|
+
if self.thread_percentage is not None:
|
|
181
|
+
os.environ["CUDA_MPS_ACTIVE_THREAD_PERCENTAGE"] = str(
|
|
182
|
+
self.thread_percentage
|
|
183
|
+
)
|
|
184
|
+
return
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Async parallel inference across multiple Ollama servers.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import math
|
|
7
|
+
from langchain_ollama import ChatOllama
|
|
8
|
+
from langchain_core.prompts import PromptTemplate
|
|
9
|
+
from langchain_core.output_parsers import BaseOutputParser
|
|
10
|
+
from typing import List, Dict, Any, Optional, Union
|
|
11
|
+
from .server import OllamaServer
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
async def _async_inference(
|
|
15
|
+
query: Dict[str, str],
|
|
16
|
+
prompt: PromptTemplate,
|
|
17
|
+
model: str,
|
|
18
|
+
parser: Optional[BaseOutputParser] = None,
|
|
19
|
+
model_kwargs: Optional[Dict[str, Any]] = None,
|
|
20
|
+
base_url: Optional[str] = None,
|
|
21
|
+
) -> Dict[str, Any]:
|
|
22
|
+
"""Run a single async inference call and return a result dict."""
|
|
23
|
+
# Note: model_kwargs can include any ChatOllama init args except 'model' and 'base_url'
|
|
24
|
+
kwargs = dict(model=model, **(model_kwargs or {}))
|
|
25
|
+
if base_url:
|
|
26
|
+
kwargs["base_url"] = base_url
|
|
27
|
+
|
|
28
|
+
llm = ChatOllama(**kwargs)
|
|
29
|
+
# If a parser is provided, chain it after the LLM. Otherwise just prompt → LLM.
|
|
30
|
+
if parser:
|
|
31
|
+
chain = prompt | llm | parser
|
|
32
|
+
else:
|
|
33
|
+
chain = prompt | llm
|
|
34
|
+
# If the parser is used, we need to add format instructions to the query dict for each inference call.
|
|
35
|
+
if parser:
|
|
36
|
+
format_instructions = parser.get_format_instructions()
|
|
37
|
+
query["format_instructions"] = format_instructions
|
|
38
|
+
|
|
39
|
+
response = await chain.ainvoke(query)
|
|
40
|
+
|
|
41
|
+
url = base_url or "default server"
|
|
42
|
+
|
|
43
|
+
return {"url": url, "response": response}
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
async def parallel_inference(
|
|
47
|
+
extra_ports: List[int],
|
|
48
|
+
query: Union[List[Dict[str, str]], List[str]],
|
|
49
|
+
prompt: str,
|
|
50
|
+
model: str,
|
|
51
|
+
parser: Optional[BaseOutputParser] = None,
|
|
52
|
+
model_kwargs: Optional[Dict[str, Any]] = None,
|
|
53
|
+
verbose: bool = True,
|
|
54
|
+
) -> List[Dict[str, Any]]:
|
|
55
|
+
"""Start one additional Ollama server per port in *extra_ports*, then run inference in parallel."""
|
|
56
|
+
# Create OllamaServer instances for each extra port. The default server is assumed to be already running.
|
|
57
|
+
servers = [OllamaServer(port=port) for port in extra_ports]
|
|
58
|
+
if verbose:
|
|
59
|
+
print(f"Starting {len(servers)} extra server(s)...")
|
|
60
|
+
# Boot all extra servers concurrently (blocking start() pushed to threads)
|
|
61
|
+
await asyncio.gather(*[asyncio.to_thread(srv.start) for srv in servers])
|
|
62
|
+
if verbose:
|
|
63
|
+
print("All servers ready. Running inference...")
|
|
64
|
+
# If a parser is provided, ensure the prompt includes format instructions.
|
|
65
|
+
if parser:
|
|
66
|
+
if "{format_instructions}" not in prompt:
|
|
67
|
+
prompt += "\n\nFormat Instructions:\n{format_instructions}"
|
|
68
|
+
|
|
69
|
+
prompt = PromptTemplate.from_template(prompt)
|
|
70
|
+
|
|
71
|
+
total = len(query)
|
|
72
|
+
counter = [0]
|
|
73
|
+
urls = [None] + [srv.url for srv in servers] # None → default server
|
|
74
|
+
# Limit in-flight requests to avoid overwhelming servers (one slot per server)
|
|
75
|
+
semaphore = asyncio.Semaphore(len(urls))
|
|
76
|
+
|
|
77
|
+
async def _tracked(item, url):
|
|
78
|
+
async with semaphore:
|
|
79
|
+
result = await _async_inference(
|
|
80
|
+
query=item,
|
|
81
|
+
prompt=prompt,
|
|
82
|
+
model=model,
|
|
83
|
+
parser=parser,
|
|
84
|
+
model_kwargs=model_kwargs,
|
|
85
|
+
base_url=url,
|
|
86
|
+
)
|
|
87
|
+
counter[0] += 1
|
|
88
|
+
if verbose and (counter[0] % 100 == 0 or counter[0] == total):
|
|
89
|
+
print(f" Progress: {counter[0]}/{total} done")
|
|
90
|
+
return result
|
|
91
|
+
|
|
92
|
+
try:
|
|
93
|
+
results = await asyncio.gather(
|
|
94
|
+
*[
|
|
95
|
+
_tracked(item, urls[i % len(urls)])
|
|
96
|
+
for i, item in enumerate(query)
|
|
97
|
+
]
|
|
98
|
+
)
|
|
99
|
+
if verbose:
|
|
100
|
+
print("Inference complete.")
|
|
101
|
+
except Exception as e:
|
|
102
|
+
print(f"Error during inference: {e}")
|
|
103
|
+
raise
|
|
104
|
+
finally:
|
|
105
|
+
for srv in servers:
|
|
106
|
+
srv.stop()
|
|
107
|
+
|
|
108
|
+
return list(results)
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
async def _async_batch_on_server(
|
|
112
|
+
chunk: Union[List[Dict[str, str]], List[str]],
|
|
113
|
+
prompt: PromptTemplate,
|
|
114
|
+
model: str,
|
|
115
|
+
parser: Optional[BaseOutputParser] = None,
|
|
116
|
+
model_kwargs: Optional[Dict[str, Any]] = None,
|
|
117
|
+
base_url: Optional[str] = None,
|
|
118
|
+
counter: Optional[List[int]] = None,
|
|
119
|
+
total: Optional[int] = None,
|
|
120
|
+
verbose: bool = False,
|
|
121
|
+
) -> Dict[str, Any]:
|
|
122
|
+
"""Run a batch of inference calls on a single server and return the responses along with the server URL."""
|
|
123
|
+
kwargs = dict(model=model, **(model_kwargs or {}))
|
|
124
|
+
if base_url:
|
|
125
|
+
kwargs["base_url"] = base_url
|
|
126
|
+
|
|
127
|
+
llm = ChatOllama(**kwargs)
|
|
128
|
+
chain = prompt | llm | parser if parser else prompt | llm
|
|
129
|
+
|
|
130
|
+
if parser:
|
|
131
|
+
fmt = parser.get_format_instructions()
|
|
132
|
+
for q in chunk:
|
|
133
|
+
if isinstance(q, dict):
|
|
134
|
+
q["format_instructions"] = fmt
|
|
135
|
+
|
|
136
|
+
all_responses = []
|
|
137
|
+
for i in range(0, len(chunk), 100):
|
|
138
|
+
# Process the batch in sub-chunks to avoid overwhelming the server. Adjust the sub-chunk size as needed.
|
|
139
|
+
sub = chunk[i : i + 100]
|
|
140
|
+
responses = await chain.abatch(sub)
|
|
141
|
+
all_responses.extend(responses)
|
|
142
|
+
if counter is not None:
|
|
143
|
+
counter[0] += len(responses)
|
|
144
|
+
if verbose:
|
|
145
|
+
print(f" Progress: {counter[0]}/{total} done")
|
|
146
|
+
|
|
147
|
+
return {"responses": all_responses, "url": base_url or "default server"}
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
async def parallel_batch_inference(
|
|
151
|
+
extra_ports: list[int],
|
|
152
|
+
query_list: List[Dict[str, str]],
|
|
153
|
+
prompt: str,
|
|
154
|
+
model: str,
|
|
155
|
+
parser: Optional[BaseOutputParser] = None,
|
|
156
|
+
model_kwargs: Optional[Dict[str, Any]] = None,
|
|
157
|
+
verbose: bool = True,
|
|
158
|
+
):
|
|
159
|
+
"""Start one additional Ollama server per port in *extra_ports*, then run batch inference in parallel."""
|
|
160
|
+
all_ports = [None] + extra_ports # None → default server
|
|
161
|
+
n_servers = len(all_ports)
|
|
162
|
+
# Split the query list into at most n_servers chunks.
|
|
163
|
+
chunk_size = math.ceil(len(query_list) / n_servers)
|
|
164
|
+
chunks = [
|
|
165
|
+
query_list[i : i + chunk_size] for i in range(0, len(query_list), chunk_size)
|
|
166
|
+
]
|
|
167
|
+
|
|
168
|
+
# Create OllamaServer instances for each extra port. The default server is assumed to be already running.
|
|
169
|
+
servers = [OllamaServer(port=p) for p in extra_ports]
|
|
170
|
+
|
|
171
|
+
if verbose:
|
|
172
|
+
print(
|
|
173
|
+
f"Starting {len(servers)} extra server(s), with {len(chunks)} chunk(s) of queries..."
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
if parser:
|
|
177
|
+
if "{format_instructions}" not in prompt:
|
|
178
|
+
prompt += "\n\nFormat Instructions:\n{format_instructions}"
|
|
179
|
+
|
|
180
|
+
prompt = PromptTemplate.from_template(prompt)
|
|
181
|
+
|
|
182
|
+
# Boot all extra servers concurrently (blocking start() pushed to threads)
|
|
183
|
+
await asyncio.gather(*[asyncio.to_thread(srv.start) for srv in servers])
|
|
184
|
+
|
|
185
|
+
if verbose:
|
|
186
|
+
print("All servers ready. Running batch inference...")
|
|
187
|
+
|
|
188
|
+
total = len(query_list)
|
|
189
|
+
counter = [0]
|
|
190
|
+
|
|
191
|
+
try:
|
|
192
|
+
urls = [None] + [srv.url for srv in servers]
|
|
193
|
+
nested = await asyncio.gather(
|
|
194
|
+
*[
|
|
195
|
+
_async_batch_on_server(
|
|
196
|
+
chunk=chunk,
|
|
197
|
+
prompt=prompt,
|
|
198
|
+
model=model,
|
|
199
|
+
parser=parser,
|
|
200
|
+
model_kwargs=model_kwargs,
|
|
201
|
+
base_url=url,
|
|
202
|
+
counter=counter,
|
|
203
|
+
total=total,
|
|
204
|
+
verbose=verbose,
|
|
205
|
+
)
|
|
206
|
+
for url, chunk in zip(urls, chunks)
|
|
207
|
+
]
|
|
208
|
+
)
|
|
209
|
+
if verbose:
|
|
210
|
+
print("Batch inference complete.")
|
|
211
|
+
except Exception as e:
|
|
212
|
+
print(f"Error during batch inference: {e}")
|
|
213
|
+
raise
|
|
214
|
+
finally:
|
|
215
|
+
for srv in servers:
|
|
216
|
+
srv.stop()
|
|
217
|
+
|
|
218
|
+
# Flatten while preserving per-server chunk order
|
|
219
|
+
return [
|
|
220
|
+
{"url": chunk_result["url"], "response": response}
|
|
221
|
+
for chunk_result in nested
|
|
222
|
+
for response in chunk_result["responses"]
|
|
223
|
+
]
|