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

Enhance Speculative Generation with Better Type Hints and Cleaner Code #611

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
15 changes: 8 additions & 7 deletions src/petals/models/llama/speculative_model.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Optional, Union
from typing import Optional, Union, List

import torch
from transformers.generation import GenerationConfig, LogitsProcessorList, StoppingCriteriaList
Expand All @@ -9,7 +9,6 @@
from petals.models.llama.config import DistributedLlamaConfig
from petals.models.llama.model import DistributedLlamaForCausalLM


class DistributedLlamaForSpeculativeGeneration(DistributedLlamaForCausalLM, GenerationMixin):
def __init__(self, config: DistributedLlamaConfig, small_model: LlamaForCausalLM):
DistributedLlamaForCausalLM.__init__(self, config)
Expand Down Expand Up @@ -39,7 +38,7 @@ def _sample(
batch_size = input_ids.shape[0]
unfinished_sequences = torch.ones(batch_size, dtype=torch.long, device=input_ids.device)
finished = False
firsts = True
first_iteration = True

while not finished:
speculative_inference_iteration_size = min(
Expand All @@ -57,18 +56,19 @@ def _sample(
assert input_ids.shape[1] + speculative_inference_iteration_size == full_sequence.shape[1]

input_for_validation = full_sequence
if not firsts:
if not first_iteration:
self.active_session.position = input_ids.shape[1] - 1
input_for_validation = input_for_validation[:, -speculative_inference_iteration_size - 1 :]
else:
firsts = False
first_iteration = False
input_for_validation = input_for_validation[:, :-1]

with torch.no_grad():
precise_model_outputs = self(input_for_validation)
full_token_logits = precise_model_outputs.logits[:, -speculative_inference_iteration_size:, :].clone()

all_valid_tokens = []
first_token = None
all_valid_tokens: List[torch.Tensor] = []
first_token: Optional[torch.Tensor] = None
for i in range(speculative_inference_iteration_size):
token_logits = full_token_logits[:, i, :]
token_scores = logits_processor(
Expand Down Expand Up @@ -109,3 +109,4 @@ def _sample(
streamer.end()

return input_ids