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
13 changes: 13 additions & 0 deletions llmsql/_cli/inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,6 +187,16 @@ def add_common_benchmark_args(parser: argparse.ArgumentParser) -> None:
parser.add_argument("--batch-size", type=int, default=8)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--limit", type=parse_limit)
parser.add_argument(
"--resume",
action=argparse.BooleanOptionalAction,
default=False,
help=(
"Keep the completions already present in --output-file and "
"only generate the missing questions (use --no-resume to "
"always start from an empty file, which is the default)."
),
)

# =========================
# COMMON GENERATION ARGS
Expand Down Expand Up @@ -350,6 +360,7 @@ def _execute_transformers(args: argparse.Namespace) -> None:
batch_size=args.batch_size,
limit=args.limit,
seed=args.seed,
resume=args.resume,
)

@staticmethod
Expand All @@ -374,6 +385,7 @@ def _execute_vllm(args: argparse.Namespace) -> None:
num_fewshots=args.num_fewshots,
batch_size=args.batch_size,
seed=args.seed,
resume=args.resume,
)

@staticmethod
Expand All @@ -395,4 +407,5 @@ def _execute_api(args: argparse.Namespace) -> None:
limit=args.limit,
num_fewshots=args.num_fewshots,
seed=args.seed,
resume=args.resume,
)
49 changes: 17 additions & 32 deletions llmsql/inference/inference_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,17 @@
import nest_asyncio
from tqdm.asyncio import tqdm

from llmsql.config.config import (
DEFAULT_LLMSQL_VERSION,
get_repo_id,
)
from llmsql.config.config import DEFAULT_LLMSQL_VERSION
from llmsql.loggers.logging_config import log
from llmsql.utils.inference_utils import (
_maybe_download,
_setup_seed,
resolve_workdir_path,
prepare_benchmark,
prepare_output_file,
skip_completed,
)
from llmsql.utils.utils import (
build_all_requests,
choose_prompt_builder,
load_jsonl,
overwrite_jsonl,
save_jsonl_lines,
)

Expand Down Expand Up @@ -180,6 +176,7 @@ def inference_api(
limit: int | float | None = None,
num_fewshots: int = 5,
seed: int = 42,
resume: bool = False,
) -> list[dict[str, str]]:
"""Run SQL generation using an OpenAI-compatible Chat Completions API.

Expand All @@ -205,6 +202,9 @@ def inference_api(
limit: Limit the number of questions to evaluate. If an integer, evaluates
the first N samples. If a float between 0.0 and 1.0, evaluates the
first X*100% of samples. If None, evaluates all samples (default).
resume: If True and `output_file` already exists, keep the completions it
contains and only generate the missing questions. If False
(default), the file is truncated first.

Returns:
List of dicts containing `question_id` and generated `completion`.
Expand All @@ -213,28 +213,11 @@ def inference_api(
api_kwargs = api_kwargs or {}
request_headers = request_headers or {}

workdir = resolve_workdir_path(workdir_path)

repo_id = get_repo_id(version)
questions_path = _maybe_download(repo_id, "questions.jsonl", workdir)
tables_path = _maybe_download(repo_id, "tables.jsonl", workdir)

questions = load_jsonl(questions_path)
tables_list = load_jsonl(tables_path)
tables = {t["table_id"]: t for t in tables_list}

if limit is not None:
if isinstance(limit, float):
if not (0.0 < limit <= 1.0):
raise ValueError(
f"When a float, `limit` must be between 0.0 and 1.0, got {limit}."
)
limit = max(1, int(len(questions) * limit))
if not isinstance(limit, int) or limit < 1:
raise ValueError(
f"`limit` must be a positive integer or a float in (0.0, 1.0], got {limit!r}."
)
questions = questions[:limit]
run = prepare_benchmark(
version=version,
workdir_path=workdir_path,
limit=limit,
)

key = api_key or os.environ.get("OPENAI_API_KEY")
headers: dict[str, str] = {
Expand All @@ -246,7 +229,9 @@ def inference_api(

prompt_builder = choose_prompt_builder(num_fewshots)

overwrite_jsonl(output_file)
questions = skip_completed(
run.questions, prepare_output_file(output_file, resume=resume)
)

coro = _inference_api_async(
model_name,
Expand All @@ -257,7 +242,7 @@ def inference_api(
requests_per_minute=requests_per_minute,
api_kwargs=api_kwargs,
questions=questions,
tables=tables,
tables=run.tables,
prompt_builder=prompt_builder,
output_file=output_file,
)
Expand Down
46 changes: 18 additions & 28 deletions llmsql/inference/inference_function.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,17 @@
import nest_asyncio
from tqdm.asyncio import tqdm

from llmsql.config.config import DEFAULT_LLMSQL_VERSION, get_repo_id
from llmsql.config.config import DEFAULT_LLMSQL_VERSION
from llmsql.loggers.logging_config import log
from llmsql.utils.inference_utils import (
_maybe_download,
_setup_seed,
resolve_workdir_path,
prepare_benchmark,
prepare_output_file,
skip_completed,
)
from llmsql.utils.utils import (
build_all_requests,
choose_prompt_builder,
load_jsonl,
overwrite_jsonl,
save_jsonl_lines,
)

Expand Down Expand Up @@ -186,6 +185,7 @@ def inference_function(
limit: int | float | None = None,
num_fewshots: int = 5,
seed: int = 42,
resume: bool = False,
) -> list[dict[str, str]]:
"""Run SQL generation using a user-provided async callable.

