Skip to content
Open
Show file tree
Hide file tree
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
35 changes: 33 additions & 2 deletions llmsql/_cli/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,9 @@ def _add_args(self) -> None:
# COMMON BENCHMARK ARGS
# =========================
def add_common_benchmark_args(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--version", default="2.0", choices=get_available_versions())
parser.add_argument(
"--version", default="2.0", choices=get_available_versions()
)
parser.add_argument("--output-file", default="llm_sql_predictions.jsonl")
parser.add_argument(
"--workdir-path",
Expand Down Expand Up @@ -283,6 +285,20 @@ def add_common_generation_args(
type=json.loads,
help="JSON string for SamplingParams kwargs",
)
# LoRA args
self._parser_vllm.add_argument(
"--enable-lora", action="store_true", help="Enable LoRA adapters"
)
self._parser_vllm.add_argument("--lora-path", help="Path to LoRA adapter")
self._parser_vllm.add_argument("--lora-name", help="Name of LoRA adapter")
self._parser_vllm.add_argument(
"--lora-scale", type=float, default=1.0, help="LoRA scaling factor"
)
self._parser_vllm.add_argument(
"--lora-config",
type=json.loads,
help="JSON string for LoRA config dict",
)

add_common_benchmark_args(self._parser_vllm)

Expand Down Expand Up @@ -356,17 +372,32 @@ def _execute_transformers(args: argparse.Namespace) -> None:
def _execute_vllm(args: argparse.Namespace) -> None:
from llmsql import inference_vllm

llm_kwargs = merge_model_args(args.model_args, args.llm_kwargs)
lora_config = args.lora_config
if lora_config is None and args.lora_path:
lora_config = {
"lora_path": args.lora_path,
"lora_name": args.lora_name if args.lora_name else "default",
"lora_scale": args.lora_scale,
}
# Providing a LoRA config implies `enable_lora=True`.
if args.enable_lora or lora_config is not None:
if llm_kwargs is None:
llm_kwargs = {}
llm_kwargs["enable_lora"] = True

inference_vllm(
model_name=args.model_name,
trust_remote_code=args.trust_remote_code,
tensor_parallel_size=args.tensor_parallel_size,
hf_token=args.hf_token,
llm_kwargs=merge_model_args(args.model_args, args.llm_kwargs),
llm_kwargs=llm_kwargs,
use_chat_template=args.use_chat_template,
max_new_tokens=args.max_new_tokens,
temperature=args.temperature,
do_sample=args.do_sample,
sampling_kwargs=args.sampling_kwargs,
lora_config=lora_config,
version=args.version,
output_file=args.output_file,
workdir_path=args.workdir_path,
Expand Down
2 changes: 1 addition & 1 deletion llmsql/inference/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ Runs inference using the [vLLM](https://github.com/vllm-project/vllm) backend fo
| `tensor_parallel_size` | `int` | `1` | Number of GPUs for tensor parallelism. |
| `hf_token` | `str \| None` | `None` | Hugging Face authentication token. |
| `llm_kwargs` | `dict \| None` | `None` | Additional kwargs for `vllm.LLM()`. |
| `llm_kwargs` | `bool` | `True` | Whether to use chat template of the tokenizer |
| `use_chat_template` | `bool` | `True` | Whether to use chat template of the tokenizer |

#### Generation

Expand Down
7 changes: 4 additions & 3 deletions llmsql/inference/inference_transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,8 @@ def inference_transformers(

# Tokenizer Loading:
tokenizer_kwargs: Additional arguments for AutoTokenizer.from_pretrained(). 'padding_side' defaults to "left".
Note: 'trust_remote_code', 'token' are handled separately and will override values here.
Note: 'trust_remote_code', 'token' are handled separately;
values in tokenizer_kwargs take precedence if explicitly passed.


# Prompt & Chat:
Expand Down Expand Up @@ -231,11 +232,11 @@ def inference_transformers(

if tok_name:
load_tok_args = {
"trust_remote_code": True,
"trust_remote_code": trust_remote_code,
"token": hf_token,
"padding_side": tokenizer_kwargs.get("padding_side", "left"),
**tokenizer_kwargs,
}
load_tok_args.update(tokenizer_kwargs)
tokenizer = AutoTokenizer.from_pretrained(tok_name, **load_tok_args)

if tokenizer.pad_token is None:
Expand Down
18 changes: 8 additions & 10 deletions llmsql/inference/inference_vllm.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,11 @@
max_new_tokens=256,
temperature=0.7,
tensor_parallel_size=1,
lora_path="path/to/lora"
lora_path="path/to/lora",
)

Notes
~~~~~
-----

This function uses the vLLM backend. Outputs may differ from the Transformers
backend due to differences in implementation, batching, and numerical precision.
Expand Down Expand Up @@ -105,8 +105,8 @@ def inference_vllm(
hf_token: Hugging Face authentication token.
llm_kwargs: Additional arguments for vllm.LLM().
Note: 'model', 'tokenizer', 'tensor_parallel_size',
'trust_remote_code' are handled separately and will
override values here.
'trust_remote_code', 'hf_token' are handled separately;
values in llm_kwargs take precedence on conflicts.

lora_config: Optional dict with LoRA parameters:
- lora_path: Path to the pretrained LoRA adapter (required if enable_lora)
Expand All @@ -124,7 +124,7 @@ def inference_vllm(
do_sample: Whether to use sampling vs greedy decoding.
sampling_kwargs: Additional arguments for vllm.SamplingParams().
Note: 'temperature', 'max_tokens' are handled
separately and will override values here.
separately; values in sampling_kwargs take precedence.

# Benchmark:
version: LLMSQL version
Expand Down Expand Up @@ -188,19 +188,17 @@ def inference_vllm(
)
if enable_lora and lora_config is None:
raise ValueError("`enable_lora` is True but no `lora_config` was provided.")
if lora_config is not None and not enable_lora:
raise ValueError(
"`lora_config` provided but `enable_lora` is not True in llm_kwargs."
)

# --- init model ---
llm_init_args = {
"model": model_name,
"tokenizer": model_name,
"tensor_parallel_size": tensor_parallel_size,
"trust_remote_code": trust_remote_code,
**llm_kwargs, # user overrides
}
if hf_token:
llm_init_args["hf_token"] = hf_token
llm_init_args.update(llm_kwargs)

log.info(f"Loading vLLM model '{model_name}' (tp={tensor_parallel_size})...")
llm = LLM(**llm_init_args)
Expand Down
96 changes: 96 additions & 0 deletions tests/cli/test_model_args.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,102 @@ def test_vllm_model_args_reach_llm_kwargs(monkeypatch, flag):
}


def test_vllm_lora_path_produces_lora_config(monkeypatch):
mock_inference = MagicMock(return_value=[])
import llmsql

monkeypatch.setitem(llmsql.__dict__, "inference_vllm", mock_inference)

_run_cli(
monkeypatch,
[
"inference",
"vllm",
"--model-name",
"m",
"--lora-path",
"/path/to/adapter",
],
)

mock_inference.assert_called_once()
kwargs = mock_inference.call_args.kwargs
assert kwargs["lora_config"] == {
"lora_path": "/path/to/adapter",
"lora_name": "default",
"lora_scale": 1.0,
}
# `--lora-path` implies `enable_lora=True`
assert kwargs["llm_kwargs"]["enable_lora"] is True


def test_vllm_lora_name_and_scale_are_forwarded(monkeypatch):
mock_inference = MagicMock(return_value=[])
import llmsql

monkeypatch.setitem(llmsql.__dict__, "inference_vllm", mock_inference)

_run_cli(
monkeypatch,
[
"inference",
"vllm",
"--model-name",
"m",
"--lora-path",
"/path/to/adapter",
"--lora-name",
"my-adapter",
"--lora-scale",
"0.5",
],
)

kwargs = mock_inference.call_args.kwargs
assert kwargs["lora_config"] == {
"lora_path": "/path/to/adapter",
"lora_name": "my-adapter",
"lora_scale": 0.5,
}


def test_vllm_lora_config_json_implies_enable_lora(monkeypatch):
mock_inference = MagicMock(return_value=[])
import llmsql

monkeypatch.setitem(llmsql.__dict__, "inference_vllm", mock_inference)

lora_config = {"lora_path": "/path/to/adapter", "lora_name": "n"}
_run_cli(
monkeypatch,
[
"inference",
"vllm",
"--model-name",
"m",
"--lora-config",
json.dumps(lora_config),
],
)

kwargs = mock_inference.call_args.kwargs
assert kwargs["lora_config"] == lora_config
assert kwargs["llm_kwargs"]["enable_lora"] is True


def test_vllm_without_lora_keeps_none(monkeypatch):
mock_inference = MagicMock(return_value=[])
import llmsql

monkeypatch.setitem(llmsql.__dict__, "inference_vllm", mock_inference)

_run_cli(monkeypatch, ["inference", "vllm", "--model-name", "m"])

kwargs = mock_inference.call_args.kwargs
assert kwargs["lora_config"] is None
assert kwargs["llm_kwargs"] is None


@pytest.mark.parametrize(
"argv",
[
Expand Down
64 changes: 64 additions & 0 deletions tests/inference/test_inference_transformers_tokenizer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
"""Tokenizer loading in ``inference_transformers`` (issue #110).

Covers the ``trust_remote_code`` argument reaching ``AutoTokenizer.from_pretrained``
and the documented precedence where ``tokenizer_kwargs`` override explicit params.
"""

from unittest.mock import MagicMock

import pytest

import llmsql.inference.inference_transformers as it


class _StopLoading(Exception):
pass


def _captured_tokenizer_kwargs(monkeypatch, **kwargs):
captured = {}

def fake_tok_from_pretrained(name, **load_kwargs):
captured["name"] = name
captured.update(load_kwargs)
raise _StopLoading

monkeypatch.setattr(
it.AutoModelForCausalLM, "from_pretrained", lambda *a, **k: MagicMock()
)
monkeypatch.setattr(it.AutoTokenizer, "from_pretrained", fake_tok_from_pretrained)
with pytest.raises(_StopLoading):
it.inference_transformers("some/model", **kwargs)
return captured


def test_tokenizer_respects_trust_remote_code_false(monkeypatch):
captured = _captured_tokenizer_kwargs(monkeypatch, trust_remote_code=False)
assert captured["name"] == "some/model"
assert captured["trust_remote_code"] is False


def test_tokenizer_respects_trust_remote_code_true(monkeypatch):
captured = _captured_tokenizer_kwargs(monkeypatch, trust_remote_code=True)
assert captured["trust_remote_code"] is True


def test_tokenizer_kwargs_override_explicit_trust_remote_code(monkeypatch):
captured = _captured_tokenizer_kwargs(
monkeypatch,
trust_remote_code=True,
tokenizer_kwargs={"trust_remote_code": False},
)
assert captured["trust_remote_code"] is False


def test_tokenizer_kwargs_override_padding_side_default(monkeypatch):
captured = _captured_tokenizer_kwargs(
monkeypatch, tokenizer_kwargs={"padding_side": "right"}
)
assert captured["padding_side"] == "right"


def test_tokenizer_padding_side_defaults_to_left(monkeypatch):
captured = _captured_tokenizer_kwargs(monkeypatch)
assert captured["padding_side"] == "left"
Loading
Loading