Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mask cache Performance Optimization for vllm #939

Merged
merged 5 commits into from
Jun 16, 2024
Merged
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
21 changes: 14 additions & 7 deletions outlines/integrations/vllm.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@

import math
from collections import defaultdict
from typing import TYPE_CHECKING, DefaultDict, List, Optional, Type, Union
from typing import TYPE_CHECKING, DefaultDict, Dict, List, Optional, Type, Union

import torch
from pydantic import BaseModel
Expand Down Expand Up @@ -78,6 +78,7 @@ def __init__(self, regex_string: str, llm: "LLM"):
"`tokenizer` attribute or a `get_tokenizer` method."
)
tokenizer = adapt_tokenizer(tokenizer=tokenizer)
self.mask_cache: Dict[int, torch.Tensor] = {}
self.fsm = RegexGuide(regex_string, tokenizer)
self._fsm_state: DefaultDict[int, int] = defaultdict(int)

Expand Down Expand Up @@ -107,12 +108,18 @@ def __call__(self, input_ids: List[int], scores: torch.Tensor) -> torch.Tensor:
state=self._fsm_state[last_seq_id], token_id=last_token
)

allowed_tokens = self.fsm.get_next_instruction(
state=self._fsm_state[seq_id]
).tokens

mask = torch.full((scores.shape[-1],), -math.inf, device=scores.device)
mask[allowed_tokens] = 0
state_id = self._fsm_state[seq_id]
if state_id not in self.mask_cache:
allowed_tokens = self.fsm.get_next_instruction(
state=self._fsm_state[seq_id]
).tokens
mask = torch.full((scores.shape[-1],), -math.inf)
mask[allowed_tokens] = 0
mask = mask.pin_memory()
self.mask_cache[state_id] = mask
else:
mask = self.mask_cache[state_id]
mask = mask.to(device=scores.device, non_blocking=True)
biased_scores = scores + mask

return biased_scores
Expand Down
Loading