[Misc] Various code simplifications (#31666)

Signed-off-by: njhill <nickhill123@gmail.com>
This commit is contained in:
Nick Hill
2026-01-04 18:35:56 -08:00
committed by GitHub
parent bb4337b34c
commit 43e3f8e4a9
7 changed files with 66 additions and 135 deletions
+24 -36
View File
@@ -5,6 +5,7 @@ from __future__ import annotations
import hashlib
import importlib.metadata
import os
import tempfile
from typing import TYPE_CHECKING
import numpy as np
@@ -34,9 +35,6 @@ else:
"convert_slow_tokenizer", globals(), "transformers.convert_slow_tokenizer"
)
TokenizerLike = object
SchedulerOutput = object
InputBatch = object
logger = init_logger(__name__)
@@ -72,13 +70,12 @@ def apply_grammar_bitmask(
# request in the batch, as the logit indices are offset by this amount.
struct_out_req_batch_indices: dict[str, int] = {}
cumulative_offset = 0
seq = sorted(input_batch.req_id_to_index.items(), key=lambda x: x[1])
for req_id, batch_index in seq:
spec_tokens = scheduler_output.scheduled_spec_decode_tokens
struct_out_req_ids = set(grammar_output.structured_output_request_ids)
for batch_index, req_id in enumerate(input_batch.req_ids):
logit_index = batch_index + cumulative_offset
cumulative_offset += len(
scheduler_output.scheduled_spec_decode_tokens.get(req_id, [])
)
if req_id in grammar_output.structured_output_request_ids:
cumulative_offset += len(spec_tokens.get(req_id, ()))
if req_id in struct_out_req_ids:
struct_out_req_batch_indices[req_id] = logit_index
out_indices = []
@@ -91,14 +88,12 @@ def apply_grammar_bitmask(
)
cumulative_index = 0
for req_id in grammar_output.structured_output_request_ids:
num_spec_tokens = len(
scheduler_output.scheduled_spec_decode_tokens.get(req_id, [])
)
if req_id in struct_out_req_batch_indices:
logit_index = struct_out_req_batch_indices[req_id]
num_spec_tokens = len(spec_tokens.get(req_id, ()))
if (logit_idx := struct_out_req_batch_indices.get(req_id)) is not None:
for i in range(1 + num_spec_tokens):
sorted_bitmask[logit_index + i] = grammar_bitmask[cumulative_index + i]
out_indices.append(logit_index + i)
bitmask_index = logit_idx + i
sorted_bitmask[bitmask_index] = grammar_bitmask[cumulative_index + i]
out_indices.append(bitmask_index)
cumulative_index += 1 + num_spec_tokens
# Copy async to device as tensor.
@@ -149,21 +144,19 @@ def get_outlines_cache_path() -> str:
if outlines_cache_dir:
# OUTLINES_CACHE_DIR takes precedence
return outlines_cache_dir
elif xdg_cache_home:
if xdg_cache_home:
return os.path.join(xdg_cache_home, ".cache", "outlines")
# If homedir is "/", we may be inside a container, and thus writing to
# root would be problematic, so we fall back to using a tempfile.
# Also validate the path exists, since os.path.expanduser does
# not guarantee existence.
elif os.path.isdir(home_dir) and home_dir != "/":
if os.path.isdir(home_dir) and home_dir != "/":
# Default Unix fallback: ~/.cache/outlines
return os.path.join(home_dir, ".cache", "outlines")
else:
import tempfile
# home_dir may be / inside a docker container without existing user
tempdir = tempfile.gettempdir()
return os.path.join(tempdir, ".cache", "outlines")
# home_dir may be / inside a docker container without existing user
tempdir = tempfile.gettempdir()
return os.path.join(tempdir, ".cache", "outlines")
def get_outlines_cache():
@@ -184,8 +177,8 @@ def get_outlines_cache():
cache.clear()
cache.set("__version__", outlines_version)
return cache
else:
return LRUCache(maxsize=128)
return LRUCache(maxsize=128)
re_llama_byte_token = re.compile(r"^<0x[0-9A-F]{2}>$")
@@ -193,8 +186,7 @@ re_replacement_seq = re.compile(r"^.{0,6}�+.{0,6}$")
def _reduced_vocabulary(
tokenizer: TokenizerLike,
eos_token_id: int,
tokenizer: TokenizerLike, eos_token_id: int
) -> dict[bytes, list[int]]:
"""Create a map from vocabulary tokens to lists of equivalent token ids.
@@ -267,17 +259,13 @@ def get_outlines_vocabulary(tokenizer: TokenizerLike) -> oc.Vocabulary:
return tokenizer._outlines_vocabulary # type: ignore
try:
if (
hasattr(
tokenizer,
"eos_token_id",
)
and tokenizer.eos_token_id is not None
):
if hasattr(tokenizer, "eos_token_id") and tokenizer.eos_token_id is not None:
eos_token_id = tokenizer.eos_token_id
else:
raise ValueError(
f"Error during structured outputs setup for outlines: Tokenizer ({type(tokenizer)}) has no `eos_token_id` property, but `eos_token_id` is required for structured outputs to work properly." # noqa: E501
"Error during structured outputs setup for outlines: Tokenizer "
f"({type(tokenizer)}) has no `eos_token_id` property, but "
"`eos_token_id` is required for structured outputs to work properly."
)
reduced_vocab = _reduced_vocabulary(
@@ -290,7 +278,7 @@ def get_outlines_vocabulary(tokenizer: TokenizerLike) -> oc.Vocabulary:
return vocabulary
except AttributeError as e:
raise ValueError(
f"Cannot get the vocabulary of the tokenizer "
"Cannot get the vocabulary of the tokenizer "
f"({type(tokenizer)}). The tokenizer should have a "
"get_vocab method."
) from e