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

Add logits method to Sequence class #237

Closed
wants to merge 5 commits into from
Closed
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
37 changes: 34 additions & 3 deletions outlines/text/generate/sequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,38 @@ def is_finished(self, token_ids: torch.LongTensor) -> torch.BoolTensor:
def postprocess_completions(self, completions: List[str]) -> List[str]:
return completions

def _next_token_logits(
self,
num_prompt_tokens: int,
token_ids: torch.LongTensor,
attention_mask: torch.LongTensor,
) -> torch.FloatTensor:
logits = self.model(token_ids, attention_mask)
logits = self.create_proposal(token_ids[:, num_prompt_tokens:], logits)
return logits

def next_token_logits(self, prompt: Union[str, List[str]]) -> torch.FloatTensor:
"""Compute the next-token logits for a given prompt.

Parameters
----------
prompt
The input prompt.

Returns
-------
An array of shape `(batch_size, vocab_size)` containing the logits
(unnormalised log probabilities) for the next token generation.

"""
token_ids, attention_mask = self.model.tokenizer.encode(prompt)
num_prompt_tokens = token_ids.shape[-1]
SamDuffield marked this conversation as resolved.
Show resolved Hide resolved
token_ids = token_ids.to(self.device)
attention_mask = attention_mask.to(self.device)
return self._next_token_logits(
num_prompt_tokens, token_ids, attention_mask
).squeeze()

def step(
self,
rng: torch.Generator,
Expand Down Expand Up @@ -78,9 +110,8 @@ def step(

"""
num_input_dims = token_ids.ndim
probs = self.model(token_ids, attention_mask)
probs = self.create_proposal(token_ids[:, num_prompt_tokens:], probs)
probs = torch.nn.functional.softmax(probs, dim=-1)
logits = self._next_token_logits(num_prompt_tokens, token_ids, attention_mask)
probs = torch.nn.functional.softmax(logits, dim=-1)

# Sample `samples`-many new tokens
next_token_ids = vectorized_random_choice(rng, probs, samples)
Expand Down