Expand Down Expand Up @@ -259,6 +259,10 @@ def inference_function(
samples (default).
num_fewshots: Number of few-shot examples (0, 1, or 5).
seed: Random seed for reproducibility.
resume: If ``True`` and ``output_file`` already exists, keep the
completions it contains and only generate the missing questions.
If ``False`` (default), ``output_file`` is truncated first — the
historical behaviour.

Returns:
List of dicts containing ``question_id`` and generated ``completion``,
Expand Down Expand Up @@ -288,32 +292,18 @@ def inference_function(
)

function_kwargs = function_kwargs or {}
workdir = resolve_workdir_path(workdir_path)

repo_id = get_repo_id(version)
questions_path = _maybe_download(repo_id, "questions.jsonl", workdir)
tables_path = _maybe_download(repo_id, "tables.jsonl", workdir)

questions = load_jsonl(questions_path)
tables_list = load_jsonl(tables_path)
tables = {t["table_id"]: t for t in tables_list}

if limit is not None:
if isinstance(limit, float):
if not (0.0 < limit <= 1.0):
raise ValueError(
f"When a float, `limit` must be between 0.0 and 1.0, got {limit}."
)
limit = max(1, int(len(questions) * limit))
if not isinstance(limit, int) or limit < 1:
raise ValueError(
f"`limit` must be a positive integer or a float in (0.0, 1.0], got {limit!r}."
)
questions = questions[:limit]
run = prepare_benchmark(
version=version,
workdir_path=workdir_path,
limit=limit,
)

prompt_builder = choose_prompt_builder(num_fewshots)

overwrite_jsonl(output_file)
questions = skip_completed(
run.questions, prepare_output_file(output_file, resume=resume)
)

coro = _inference_function_async(
inference_callable=inference_function,
Expand All @@ -322,7 +312,7 @@ def inference_function(
raise_on_error=raise_on_error,
function_kwargs=function_kwargs,
questions=questions,
tables=tables,
tables=run.tables,
prompt_builder=prompt_builder,
output_file=output_file,
)
Expand Down
53 changes: 17 additions & 36 deletions llmsql/inference/inference_transformers.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,20 +44,16 @@
from tqdm import tqdm
from transformers import AutoModelForCausalLM, AutoTokenizer

from llmsql.config.config import (
DEFAULT_LLMSQL_VERSION,
get_repo_id,
)
from llmsql.config.config import DEFAULT_LLMSQL_VERSION
from llmsql.loggers.logging_config import log
from llmsql.utils.inference_utils import (
_maybe_download,
_setup_seed,
resolve_workdir_path,
prepare_benchmark,
prepare_output_file,
skip_completed,
)
from llmsql.utils.utils import (
choose_prompt_builder,
load_jsonl,
overwrite_jsonl,
save_jsonl_lines,
)

Expand Down Expand Up @@ -120,6 +116,7 @@ def inference_transformers(
batch_size: int = 8,
limit: int | float | None = None,
seed: int = 42,
resume: bool = False,
) -> list[dict[str, str]]:
"""
Inference a causal model (Transformers) on the LLMSQL benchmark.
Expand Down Expand Up @@ -169,6 +166,9 @@ def inference_transformers(
limit: Limit the number of questions to evaluate. If an integer, evaluates
the first N samples. If a float between 0.0 and 1.0, evaluates the
first X*100% of samples. If None, evaluates all samples (default).
resume: If True and `output_file` already exists, keep the completions it
contains and only generate the missing questions. If False
(default), the file is truncated first.

Returns:
List of generated SQL results with metadata.
Expand Down Expand Up @@ -254,40 +254,21 @@ def inference_transformers(
model.eval()

# --- Load necessary files ---
workdir = resolve_workdir_path(workdir_path)
repo_id = get_repo_id(version)

questions_path = _maybe_download(repo_id, "questions.jsonl", workdir)
tables_path = _maybe_download(repo_id, "tables.jsonl", workdir)

questions = load_jsonl(questions_path)
tables_list = load_jsonl(tables_path)
tables = {t["table_id"]: t for t in tables_list}

# --- Apply limit ---
if limit is not None:
if isinstance(limit, float):
if not (0.0 < limit <= 1.0):
raise ValueError(
f"When a float, `limit` must be between 0.0 and 1.0, got {limit}."
)
limit = max(1, int(len(questions) * limit))
if not isinstance(limit, int) or limit < 1:
raise ValueError(
f"`limit` must be a positive integer or a float in (0.0, 1.0], got {limit!r}."
)
log.info(
f"Limiting evaluation to first {limit} questions out of {len(questions)}"
)
questions = questions[:limit]
run = prepare_benchmark(
version=version,
workdir_path=workdir_path,
limit=limit,
)

# --- Chat template setup ---
use_chat_template = chat_template or getattr(tokenizer, "chat_template", None)
if use_chat_template:
log.info("Using chat template for prompt formatting.")

# --- Output setup ---
overwrite_jsonl(output_file)
questions = skip_completed(
run.questions, prepare_output_file(output_file, resume=resume)
)
log.info(f"Writing results to {output_file}")

prompt_builder = choose_prompt_builder(num_fewshots)
Expand All @@ -302,7 +283,7 @@ def inference_transformers(
prompts = []

for q in batch:
tbl = tables[q["table_id"]]
tbl = run.tables[q["table_id"]]
example_row = tbl["rows"][0] if tbl["rows"] else []
text = prompt_builder(
q["question"], tbl["header"], tbl["types"], example_row
Expand Down
Loading
Loading